branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>Hl4p3x/tenkai-pow3<file_sep>/java/org/l2jmobius/gameserver/gui/AdminTab.java
package org.l2jmobius.gameserver.gui;
import org.l2jmobius.gameserver.gui.playertable.PlayerTablePane;
import org.l2jmobius.gameserver.model.announce.Announcement;
import org.l2jmobius.gameserver.util.Broadcast;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AdminTab extends JPanel {
private static final long serialVersionUID = 1L;
private GridBagConstraints cons = new GridBagConstraints();
private GridBagLayout layout = new GridBagLayout();
private JPanel listPanel = new PlayerTablePane();
private JPanel infoPanel = new JPanel();
public AdminTab() {
JTextArea talkadmin = new JTextArea();
JButton bouton = new JButton("Send");
bouton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Broadcast.toAllOnlinePlayers(talkadmin.getText());
}
});
setLayout(layout);
cons.fill = GridBagConstraints.HORIZONTAL;
infoPanel.setLayout(layout);
cons.insets = new Insets(5, 5, 5, 5);
cons.gridwidth = 3;
cons.gridheight = 20;
cons.weightx = 1;
cons.weighty = 1;
cons.gridx = 0;
cons.gridy = 2;
infoPanel.add(bouton, cons);
infoPanel.setPreferredSize(new Dimension(235, infoPanel.getHeight()));
cons.fill = GridBagConstraints.BOTH;
cons.weightx = 1;
cons.weighty = 1;
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listPanel, infoPanel);
splitPane.setResizeWeight(0.3);
splitPane.setDividerLocation(535);
add(splitPane, cons);
listPanel.add(talkadmin, cons);
}
}<file_sep>/java/org/l2jmobius/gameserver/network/clientpackets/RequestRestart.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.gameserver.network.clientpackets;
import java.util.logging.Logger;
import org.l2jmobius.commons.network.PacketReader;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.network.ConnectionState;
import org.l2jmobius.gameserver.network.Disconnection;
import org.l2jmobius.gameserver.network.GameClient;
import org.l2jmobius.gameserver.network.serverpackets.ActionFailed;
import org.l2jmobius.gameserver.network.serverpackets.CharSelectionInfo;
import org.l2jmobius.gameserver.network.serverpackets.RestartResponse;
import org.l2jmobius.gameserver.util.OfflineTradeUtil;
import org.l2jmobius.gameserver.events.ElpiesArena.ElpiesArena;
/**
* @version $Revision: 1.11.2.1.2.4 $ $Date: 2005/03/27 15:29:30 $
*/
public class RequestRestart implements IClientIncomingPacket
{
protected static final Logger LOGGER_ACCOUNTING = Logger.getLogger("accounting");
@Override
public boolean read(GameClient client, PacketReader packet)
{
return true;
}
@Override
public void run(GameClient client)
{
final PlayerInstance player = client.getPlayer();
if (player == null)
{
return;
}
if (!player.canLogout())
{
client.sendPacket(RestartResponse.FALSE);
player.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
LOGGER_ACCOUNTING.info("Logged out, " + client);
if (!OfflineTradeUtil.enteredOfflineMode(player))
{
Disconnection.of(client, player).storeMe().deleteMe();
}
if (ElpiesArena.elpy.containsKey(player.getObjectId())) {
ElpiesArena.getInstance().removePlayer(player);
}
// return the client to the authed status
client.setConnectionState(ConnectionState.AUTHENTICATED);
client.sendPacket(RestartResponse.TRUE);
// send char list
final CharSelectionInfo cl = new CharSelectionInfo(client.getAccountName(), client.getSessionId().playOkID1);
client.sendPacket(cl);
client.setCharSelection(cl.getCharInfo());
}
}
<file_sep>/data/scripts/ai/bosses/Piggy/Piggy.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.bosses.Piggy;
import org.l2jmobius.commons.concurrent.ThreadPool;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.ai.CtrlIntention;
import org.l2jmobius.gameserver.data.xml.impl.SkillData;
import org.l2jmobius.gameserver.enums.ChatType;
import org.l2jmobius.gameserver.enums.MountType;
import org.l2jmobius.gameserver.geoengine.GeoEngine;
import org.l2jmobius.gameserver.model.Location;
import org.l2jmobius.gameserver.model.World;
import org.l2jmobius.gameserver.model.actor.Attackable;
import org.l2jmobius.gameserver.model.actor.Npc;
import org.l2jmobius.gameserver.model.actor.Playable;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.holders.SkillHolder;
import org.l2jmobius.gameserver.model.skills.Skill;
import org.l2jmobius.gameserver.network.NpcStringId;
import org.l2jmobius.gameserver.network.serverpackets.ExSendUIEvent;
import org.l2jmobius.gameserver.network.serverpackets.ExShowScreenMessage;
import org.l2jmobius.gameserver.network.serverpackets.NpcHtmlMessage;
import org.l2jmobius.gameserver.network.serverpackets.NpcSay;
import org.l2jmobius.gameserver.util.Util;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Future;
import ai.AbstractNpcAI;
/**
* Piggy' AI.
*
* @author Barroso_K
*/
public class Piggy extends AbstractNpcAI {
// NPC
private static final int PIGGY = 9009120;
private static final String[] PIGGY_SPEACH_ON_HIT = {
"Stop hitting me please",
"What have i done to deserve that ?",
"Why are you so mean to me ?",
"Stop it hurts",
"I have kids !",
"Stop i'll give you some adena !",
"I won't forgive you"
};
private long _lastSpoke = 0;
private int _speakInterval = 10; // Seconds
private int _angryTime = 5; // Seconds
public static Future<?> _timer;
public int _timeLeft = 0;
private final PiggySkill[] PIGGY_SKILLS =
{
new PiggySkill(15271, 20, 100, true, 1000), // Body Slam
new PiggySkill(15287, 25, 250, false), // Twister
new PiggySkill(15305, 30, 300, false, 400), // Hurricane
new PiggySkill(15342, 10, 500, false) // Shock Smash
};
private class PiggySkill {
private int skillId;
private int brutDamages;
private int percentDamage;
private boolean isAoe;
private int range;
PiggySkill(int skillId, int percentDamage, int brutDamages, boolean isAoe, int range) {
this.skillId = skillId;
this.percentDamage = percentDamage;
this.brutDamages = brutDamages;
this.isAoe = isAoe;
this.range = range;
}
PiggySkill(int skillId, int percentDamage, int brutDamages, boolean isAoe) {
this.skillId = skillId;
this.percentDamage = percentDamage;
this.brutDamages = brutDamages;
this.isAoe = isAoe;
}
public int getSkillId() {
return this.skillId;
}
public int getPercentDamage() {
return this.percentDamage;
}
public boolean isAoe() {
return this.isAoe;
}
public int getRange() {
return this.range;
}
public Skill getSkill() {
return SkillData.getInstance().getSkill(this.skillId, 1);
}
public int getBrutDamages() {
return this.brutDamages;
}
}
private Playable _actualVictim;
private boolean _isAngry = false;
private static Npc _piggy;
public static Location PIGGY_LOC = new Location(-51640, -70248, -3418);
public static boolean isSpawned = false;
public static int[] servitors = {9009121, 9009122, 9009123};
public static Vector<Npc> _servitors = new Vector<>();
private static final SkillHolder SERVITOR_HEAL = new SkillHolder(1401, 10);
private static final String[] SERVITORS_SPEACH = {
"Here's some heal master !!",
"Are you okay king ?",
"I'm coming for you master !",
"I'm here to help you !",
"I'll take care of you don't worry master",
"The doctor is here !",
"Let me take care of this my king",
"You will soon feel better believe me"
};
public static int SCARECROW = 9009124;
public static Location SCARECROW_LOC = new Location(-51624, -68840, -3418);
public static Npc _scarecrow;
public static boolean _scarecrowSpawned = false;
public int _totalhits = 0;
public int _maxHits = 100;
private static final int NPC_ID = 9009126;
private Npc _teleporter;
public Piggy() {
registerMobs(PIGGY);
addAttackId(SCARECROW);
for (int mob : servitors) {
addAttackId(mob);
addKillId(mob);
}
if (isSpawned) {
return;
}
addStartNpc(NPC_ID);
addTalkId(NPC_ID);
addFirstTalkId(NPC_ID);
_teleporter = addSpawn(NPC_ID, 147414, 27928, -2271, 20352, false, 0);
_teleporter.setTitle("Piggy Raidboss");
if (_piggy != null) {
_piggy.deleteMe();
}
_piggy = addSpawn(PIGGY, PIGGY_LOC, false, 0);
isSpawned = true;
startQuestTimer("regen_task", 10000, _piggy, null, true);
startQuestTimer("think", 10000, _piggy, null, true);
startQuestTimer("skill_task", 3000, _piggy, null, true);
startQuestTimer("spawn_servitors", 100, _piggy, null, false);
startQuestTimer("heal_the_king", 10000, _piggy, null, true);
}
@Override
public String onAdvEvent(String event, Npc npc, PlayerInstance player) {
if (npc != null) {
if (event.equalsIgnoreCase("skill_task")) {
callSkillAI(npc);
} else if (event.equalsIgnoreCase("spawn_scarecrow")) {
if (_scarecrow != null) {
return "";
}
_scarecrow = addSpawn(SCARECROW, SCARECROW_LOC.getX(), SCARECROW_LOC.getY(), SCARECROW_LOC.getZ(), -1, false, 0, true, 0);
_scarecrowSpawned = true;
startQuestTimer("unspawn_scarecrow", 10000, _piggy, null, false);
} else if (event.equalsIgnoreCase("think")) {
if (getRandom(20) == 0 && !_isAngry && !_scarecrowSpawned) {
startQuestTimer("spawn_scarecrow", 1, _piggy, null, false);
}
} else if (event.equalsIgnoreCase("unspawn_scarecrow")) {
_scarecrow.deleteMe();
_scarecrowSpawned = false;
if (_totalhits > _maxHits) {
_totalhits = _maxHits;
}
_piggy.reduceCurrentHp(getDamages(_piggy.getMaxHp(), (int) ((float) _totalhits / _maxHits * 100), 0), null, null, false, true, false, false);
_totalhits = 0;
} else if (event.equalsIgnoreCase("spawn_servitors")) {
if (_servitors.size() >= 15) {
return "";
}
int radius = 250;
for (int a = 0; a < 2; a++) {
for (int i = 0; i < 7; i++) {
int x = (int) (radius * Math.cos(i * 0.618));
int y = (int) (radius * Math.sin(i * 0.618));
Npc pig = addSpawn(servitors[Rnd.get(servitors.length)], PIGGY_LOC.getX() + x, PIGGY_LOC.getY() + y, PIGGY_LOC.getZ() + 20, -1, false, 0, true, 0);
_servitors.add(pig);
}
radius += 300;
}
startQuestTimer("spawn_servitors", 300000, _piggy, null, true);
} else if (event.equalsIgnoreCase("heal_the_king")) {
for (Npc pig : _servitors) {
if (getRandom(20) == 0) {
if (Util.checkIfInRange((SERVITOR_HEAL.getSkill().getCastRange() < 600) ? 600 : SERVITOR_HEAL.getSkill().getCastRange(), pig, _piggy, true)) {
pig.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
pig.setTarget(_piggy);
pig.doCast(SERVITOR_HEAL.getSkill());
pig.broadcastPacket(new NpcSay(pig.getObjectId(),
ChatType.NPC_GENERAL,
pig.getTemplate().getId(), getRandomEntry(SERVITORS_SPEACH)));
} else {
pig.getAI().setIntention(CtrlIntention.AI_INTENTION_FOLLOW, _piggy, null);
}
}
}
} else if (event.equalsIgnoreCase("get_angry")) {
_isAngry = true;
_timeLeft = _angryTime;
_timer = ThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
World.getInstance().forEachVisibleObjectInRange(_piggy, Playable.class, 1200, c ->
{
// c.sendPacket(new ExSendUIEvent(c.getActingPlayer(), ExSendUIEvent.TYPE_NORNIL, _timeLeft--, 0, 0, 0, 0, 2518008));
c.sendPacket(new ExSendUIEvent(c.getActingPlayer(), ExSendUIEvent.TYPE_NORNIL, _timeLeft--, _angryTime, NpcStringId.YOU_MADE_ME_ANGRY));
});
}
}, 0, 1000);
startQuestTimer("stop_angry", _angryTime * 1000, _piggy, null, false);
} else if (event.equalsIgnoreCase("stop_angry")) {
if (!_isAngry) {
return "";
}
_timer.cancel(true);
_isAngry = false;
_piggy.broadcastPacket(new NpcSay(_piggy.getObjectId(),
ChatType.NPC_GENERAL,
_piggy.getTemplate().getId(), "Thanks i'm a bit more relaxed now"));
}
}
return super.onAdvEvent(event, npc, player);
}
@Override
public String onSpawn(Npc npc) {
((Attackable) npc).setCanReturnToSpawnPoint(false);
npc.setRandomWalking(true);
npc.disableCoreAI(true);
return super.onSpawn(npc);
}
@Override
public String onAttack(Npc npc, PlayerInstance attacker, int damage, boolean isSummon) {
if (npc.getId() == PIGGY) {
if (npc.isHpBlocked()) {
return null;
}
if (_lastSpoke + (_speakInterval * 1000) < System.currentTimeMillis()) {
_piggy.broadcastPacket(new NpcSay(_piggy.getObjectId(),
ChatType.NPC_GENERAL,
_piggy.getTemplate().getId(), getRandomEntry(PIGGY_SPEACH_ON_HIT)));
_lastSpoke = System.currentTimeMillis();
}
if (_isAngry) {
_piggy.broadcastPacket(new NpcSay(_piggy.getObjectId(),
ChatType.NPC_GENERAL,
_piggy.getTemplate().getId(), "I TOLD YOU I WAS ANGRY !"));
_piggy.doCast(PIGGY_SKILLS[0].getSkill());
ThreadPool.schedule(() -> {
World.getInstance().forEachVisibleObjectInRange(_piggy, Playable.class, 1200, c ->
{
final int hpRatio = (int) ((c.getCurrentHp() / c.getMaxHp()) * 100);
if (hpRatio > 10) {
c.reduceCurrentHp(getDamages(c.getMaxHp(), PIGGY_SKILLS[0].getPercentDamage() * 2, PIGGY_SKILLS[0].getBrutDamages()), _piggy, PIGGY_SKILLS[0].getSkill(), false, true, false, false);
}
});
_timer.cancel(true);
_isAngry = false;
}, PIGGY_SKILLS[0].getSkill().getHitTime());
return "";
}
// Debuff strider-mounted players.
if ((attacker.getMountType() == MountType.STRIDER) && !attacker.isAffectedBySkill(4258)) {
npc.setTarget(attacker);
npc.doCast(SkillData.getInstance().getSkill(4258, 1));
}
} else if (npc.getId() == SCARECROW) {
_totalhits++;
World.getInstance().forEachVisibleObjectInRange(_piggy, Playable.class, 1200, c ->
{
c.sendPacket(new ExSendUIEvent(c.getActingPlayer(), ExSendUIEvent.TYPE_NORNIL, _totalhits, _maxHits, NpcStringId.HIT_ME_MORE_HIT_ME_MORE));
});
} else {
}
return super.onAttack(npc, attacker, damage, isSummon);
}
@Override
public String onKill(Npc npc, PlayerInstance killer, boolean isSummon) {
if (npc.getId() == PIGGY) {
cancelQuestTimer("regen_task", npc, null);
cancelQuestTimer("think", npc, null);
cancelQuestTimer("skill_task", npc, null);
cancelQuestTimer("spawn_servitors", npc, null);
cancelQuestTimer("heal_king", npc, null);
isSpawned = false;
for (Npc s : _servitors) {
s.deleteMe();
}
}
return super.onKill(npc, killer, isSummon);
}
@Override
public String onAggroRangeEnter(Npc npc, PlayerInstance player, boolean isSummon) {
return null;
}
private void callSkillAI(Npc npc) {
if (npc.isInvul() || npc.isCastingNow()) {
return;
}
if (!_isAngry && getRandom(20) == 0 && !_scarecrowSpawned) {
_piggy.broadcastPacket(new NpcSay(npc.getObjectId(),
ChatType.NPC_GENERAL,
_piggy.getTemplate().getId(), "If you touch me i'll get angry guys"));
World.getInstance().forEachVisibleObjectInRange(_piggy, Playable.class, 1200, c ->
{
c.sendPacket(new ExShowScreenMessage("Piggy will be angry very soon, care !", 5000));
});
startQuestTimer("get_angry", 3000, _piggy, null, false);
}
// Pickup a target if no or dead victim. 10% luck he decides to reconsiders his target.
if ((_actualVictim == null) || _actualVictim.isDead() || !(npc.isInSurroundingRegion(_actualVictim)) || (getRandom(10) == 0)) {
_actualVictim = getRandomTarget(npc);
}
if (_actualVictim == null) {
if (getRandom(10) == 0) {
final int x = npc.getX();
final int y = npc.getY();
final int z = npc.getZ();
final int posX = x + getRandom(-1400, 1400);
final int posY = y + getRandom(-1400, 1400);
if (GeoEngine.getInstance().canMoveToTarget(x, y, z, posX, posY, z, npc.getInstanceWorld())) {
npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new Location(posX, posY, z, 0));
}
}
return;
}
final PiggySkill skill = getRandomSkill(npc);
// Cast the skill or follow the target.
if (Util.checkIfInRange((skill.getSkill().getCastRange() < 600) ? 600 : skill.getSkill().getCastRange(), npc, _actualVictim, true)) {
npc.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
npc.setTarget(_actualVictim);
System.out.println("Skill: " + skill.getSkill().getName());
npc.doCast(skill.getSkill());
ThreadPool.schedule(() -> {
if (skill.isAoe()) {
World.getInstance().forEachVisibleObjectInRange(_piggy, Playable.class, skill.getRange(), c ->
{
final int hpRatio = (int) ((c.getCurrentHp() / c.getMaxHp()) * 100);
if (hpRatio > 10) {
c.reduceCurrentHp(getDamages(c.getMaxHp(), skill.getPercentDamage(), skill.getBrutDamages()), _piggy, skill.getSkill(), false, true, false, false);
}
});
} else {
_actualVictim.reduceCurrentHp(getDamages(_actualVictim.getMaxHp(), skill.getPercentDamage(), skill.getBrutDamages()), _piggy, skill.getSkill(), false, true, false, false);
}
}, skill.getSkill().getHitTime());
} else {
npc.getAI().setIntention(CtrlIntention.AI_INTENTION_FOLLOW, _actualVictim, null);
}
}
private float getDamages(int totalHp, int percent, int brut) {
return (totalHp - totalHp * (((100 - percent) / 100f))) + brut;
}
/**
* Pick a random skill.<br>
* Piggy will mostly use utility skills. If Piggy feels surrounded, he will use AoE skills.<br>
* Lower than 50% HPs, he will begin to use Meteor skill.
*
* @param npc piggy
* @return a skill holder
*/
private PiggySkill getRandomSkill(Npc npc) {
final int hpRatio = (int) ((npc.getCurrentHp() / npc.getMaxHp()) * 100);
return getRandomEntry(PIGGY_SKILLS);
}
/**
* Pickup a random Playable from the zone, deads targets aren't included.
*
* @param npc
* @return a random Playable.
*/
private Playable getRandomTarget(Npc npc) {
final List<Playable> result = new ArrayList<>();
World.getInstance().forEachVisibleObject(npc, Playable.class, obj ->
{
if ((obj == null) || obj.isPet()) {
return;
} else if (!obj.isDead() && obj.isPlayable()) {
result.add(obj);
}
});
return getRandomEntry(result);
}
@Override
public String onFirstTalk(Npc npc, PlayerInstance player) {
StringBuilder tb = new StringBuilder();
tb.append("<html><center><font color=\"3D81A8\">Piggy Raidboss</font></center><br1>Hi " + player.getName() + "<br>");
tb.append("<font color=\"3D81A8\">Available Actons:</font><br>");
tb.append("<br>");
tb.append("<center><button value=\"Teleport to Fantasy Island\" action=\"bypass -h gm_event piggy_raidboss teleport_to_fantasy\"\n" +
" width=200\n" +
" height=40 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\">\n" +
" </center> ");
tb.append("</body></html>");
NpcHtmlMessage msg = new NpcHtmlMessage(NPC_ID);
msg.setHtml(tb.toString());
player.sendPacket(msg);
return "";
}
}<file_sep>/config/Custom/NpcStatMultipliers.ini
# ---------------------------------------------------------------------------
# NPC Stat Multipliers
# ---------------------------------------------------------------------------
# Enable/Disable NPC stat multipliers.
EnableNpcStatMultipliers = True
# Monsters
MonsterHP = 0.5
MonsterMP = 0.5
MonsterPAtk = 1.0
MonsterMAtk = 1.0
MonsterPDef = 0.4
MonsterMDef = 0.4
MonsterAggroRange = 1.0
MonsterClanHelpRange = 1.0
# Raidbosses
RaidbossHP = 1.0
RaidbossMP = 1.0
RaidbossPAtk = 1.0
RaidbossMAtk = 1.0
RaidbossPDef = 0.5
RaidbossMDef = 0.5
RaidbossAggroRange = 1.0
RaidbossClanHelpRange = 1.0
# Guards
GuardHP = 2.0
GuardMP = 2.0
GuardPAtk = 2.0
GuardMAtk = 2.0
GuardPDef = 2.0
GuardMDef = 2.0
GuardAggroRange = 1.0
GuardClanHelpRange = 1.0
# Defenders
DefenderHP = 2.0
DefenderMP = 2.0
DefenderPAtk = 2.0
DefenderMAtk = 2.0
DefenderPDef = 2.0
DefenderMDef = 2.0
DefenderAggroRange = 1.0
DefenderClanHelpRange = 1.0
<file_sep>/config/TrainingCamp.ini
# ---------------------------------------------------------------------------
# Training Camp
# ---------------------------------------------------------------------------
# Enable or disable Training Camp
# Default: True
TrainingCampEnable = True
# Only Premium account can access training camp
# Default: True
TrainingCampPremiumOnly = True
# Max duration for Training Camp in seconds. NA : 18000, RU : 36000
# Default: 18000
TrainingCampDuration = 18000
# Min level to enter Training Camp
# Default: 18
TrainingCampMinLevel = 18
# Max level to enter Training Camp
# Default: 127
TrainingCampMaxLevel = 127
# Multiplier for rewarded EXP
# Default: 1.0
TrainingCampExpMultiplier = 2.0
# Multiplier for rewarded SP
# Default: 1.0
TrainingCampSpMultiplier = 2.0
<file_sep>/config/Custom/AutoPotions.ini
# ---------------------------------------------------------------------------
# Auto Potion Settings
# ---------------------------------------------------------------------------
# Use .apon / .apoff voiced commands to enable / disable.
# Enable auto potion commands.
AutoPotionsEnabled = True
# Use auto potions in Olympiad.
AutoPotionsInOlympiad = false
# Minimum player level to use the commands.
AutoPotionMinimumLevel = 1
# Enable auto CP potions.
AutoCpEnabled = true
# Percentage that CP potions will be used.
AutoCpPercentage = 70
# Auto CP item ids. Order by use priority.
AutoCpItemIds = 5592,5591
# Enable auto HP potions.
AutoHpEnabled = true
# Percentage that HP potions will be used.
AutoHpPercentage = 70
# Auto HP item ids. Order by use priority.
AutoHpItemIds = 1540,1539,1061,1060
# Enable auto MP potions.
AutoMpEnabled = true
# Percentage that MP potions will be used.
AutoMpPercentage = 70
# Auto MP item ids. Order by use priority.
AutoMpItemIds = 728
<file_sep>/data/scripts/handlers/voicedcommandhandlers/MyHiddenStats.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package scripts.handlers.voicedcommandhandlers;
import org.l2jmobius.Config;
import org.l2jmobius.gameserver.handler.IVoicedCommandHandler;
import org.l2jmobius.gameserver.instancemanager.PremiumManager;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.stats.Stat;
import org.l2jmobius.gameserver.network.serverpackets.NpcHtmlMessage;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
public class MyHiddenStats implements IVoicedCommandHandler
{
private static final String[] VOICED_COMMANDS =
{
"myhiddenstats"
};
@Override
public boolean useVoicedCommand(String command, PlayerInstance player, String target)
{
if (command.startsWith("myhiddenstats"))
{
final NpcHtmlMessage msg = new NpcHtmlMessage(5);
String html = "<html>" + "<body>" +
"<center><table><tr><td><img src=icon.etc_alphabet_h_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_i_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_d_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_d_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_e_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_n_i00 width=32 height=32></td></tr></table></center>" +
"<center><table><tr><td><img src=icon.etc_alphabet_s_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_t_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_a_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_t_i00 width=32 height=32></td><td><img src=icon.etc_alphabet_s_i00 width=32 height=32></td></tr></table></center><br><br>" +
"<center><table width=300><tr><td FIXWIDTH=150>Stat</td><td FIXWIDTH=150>Value</td</tr></table><img src=\"L2UI.Squaregray\" width=300 height=1>";
html += getStatHtm("Shield Def", player.getShldDef(), 0, false, "");
html += getStatHtm("Dmg Absorbed", player.getStat().getValue(Stat.ABSORB_DAMAGE_PERCENT, 0), 0, false, "%");
html += getStatHtm("Heal Effect", player.getStat().getValue(Stat.HEAL_EFFECT, 100) - 100, 0, true,
"%");
html += getStatHtm("Heals Effect Add", player.getStat().getValue(Stat.HEAL_EFFECT_ADD, 100) - 100, 0, true, "%");
html += getStatHtm("Momentum Max", player.getStat().getValue(Stat.MAX_MOMENTUM, 100) - 100, 0, true,
"%");
html += getStatHtm("Max Targets", player.getStat().getValue(Stat.ATTACK_COUNT_MAX, 1) - 1, 0, true, "");
html += getStatHtm("P. Skill Power", player.getStat().getValue(Stat.PHYSICAL_SKILL_POWER, 100) - 100, 0,
true, "%");
html += getStatHtm("P. Crit Dmg", player.getStat().getValue(Stat.CRITICAL_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("P. Crit Dmg Recvd", player.getStat().getValue(Stat.DEFENCE_CRITICAL_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("Skill Crit", player.getStat().getValue(Stat.SKILL_CRITICAL, 100) - 100, 0, true,
"%");
html += getStatHtm("Skill Crit Probability", player.getStat().getValue(Stat.SKILL_CRITICAL_PROBABILITY, 100) - 100, 0, true,
"%");
html += getStatHtm("M. Skill Power", player.getStat().getValue(Stat.MAGICAL_SKILL_POWER, 100) - 100, 0, true,
"%");
html += getStatHtm("M. Crit Dmg", player.getStat().getValue(Stat.MAGIC_CRITICAL_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("M. Crit Dmg Recvd", player.getStat().getValue(Stat.DEFENCE_MAGIC_CRITICAL_DAMAGE, 100) - 100, 0, true,
"%");
html += getStatHtm("Fixed P. Crit Dmg", player.getStat().getValue(Stat.CRITICAL_DAMAGE_ADD, 0), 0, true, "");
html += getStatHtm("Reflected Dmg", player.getStat().getValue(Stat.REFLECT_DAMAGE_PERCENT, 0), 0, true, "%");
html += getStatHtm("Reflection Resistance", player.getStat().getValue(Stat.REFLECT_DAMAGE_PERCENT_DEFENSE, 0), 0, true, "%");
html += getStatHtm("PvP P. Dmg", player.getStat().getValue(Stat.PVP_PHYSICAL_ATTACK_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("PvP P. Skill Dmg", player.getStat().getValue(Stat.PVP_PHYSICAL_SKILL_DAMAGE, 100) - 100, 0,
true, "%");
html += getStatHtm("PvP M. Dmg", player.getStat().getValue(Stat.PVP_MAGICAL_SKILL_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("PvP P. Dmg Res", player.getStat().getValue(Stat.PVP_PHYSICAL_ATTACK_DEFENCE, 100) - 100, 0, true,
"%");
html += getStatHtm("PvP P. Skill Dmg Res", player.getStat().getValue(Stat.PVP_PHYSICAL_SKILL_DEFENCE, 100) - 100, 0,
true, "%");
html += getStatHtm("PvP M. Dmg Res", player.getStat().getValue(Stat.PVP_MAGICAL_SKILL_DEFENCE, 100) - 100, 0, true,
"%");
html += getStatHtm("PvE P. Dmg", player.getStat().getValue(Stat.PVE_PHYSICAL_ATTACK_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("PvE P. Skill Dmg", player.getStat().getValue(Stat.PVE_PHYSICAL_SKILL_DAMAGE, 100) - 100, 0,
true, "%");
html += getStatHtm("PvE M. Dmg", player.getStat().getValue(Stat.PVE_MAGICAL_SKILL_DAMAGE, 100) - 100, 0, true, "%");
html += getStatHtm("PvE P. Dmg Res", player.getStat().getValue(Stat.PVE_PHYSICAL_ATTACK_DEFENCE, 100) - 100, 0, true,
"%");
html += getStatHtm("PvE P. Skill Dmg Res", player.getStat().getValue(Stat.PVE_PHYSICAL_SKILL_DEFENCE, 100) - 100, 0,
true, "%");
html += getStatHtm("PvE M. Dmg Res", player.getStat().getValue(Stat.PVE_MAGICAL_SKILL_DEFENCE, 100) - 100, 0, true,
"%");
html += getStatHtm("Resist abnormal debuff", player.getStat().getValue(Stat.RESIST_ABNORMAL_DEBUFF, 100) - 100, 0, true, "%");
html += getStatHtm("Physical abnormal Res", player.getStat().getValue(Stat.ABNORMAL_RESIST_PHYSICAL, 100) - 100, 0,
true, "%");
html += getStatHtm("Magical abnormal Res", player.getStat().getValue(Stat.ABNORMAL_RESIST_MAGICAL, 100) - 100, 0,
true, "%");
html += getStatHtm("Immobile Res", player.getStat().getValue(Stat.IMMOBILE_DAMAGE_RESIST, 100) - 100, 0, true, "%");
html += getStatHtm("Dispell Res", player.getStat().getValue(Stat.RESIST_DISPEL_BUFF, 100) - 100, 0, true, "%");
html += getStatHtm("absorbDamChance", player.getStat().getValue(Stat.ABSORB_DAMAGE_CHANCE, 100) - 100, 0, true, "%");
html += getStatHtm("FixedDamageResist", player.getStat().getValue(Stat.REAL_DAMAGE_RESIST, 100) - 100, 0, true, "%");
html += "</table><br>" + "</body></html>";
player.sendPacket(new NpcHtmlMessage(0, html));
msg.setHtml(html);
player.sendPacket(msg);
}
else
{
return false;
}
return true;
}
private String getStatHtm(String statName, double statVal, double statDefault, boolean plusIfPositive, String suffix)
{
if (statVal == statDefault)
{
return "";
}
return "<table width=300 border=0><tr><td FIXWIDTH=150>" + statName + ":</td><td FIXWIDTH=150>" +
(plusIfPositive && statVal >= 0 ? "+" : "") + new DecimalFormat("#0.##").format(statVal) + suffix +
"</td></tr></table><img src=\"L2UI.Squaregray\" width=300 height=1>";
}
@Override
public String[] getVoicedCommandList()
{
return VOICED_COMMANDS;
}
}<file_sep>/java/org/l2jmobius/gameserver/util/Point3D.kt
package org.l2jmobius.gameserver.util
import java.io.Serializable
class Point3D : Serializable {
@Volatile
@set:Synchronized
var x: Int = 0
@Volatile
@set:Synchronized
var y: Int = 0
@Volatile
@set:Synchronized
var z: Int = 0
constructor(pX: Int, pY: Int, pZ: Int) {
x = pX
y = pY
z = pZ
}
constructor(pX: Int, pY: Int) {
x = pX
y = pY
z = 0
}
constructor(worldPosition: Point3D) {
synchronized(worldPosition) {
x = worldPosition.x
y = worldPosition.y
z = worldPosition.z
}
}
@Synchronized
fun setTo(point: Point3D) {
synchronized(point) {
x = point.x
y = point.y
z = point.z
}
}
override fun toString(): String {
return "($x, $y, $z)"
}
override fun hashCode(): Int {
return x xor y xor z
}
@Synchronized
override fun equals(other: Any?): Boolean {
if (other is Point3D) {
val point3D = other
var ret = false
synchronized(point3D) {
ret = point3D.x == x && point3D.y == y && point3D.z == z
}
return ret
}
return false
}
@Synchronized
fun equals(pX: Int, pY: Int, pZ: Int): Boolean {
return x == pX && y == pY && z == pZ
}
@Synchronized
fun distanceSquaredTo(point: Point3D): Long {
var dx = 0L
var dy = 0L
synchronized(point) {
dx = (x - point.x).toLong()
dy = (y - point.y).toLong()
}
return dx * dx + dy * dy
}
@Synchronized
fun setXYZ(pX: Int, pY: Int, pZ: Int) {
x = pX
y = pY
z = pZ
}
companion object {
private const val serialVersionUID = 4638345252031872576L
}
}<file_sep>/config/Event.ini
# ---------------------------------------------------------------------------
# Enable/Disable InstancedEvent System
# ---------------------------------------------------------------------------
InstancedEventEnabled = true
# ---------------------------------------------------------------------------
# Time Between events (in minutes, 300 = 5 hours)
# ---------------------------------------------------------------------------
InstancedEventInterval = 60
# ---------------------------------------------------------------------------
# Event running time (in minutes).
# ---------------------------------------------------------------------------
InstancedEventRunningTime = 10
# ---------------------------------------------------------------------------
# Min/Max amount of players allowed in each team.
# ---------------------------------------------------------------------------
InstancedEventMinPlayersInTeams = 2
# ---------------------------------------------------------------------------
# Respawn and exit delay timers (in seconds);
# ---------------------------------------------------------------------------
InstancedEventRespawnTeleportDelay = 5
InstancedEventStartLeaveTeleportDelay = 5
InstancedEventTargetTeamMembersAllowed = true
InstancedEventScrollsAllowed = false
InstancedEventPotionsAllowed = false
InstancedEventSummonByItemAllowed = false
InstancedEventRewardTeamTie = true
InstancedEventMinPlayerLevel = 85
# ---------------------------------------------------------------------------
# Participant's effects handling on teleport/death.
# Effects lasting through death never removed.
# 0 - always remove all effects.
# 1 - remove all effects only during port to event (noblesse blessing can be used)
# 2 - never remove any effect
# ---------------------------------------------------------------------------
InstancedEventEffectsRemoval = 0
<file_sep>/java/org/l2jmobius/gameserver/events/CreatureInvasion/CreatureInvasion.java
package org.l2jmobius.gameserver.events.CreatureInvasion;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.enums.ChatType;
import org.l2jmobius.gameserver.model.actor.Creature;
import org.l2jmobius.gameserver.model.actor.Npc;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.quest.Quest;
import org.l2jmobius.gameserver.model.skills.Skill;
import org.l2jmobius.gameserver.network.serverpackets.NpcHtmlMessage;
import org.l2jmobius.gameserver.network.serverpackets.NpcSay;
import org.l2jmobius.gameserver.util.Broadcast;
import java.util.*;
public class CreatureInvasion extends Quest {
//Config
private static final int timeToEndInvasion = 15; //Minutes
private static final int[] invaderIds = {900900, 900901};
private static final int rewardId = 10639;
private static final int[][] rewards = {{5, 10}, {10, 20}};
private Map<Integer, int[]> invadersReward = new HashMap<Integer, int[]>();
//Vars
private static boolean isUnderInvasion = false;
private Map<Integer, invaderInfo> attackInfo = new HashMap<Integer, invaderInfo>();
private ArrayList<Creature> invaders = new ArrayList<Creature>();
private static final int NPC_ID = 9009125;
private Npc _teleporter;
public void StartInvasion() {
if (isUnderInvasion) {
startQuestTimer("end_invasion", 1, null, null, false);
} else {
startQuestTimer("start_invasion", 1, null, null, false);
}
}
public CreatureInvasion(int id) {
super(id);
int i = 0;
for (int mob : invaderIds) {
invadersReward.put(mob, rewards[i]);
addAttackId(mob);
addKillId(mob);
i++;
}
}
private class invaderInfo {
private Long attackedTime;
private int playerId;
private String externalIP;
private invaderInfo(int playerId, String externalIP) {
this.playerId = playerId;
this.externalIP = externalIP;
setAttackedTime();
}
private long getAttackedTime() {
return attackedTime;
}
private void setAttackedTime() {
attackedTime = System.currentTimeMillis();
}
private int getPlayerId() {
return playerId;
}
private String getExternalIP() {
return externalIP;
}
private void updateInfo(int playerId, String externalIP) {
this.playerId = playerId;
this.externalIP = externalIP;
setAttackedTime();
}
}
@Override
public String onAttack(Npc npc, PlayerInstance player, int damage, boolean isPet, Skill skill) {
if (!isUnderInvasion) {
player.doDie(npc);
return "";
}
synchronized (attackInfo) {
invaderInfo info = attackInfo.get(npc.getObjectId()); //Get the attack info from this npc
int sameIPs = 0;
int underAttack = 0;
for (Map.Entry<Integer, invaderInfo> entry : attackInfo.entrySet()) {
if (entry == null) {
continue;
}
invaderInfo i = entry.getValue();
if (i == null) {
continue;
}
if (System.currentTimeMillis() < i.getAttackedTime() + 5000) {
if (i.getPlayerId() == player.getObjectId()) {
underAttack++;
}
if (i.getExternalIP().equalsIgnoreCase(player.getIPAddress())) {
sameIPs++;
}
if (underAttack > 1 || sameIPs > 1) {
player.doDie(npc);
if (underAttack > 1) {
npc.broadcastPacket(new NpcSay(npc.getObjectId(),
ChatType.NPC_GENERAL,
npc.getTemplate().getId(),
player.getName() + " you cant attack more than one mob at same time!"));
} else if (sameIPs > 1) {
npc.broadcastPacket(new NpcSay(npc.getObjectId(),
ChatType.NPC_GENERAL,
npc.getTemplate().getId(),
player.getName() + " dualbox is not allowed here!"));
}
return "";
}
}
}
if (info == null) //Don't exist any info from this npc
{
//Add the correct info
info = new invaderInfo(player.getObjectId(), player.getIPAddress());
//Insert to the map
attackInfo.put(npc.getObjectId(), info);
} else {
//Already exists information for this NPC
//Check if the attacker is the same as the stored
if (info.getPlayerId() != player.getObjectId()) {
//The attacker is not same
//If the last attacked stored info +10 seconds is bigger than the current time, this mob is currently attacked by someone
if (info.getAttackedTime() + 5000 > System.currentTimeMillis()) {
player.doDie(npc);
npc.broadcastPacket(new NpcSay(npc.getObjectId(),
ChatType.NPC_GENERAL,
npc.getTemplate().getId(),
player.getName() + " don't attack mobs from other players!"));
return "";
} else {
//Add new information, none is currently attacking this NPC
info.updateInfo(player.getObjectId(), player.getIPAddress());
}
} else {
//player id is the same, update the attack time
info.setAttackedTime();
}
}
}
return super.onAttack(npc, player, damage, isPet, skill);
}
@Override
public String onKill(Npc npc, PlayerInstance player, boolean isPet) {
synchronized (attackInfo) {
invaderInfo info = attackInfo.get(npc.getObjectId()); //Get the attack info
if (info != null) {
attackInfo.remove(npc.getObjectId()); //Delete the stored info for this npc
}
}
if (isUnderInvasion) {
Npc inv =
addSpawn(invaderIds[Rnd.get(invaderIds.length)], npc.getX() + Rnd.get(100), npc.getY() + Rnd.get(100), npc.getZ(), 0, false, 0);
invaders.add(inv);
}
int[] rewards = invadersReward.get(npc.getId());
player.addItem("event", rewardId, randomBetween(rewards[0], rewards[1]), player, true);
return super.onKill(npc, player, isPet);
}
public int randomBetween(int low, int high) {
Random r = new Random();
return r.nextInt(high - low) + low;
}
@SuppressWarnings("unused")
@Override
public String onAdvEvent(String event, Npc npc, PlayerInstance player) {
if (event.equalsIgnoreCase("teleport_to_fantasy")) {
player.teleToLocation(-59004, -56889, -2032);
} else if (event.startsWith("start_invasion")) {
if (isUnderInvasion) {
return "";
}
isUnderInvasion = true;
addStartNpc(NPC_ID);
addTalkId(NPC_ID);
addFirstTalkId(NPC_ID);
_teleporter = addSpawn(NPC_ID, 147448, 27928, -2271, 20352, false, 0);
_teleporter.setTitle("Creature Invasion");
int radius = 1000;
for (int a = 0; a < 2; a++) {
for (int i = 0; i < 50; i++) {
int x = (int) (radius * Math.cos(i * 0.618));
int y = (int) (radius * Math.sin(i * 0.618));
Npc inv = addSpawn(invaderIds[Rnd.get(invaderIds.length)], -59718 + x, -56909 + y, -2029 + 20, -1, false, 0, false, 0);
invaders.add(inv);
}
radius += 300;
}
Broadcast.toAllOnlinePlayers("Fantasy Island is under invasion!");
Broadcast.toAllOnlinePlayers("Don't attack mobs from other players!");
Broadcast.toAllOnlinePlayers("Dualbox is not allowed on the event!");
Broadcast.toAllOnlinePlayers("The invasion will lasts for: " + timeToEndInvasion + " minute(s)!");
startQuestTimer("end_invasion", timeToEndInvasion * 60000, null, null);
} else if (event.startsWith("end_invasion")) {
isUnderInvasion = false;
if (_teleporter != null) {
_teleporter.deleteMe();
}
for (Creature chara : invaders) {
if (chara == null) {
continue;
}
chara.deleteMe();
}
invaders.clear();
attackInfo.clear();
Broadcast.toAllOnlinePlayers("The invasion has been ended!");
}
return "";
}
@Override
public String onFirstTalk(Npc npc, PlayerInstance player) {
StringBuilder tb = new StringBuilder();
tb.append("<html><center><font color=\"3D81A8\">Creature Invasion</font></center><br1>Hi " + player.getName() + "<br>");
tb.append("<font color=\"3D81A8\">Available Actons:</font><br>");
tb.append("<br>");
tb.append(" <center><button value=\"Teleport to Fantasy Island\" action=\"bypass -h gm_event creature_invasion teleport_to_fantasy\"\n" +
" width=200\n" +
" height=40 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></center>\n" +
" ");
tb.append("</body></html>");
NpcHtmlMessage msg = new NpcHtmlMessage(NPC_ID);
msg.setHtml(tb.toString());
player.sendPacket(msg);
return "";
}
public static CreatureInvasion getInstance() {
return CreatureInvasion.SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
protected static final CreatureInvasion INSTANCE = new CreatureInvasion(999120);
}
}<file_sep>/data/html/villagemaster/SubClass_ChangeNo.htm
<html>
<body>Change Subclass:<br>
You can't change subclasses when you don't have a subclass to begin with.<br>
<Button ALIGN=LEFT ICON="NORMAL" action="bypass -h npc_%objectId%_Subclass 1">Add subclass.</Button>
</body>
</html><file_sep>/java/org/l2jmobius/gameserver/events/instanced/EventTeleporter.java
package org.l2jmobius.gameserver.events.instanced;
import org.l2jmobius.commons.concurrent.ThreadPool;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.geoengine.GeoEngine;
import org.l2jmobius.gameserver.model.Location;
import org.l2jmobius.gameserver.model.actor.Npc;
import org.l2jmobius.gameserver.model.actor.Summon;
import org.l2jmobius.gameserver.model.actor.instance.PetInstance;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.skills.AbnormalVisualEffect;
import org.l2jmobius.gameserver.util.Point3D;
import org.l2jmobius.Config;
import org.l2jmobius.gameserver.events.instanced.EventInstance.EventState;
import org.l2jmobius.gameserver.events.instanced.EventInstance.EventType;
public class EventTeleporter implements Runnable {
private PlayerInstance playerInstance = null;
private Point3D coordinates = null;
private boolean restore = false;
private boolean heal = true;
public EventTeleporter(PlayerInstance playerInstance, Point3D coordinates, boolean fastSchedule, boolean restore) {
this.playerInstance = playerInstance;
this.coordinates = coordinates;
this.restore = restore;
long delay = (playerInstance.getEvent() == null || playerInstance.getEvent().isState(EventState.STARTED) ?
Config.INSTANCED_EVENT_RESPAWN_TELEPORT_DELAY : Config.INSTANCED_EVENT_START_LEAVE_TELEPORT_DELAY ) * 1000;
ThreadPool.schedule(this, fastSchedule ? 0 : delay);
}
public EventTeleporter(PlayerInstance playerInstance, Point3D coordinates, boolean fastSchedule, boolean restore, boolean heal) {
this.playerInstance = playerInstance;
this.coordinates = coordinates;
this.restore = restore;
this.heal = heal;
long delay = (playerInstance.getEvent() == null || playerInstance.getEvent().isState(EventState.STARTED) ?
Config.INSTANCED_EVENT_RESPAWN_TELEPORT_DELAY : Config.INSTANCED_EVENT_START_LEAVE_TELEPORT_DELAY) * 1000;
ThreadPool.schedule(this, fastSchedule ? 0 : delay);
}
@Override
public void run() {
if (playerInstance == null) {
return;
}
EventInstance event = playerInstance.getEvent();
if (event == null) {
return;
}
try {
playerInstance.stopAllEffects();
PetInstance pet = playerInstance.getPet();
if (pet != null) {
// In LC, SS and SS2, players don't need summons and summons are even able to attack during event so better unsummon
if (pet.isMountable() || event.isType(EventType.LuckyChests) || event.isType(EventType.StalkedSalkers) ||
event.isType(EventType.SimonSays)) {
pet.unSummon(playerInstance);
} else {
pet.stopAllEffects();
}
}
if (event.getConfig().isAllVsAll()) {
playerInstance.leaveParty();
}
for (Summon summon : playerInstance.getServitorsAndPets()) {
// In LC, SS and SS2, players don't need summons and summons are even able to attack during event so better unsummon
if (event.isType(EventType.LuckyChests) || event.isType(EventType.StalkedSalkers) || event.isType(EventType.SimonSays)) {
summon.unSummon(playerInstance);
} else {
summon.stopAllEffects();
}
}
if (playerInstance.isDead()) {
playerInstance.restoreExp(100.0);
playerInstance.doRevive();
}
if (heal) {
playerInstance.setCurrentCp(playerInstance.getMaxCp());
playerInstance.setCurrentHp(playerInstance.getMaxHp());
playerInstance.setCurrentMp(playerInstance.getMaxMp());
}
int x = 0, y = 0, z = 0;
if (event.isState(EventState.STARTED) && !restore) {
playerInstance.setInstanceId(event.getInstanceId());
if (event.getConfig().spawnsPlayersRandomly()) {
EventLocation location = event.getConfig().getLocation();
Location pos = location.getZone().getZone().getRandomPoint();
x = pos.getX();
y = pos.getY();
z = GeoEngine.getInstance().getHeight(pos.getX(), pos.getY(), pos.getZ());
} else {
float r1 = Rnd.get(1000);
int r2 = Rnd.get(100);
x = Math.round((float) Math.cos(r1 / 1000 * 2 * Math.PI) * r2 + coordinates.getX());
y = Math.round((float) Math.sin(r1 / 1000 * 2 * Math.PI) * r2 + coordinates.getY());
z = GeoEngine.getInstance().getHeight(x, y, coordinates.getZ());
}
} else {
playerInstance.setInstanceId(0);
playerInstance.setEvent(null);
playerInstance.returnedFromEvent();
if (playerInstance.getEventSavedPosition().getX() == 0 && playerInstance.getEventSavedPosition().getY() == 0 &&
playerInstance.getEventSavedPosition().getZ() == 0) {
x = coordinates.getX();
y = coordinates.getY();
z = GeoEngine.getInstance().getHeight(coordinates.getX(), coordinates.getY(), coordinates.getZ());
} else {
x = playerInstance.getEventSavedPosition().getX();
y = playerInstance.getEventSavedPosition().getY();
z = playerInstance.getEventSavedPosition().getZ();
}
}
playerInstance.teleToLocation(x, y, z);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/config/Custom/FindPvP.ini
# ---------------------------------------------------------------------------
# Find PvP
# ---------------------------------------------------------------------------
# Bypass example:
# <Button ALIGN=LEFT ICON="NORMAL" action="bypass -h FindPvP">Go to PvP!</Button>
# Enable FindPvP bypass.
# Default: False
EnableFindPvP = True
<file_sep>/java/org/l2jmobius/gameserver/gui/playertable/PlayerTableRenderer.java
package org.l2jmobius.gameserver.gui.playertable;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
public class PlayerTableRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
private PlayerTableModel table;
public PlayerTableRenderer(PlayerTableModel table) {
this.table = table;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
Component c;
if (value instanceof Component) {
c = (Component) value;
if (isSelected) {
c.setForeground(table.getSelectionForeground());
c.setBackground(table.getSelectionBackground());
}
} else {
c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
}
if (!isSelected) {
c.setBackground(table.getBackground());
}
return c;
}
public interface TooltipTable {
String getToolTip(int row, int col);
boolean getIsMarked(int row);
}
}<file_sep>/data/scripts/handlers/voicedcommandhandlers/Zone.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package scripts.handlers.voicedcommandhandlers;
import org.l2jmobius.gameserver.handler.IVoicedCommandHandler;
import org.l2jmobius.gameserver.instancemanager.UpgradableFarmZoneManager;
import org.l2jmobius.gameserver.instancemanager.ZoneManager;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.stats.Stat;
import org.l2jmobius.gameserver.model.zone.ZoneId;
import org.l2jmobius.gameserver.model.zone.ZoneType;
import org.l2jmobius.gameserver.model.zone.type.FarmZone;
import org.l2jmobius.gameserver.network.serverpackets.NpcHtmlMessage;
import java.text.DecimalFormat;
public class Zone implements IVoicedCommandHandler
{
private static final String[] VOICED_COMMANDS =
{
"zone"
};
@Override
public boolean useVoicedCommand(String command, PlayerInstance player, String target)
{
if (command.startsWith("zone"))
{
if (player.isInsideZone(ZoneId.FARM)) {
ZoneType zone = ZoneManager.getInstance().getZone(player.getLocation(), FarmZone.class);
if (zone != null) {
UpgradableFarmZoneManager.getInstance().getPanel(player, "farm_zone;" + String.valueOf(zone.getId()));
}
}
}
else
{
return false;
}
return true;
}
@Override
public String[] getVoicedCommandList()
{
return VOICED_COMMANDS;
}
}<file_sep>/data/scripts/handlers/bypasshandlers/Teleport.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package scripts.handlers.bypasshandlers;
import org.l2jmobius.Config;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.enums.ChatType;
import org.l2jmobius.gameserver.handler.IBypassHandler;
import org.l2jmobius.gameserver.model.World;
import org.l2jmobius.gameserver.model.actor.Creature;
import org.l2jmobius.gameserver.model.actor.instance.MerchantInstance;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.actor.instance.TeleporterInstance;
import org.l2jmobius.gameserver.network.SystemMessageId;
import org.l2jmobius.gameserver.network.serverpackets.CreatureSay;
import org.l2jmobius.gameserver.network.serverpackets.SystemMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Level;
public class Teleport implements IBypassHandler
{
private static final String[] COMMANDS =
{
"teleto",
"pvpzone"
};
@Override
public boolean useBypass(String command, PlayerInstance player, Creature target)
{
if (!(target instanceof TeleporterInstance))
{
return false;
}
StringTokenizer st = new StringTokenizer(command, " ");
st.nextToken();
if (command.startsWith("teleto")) // Tenkai custom - raw teleport coordinates, only check for TW ward
{
if (player.isCombatFlagEquipped())
{
player.sendPacket(SystemMessageId.YOU_CANNOT_TELEPORT_WHILE_IN_POSSESSION_OF_A_WARD);
return false;
}
if (player.getPvpFlag() > 0)
{
player.sendMessage("You can't teleport while flagged!");
return false;
}
int[] coords = new int[3];
try
{
for (int i = 0; i < 3; i++)
{
coords[i] = Integer.valueOf(st.nextToken());
}
player.teleToLocation(coords[0], coords[1], coords[2]);
player.setInstanceId(0);
}
catch (Exception e)
{
LOGGER.warning("L2Teleporter - " + target.getName() + "(" + target.getId() +
") - failed to parse raw teleport coordinates from html");
e.printStackTrace();
}
return true;
}
return false;
}
@Override
public String[] getBypassList()
{
return COMMANDS;
}
}
<file_sep>/java/org/l2jmobius/gameserver/model/actor/instance/BufferInstance.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.gameserver.model.actor.instance;
import org.l2jmobius.Config;
import org.l2jmobius.gameserver.data.xml.impl.BuyListData;
import org.l2jmobius.gameserver.data.xml.impl.SkillData;
import org.l2jmobius.gameserver.enums.InstanceType;
import org.l2jmobius.gameserver.enums.TaxType;
import org.l2jmobius.gameserver.instancemanager.CastleManager;
import org.l2jmobius.gameserver.model.actor.Creature;
import org.l2jmobius.gameserver.model.actor.Summon;
import org.l2jmobius.gameserver.model.actor.templates.NpcTemplate;
import org.l2jmobius.gameserver.model.buylist.ProductList;
import org.l2jmobius.gameserver.model.entity.Castle;
import org.l2jmobius.gameserver.model.itemcontainer.Inventory;
import org.l2jmobius.gameserver.model.items.Item;
import org.l2jmobius.gameserver.model.items.instance.ItemInstance;
import org.l2jmobius.gameserver.model.olympiad.OlympiadManager;
import org.l2jmobius.gameserver.model.skills.EffectScope;
import org.l2jmobius.gameserver.model.skills.Skill;
import org.l2jmobius.gameserver.model.zone.ZoneId;
import org.l2jmobius.gameserver.network.SystemMessageId;
import org.l2jmobius.gameserver.network.serverpackets.*;
import org.l2jmobius.gameserver.taskmanager.AttackStanceTaskManager;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @version $Revision: 1.10.4.9 $ $Date: 2005/04/11 10:06:08 $
*/
public class BufferInstance extends NpcInstance
{
private static final int[] buffs = { 14791, 14792, 14793, 14794, 30814, 14788, 14789, 14790, 17175, 17176, 17177};
public BufferInstance(NpcTemplate template)
{
super(template);
setInstanceType(InstanceType.BufferInstance);
}
@Override
public void onBypassFeedback(PlayerInstance player, String command)
{
if (player == null)
{
return;
}
if (player.getEvent() != null)
{
player.sendMessage("I can not help you if you are registered for an event");
player.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
if (AttackStanceTaskManager.getInstance().hasAttackStanceTask(player))
{
player.sendMessage("I can not help you while you are fighting");
player.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
if (command.startsWith("BuffMe"))
{
if (player.isInCombat() || player.isDead() || player.isInOlympiadMode() || player.getPvpFlag() > 0 ||
OlympiadManager.getInstance().isRegisteredInComp(player) || player.isPlayingEvent())
{
player.sendMessage("You can't use this option now!");
return;
}
StringTokenizer st = new StringTokenizer(command, " ");
st.nextToken();
int skillId = Integer.valueOf(st.nextToken());
if (skillId < 4)
{
int i = 0;
for (int id : buffs)
{
int level = 1;
if (i < 4) {
level = 4;
}
giveBuff(player, id, level);
i++;
}
}
else
{
giveBuff(player, skillId, 1);
}
showChatWindow(player, 2);
}
else if (command.startsWith("Buff"))
{
StringTokenizer st = new StringTokenizer(command.substring(5), " ");
int buffId = Integer.parseInt(st.nextToken());
int chatPage = Integer.parseInt(st.nextToken());
int buffLevel = SkillData.getInstance().getMaxLevel(buffId);
Skill skill = SkillData.getInstance().getSkill(buffId, buffLevel);
if (skill != null)
{
skill.applyEffects(player, player);
player.setCurrentMp(player.getMaxMp());
}
showChatWindow(player, chatPage);
}
else if (command.startsWith("Heal"))
{
if ((player.isInCombat() || player.getPvpFlag() > 0) && !player.isInsideZone(ZoneId.PEACE))
{
player.sendMessage("You cannot be healed while engaged in combat.");
return;
}
player.setCurrentHp(player.getMaxHp());
player.setCurrentMp(player.getMaxMp());
player.setCurrentCp(player.getMaxCp());
for (Summon summon : player.getServitorsAndPets())
{
summon.setCurrentHp(summon.getMaxHp());
summon.setCurrentMp(summon.getMaxMp());
summon.setCurrentCp(summon.getMaxCp());
}
showChatWindow(player);
}
else if (command.startsWith("RemoveBuffs"))
{
player.stopAllEffectsExceptThoseThatLastThroughDeath();
showChatWindow(player, 0);
}
else if (command.startsWith("Pet") && player.getPet() == null && player.getServitorsAndPets().isEmpty())
{
player.sendPacket(SystemMessageId.THAT_IS_AN_INCORRECT_TARGET);
}
else if (command.startsWith("PetBuff"))
{
StringTokenizer st = new StringTokenizer(command.substring(8), " ");
int buffId = Integer.parseInt(st.nextToken());
int chatPage = Integer.parseInt(st.nextToken());
int buffLevel = SkillData.getInstance().getMaxLevel(buffId);
Skill skill = SkillData.getInstance().getSkill(buffId, buffLevel);
if (skill != null)
{
if (player.getPet() != null)
{
skill.applyEffects(player, player.getPet());
player.setCurrentMp(player.getMaxMp());
}
for (Summon summon : player.getServitorsAndPets())
{
skill.applyEffects(player, summon);
player.setCurrentMp(player.getMaxMp());
}
}
showChatWindow(player, chatPage);
}
else if (command.startsWith("PetHeal"))
{
if (player.getPet() != null)
{
player.getPet().setCurrentHp(player.getPet().getMaxHp());
player.getPet().setCurrentMp(player.getPet().getMaxMp());
player.getPet().setCurrentCp(player.getPet().getMaxCp());
}
for (Summon summon : player.getServitorsAndPets())
{
summon.setCurrentHp(summon.getMaxHp());
summon.setCurrentMp(summon.getMaxMp());
summon.setCurrentCp(summon.getMaxCp());
}
showChatWindow(player, 10);
}
else if (command.startsWith("PetRemoveBuffs"))
{
player.getPet().stopAllEffects();
showChatWindow(player, 0);
}
else if (command.startsWith("Chat"))
{
showChatWindow(player, Integer.valueOf(command.substring(5)));
}
else
{
super.onBypassFeedback(player, command);
}
}
private static void giveBuff(PlayerInstance player, int skillId, int level)
{
if (player == null)
{
return;
}
boolean buffSelf = true;
boolean buffSummon = player.getTarget() != player;
if (buffSummon)
{
if (player.getPet() != null)
{
SkillData.getInstance().getSkill(skillId, level).applyEffects(player.getPet(), player.getPet());
player.getPet().setCurrentHpMp(player.getPet().getMaxHp(), player.getPet().getMaxMp());
if (player.getTarget() == player.getPet())
{
buffSelf = false;
}
}
if (player.getServitorsAndPets() != null)
{
for (Summon summon : player.getServitorsAndPets())
{
if (summon == null)
{
continue;
}
SkillData.getInstance().getSkill(skillId, level).applyEffects(summon, summon);
summon.setCurrentHpMp(summon.getMaxHp(), summon.getMaxMp());
if (player.getTarget() == summon)
{
buffSelf = false;
}
}
}
}
if (buffSelf)
{
SkillData.getInstance().getSkill(skillId, level).applyEffects(player, player);
player.setCurrentHpMp(player.getMaxHp(), player.getMaxMp());
}
}
public static void buff(PlayerInstance character)
{
int type = 2;
if (character instanceof PlayerInstance)
{
PlayerInstance player = (PlayerInstance) character;
if (!player.isMageClass())
{
ItemInstance shield = player.getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
if (shield != null && shield.getItem().getType1() == Item.TYPE1_SHIELD_ARMOR)
{
type = 0;
}
else
{
type = 1;
}
}
}
else
{
type = 1;
}
for (int buff : buffs)
{
if (buff == 15649 && type != 0 || buff == 15650 && type != 1 || buff == 15648 && type != 2)
{
continue;
}
SkillData.getInstance().getSkill(buff, 1).applyEffects(character, character);
character.setCurrentMp(character.getMaxMp());
}
}
@Override
public String getHtmlPath(int npcId, int value, PlayerInstance player)
{
String pom;
if (value == 0)
{
pom = Integer.toString(npcId);
}
else
{
pom = npcId + "-" + value;
}
return "data/html/buffer/" + pom + ".htm";
}
@Override
public void showChatWindow(PlayerInstance player, int val)
{
if (val >= 10 && player.getPet() == null && player.getServitorsAndPets().isEmpty())
{
val = 0;
}
// Send a Server->Client NpcHtmlMessage containing the text of the L2NpcInstance to the L2PcInstance
NpcHtmlMessage html = new NpcHtmlMessage(getObjectId());
html.setFile(player, getHtmlPath(getId(), val, player));
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
// Send a Server->Client ActionFailed to the L2PcInstance in order to avoid that the client wait another packet
player.sendPacket(ActionFailed.STATIC_PACKET);
}
}
<file_sep>/config/Custom/PasswordChange.ini
# ---------------------------------------------------------------------------
# Password Change
# ---------------------------------------------------------------------------
# Enables .changepassword voiced command which allows the players to change their account's password ingame.
# Default: False
AllowChangePassword = True
<file_sep>/java/org/l2jmobius/commons/util/xml/XmlNode.kt
package l2server.util.xml
import org.w3c.dom.Node
import java.util.ArrayList
import java.util.function.Function
import kotlin.collections.HashMap
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
/**
* @author Pere
*/
class XmlNode internal constructor(private val base: Node) {
val name: String = base.nodeName
val text: String? = base.firstChild?.nodeValue
val firstChild: XmlNode?
get() {
val children = getChildren()
return if (children.isEmpty()) {
null
} else children[0]
}
fun hasAttributes() = base.attributes.length > 0
fun hasAttribute(name: String) = base.attributes.getNamedItem(name) != null
private fun getAttributeValue(name: String): String? = base.attributes.getNamedItem(name)?.nodeValue
private fun <T> parse(name: String, value: String?, expectedType: Class<T>, parseFunction: Function<String, T>): T {
if (value == null) {
throw IllegalArgumentException(expectedType.simpleName + " value required for \"" + name + "\", but not specified.\r\nNode: " + this)
}
try {
return parseFunction.apply(value)
} catch (e: Exception) {
throw IllegalArgumentException(expectedType.simpleName + " value required for \"" + name + "\", but found: " + value)
}
}
private fun <T> parse(name: String, value: String?, expectedType: Class<T>, parseFunction: Function<String, T>, default: T): T {
if (value == null) {
return default
}
try {
return parseFunction.apply(value)
} catch (e: Exception) {
throw IllegalArgumentException(expectedType.simpleName + " value required for \"" + name + "\", but found: " + value)
}
}
fun getBool(name: String): Boolean {
return parse(name, getAttributeValue(name), Boolean::class.java, Function { java.lang.Boolean.parseBoolean(it) })
}
fun getBool(name: String, default: Boolean): Boolean {
return parse(name, getAttributeValue(name), Boolean::class.java, Function { java.lang.Boolean.parseBoolean(it) }, default)
}
fun getInt(name: String): Int {
return parse(name, getAttributeValue(name), Int::class.java, Function { Integer.parseInt(it) })
}
fun getInt(name: String, default: Int): Int {
return parse(name, getAttributeValue(name), Int::class.java, Function { Integer.parseInt(it) }, default)
}
fun getLong(name: String): Long {
return parse(name, getAttributeValue(name), Long::class.java, Function { java.lang.Long.parseLong(it) })
}
fun getLong(name: String, default: Long): Long {
return parse(name, getAttributeValue(name), Long::class.java, Function { java.lang.Long.parseLong(it) }, default)
}
fun getFloat(name: String): Float {
return parse(name, getAttributeValue(name), Float::class.java, Function { java.lang.Float.parseFloat(it) })
}
fun getFloat(name: String, default: Float): Float {
return parse(name, getAttributeValue(name), Float::class.java, Function { java.lang.Float.parseFloat(it) }, default)
}
fun getDouble(name: String): Double {
return parse(name, getAttributeValue(name), Double::class.java, Function { java.lang.Double.parseDouble(it) })
}
fun getDouble(name: String, default: Double): Double {
return parse(name, getAttributeValue(name), Double::class.java, Function { java.lang.Double.parseDouble(it) }, default)
}
fun getString(name: String): String {
return parse(name, getAttributeValue(name), String::class.java, Function { it })
}
fun getString(name: String, default: String): String {
return parse(name, getAttributeValue(name), String::class.java, Function { it }, default)
}
fun getAttributes(): Map<String, String> {
val attributes = HashMap<String, String>()
for (i in 0 until base.attributes.length) {
val name = base.attributes.item(i).nodeName
val value = base.attributes.item(i).nodeValue
attributes[name] = value
}
return attributes
}
fun getChildren(): List<XmlNode> {
val children = ArrayList<XmlNode>()
var baseSubNode: Node? = base.firstChild
while (baseSubNode != null) {
if (baseSubNode.nodeType == Node.ELEMENT_NODE) {
val child = XmlNode(baseSubNode)
children.add(child)
}
baseSubNode = baseSubNode.nextSibling
}
return children
}
fun getChildren(name: String): List<XmlNode> {
val list = ArrayList<XmlNode>()
for (node in getChildren()) {
if (node.name == name) {
list.add(node)
}
}
return list
}
fun getChild(name: String): XmlNode? {
val children = getChildren(name)
return if (children.isEmpty()) {
null
} else children[0]
}
override fun toString(): String {
return toString(0)
}
private fun toString(tabDepth: Int): String {
val tabsBuilder = StringBuilder()
for (i in 0 until tabDepth) {
tabsBuilder.append("\t")
}
val tabs = tabsBuilder.toString()
val result = StringBuilder("$tabs<$name")
for ((key, value) in getAttributes()) {
result.append(" ").append(key).append("=\"").append(value).append("\"")
}
val children = getChildren()
if (!children.isEmpty() || text != null && text.isNotEmpty()) {
result.append(">\r\n")
for (child in children) {
result.append(child.toString(tabDepth + 1)).append("\r\n")
}
result.append(tabs).append("<").append(name).append(">\r\n")
} else {
result.append(" />")
}
return result.toString()
}
}
<file_sep>/config/Custom/ClassBalance.ini
# ---------------------------------------------------------------------------
# Class Balance
# ---------------------------------------------------------------------------
# Multiply parameters based on player class. May use both class id or enums.
# Example: ELVEN_FIGHTER*2;PALUS_KNIGHT*2.5;...
PveMagicalSkillDamageMultipliers = 189*2.5;168*1.5;166*1.5;167*1.5;170*1.5;169*1.5;179*2;180*2;181*2;
PvpMagicalSkillDamageMultipliers = 189*2.5;176*2;177*2;178*2;
PveMagicalSkillDefenceMultipliers =
PvpMagicalSkillDefenceMultipliers =
PveMagicalSkillCriticalChanceMultipliers =
PvpMagicalSkillCriticalChanceMultipliers =
PveMagicalSkillCriticalDamageMultipliers =
PvpMagicalSkillCriticalDamageMultipliers =
PvePhysicalSkillDamageMultipliers =
PvpPhysicalSkillDamageMultipliers =
PvePhysicalSkillDefenceMultipliers =
PvpPhysicalSkillDefenceMultipliers =
PvePhysicalSkillCriticalChanceMultipliers =
PvpPhysicalSkillCriticalChanceMultipliers =
PvePhysicalSkillCriticalDamageMultipliers =
PvpPhysicalSkillCriticalDamageMultipliers =
PvePhysicalAttackDamageMultipliers = 152*1.2;157*1;154*1;153*1.5;156*2;155*1.5;174*2;175*2;176*2;177*2;
PvpPhysicalAttackDamageMultipliers =
PvePhysicalAttackDefenceMultipliers =
PvpPhysicalAttackDefenceMultipliers =
PvePhysicalAttackCriticalChanceMultipliers =
PvpPhysicalAttackCriticalChanceMultipliers =
PvePhysicalAttackCriticalDamageMultipliers =
PvpPhysicalAttackCriticalDamageMultipliers =
PveBlowSkillDamageMultipliers = 158*1;161*1;160*1;159*1;
PvpBlowSkillDamageMultipliers =
PveEnergySkillDamageMultipliers =
PvpEnergySkillDamageMultipliers =
PveEnergySkillDefenceMultipliers =
PvpEnergySkillDefenceMultipliers =
PveBlowSkillDefenceMultipliers =
PvpBlowSkillDefenceMultipliers =
PlayerHealingSkillMultipliers =
SkillMasteryChanceMultipliers =
ExpAmountMultipliers =
SpAmountMultipliers =
<file_sep>/java/org/l2jmobius/gameserver/events/instanced/EventInstance.java
package org.l2jmobius.gameserver.events.instanced;
import org.l2jmobius.Config;
import org.l2jmobius.commons.concurrent.ThreadPool;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.datatables.EventPrizesTable;
import org.l2jmobius.gameserver.enums.ChatType;
import org.l2jmobius.gameserver.enums.PartyDistributionType;
import org.l2jmobius.gameserver.geoengine.GeoEngine;
import org.l2jmobius.gameserver.instancemanager.InstanceManager;
import org.l2jmobius.gameserver.model.Location;
import org.l2jmobius.gameserver.model.Party;
import org.l2jmobius.gameserver.model.actor.Creature;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.olympiad.OlympiadManager;
import org.l2jmobius.gameserver.model.zone.ZoneId;
import org.l2jmobius.gameserver.network.clientpackets.Say2;
import org.l2jmobius.gameserver.network.serverpackets.*;
import org.l2jmobius.gameserver.taskmanager.AttackStanceTaskManager;
import org.l2jmobius.gameserver.util.Broadcast;
import org.l2jmobius.gameserver.util.Point3D;
import org.l2jmobius.loginserver.network.GameServerPacketHandler;
import java.util.List;
import java.util.Random;
public abstract class EventInstance {
public enum EventType {
TVT,
LuckyChests,
CaptureTheFlag,
SimonSays,
VIP,
Survival,
DeathMatch,
KingOfTheHill,
TeamSurvival,
CursedBattle,
DestroyTheGolem,
FieldDomination,
StalkedSalkers
}
public enum EventState {
INACTIVE,
READY,
STARTED,
REWARDING
}
protected final EventConfig config;
protected final int id;
protected final int instanceId;
protected EventTeam[] teams = new EventTeam[4];
protected EventState state = EventState.INACTIVE;
private int participants;
private long startTime = 0;
public int randomBetween(int low, int high) {
Random r = new Random();
return r.nextInt(high-low) + low;
}
public EventInstance(int id, EventConfig config) {
this.id = id;
this.config = config;
teams[0] = new EventTeam(0, config.getTeamName(0), config.getLocation().getSpawn(0));
teams[1] = new EventTeam(1, config.getTeamName(1), config.getLocation().getSpawn(1));
teams[2] = new EventTeam(2, config.getTeamName(2), config.getLocation().getSpawn(2));
teams[3] = new EventTeam(3, config.getTeamName(3), config.getLocation().getSpawn(3));
instanceId = id + 40000;
InstanceManager.getInstance().createInstance();
setState(EventState.READY);
ThreadPool.schedule(() -> sendToAllParticipants("Match found! The event is starting in 20 seconds."), 5000L);
ThreadPool.schedule(this::startFight, 20000L);
}
public boolean startFight() {
for (EventTeam team : teams) {
for (PlayerInstance player : team.getParticipatedPlayers().values()) {
if (player != null &&
(OlympiadManager.getInstance().isRegisteredInComp(player) || player.isInOlympiadMode() || player.isOlympiadStart() ||
player.isFlyingMounted() || player.inObserverMode())) {
removeParticipant(player.getObjectId());
}
}
}
if (id != 100) {
// Check for enough participants
if (!config.isAllVsAll()) {
if (config.getLocation().getTeamCount() != 4) {
if (teams[0].getParticipatedPlayerCount() < Config.INSTANCED_EVENT_MIN_PLAYERS_IN_TEAMS ||
teams[1].getParticipatedPlayerCount() < Config.INSTANCED_EVENT_MIN_PLAYERS_IN_TEAMS ) {
// Set state INACTIVE
setState(EventState.INACTIVE);
// Cleanup of teams
teams[0].onEventNotStarted();
teams[1].onEventNotStarted();
return false;
}
} else {
if (teams[0].getParticipatedPlayerCount() < Config.INSTANCED_EVENT_MIN_PLAYERS_IN_TEAMS ||
teams[1].getParticipatedPlayerCount() < Config.INSTANCED_EVENT_MIN_PLAYERS_IN_TEAMS ||
teams[2].getParticipatedPlayerCount() < Config.INSTANCED_EVENT_MIN_PLAYERS_IN_TEAMS ||
teams[3].getParticipatedPlayerCount() < Config.INSTANCED_EVENT_MIN_PLAYERS_IN_TEAMS ) {
// Set state INACTIVE
setState(EventState.INACTIVE);
// Cleanup of teams
teams[0].onEventNotStarted();
teams[1].onEventNotStarted();
teams[2].onEventNotStarted();
teams[3].onEventNotStarted();
return false;
}
}
} else {
if (teams[0].getParticipatedPlayerCount() < 2) {
setState(EventState.INACTIVE);
teams[0].onEventNotStarted();
return false;
}
participants = teams[0].getParticipatedPlayerCount();
}
}
// Iterate over all teams
for (EventTeam team : teams) {
int divider = 7;
if (team.getParticipatedPlayerCount() > 2) {
while (team.getParticipatedPlayerCount() % divider > 0 && team.getParticipatedPlayerCount() % divider <= 2 && divider > 5) {
divider--;
}
}
int partyCount = team.getParticipatedPlayerCount() / divider;
if (team.getParticipatedPlayerCount() % divider > 0) {
partyCount++;
}
Party[] parties = new Party[partyCount];
int currentParty = 0;
// Iterate over all participated player instances in this team
for (PlayerInstance playerInstance : team.getParticipatedPlayers().values()) {
if (playerInstance != null) {
playerInstance.setEventPoints(0);
try {
playerInstance.eventSaveData();
} catch (Exception e) {
e.printStackTrace();
}
if (playerInstance.isMounted()) {
playerInstance.dismount();
}
// Teleporter implements Runnable and starts itself
new EventTeleporter(playerInstance, team.getCoords(), false, false);
playerInstance.leaveParty();
if (!config.isAllVsAll()) {
// Add the player into the current party or create it if it still doesn't exist
if (parties[currentParty] == null) {
parties[currentParty] = new Party(playerInstance, PartyDistributionType.FINDERS_KEEPERS);
playerInstance.setParty(parties[currentParty]);
} else {
playerInstance.joinParty(parties[currentParty]);
}
// Rotate current party index
currentParty++;
if (currentParty >= partyCount) {
currentParty = 0;
}
}
}
}
}
Broadcast.toAllOnlinePlayers("The " + config.getEventName() + " has started.");
if (!config.isType(EventType.TeamSurvival) && !config.isType(EventType.Survival) && !config.isType(EventType.SimonSays)) {
ThreadPool.schedule(this::stopFight, 60000 * Config.INSTANCED_EVENT_RUNNING_TIME );
}
// Set state STARTED
setState(EventState.STARTED);
startTime = System.currentTimeMillis();
return true;
}
public long getStartTime() {
return startTime;
}
public abstract void calculateRewards();
protected void onContribution(PlayerInstance player, int weight) {
if (player == null) {
}
/*
int rewardId = 6392;
int rewardQt = weight;
player.addItem("Instanced Events", rewardId, rewardQt, player, true);
StatusUpdate statusUpdate = new StatusUpdate(player);
statusUpdate.addAttribute(StatusUpdate.CUR_LOAD, player.getCurrentLoad());
player.sendPacket(statusUpdate);
*/
}
protected void rewardTeams(int winnerTeam) {
EventTeam winner = null;
if (winnerTeam >= 0) {
winner = teams[winnerTeam];
}
for (EventTeam team : teams) {
int totalPoints = 0;
for (PlayerInstance player : team.getParticipatedPlayers().values()) {
if (player != null) {
totalPoints += player.getEventPoints();
}
}
float teamMultiplier = 0.5f;
if (team == winner) {
if (config.getLocation().getTeamCount() == 4) {
teamMultiplier = 2.5f;
} else {
teamMultiplier = 1.5f;
}
}
for (PlayerInstance player : team.getParticipatedPlayers().values()) {
if (player == null) {
continue;
}
if (team == winner) {
player.sendPacket(new CreatureSay(player, ChatType.PARTYROOM_ALL, "Instanced Events", "Your team has won!!!"));
} else {
player.sendPacket(new CreatureSay(player, ChatType.PARTYROOM_ALL, "Instanced Events", "Your team has lost :("));
}
float performanceMultiplier = player.getEventPoints() * ((float) team.getParticipatedPlayerCount() / (float) totalPoints);
String performanceString;
if (player.getEventPoints() == 0) {
performanceMultiplier = 0;
}
if (performanceMultiplier < 0.35) {
performanceString = "horrible";
} else if (performanceMultiplier < 0.8) {
performanceString = "bad";
} else if (performanceMultiplier < 1.2) {
performanceString = "okay";
} else if (performanceMultiplier < 1.8) {
performanceString = "good";
} else if (performanceMultiplier < 3.0) {
performanceString = "very good";
} else {
performanceString = "amazing";
}
player.sendPacket(new CreatureSay(player,
ChatType.PARTYROOM_ALL,
"Instanced Events",
"Your performance in this event has been " + performanceString + "."));
EventPrizesTable.getInstance().rewardPlayer("InstancedEvents", player, teamMultiplier, performanceMultiplier);
StatusUpdate statusUpdate = new StatusUpdate(player);
player.sendPacket(statusUpdate);
}
}
}
protected void rewardPlayers(List<PlayerInstance> players) {
if (players == null || players.isEmpty()) {
return;
}
int totalPoints = 0;
for (PlayerInstance player : players) {
if (player != null) {
totalPoints += player.getEventPoints();
}
}
for (PlayerInstance player : players) {
if (player == null) {
continue;
}
// Avoid 0 division
if (totalPoints <= 0) {
totalPoints = 1;
}
float performanceMultiplier = player.getEventPoints() * ((float) participants / (float) totalPoints);
EventPrizesTable.getInstance().rewardPlayer("InstancedEvents", player, 1.0f, performanceMultiplier);
StatusUpdate statusUpdate = new StatusUpdate(player);
NpcHtmlMessage npcHtmlMessage = new NpcHtmlMessage(0);
npcHtmlMessage.setHtml(
"<html><head><title>Instanced Events</title></head><body>The event has finished. Look at your inventory, there should be your reward.</body></html>");
player.sendPacket(npcHtmlMessage);
// TODO: Place this at the HTML
player.sendPacket(new CreatureSay(player, ChatType.PARTYROOM_ALL, "Instanced Events", "Event score:"));
for (PlayerInstance rewarded : players) {
if (rewarded != null) {
player.sendPacket(new CreatureSay(player, ChatType.PARTYROOM_ALL,
"Instanced Events",
rewarded.getName() + ": " + rewarded.getEventPoints()));
}
}
}
}
public void stopFight() {
Broadcast.toAllOnlinePlayers("The " + config.getEventName() + " has ended.");
calculateRewards();
// Iterate over all teams
for (EventTeam team : teams) {
for (PlayerInstance playerInstance : team.getParticipatedPlayers().values()) {
// Check for nullpointer
if (playerInstance != null) {
if (playerInstance.getCtfFlag() != null) {
playerInstance.setCtfFlag(null);
}
playerInstance.setEventPoints(-1);
// TODO: EVENT: TELEPORT TO MAIN TOWN
new EventTeleporter(playerInstance, new Point3D(playerInstance.getEventSavedPosition().getX(), playerInstance.getEventSavedPosition().getY(), playerInstance.getEventSavedPosition().getZ()), true, true);
}
team.setVIP(null);
}
}
// Cleanup of teams
teams[0].cleanMe();
teams[1].cleanMe();
if (config.getLocation().getTeamCount() == 4) {
teams[2].cleanMe();
teams[3].cleanMe();
}
ThreadPool.schedule(() -> {
// Set state INACTIVE
setState(EventState.INACTIVE);
}, 5000L);
}
public synchronized boolean addParticipant(PlayerInstance playerInstance) {
// Check for nullpointer
if (playerInstance == null) {
return false;
}
playerInstance.setEvent(this);
byte teamId = 0;
if (config.isAllVsAll()) {
return teams[teamId].addPlayer(playerInstance);
}
if (playerInstance.getClassId().getId() == 146) {
if (config.getLocation().getTeamCount() == 2) {
// Check to which team the player should be added
if (teams[0].getHealersCount() == teams[1].getHealersCount()) {
teamId = (byte) Rnd.get(2);
} else {
teamId = (byte) (teams[0].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() ? 1 : 0);
}
} else {
int minHealers = 50;
for (byte i = 0; i < 4; i++) {
if (teams[i].getHealersCount() < minHealers) {
teamId = i;
minHealers = teams[i].getHealersCount();
}
}
}
} else if (config.getLocation().getTeamCount() == 2) {
// Check to which team the player should be added
if (teams[0].getParticipatedPlayerCount() == teams[1].getParticipatedPlayerCount()) {
teamId = (byte) Rnd.get(2);
} else {
teamId = (byte) (teams[0].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() ? 1 : 0);
}
} else {
// Check to which team the player should be added
if (teams[0].getParticipatedPlayerCount() < teams[1].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() < teams[2].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() < teams[3].getParticipatedPlayerCount()) {
teamId = (byte) 0;
} else if (teams[1].getParticipatedPlayerCount() < teams[0].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() < teams[2].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() < teams[3].getParticipatedPlayerCount()) {
teamId = (byte) 1;
} else if (teams[2].getParticipatedPlayerCount() < teams[0].getParticipatedPlayerCount() &&
teams[2].getParticipatedPlayerCount() < teams[1].getParticipatedPlayerCount() &&
teams[2].getParticipatedPlayerCount() < teams[3].getParticipatedPlayerCount()) {
teamId = (byte) 2;
} else if (teams[3].getParticipatedPlayerCount() < teams[0].getParticipatedPlayerCount() &&
teams[3].getParticipatedPlayerCount() < teams[1].getParticipatedPlayerCount() &&
teams[3].getParticipatedPlayerCount() < teams[2].getParticipatedPlayerCount()) {
teamId = (byte) 3;
} else if (teams[0].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[2].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() == teams[3].getParticipatedPlayerCount()) {
while (teamId == 0 || teamId == 2) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[0].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[3].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() == teams[2].getParticipatedPlayerCount()) {
while (teamId == 0 || teamId == 3) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[0].getParticipatedPlayerCount() > teams[2].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() > teams[2].getParticipatedPlayerCount() &&
teams[2].getParticipatedPlayerCount() == teams[3].getParticipatedPlayerCount()) {
while (teamId == 0 || teamId == 1) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[0].getParticipatedPlayerCount() < teams[1].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() < teams[3].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() == teams[2].getParticipatedPlayerCount()) {
while (teamId == 1 || teamId == 3) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[0].getParticipatedPlayerCount() < teams[1].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() < teams[2].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() == teams[3].getParticipatedPlayerCount()) {
while (teamId == 1 || teamId == 2) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[0].getParticipatedPlayerCount() < teams[2].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() < teams[3].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() == teams[1].getParticipatedPlayerCount()) {
while (teamId == 2 || teamId == 3) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[0].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() > teams[2].getParticipatedPlayerCount() &&
teams[0].getParticipatedPlayerCount() > teams[3].getParticipatedPlayerCount()) {
while (teamId == 0) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[1].getParticipatedPlayerCount() > teams[0].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() > teams[2].getParticipatedPlayerCount() &&
teams[1].getParticipatedPlayerCount() > teams[3].getParticipatedPlayerCount()) {
while (teamId == 1) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[2].getParticipatedPlayerCount() > teams[0].getParticipatedPlayerCount() &&
teams[2].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[2].getParticipatedPlayerCount() > teams[3].getParticipatedPlayerCount()) {
while (teamId == 2) {
teamId = (byte) Rnd.get(4);
}
} else if (teams[3].getParticipatedPlayerCount() > teams[0].getParticipatedPlayerCount() &&
teams[3].getParticipatedPlayerCount() > teams[1].getParticipatedPlayerCount() &&
teams[3].getParticipatedPlayerCount() > teams[2].getParticipatedPlayerCount()) {
teamId = (byte) Rnd.get(3);
} else {
teamId = (byte) Rnd.get(4);
}
}
return teams[teamId].addPlayer(playerInstance);
}
public boolean removeParticipant(int playerObjectId) {
// Get the teamId of the player
byte teamId = getParticipantTeamId(playerObjectId);
// Check if the player is participant
if (teamId != -1) {
// Remove the player from team
teams[teamId].removePlayer(playerObjectId);
return true;
}
return false;
}
public void sendToAllParticipants(IClientOutgoingPacket packet) {
for (PlayerInstance playerInstance : teams[0].getParticipatedPlayers().values()) {
if (playerInstance != null) {
playerInstance.sendPacket(packet);
}
}
for (PlayerInstance playerInstance : teams[1].getParticipatedPlayers().values()) {
if (playerInstance != null) {
playerInstance.sendPacket(packet);
}
}
if (config.getLocation().getTeamCount() == 4) {
for (PlayerInstance playerInstance : teams[2].getParticipatedPlayers().values()) {
if (playerInstance != null) {
playerInstance.sendPacket(packet);
}
}
for (PlayerInstance playerInstance : teams[3].getParticipatedPlayers().values()) {
if (playerInstance != null) {
playerInstance.sendPacket(packet);
}
}
}
}
public void sendToAllParticipants(String message) {
sendToAllParticipants(new CreatureSay(null, ChatType.PARTYROOM_ALL, "Instanced Events", message));
}
public void onLogin(PlayerInstance playerInstance) {
if (playerInstance != null && isPlayerParticipant(playerInstance.getObjectId())) {
removeParticipant(playerInstance.getObjectId());
// TODO: EVENT: Teleport port back to main town
/*EventTeam team = getParticipantTeam(playerInstance.getObjectId());
team.addPlayer(playerInstance);
if (isState(EventState.STARTING) || isState(EventState.STARTED))
{
for (L2Effect effect : playerInstance.getAllEffects()) if (effect != null) effect.exit();
new EventTeleporter(playerInstance, getParticipantTeam(playerInstance.getObjectId()).getCoords(), true, false);
}*/
}
}
public void onLogout(PlayerInstance playerInstance) {
if (playerInstance != null && isPlayerParticipant(playerInstance.getObjectId())) {
removeParticipant(playerInstance.getObjectId());
}
}
public String getInfo(PlayerInstance player) {
String html = "<center><font color=\"LEVEL\">" + config.getEventString() + "</font></center><br>";
if (isState(EventState.READY)) {
if (config.isAllVsAll()) {
if (teams[0].getParticipatedPlayerCount() > 0) {
html += "Participants:<br>";
for (PlayerInstance participant : teams[0].getParticipatedPlayers().values()) {
if (participant != null) {
html += EventsManager.getInstance().getPlayerString(participant, player) + ", ";
}
}
html = html.substring(0, html.length() - 2) + ".";
}
} else {
for (EventTeam team : teams) {
if (team.getParticipatedPlayerCount() > 0) {
html += "Team " + team.getName() + " participants:<br>";
for (PlayerInstance participant : team.getParticipatedPlayers().values()) {
if (participant != null) {
html += EventsManager.getInstance().getPlayerString(participant, player) + ", ";
}
}
html = html.substring(0, html.length() - 2) + ".<br>";
}
}
if (html.length() > 4) {
html = html.substring(0, html.length() - 4);
}
}
} else if (isState(EventState.STARTED)) {
html += getRunningInfo(player);
} else if (isState(EventState.INACTIVE)) {
html += "This event has ended.";
}
return html;
}
public abstract String getRunningInfo(PlayerInstance player);
public void observe(PlayerInstance playerInstance) {
if (playerInstance.getEvent() != null) {
playerInstance.sendMessage("You cannot observe an event when you are participating on it.");
playerInstance.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
if (AttackStanceTaskManager.getInstance().hasAttackStanceTask(playerInstance)) {
playerInstance.sendMessage("You cannot observe an event while fighting.");
playerInstance.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
if (playerInstance.isInsideZone(ZoneId.NO_SUMMON_FRIEND) || playerInstance.inObserverMode()) {
playerInstance.sendMessage("You cannot observe an event from here.");
playerInstance.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
int x;
int y;
int z;
if (config.getLocation().getZone() == null) {
int rndTm = Rnd.get(config.getLocation().getTeamCount());
x = config.getLocation().getSpawn(rndTm).getX();
y = config.getLocation().getSpawn(rndTm).getY();
z = GeoEngine.getInstance().getHeight(x, y, config.getLocation().getGlobalZ());
} else {
Location pos = config.getLocation().getZone().getZone().getRandomPoint();
x = pos.getX();
y = pos.getY();
z = GeoEngine.getInstance().getHeight(pos.getX(), pos.getY(), pos.getZ());
}
playerInstance.setInstanceId(instanceId);
playerInstance.enterEventObserverMode(x, y, z);
}
public boolean onAction(PlayerInstance playerInstance, int targetPlayerObjectId) {
EventTeam playerTeam = getParticipantTeam(playerInstance.getObjectId());
EventTeam targetPlayerTeam = getParticipantTeam(targetPlayerObjectId);
if (playerTeam == null || targetPlayerTeam == null) {
return false;
}
return !(playerTeam == targetPlayerTeam && playerInstance.getObjectId() != targetPlayerObjectId &&
!Config.INSTANCED_EVENT_TARGET_TEAM_MEMBERS_ALLOWED);
}
public boolean onForcedAttack(PlayerInstance playerInstance, int targetPlayerObjectId) {
EventTeam playerTeam = getParticipantTeam(playerInstance.getObjectId());
EventTeam targetPlayerTeam = getParticipantTeam(targetPlayerObjectId);
if (playerTeam == null || targetPlayerTeam == null) {
return false;
}
return !(playerTeam == targetPlayerTeam && playerInstance.getObjectId() != targetPlayerObjectId && config.isPvp());
}
public boolean onScrollUse(int playerObjectId) {
if (!isState(EventState.STARTED)) {
return true;
}
return !(isPlayerParticipant(playerObjectId) && !Config.INSTANCED_EVENT_SCROLL_ALLOWED);
}
public boolean onPotionUse(int playerObjectId) {
if (!isState(EventState.STARTED)) {
return true;
}
return !(isPlayerParticipant(playerObjectId) && !Config.INSTANCED_EVENT_POTIONS_ALLOWED);
}
public boolean onEscapeUse(int playerObjectId) {
if (!isState(EventState.STARTED)) {
return true;
}
return !isPlayerParticipant(playerObjectId);
}
public boolean onItemSummon(int playerObjectId) {
if (!isState(EventState.STARTED)) {
return true;
}
return !(isPlayerParticipant(playerObjectId) && !Config.INSTANCED_EVENT_SUMMON_BY_ITEM_ALLOWED);
}
public abstract void onKill(Creature killerCharacter, PlayerInstance killedPlayerInstance);
public boolean isType(EventType type) {
return config.getType() == type;
}
public EventType getType() {
return config.getType();
}
public void setState(EventState state) {
this.state = state;
}
public boolean isState(EventState state) {
return this.state == state;
}
public byte getParticipantTeamId(int playerObjectId) {
if (config.getLocation().getTeamCount() != 4) {
return (byte) (teams[0].containsPlayer(playerObjectId) ? 0 : teams[1].containsPlayer(playerObjectId) ? 1 : -1);
} else {
return (byte) (teams[0].containsPlayer(playerObjectId) ? 0 : teams[1].containsPlayer(playerObjectId) ? 1 :
teams[2].containsPlayer(playerObjectId) ? 2 : teams[3].containsPlayer(playerObjectId) ? 3 : -1);
}
}
public EventTeam getParticipantTeam(int playerObjectId) {
if (config.getLocation().getTeamCount() != 4) {
return teams[0].containsPlayer(playerObjectId) ? teams[0] : teams[1].containsPlayer(playerObjectId) ? teams[1] : null;
} else {
return teams[0].containsPlayer(playerObjectId) ? teams[0] : teams[1].containsPlayer(playerObjectId) ? teams[1] :
teams[2].containsPlayer(playerObjectId) ? teams[2] : teams[3].containsPlayer(playerObjectId) ? teams[3] : null;
}
}
public EventTeam getParticipantEnemyTeam(int playerObjectId) {
if (config.getLocation().getTeamCount() != 4) {
return teams[0].containsPlayer(playerObjectId) ? teams[1] : teams[1].containsPlayer(playerObjectId) ? teams[0] : null;
} else {
return teams[0].containsPlayer(playerObjectId) ? teams[1] : teams[1].containsPlayer(playerObjectId) ? teams[0] :
teams[2].containsPlayer(playerObjectId) ? teams[3] : teams[3].containsPlayer(playerObjectId) ? teams[2] : null;
}
}
public Point3D getParticipantTeamCoordinates(int playerObjectId) {
if (config.getLocation().getTeamCount() != 4) {
return teams[0].containsPlayer(playerObjectId) ? teams[0].getCoords() :
teams[1].containsPlayer(playerObjectId) ? teams[1].getCoords() : null;
} else {
return teams[0].containsPlayer(playerObjectId) ? teams[0].getCoords() : teams[1].containsPlayer(playerObjectId) ? teams[1].getCoords() :
teams[2].containsPlayer(playerObjectId) ? teams[2].getCoords() :
teams[3].containsPlayer(playerObjectId) ? teams[3].getCoords() : null;
}
}
public boolean isPlayerParticipant(int playerObjectId) {
if (!isState(EventState.STARTED)) {
return false;
}
if (config.getLocation().getTeamCount() != 4) {
return teams[0].containsPlayer(playerObjectId) || teams[1].containsPlayer(playerObjectId);
} else {
return teams[0].containsPlayer(playerObjectId) || teams[1].containsPlayer(playerObjectId) || teams[2].containsPlayer(playerObjectId) ||
teams[3].containsPlayer(playerObjectId);
}
}
public int getParticipatedPlayersCount() {
//if (!isState(EventState.PARTICIPATING) && !isState(EventState.STARTING) && !isState(EventState.STARTED))
// return 0;
int count = 0;
for (int teamId = 0; teamId < config.getLocation().getTeamCount(); teamId++) {
count += teams[teamId].getParticipatedPlayerCount();
}
return count;
}
protected PlayerInstance selectRandomParticipant() {
return teams[0].selectRandomParticipant();
}
public int getId() {
return id;
}
public EventConfig getConfig() {
return config;
}
public int getInstanceId() {
return instanceId;
}
public void setImportant(PlayerInstance player, boolean important) {
if (player == null) {
return;
}
if (config.getLocation().getTeamCount() != 4 && config.isAllVsAll()) {
player.setTeam(getParticipantTeamId(player.getObjectId()) + 1);
} else {
if (getParticipantTeamId(player.getObjectId()) == 0) {
player.getAppearance().setNameColor(Integer.decode("0xFF0000"));
player.getAppearance().setTitleColor(Integer.decode("0xFF0000"));
}
if (getParticipantTeamId(player.getObjectId()) == 1) {
player.getAppearance().setNameColor(Integer.decode("0x0000FF"));
player.getAppearance().setTitleColor(Integer.decode("0x0000FF"));
}
if (getParticipantTeamId(player.getObjectId()) == 2) {
player.getAppearance().setNameColor(Integer.decode("0x00FFFF"));
player.getAppearance().setTitleColor(Integer.decode("0x00FFFF"));
}
if (getParticipantTeamId(player.getObjectId()) == 3) {
player.getAppearance().setNameColor(Integer.decode("0x00FF00"));
player.getAppearance().setTitleColor(Integer.decode("0x00FF00"));
}
player.setTeam(0);
}
player.broadcastUserInfo();
if (isType(EventType.LuckyChests) || isType(EventType.StalkedSalkers) || isType(EventType.SimonSays)) {
player.disarmWeapons();
player.setIsEventDisarmed(true);
}
}
public EventTeam[] getTeams() {
return teams;
}
}
<file_sep>/config/Custom/OfflineTrade.ini
# ---------------------------------------------------------------------------
# Offline trade/craft
# ---------------------------------------------------------------------------
# Option to enable or disable offline trade feature.
# Enable -> true, Disable -> false
OfflineTradeEnable = True
# Option to enable or disable offline craft feature.
# Enable -> true, Disable -> false
OfflineCraftEnable = True
# If set to True, off-line shops will be possible only peace zones.
# Default: False
OfflineModeInPeaceZone = True
# If set to True, players in off-line shop mode wont take any damage, thus they cannot be killed.
# Default: False
OfflineModeNoDamage = True
# If set to True, name color will be changed then entering offline mode
OfflineSetNameColor = True
# Color of the name in offline mode (if OfflineSetNameColor = True)
OfflineNameColor = 808080
# Allow fame for characters in offline mode
# Enable -> true, Disable -> false
OfflineFame = True
#Restore offline traders/crafters after restart/shutdown. Default: false.
RestoreOffliners = True
#Do not restore offline characters, after OfflineMaxDays days spent from first restore.
#Require server restart to disconnect expired shops.
#0 = disabled (always restore).
#Default: 10
OfflineMaxDays = 0
#Disconnect shop after finished selling, buying.
#Default: True
OfflineDisconnectFinished = True
#Store offline trader transactions in realtime.
#Uses more datatabase resources, but helps if server shuts down unexpectedly.
StoreOfflineTradeInRealtime = True
<file_sep>/config/Custom/WalkerBotProtection.ini
# ---------------------------------------------------------------------------
# Walker/Bot protection
# ---------------------------------------------------------------------------
# Basic protection against L2Walker.
# Default: False
L2WalkerProtection = True
<file_sep>/out/production/Test/html/villagemaster/SubClass_Modify.htm
<html>
<body>Addition of a sub-class:<br>
Which of the following sub classes would you like to change?<br>
Sub-class 1<br>
<Button ALIGN=LEFT ICON="NORMAL" action="bypass -h npc_%objectId%_Subclass 6 1">%sub1%</Button>
Sub-class 2<br>
<Button ALIGN=LEFT ICON="NORMAL" action="bypass -h npc_%objectId%_Subclass 6 2">%sub2%</Button>
Sub-class 3<br>
<Button ALIGN=LEFT ICON="NORMAL" action="bypass -h npc_%objectId%_Subclass 6 3">%sub3%</Button>
<br><br>
If you change a sub-class, you'll start at level 40 after the 2nd class transfer.
</body>
</html><file_sep>/java/org/l2jmobius/gameserver/events/instanced/EventTeam.java
package org.l2jmobius.gameserver.events.instanced;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.datatables.SpawnTable;
import org.l2jmobius.gameserver.model.Spawn;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.util.Point3D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class EventTeam {
/**
* The name of the team<br>
*/
private String name;
/**
* The team spot coordinated<br>
*/
private Point3D coordinates;
/**
* The points of the team<br>
*/
private short points;
/**
* Name and instance of all participated players in HashMap<br>
*/
private Map<Integer, PlayerInstance> participatedPlayers = new LinkedHashMap<>();
private int flagId = 44004;
private Spawn flagSpawn;
private int golemId = 44003;
private Spawn golemSpawn;
private PlayerInstance VIP;
/**
* C'tor initialize the team<br><br>
*
* @param name as String<br>
* @param coordinates as int[]<br>
*/
public EventTeam(int id, String name, Point3D coordinates) {
flagId = 9009113 + id;
this.name = name;
this.coordinates = coordinates;
points = 0;
flagSpawn = null;
}
/**
* Adds a player to the team<br><br>
*
* @param playerInstance as Player<br>
* @return boolean: true if success, otherwise false<br>
*/
public boolean addPlayer(PlayerInstance playerInstance) {
if (playerInstance == null) {
return false;
}
synchronized (participatedPlayers) {
participatedPlayers.put(playerInstance.getObjectId(), playerInstance);
}
return true;
}
/**
* Removes a player from the team<br><br>
*/
public void removePlayer(int playerObjectId) {
synchronized (participatedPlayers) {
/*if (!EventsManager.getInstance().isType(EventType.DM)
&& !EventsManager.getInstance().isType(EventType.SS)
&& !EventsManager.getInstance().isType(EventType.SS2))
participatedPlayers.get(playerObjectId).setEvent(null);*/
participatedPlayers.remove(playerObjectId);
}
}
/**
* Increases the points of the team<br>
*/
public void increasePoints() {
++points;
}
public void decreasePoints() {
--points;
}
/**
* Cleanup the team and make it ready for adding players again<br>
*/
public void cleanMe() {
participatedPlayers.clear();
participatedPlayers = new HashMap<>();
points = 0;
}
public void onEventNotStarted() {
for (PlayerInstance player : participatedPlayers.values()) {
if (player != null) {
player.setEvent(null);
}
}
cleanMe();
}
/**
* Is given player in this team?<br><br>
*
* @return boolean: true if player is in this team, otherwise false<br>
*/
public boolean containsPlayer(int playerObjectId) {
boolean containsPlayer;
synchronized (participatedPlayers) {
containsPlayer = participatedPlayers.containsKey(playerObjectId);
}
return containsPlayer;
}
/**
* Returns the name of the team<br><br>
*
* @return String: name of the team<br>
*/
public String getName() {
return name;
}
/**
* Returns the coordinates of the team spot<br><br>
*
* @return int[]: team coordinates<br>
*/
public Point3D getCoords() {
return coordinates;
}
/**
* Returns the points of the team<br><br>
*
* @return short: team points<br>
*/
public short getPoints() {
return points;
}
/**
* Returns name and instance of all participated players in HashMap<br><br>
*
* @return Map<String , Player>: map of players in this team<br>
*/
public Map<Integer, PlayerInstance> getParticipatedPlayers() {
// Map<Integer, PlayerInstance> participatedPlayers = null;
synchronized (participatedPlayers) {
// this.participatedPlayers = participatedPlayers;
}
return participatedPlayers;
}
/**
* Returns player count of this team<br><br>
*
* @return int: number of players in team<br>
*/
public int getParticipatedPlayerCount() {
int participatedPlayerCount;
synchronized (participatedPlayers) {
participatedPlayerCount = participatedPlayers.size();
}
return participatedPlayerCount;
}
public int getAlivePlayerCount() {
int alivePlayerCount = 0;
ArrayList<PlayerInstance> toIterate = new ArrayList<>(participatedPlayers.values());
for (PlayerInstance player : toIterate) {
if (!player.isOnline() || player.getClient() == null || player.getEvent() == null) {
participatedPlayers.remove(player.getObjectId());
}
if (!player.isDead()) {
alivePlayerCount++;
}
}
return alivePlayerCount;
}
public int getHealersCount() {
int count = 0;
for (PlayerInstance player : participatedPlayers.values()) {
if (player.getClassId().getId() == 146) {
count++;
}
}
return count;
}
public PlayerInstance selectRandomParticipant() {
int rnd = Rnd.get(participatedPlayers.size());
int i = 0;
for (PlayerInstance participant : participatedPlayers.values()) {
if (i == rnd) {
return participant;
}
i++;
}
return null;
}
public void setName(String name) {
this.name = name;
}
public void setCoords(Point3D coords) {
coordinates = coords;
}
public Spawn getFlagSpawn() {
return flagSpawn;
}
public void setFlagSpawn(Spawn spawn) {
if (flagSpawn != null && flagSpawn.getLastSpawn() != null) {
flagSpawn.getLastSpawn().deleteMe();
flagSpawn.stopRespawn();
SpawnTable.getInstance().deleteSpawn(flagSpawn, false);
}
flagSpawn = spawn;
}
public int getFlagId() {
return flagId;
}
public void setVIP(PlayerInstance character) {
VIP = character;
}
public PlayerInstance getVIP() {
return VIP;
}
public boolean isAlive() {
return getAlivePlayerCount() > 0;
}
public Spawn getGolemSpawn() {
return golemSpawn;
}
public void setGolemSpawn(Spawn spawn) {
if (golemSpawn != null && golemSpawn.getLastSpawn() != null) {
golemSpawn.getLastSpawn().deleteMe();
}
golemSpawn = spawn;
}
public int getGolemId() {
return golemId;
}
}
<file_sep>/java/org/l2jmobius/gameserver/model/actor/instance/JukeBoxInstance.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.gameserver.model.actor.instance;
import org.l2jmobius.gameserver.data.xml.impl.RecipeData;
import org.l2jmobius.gameserver.enums.InstanceType;
import org.l2jmobius.gameserver.model.actor.Npc;
import org.l2jmobius.gameserver.model.actor.templates.NpcTemplate;
import org.l2jmobius.gameserver.model.holders.RecipeHolder;
import org.l2jmobius.gameserver.network.SystemMessageId;
import org.l2jmobius.gameserver.network.serverpackets.*;
import org.l2jmobius.gameserver.util.BuilderUtil;
/**
* @author Inia
*/
public class JukeBoxInstance extends Npc {
public JukeBoxInstance(NpcTemplate template) {
super(template);
setRandomAnimation(false);
setInstanceType(InstanceType.JukeBoxInstance);
}
private void playSound(PlayerInstance activeChar, String sound) {
if (activeChar.getInventory().getInventoryItemCount(5343, 0) > 0) {
activeChar.destroyItemByItemId("jukebox", 5343, 1, null, true);
final PlaySound snd = new PlaySound(1, sound, 0, 0, 0, 0, 0);
activeChar.sendPacket(snd);
activeChar.broadcastPacket(snd);
BuilderUtil.sendSysMessage(activeChar, "Playing " + sound + ".");
broadcastPacket(new SocialAction(this.getObjectId(), 1));
} else {
activeChar.sendMessage("You need a music ticket !");
}
}
@Override
public void onBypassFeedback(PlayerInstance player, String command) {
if (player == null) {
return;
}
if (command.startsWith("play")) {
String[] cmds = command.split(" ");
playSound(player, cmds[1]);
return;
}
if (command.startsWith("Chat")) {
if (command.substring(5) == null) {
showChatWindow(player);
return;
}
showChatWindow(player, Integer.valueOf(command.substring(5)));
} else {
super.onBypassFeedback(player, command);
}
}
@Override
public String getHtmlPath(int npcId, int value, PlayerInstance player) {
String pom;
if (value == 0) {
pom = Integer.toString(npcId);
} else {
pom = npcId + "-" + value;
}
return "data/html/jukebox/" + pom + ".htm";
}
@Override
public void showChatWindow(PlayerInstance player, int val) {
NpcHtmlMessage html = new NpcHtmlMessage(getObjectId());
html.setFile(player, getHtmlPath(getId(), val, player));
html.replace("%objectId%", String.valueOf(getObjectId()));
player.sendPacket(html);
}
}
<file_sep>/java/org/l2jmobius/commons/util/xml/XmlDocument.kt
package l2server.util.xml
import org.w3c.dom.Node
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
import javax.xml.parsers.DocumentBuilderFactory
/**
* @author Pere
*/
class XmlDocument {
val root: XmlNode
constructor(file: File) {
if (!file.exists()) {
throw FileNotFoundException("The following XML could not be loaded: " + file.absolutePath)
}
val stream = FileInputStream(file)
try {
root = load(stream)
} catch (e: Exception) {
throw RuntimeException("Failed to load XML file $file", e)
}
}
constructor(stream: InputStream) {
root = load(stream)
}
fun getChildren(): List<XmlNode> = root.getChildren()
private fun load(stream: InputStream): XmlNode {
val doc = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().parse(stream)
var baseNode: Node? = doc.firstChild
while (baseNode != null) {
if (baseNode.nodeType == Node.ELEMENT_NODE) {
return XmlNode(baseNode)
}
baseNode = baseNode.nextSibling
}
throw RuntimeException("Tried to load an empty XML document!")
}
companion object {
private val DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance()
init {
DOCUMENT_BUILDER_FACTORY.isValidating = false
DOCUMENT_BUILDER_FACTORY.isIgnoringComments = true
}
}
}
<file_sep>/config/Custom/ScreenWelcomeMessage.ini
# ---------------------------------------------------------------------------
# Welcome message
# ---------------------------------------------------------------------------
# Show screen welcome message on character login
# Default: False
ScreenWelcomeMessageEnable = True
# Screen welcome message text to show on character login if enabled
# ('#' for a new line, but message can have max 2 lines)
ScreenWelcomeMessageText = Join the discord for any question
# Show screen welcome message for x seconds when character log in to game if enabled
ScreenWelcomeMessageTime = 20
<file_sep>/java/org/l2jmobius/gameserver/events/instanced/EventPrize.java
package org.l2jmobius.gameserver.events.instanced;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.util.xml.XmlNode;
import java.util.ArrayList;
import java.util.List;
public class EventPrize {
protected final float chance;
protected final boolean dependsOnPerformance;
public EventPrize(XmlNode node) {
chance = node.getFloat("chance");
dependsOnPerformance = node.getBool("dependsOnPerformance", false);
}
public EventPrizeItem getItem() {
return null;
}
public static class EventPrizeItem extends EventPrize {
private final int id;
private final int min;
private final int max;
public EventPrizeItem(XmlNode node) {
super(node);
id = node.getInt("id");
min = node.getInt("min");
max = node.getInt("max");
}
public int getId() {
return id;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
@Override
public EventPrizeItem getItem() {
return this;
}
}
public static class EventPrizeCategory extends EventPrize {
private final List<EventPrizeItem> items = new ArrayList<>();
public EventPrizeCategory(XmlNode node) {
super(node);
for (XmlNode subNode : node.getChildren()) {
if (subNode.getName().equalsIgnoreCase("item")) {
items.add(new EventPrizeItem(subNode));
}
}
}
@Override
public EventPrizeItem getItem() {
float rnd = Rnd.get(100000) / 1000.0f;
float percent = 0.0f;
for (EventPrizeItem item : items) {
percent += item.getChance();
if (percent > rnd) {
return item;
}
}
return items.get(0);
}
}
public float getChance() {
return chance;
}
public boolean dependsOnPerformance() {
return dependsOnPerformance;
}
}
<file_sep>/java/org/l2jmobius/gameserver/gui/ServerGui.java
package org.l2jmobius.gameserver.gui;
import javax.swing.*;
import java.awt.*;
public class ServerGui {
private static JFrame frame;
//private JMenuBar menuBar = new JMenuBar();
//private JMenu fileMenu = new JMenu("File");
//private JMenu helpMenu = new JMenu("Help");
//private ActionListener menuListener = new MenuActionListener();
private static JTabbedPane tabPane = new JTabbedPane();
private static ConsoleTab consoleTab;
private static AdminTab adminTab;
private static CommandTab commandTab;
public void init() {
frame = new JFrame("L2 Server");
//Menu Bar Items
//File Menu
/*JMenuItem itemExit = new JMenuItem("Exit");
itemExit.setActionCommand("Exit");
itemExit.addActionListener(menuListener);
fileMenu.add(itemExit);
//Help
JMenuItem itemAbout = new JMenuItem("About");
itemAbout.setActionCommand("About");
itemAbout.addActionListener(menuListener);
helpMenu.add(itemAbout);
menuBar.add(fileMenu);
menuBar.add(helpMenu);
frame.setJMenuBar(menuBar);*/
// Console Tab
consoleTab = new ConsoleTab(true);
adminTab = new AdminTab();
commandTab = new CommandTab();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabPane.add("Console", consoleTab);
tabPane.add("Admin", adminTab);
tabPane.add("Command", commandTab);
//build the frame
frame.add(tabPane, BorderLayout.CENTER);
//add the window listeners
addListeners();
frame.setLocation(50, 50);
frame.setMinimumSize(new Dimension(930, 700));
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public JTabbedPane getTabPane() {
return tabPane;
}
private void addListeners() {
//Window Closing
/*frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent event)
{
close();
}
});*/
}
// MenuActions
/*public class MenuActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
String actionCmd = ev.getActionCommand();
if (actionCmd.equals("Exit"))
{
System.exit(0);
}
}
}*/
public static JFrame getMainFrame() {
return frame;
}
public static ConsoleTab getConsoleTab() {
return consoleTab;
}
public static AdminTab getAdminTab() {
return adminTab;
}
}
<file_sep>/java/org/l2jmobius/gameserver/events/instanced/EventConfig.java
package org.l2jmobius.gameserver.events.instanced;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.events.instanced.EventInstance.EventType;
import org.l2jmobius.gameserver.events.instanced.types.*;
import java.util.Random;
public class EventConfig {
private EventType type = EventType.TVT;
private EventLocation location = null;
private String[] teamNames = new String[4];
public EventConfig() {
selectEvent();
if (location.getTeamCount() == 4) {
while (selectTeamNames(Rnd.get(4))) {
}
} else {
while (!selectTeamNames(Rnd.get(4))) {
}
}
}
public EventConfig(boolean pvp) {
selectEvent();
while (pvp != isPvp()) {
selectEvent();
}
if (location.getTeamCount() == 4) {
while (selectTeamNames(Rnd.get(4))) {
}
} else {
while (!selectTeamNames(Rnd.get(4))) {
}
}
}
public boolean isType(EventType type) {
return this.type == type;
}
public EventType getType() {
return type;
}
public boolean isAllVsAll() {
return type == EventType.Survival || type == EventType.DeathMatch || type == EventType.KingOfTheHill || type == EventType.CursedBattle ||
type == EventType.StalkedSalkers || type == EventType.SimonSays;
}
public boolean needsClosedArena() {
return type == EventType.CaptureTheFlag || type == EventType.VIP || type == EventType.Survival || type == EventType.TeamSurvival ||
type == EventType.CursedBattle || type == EventType.StalkedSalkers;
}
public boolean spawnsPlayersRandomly() {
return type == EventType.Survival || type == EventType.DeathMatch || type == EventType.CursedBattle || type == EventType.StalkedSalkers ||
type == EventType.SimonSays;
}
public boolean needsRandomCoords() {
return spawnsPlayersRandomly() || type == EventType.LuckyChests;
}
public boolean hasNoLevelLimits() {
return type == EventType.LuckyChests || type == EventType.StalkedSalkers || type == EventType.SimonSays;
}
public boolean isPvp() {
return type == EventType.TVT || type == EventType.CaptureTheFlag || type == EventType.VIP || type == EventType.Survival ||
type == EventType.DeathMatch || type == EventType.TeamSurvival || type == EventType.CursedBattle;
}
public String getTeamName(int id) {
return teamNames[id];
}
public boolean selectTeamNames(int name) {
boolean dual = false;
switch (name) {
case 0:
teamNames[0] = "Blue";
teamNames[1] = "Red";
dual = true;
break;
case 1:
teamNames[0] = "Water";
teamNames[1] = "Fire";
teamNames[2] = "Earth";
teamNames[3] = "Wind";
break;
case 2:
teamNames[0] = "Winter";
teamNames[1] = "Autumn";
teamNames[2] = "Summer";
teamNames[3] = "Spring";
break;
case 3:
teamNames[0] = "Blue";
teamNames[1] = "Red";
teamNames[2] = "Yellow";
teamNames[3] = "Green";
}
return dual;
}
private void selectEvent() {
double[] chances = new double[]{
40.0, // TvT
40.0, // Capture the Flag
20.0, // Lucky Chests
0.0 // Simon Says
/*
5.0, // VIP TvT
9.0, // Survival
11.0, // Death Match
2.0, // King of the Hill
18.0, // Team Survival
0.0, // Cursed Battle
5.0, // Destroy the Golem
2.0, // Field Domination
2.0, // Stalked Stalkers
*/
};
double total = 0;
for (double chance : chances) {
total += chance;
}
double type = Rnd.nextDouble() * total;
for (int i = 0; i < chances.length; i++) {
type -= chances[i];
if (type < 0.0) {
this.type = EventType.values()[i];
break;
}
}
selectLocation();
}
public int randomBetween(int low, int high) {
Random r = new Random();
return r.nextInt(high-low) + low;
}
public EventLocation getLocation() {
return location;
}
public void setLocation(EventLocation location) {
this.location = location;
}
public void selectLocation() {
location = EventsManager.getInstance().getRandomLocation();
if (needsClosedArena() || needsRandomCoords()) {
while (location.getZone() == null) {
location = EventsManager.getInstance().getRandomLocation();
}
} else if (isType(EventType.KingOfTheHill)) {
while (!location.isHill()) {
location = EventsManager.getInstance().getRandomLocation();
}
}
}
public int getMaxTeamPlayers() {
return isAllVsAll() ? location.getMaxPlayers() : location.getMaxTeamPlayers();
}
public int getMinPlayers() {
return isAllVsAll() ? 2 : location.getTeamCount();
}
public EventInstance createInstance(int id) {
switch (type) {
case TVT:
return new TeamVsTeam(id, this);
case LuckyChests:
return new LuckyChests(id, this);
case CaptureTheFlag:
return new CaptureTheFlag(id, this);
case SimonSays:
return new SimonSays(id, this);
/*
case VIP:
return new VIPTeamVsTeam(id, this);
case DeathMatch:
return new DeathMatch(id, this);
case Survival:
return new Survival(id, this);
case KingOfTheHill:
return new KingOfTheHill(id, this);
case TeamSurvival:
return new TeamSurvival(id, this);
case CursedBattle:
return new CursedBattle(id, this);
case DestroyTheGolem:
return new DestroyTheGolem(id, this);
case FieldDomination:
return new FieldDomination(id, this);
case StalkedSalkers:
return new StalkedStalkers(id, this);
*/
}
return new TeamVsTeam(id, this);
}
public String getEventName() {
if (location == null) {
return "No event";
}
switch (type) {
case CaptureTheFlag:
if (location.getTeamCount() == 4) {
return "Four teams Capture the Flag";
}
return "Capture the Flag";
case VIP:
if (location.getTeamCount() == 4) {
return "VIP TvTvTvT";
}
return "VIP TvT";
case Survival:
return "Survival";
case DeathMatch:
return "Death Match";
case LuckyChests:
if (location.getTeamCount() == 4) {
return "Four teams Lucky Chests";
}
return "Lucky Chests";
case KingOfTheHill:
return "King of The Hill";
case TeamSurvival:
if (location.getTeamCount() == 4) {
return "Team Survival";
}
return "Team Survival";
case CursedBattle:
return "Cursed Battle";
case DestroyTheGolem:
if (location.getTeamCount() == 4) {
return "Four teams Destroy the Golem";
}
return "Destroy the Golem";
case FieldDomination:
if (location.getTeamCount() == 4) {
return "Four teams Field Domination";
}
return "Field Domination";
case StalkedSalkers:
return "Stalked Stalkers";
case SimonSays:
return "Simon Says";
default:
if (location.getTeamCount() == 4) {
return "TvTvTvT";
}
return "Team vs Team";
}
}
public String getEventLocationName() {
if (location == null) {
return "No event";
}
return location.getName();
}
public int getEventImageId() {
switch (type) {
case TVT:
return 20012;
case CaptureTheFlag:
return 20002;
case VIP:
return 20013;
case Survival:
return 20004;
case DeathMatch:
return 20009;
case KingOfTheHill:
return 20008;
case LuckyChests:
return 20001;
case TeamSurvival:
return 20005;
case CursedBattle:
return 20003;
case DestroyTheGolem:
return 20007;
case FieldDomination:
return 20006;
case StalkedSalkers:
return 20010;
case SimonSays:
return 20011;
}
return 0;
}
public String getEventString() {
if (location == null) {
return "No event";
}
String eventString;
switch (type) {
case CaptureTheFlag:
eventString = "Capture the Flag";
if (location.getTeamCount() == 4) {
eventString = "Four teams Capture the Flag";
}
break;
case VIP:
eventString = "VIP TvT";
if (location.getTeamCount() == 4) {
eventString = "VIP TvTvTvT";
}
break;
case Survival:
eventString = "Survival";
break;
case DeathMatch:
eventString = "Death Match";
break;
case LuckyChests:
eventString = "Lucky Chests";
if (location.getTeamCount() == 4) {
eventString = "Four teams Lucky Chests";
}
break;
case KingOfTheHill:
eventString = "King of The Hill";
break;
case TeamSurvival:
eventString = "Team Survival";
if (location.getTeamCount() == 4) {
eventString = "Four Teams Survival";
}
break;
case CursedBattle:
eventString = "Cursed Battle";
break;
case DestroyTheGolem:
eventString = "Destroy the Golem";
if (location.getTeamCount() == 4) {
eventString = "Four teams Destroy the Golem";
}
break;
case FieldDomination:
eventString = "Field Domination";
if (location.getTeamCount() == 4) {
eventString = "Four teams Field Domination";
}
break;
case StalkedSalkers:
eventString = "Stalked Stalkers";
break;
case SimonSays:
eventString = "Simon Says";
break;
default:
eventString = "Team vs Team";
if (location.getTeamCount() == 4) {
eventString = "TvTvTvT";
}
}
eventString += " at " + location.getName();
return eventString;
}
}
<file_sep>/data/scripts/handlers/itemhandlers/Deck.java
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package scripts.handlers.itemhandlers;
import org.l2jmobius.Config;
import org.l2jmobius.gameserver.cache.HtmCache;
import org.l2jmobius.gameserver.datatables.ItemTable;
import org.l2jmobius.gameserver.enums.DropType;
import org.l2jmobius.gameserver.handler.IItemHandler;
import org.l2jmobius.gameserver.model.actor.Npc;
import org.l2jmobius.gameserver.model.actor.Playable;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.model.holders.DropHolder;
import org.l2jmobius.gameserver.model.items.Item;
import org.l2jmobius.gameserver.model.items.instance.ItemInstance;
import org.l2jmobius.gameserver.model.stats.Stat;
import org.l2jmobius.gameserver.network.SystemMessageId;
import org.l2jmobius.gameserver.network.serverpackets.ActionFailed;
import org.l2jmobius.gameserver.network.serverpackets.NpcHtmlMessage;
import org.l2jmobius.gameserver.util.Util;
import java.text.DecimalFormat;
import java.util.List;
public class Deck implements IItemHandler
{
private static final int DROP_LIST_ITEMS_PER_PAGE = 10;
@Override
public boolean useItem(Playable playable, ItemInstance item, boolean forceUse)
{
if (!(playable instanceof PlayerInstance))
{
return false;
}
PlayerInstance player = (PlayerInstance) playable;
Object target = player.getTarget();
if (target == null || !(target instanceof Npc))
{
player.sendMessage("You should target a monster to see its drop list!");
return false;
}
Npc mob = (Npc) player.getTarget();
if (mob != null)
{
sendNpcDropList(player, mob, DropType.DROP, 1);
}
return true;
}
private void sendNpcDropList(PlayerInstance player, Npc npc, DropType dropType, int page)
{
final List<DropHolder> dropList = npc.getTemplate().getDropList(dropType);
if (dropList == null)
{
return;
}
int pages = dropList.size() / DROP_LIST_ITEMS_PER_PAGE;
if ((DROP_LIST_ITEMS_PER_PAGE * pages) < dropList.size())
{
pages++;
}
final StringBuilder pagesSb = new StringBuilder();
if (pages > 1)
{
pagesSb.append("<table><tr>");
for (int i = 0; i < pages; i++)
{
pagesSb.append("<td align=center><button value=\"" + (i + 1) + "\" width=20 height=20 action=\"bypass NpcViewMod dropList " + dropType + " " + npc.getObjectId() + " " + i + "\" back=\"L2UI_CT1.Button_DF_Calculator_Down\" fore=\"L2UI_CT1.Button_DF_Calculator\"></td>");
}
pagesSb.append("</tr></table>");
}
if (page >= pages)
{
page = pages - 1;
}
final int start = page > 0 ? page * DROP_LIST_ITEMS_PER_PAGE : 0;
int end = (page * DROP_LIST_ITEMS_PER_PAGE) + DROP_LIST_ITEMS_PER_PAGE;
if (end > dropList.size())
{
end = dropList.size();
}
final DecimalFormat amountFormat = new DecimalFormat("#,###");
final DecimalFormat chanceFormat = new DecimalFormat("0.00##");
int leftHeight = 0;
int rightHeight = 0;
final double dropAmountEffectBonus = player.getStat().getValue(Stat.BONUS_DROP_AMOUNT, 1);
final double dropRateEffectBonus = player.getStat().getValue(Stat.BONUS_DROP_RATE, 1);
final double spoilRateEffectBonus = player.getStat().getValue(Stat.BONUS_SPOIL_RATE, 1);
final StringBuilder leftSb = new StringBuilder();
final StringBuilder rightSb = new StringBuilder();
String limitReachedMsg = "";
for (int i = start; i < end; i++)
{
final StringBuilder sb = new StringBuilder();
final int height = 64;
final DropHolder dropItem = dropList.get(i);
final Item item = ItemTable.getInstance().getTemplate(dropItem.getItemId());
// real time server rate calculations
double rateChance = 1;
double rateAmount = 1;
if (dropType == DropType.SPOIL)
{
rateChance = Config.RATE_SPOIL_DROP_CHANCE_MULTIPLIER;
rateAmount = Config.RATE_SPOIL_DROP_AMOUNT_MULTIPLIER;
// also check premium rates if available
if (Config.PREMIUM_SYSTEM_ENABLED && player.hasPremiumStatus())
{
rateChance *= Config.PREMIUM_RATE_SPOIL_CHANCE;
rateAmount *= Config.PREMIUM_RATE_SPOIL_AMOUNT;
}
// bonus spoil rate effect
rateChance *= spoilRateEffectBonus;
}
else
{
if (Config.RATE_DROP_CHANCE_BY_ID.get(dropItem.getItemId()) != null)
{
rateChance *= Config.RATE_DROP_CHANCE_BY_ID.get(dropItem.getItemId());
}
else if (item.hasExImmediateEffect())
{
rateChance *= Config.RATE_HERB_DROP_CHANCE_MULTIPLIER;
}
else if (npc.isRaid())
{
rateChance *= Config.RATE_RAID_DROP_CHANCE_MULTIPLIER;
}
else
{
rateChance *= Config.RATE_DEATH_DROP_CHANCE_MULTIPLIER;
}
if (Config.RATE_DROP_AMOUNT_BY_ID.get(dropItem.getItemId()) != null)
{
rateAmount *= Config.RATE_DROP_AMOUNT_BY_ID.get(dropItem.getItemId());
}
else if (item.hasExImmediateEffect())
{
rateAmount *= Config.RATE_HERB_DROP_AMOUNT_MULTIPLIER;
}
else if (npc.isRaid())
{
rateAmount *= Config.RATE_RAID_DROP_AMOUNT_MULTIPLIER;
}
else
{
rateAmount *= Config.RATE_DEATH_DROP_AMOUNT_MULTIPLIER;
}
// also check premium rates if available
if (Config.PREMIUM_SYSTEM_ENABLED && player.hasPremiumStatus())
{
if (Config.PREMIUM_RATE_DROP_CHANCE_BY_ID.get(dropItem.getItemId()) != null)
{
rateChance *= Config.PREMIUM_RATE_DROP_CHANCE_BY_ID.get(dropItem.getItemId());
}
else if (item.hasExImmediateEffect())
{
// TODO: Premium herb chance? :)
}
else if (npc.isRaid())
{
// TODO: Premium raid chance? :)
}
else
{
rateChance *= Config.PREMIUM_RATE_DROP_CHANCE;
}
if (Config.PREMIUM_RATE_DROP_AMOUNT_BY_ID.get(dropItem.getItemId()) != null)
{
rateAmount *= Config.PREMIUM_RATE_DROP_AMOUNT_BY_ID.get(dropItem.getItemId());
}
else if (item.hasExImmediateEffect())
{
// TODO: Premium herb amount? :)
}
else if (npc.isRaid())
{
// TODO: Premium raid amount? :)
}
else
{
rateAmount *= Config.PREMIUM_RATE_DROP_AMOUNT;
}
}
// bonus drop amount effect
rateAmount *= dropAmountEffectBonus;
// bonus drop rate effect
rateChance *= dropRateEffectBonus;
}
sb.append("<table width=332 cellpadding=2 cellspacing=0 background=\"L2UI_CT1.Windows.Windows_DF_TooltipBG\">");
sb.append("<tr><td width=32 valign=top>");
sb.append("<button width=\"32\" height=\"32\" back=\"" + (item.getIcon() == null ? "icon.etc_question_mark_i00" : item.getIcon()) + "\" fore=\"" + (item.getIcon() == null ? "icon.etc_question_mark_i00" : item.getIcon()) + "\" itemtooltip=\"" + dropItem.getItemId() + "\">");
sb.append("</td><td fixwidth=300 align=center><font name=\"hs9\" color=\"CD9000\">");
sb.append(item.getName());
sb.append("</font></td></tr><tr><td width=32></td><td width=300><table width=295 cellpadding=0 cellspacing=0>");
sb.append("<tr><td width=48 align=right valign=top><font color=\"LEVEL\">Amount:</font></td>");
sb.append("<td width=247 align=center>");
final long min = (long) (dropItem.getMin() * rateAmount);
final long max = (long) (dropItem.getMax() * rateAmount);
if (min == max)
{
sb.append(amountFormat.format(min));
}
else
{
sb.append(amountFormat.format(min));
sb.append(" - ");
sb.append(amountFormat.format(max));
}
sb.append("</td></tr><tr><td width=48 align=right valign=top><font color=\"LEVEL\">Chance:</font></td>");
sb.append("<td width=247 align=center>");
sb.append(chanceFormat.format(Math.min(dropItem.getChance() * rateChance, 100)));
sb.append("%</td></tr></table></td></tr><tr><td width=32></td><td width=300> </td></tr></table>");
if ((sb.length() + rightSb.length() + leftSb.length()) < 16000) // limit of 32766?
{
if (leftHeight >= (rightHeight + height))
{
rightSb.append(sb);
rightHeight += height;
}
else
{
leftSb.append(sb);
leftHeight += height;
}
}
else
{
limitReachedMsg = "<br><center>Too many drops! Could not display them all!</center>";
}
}
final StringBuilder bodySb = new StringBuilder();
bodySb.append("<table><tr>");
bodySb.append("<td>");
bodySb.append(leftSb.toString());
bodySb.append("</td><td>");
bodySb.append(rightSb.toString());
bodySb.append("</td>");
bodySb.append("</tr></table>");
String html = HtmCache.getInstance().getHtm(player, "data/html/mods/NpcView/DropList.htm");
if (html == null)
{
LOGGER.warning(handlers.bypasshandlers.NpcViewMod.class.getSimpleName() + ": The html file data/html/mods/NpcView/DropList.htm could not be found.");
return;
}
html = html.replace("%name%", npc.getName());
html = html.replace("%dropListButtons%", getDropListButtons(npc));
html = html.replace("%pages%", pagesSb.toString());
html = html.replace("%items%", bodySb.toString() + limitReachedMsg);
Util.sendCBHtml(player, html);
}
private static String getDropListButtons(Npc npc)
{
final StringBuilder sb = new StringBuilder();
final List<DropHolder> dropListDeath = npc.getTemplate().getDropList(DropType.DROP);
final List<DropHolder> dropListSpoil = npc.getTemplate().getDropList(DropType.SPOIL);
if ((dropListDeath != null) || (dropListSpoil != null))
{
sb.append("<table width=275 cellpadding=0 cellspacing=0><tr>");
if (dropListDeath != null)
{
sb.append("<td align=center><button value=\"Show Drop\" width=100 height=25 action=\"bypass NpcViewMod dropList DROP " + npc.getObjectId() + "\" back=\"L2UI_CT1.Button_DF_Calculator_Down\" fore=\"L2UI_CT1.Button_DF_Calculator\"></td>");
}
if (dropListSpoil != null)
{
sb.append("<td align=center><button value=\"Show Spoil\" width=100 height=25 action=\"bypass NpcViewMod dropList SPOIL " + npc.getObjectId() + "\" back=\"L2UI_CT1.Button_DF_Calculator_Down\" fore=\"L2UI_CT1.Button_DF_Calculator\"></td>");
}
sb.append("</tr></table>");
}
return sb.toString();
}
}
| a6e807053a13921aa5b5b7c10b1eb6f853f812c4 | [
"HTML",
"Java",
"Kotlin",
"INI"
] | 32 | Java | Hl4p3x/tenkai-pow3 | 4873365a5409cbad0cf8dbaa771a46ee4a59d812 | 536b738ea5060b229ac903687cb79f43172425bc | |
refs/heads/main | <repo_name>nnsriram/Credit_Risk_Modelling<file_sep>/train.py
##########################################################
# The train.py file is used for training credit risk model
##########################################################
import pandas as pd
import numpy as np
from sklearn.externals import joblib
from sklearn.metrics import roc_auc_score
import pickle
from models import classifier_select
from preprocess import preprocess_split_train
np.random.seed(42)
import os
# train_data describes the path of the input file in the form of .csv
train_data = r'C:\Users\<NAME>\Downloads\ML_Artivatic_dataset\train_indessa.csv'
# path variable describes the folder to save the trained model
model_save_path = r'F:\models'
# preprocess the input data - the details of preprocessing are available in preprocess.py
# - input arguements : train_data variable
# - output : the entries in the .csv file are preprocessed and split into train and validation split
X_train, X_test, y_train, y_test = preprocess_split_train(train_data)
# Choice of the prediction algorithm: the choice variable could set from one of the options below
# Set 'Log_Reg' for Logistic Regression
# Set 'ADB_LR' for Boosted model with base model as Logistic Regression
# Set 'DT' for Decision Tree
# Set 'RF' for Random forest
# Set 'KNN' for K-Nearest Neighbours
# Set 'Ensemble' for ensemble of 3 networks: Log_reg, RF, KNN
choice = 'Log_Reg'
# classifier select function configures the model and returns it
# input arguements : choice of the algorithm
# output : returns the configured classifier
classifier = classifier_select(choice)
classifier.fit(X_train,y_train)
Y_pred = classifier.predict(X_test)
# Metrics - Accuracy and AUC-ROC score
print(choice)
accuracy = round(classifier.score(X_test, y_test) * 100, 2)
print("Accuracy = ", accuracy)
print("ROC = ", roc_auc_score(y_test, Y_pred))
# Save the model
filename = os.path.join(model_save_path, choice + '.sav')
joblib.dump(classifier, open(filename, 'wb'))
<file_sep>/preprocess.py
##########################################################
# The preprocess.py file is used for preprocessing the data which includes
# - cleaning the data
# - data transformations and scaling
##########################################################
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
import os
# preprocess_split_train: includes basic preprocessing operations on the training
# data and generates train and validation splits
# - input arguements : data_path - path to the train_data.csv file
# - output : returns train and validation splits
def preprocess_split_train(data_path):
if os.path.exists(data_path):
loan_df = pd.read_csv(data_path)
loan_df1 = pd.DataFrame.copy(loan_df)
# the features chosen below are qualitatively examined and inferred that they are not of significant importance
# for training
loan_df1.drop(["member_id", 'funded_amnt_inv', 'grade', 'emp_title', 'desc', 'title'], axis=1, inplace=True)
# features which contain more than 80% of null values are dropped
loan_df1.dropna(thresh=loan_df1.shape[0] * 0.2, how='all', axis=1, inplace=True)
# the features described below are inferred to categorical variables
colname1 = ['term', 'sub_grade', 'pymnt_plan', 'purpose', 'zip_code',
'delinq_2yrs', 'inq_last_6mths', 'mths_since_last_delinq', 'open_acc', 'pub_rec',
'total_acc', 'initial_list_status', 'collections_12_mths_ex_med', 'mths_since_last_major_derog',
'application_type', 'addr_state', 'last_week_pay', 'acc_now_delinq', 'batch_enrolled', 'emp_length',
'home_ownership', 'verification_status']
for k in loan_df1.keys():
if k in colname1:
# Categorical features which contain null values are replaced with most frequent entries
# in the respective columns
loan_df1[k].fillna(loan_df1[k].mode()[0], inplace=True)
else:
# Continuous features which contain null values are replaced with mean of the respective columns
loan_df1[k].fillna(loan_df1[k].mean(), inplace=True)
# X is the feature set and y is the label information
X = loan_df1.drop('loan_status', axis=1)
y = loan_df1['loan_status']
# the overall data is split into train and validation splits
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42, stratify=y)
le = {}
for x in colname1:
le[x] = LabelEncoder()
# Categorical variables are one-hot encoded
for x in colname1:
X_test[x] = le[x].fit_transform(X_test.__getattr__(x))
for x in colname1:
X_train[x] = le[x].fit_transform(X_train.__getattr__(x))
# All the features are scaled for uniform variance
scaler = StandardScaler()
scaler.fit_transform(X_train, y_train)
scaler.fit_transform(X_test, y_test)
else :
raise Exception('Data path does not exist')
return X_train, X_test, y_train, y_test
# preprocess_split_test: includes basic preprocessing operations required for the test data
# - input arguements : data_path - path to the train_data.csv file
# - output : returns preprocessed test data
def preprocess_test(data_path):
if os.path.exists(data_path):
loan_df = pd.read_csv(data_path)
loan_df1 = pd.DataFrame.copy(loan_df)
loan_df1.drop(["member_id", 'funded_amnt_inv', 'grade', 'emp_title', 'desc', 'title'], axis=1, inplace=True)
loan_df1.dropna(thresh=loan_df1.shape[0] * 0.2, how='all', axis=1, inplace=True)
colname1 = ['term', 'sub_grade', 'pymnt_plan', 'purpose', 'zip_code',
'delinq_2yrs', 'inq_last_6mths', 'mths_since_last_delinq', 'open_acc', 'pub_rec',
'total_acc', 'initial_list_status', 'collections_12_mths_ex_med', 'mths_since_last_major_derog',
'application_type', 'addr_state', 'last_week_pay', 'acc_now_delinq', 'batch_enrolled', 'emp_length',
'home_ownership',
'verification_status']
for k in loan_df1.keys():
if k in colname1:
loan_df1[k].fillna(loan_df1[k].mode()[0], inplace=True)
else:
loan_df1[k].fillna(loan_df1[k].mean(), inplace=True)
X_test = loan_df1
le = {} # create blank dictionary
for x in colname1:
le[x] = LabelEncoder()
for x in colname1:
X_test[x] = le[x].fit_transform(X_test.__getattr__(x))
scaler = StandardScaler()
scaler.fit_transform(X_test)
else:
raise Exception('Data path does not exist')
return X_test<file_sep>/README.md
# Credit Risk Modelling
This project describes the experimentation conducted with data collected over years for deciding whether a potential customer would default from paying back the load. The work describes appraoches based on machine learning for predicting the status of a loan. Different machine learning approaches are used in this study and AUC-ROC is considered as the metric of evaluation.
The approaches used for experimentation and metrics:
| Algorithm | AUC-ROC |
| :---: | :---: |
| Logistic Regression(LR) | 50.56 |
| Boosted Logistic Regression | 59.61 |
| Decision Tree | 73.45 |
| Random Forest(RF)| 73.45 |
| K-Nearest Neighbors(KNN) | 61.85 |
| Ensemble (LR,RF,KNN) | 62.7 |
To run the code clone the project
1. train.py is used for training - path to training data is required
2. test.py is used for inference - path to test data and trained model file required
Trained models for the above experiments are available at:
https://drive.google.com/file/d/1HLquUEZ0iQDWMneXlTP5gZ54MSmFhxX9/view?usp=sharing <file_sep>/models.py
##########################################################
# The models.py file is used for configuring a classifier
# based on the user's choice
##########################################################
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
# classifier_select: configures a classifier based on the choice
# - input arguements : choice of the classifier network
# - output : returns the configured classifier
def classifier_select(choice):
if choice == 'Log_Reg':
classifier = LogisticRegression()
elif choice == 'ADB_LR':
classifier = AdaBoostClassifier(base_estimator=LogisticRegression())
elif choice == 'DT':
classifier = DecisionTreeClassifier()
elif choice == 'RF':
classifier = RandomForestClassifier(501)
elif choice == 'KNN':
classifier = KNeighborsClassifier(n_neighbors=10)
elif choice == 'Ensemble':
estimators = []
model1 = LogisticRegression()
estimators.append(('log', model1))
model2 = RandomForestClassifier(501)
estimators.append(('rf', model2))
model3 = KNeighborsClassifier(n_neighbors=10)
estimators.append(('KNN', model3))
classifier = VotingClassifier(estimators)
else :
raise Exception('Invalid Classifier, please select a valid option from the list')
return classifier | 95bcbda839f44d9ba1f3836d2a2e6106d5090d60 | [
"Markdown",
"Python"
] | 4 | Python | nnsriram/Credit_Risk_Modelling | 8c98edf8de6e6bd0bbe11adc5ac70d34da34c8e7 | 57794cc15b3a78eeed9b3319bd50c7f83366e2f1 | |
refs/heads/master | <file_sep>TODO Items
** https://www.meteor.com/try/3
** Mobile export
*** Android
** Data Related
*** Create import script from a text file (mongoimport)
*** Create export script from mongodb (use mongodump)
*** Create script that reimports data from export file (use mongorestore)
<file_sep>
// flashcards = new Mongo.Collection('flashcards');
| e42b0b52e0f73ad51cd9ea5e219eb909281e904f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | caesargus/flashcard-app | 025ff11d35ebd6b4f1e456846ac2fdfeb8b53e41 | 0d0d9635929c3f311a77452d9121588177280b69 | |
refs/heads/master | <file_sep>gem 'sidekiq'
gem 'slim', '>= 1.3.0'
gem 'sinatra', '>= 1.3.0', :require => nil
gem 'sidekiq-status'
gem 'sidekiq-unique-jobs'
gem 'sidekiq-failures'
gem 'clockwork'
gem 'daemons'<file_sep>require 'sidekiq'
require 'sidekiq-status'
module RedmineSidekiq
class Configure
file = File.join(Rails.root, 'plugins/redmine_sidekiq/config/sidekiq.yml')
if File.exist?(file)
config = YAML.load_file(file)[Rails.env]
redis_conf = config['redis'].symbolize_keys
st_expire = config['status']['expiration'].to_i
else
st_expire = 30
end
Sidekiq.configure_server do |config|
config.redis = redis_conf if redis_conf
config.server_middleware do |chain|
chain.add Sidekiq::Status::ServerMiddleware, expiration: st_expire.minutes
end
end
Sidekiq.configure_client do |config|
config.redis = redis_conf if redis_conf
config.client_middleware do |chain|
chain.add Sidekiq::Status::ClientMiddleware
end
end
end
end
| eaf2846234c1864f9985e312dc67af5307ce1b5c | [
"Ruby"
] | 2 | Ruby | threeturn/redmine_sidekiq | 482ae4e7a7dcb1545a60c1e75d39bdfacf6e970f | 58aeec5faf496d527eadcf419662004791c9a208 | |
refs/heads/master | <file_sep>package com.black.fixedlength.manager;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Calendar;
import com.black.fixedlength.FLTConfig;
import com.black.fixedlength.annotation.Column;
import com.black.fixedlength.annotation.Record;
/**
* アノテーションを操作する処理をまとめたクラス
*
*/
public class FLTAnnotationManager {
/**
* 指定されたクラスの固定長幅を計算し、返却します。
* 指定するクラスには@インターフェースが実装されている必要があります。
*
* @param clazz @インターフェースが実装されいるクラス
* @return 固定長幅
*/
protected static <T> int getRecordSize(Class<T> clazz) {
Field[] fields = clazz.getDeclaredFields();
int length = 0;
for (Field field : fields) {
Column column = field.getAnnotation(Column.class);
if (column != null) {
length += column.length();
}
}
return length;
}
/**
* 指定されたクラスのレコード判定文字を取得します。
* 指定するクラスには{@code FLT}が実装されている必要があります。
*
* @param clazz @インターフェースが実装されいるクラス
* @return
*/
protected static <T> String getRecordCodeNum(Class<T> clazz) {
String ret = null;
Record annotation = clazz.getAnnotation(Record.class);
if (annotation != null) {
ret = annotation.recordCodeNum();
}
return ret;
}
/**
* 指定されたクラスに指定された文字から固定長の文字を設定します。
* 指定されたクラスに引数無しのコンストラクタが実装されている必要があります。
*
* @param conf 固定長形式情報
* @param clazz @インターフェースが実装されいるクラス
* @param str 格納する文字列
* @return 指定された{@code clazz}のインスタンス
* @throws InstantiationException 指定されたclazzが抽象クラス、インタフェース、配列クラス、プリミティブ型、またはvoidを表す場合、クラスが引数なしのコンストラクタを保持しない場合、あるいはインスタンスの生成がほかの理由で失敗した場合
* @throws IllegalAccessException {@code clazz}が対応していない場合
* @throws UnsupportedEncodingException 指定された文字セットがサポートされていない場合
* @throws IndexOutOfBoundsException 指定されたclazzまたは、指定されたstrのフォーマットが一致していない場合
* @throws ParseException 値の型変換に失敗した場合
*/
protected <T> T convertToEntity(FLTConfig conf, Class<T> clazz, String str) throws InstantiationException, IllegalAccessException, IndexOutOfBoundsException, UnsupportedEncodingException, ParseException {
T ret = (T) clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
int beginIndex = 0;
for (Field field : fields) {
field.setAccessible(true);
Column column = field.getAnnotation(Column.class);
if (column != null) {
int endIndex = beginIndex + column.length();
String value = subString(conf, str, beginIndex, endIndex);
value = conf.getTrimming() != null ? conf.getTrimming().trimming(value) : value;
field.set(ret, convert(value, field.getType(), conf));
beginIndex += column.length();
}
}
return ret;
}
/**
* 指定されたエンティティを固定長文字列に変換し、返却します。
*
* @param conf 固定長形式情報
* @param entity 変換元エンティティ
* @return 固定長文字列
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws UnsupportedEncodingException
*/
protected <T> String convertToFixedlength(FLTConfig conf, T entity) throws IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException {
String ret = "";
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Column column = field.getAnnotation(Column.class);
if (column != null) {
String value = convert(field.get(entity), conf);
int length = 0;
switch (conf.getFltType()) {
case BYTE :
length = column.length() - value.getBytes(conf.getCharCode()).length + value.length();
break;
case STRING :
length = column.length();
break;
default:
throw new IllegalArgumentException(String.format("Unknown enum tyoe %s", conf.getFltType()));
}
value = conf.getPaddingFormat(field.getType()).padding(value, length);
if (value == null) {
throw new IllegalArgumentException(String.format("Not setting PaddingFormat %s", entity.getClass()));
}
ret += value;
}
}
return ret;
}
/**
* 指定された文字列から固定長の文字列を抜き出します。
*
* @param conf 固定長形式情報
* @param str 抜き出し元の文字列
* @param beginIndex 開始インデックス(この値を含む)
* @param endIndex 終了インデックス(この値を含まない)
* @return 指定された部分文字列
* @throws UnsupportedEncodingException 指定された文字セットがサポートされていない場合
* @throws IndexOutOfBoundsException beginIndexが負であるか、endIndexがこのStringオブジェクトの長さより大きいか、あるいはbeginIndexがendIndexより大きい場合。
*/
private static String subString(FLTConfig conf, String str, int beginIndex, int endIndex) throws IndexOutOfBoundsException, UnsupportedEncodingException {
String ret = new String();
switch(conf.getFltType()) {
case BYTE :
byte[] bstr = str.getBytes(conf.getCharCode());
byte[] retBstr = new byte[endIndex - beginIndex];
for(int i = beginIndex; i < bstr.length; i++) {
retBstr[beginIndex - i] = bstr[i];
}
ret = new String(retBstr);
break;
case STRING :
ret = str.substring(beginIndex, endIndex);
break;
default:
throw new IllegalArgumentException(String.format("Unknown enum tyoe %s", conf.getFltType()));
}
return ret;
}
/**
* 指定された文字列を指定された型のオブジェクトへ変換して返します。<p>
* 指定された文字列が {@code null} や空文字列の場合に、どのような値が返されるかは実装に依存します。
* @param <T>
*
* @param str 変換する文字列
* @param type 変換する型
* @return 変換されたオブジェクト
* @throws ParseException 値の型変換に失敗した場合
* @throws IllegalArgumentException 変換に失敗した場合
*/
protected Object convert(String str, Class<?> type, FLTConfig conf) throws ParseException {
if (type == null) {
return null;
}
if (type == String.class) {
return str.toString();
} else if (type == int.class || type == Integer.class) {
return Integer.valueOf(str);
} else if (type == double.class|| type == Double.class ) {
return Double.valueOf(str);
} else if (type == long.class || type == Long.class) {
return Long.valueOf(str);
} else if (type == float.class || type == Float.class) {
return Float.valueOf(str);
} else if (type == byte.class || type == Byte.class) {
return Byte.valueOf(str);
} else if (type == char.class || type == Character.class) {
char[] chars = str.toCharArray();
return Character.valueOf(chars.length == 0 ? null : chars[0] );
} else if (type == short.class || type == Short.class) {
return Short.valueOf(str);
} else if (type == java.util.Date.class || type == java.sql.Date.class || type == Calendar.class || type == java.sql.Timestamp.class) {
if (conf.getDateFormat() == null) {
throw new IllegalArgumentException("The conversion date format is not set.");
}
if (type == java.util.Date.class) {
return conf.getDateFormat().parse(str);
} else if (type == java.sql.Date.class) {
return new java.sql.Date(conf.getDateFormat().parse(str).getTime());
} else if (type == Calendar.class) {
Calendar cal = Calendar.getInstance();
cal.setTime(conf.getDateFormat().parse(str));
return cal;
} else if (type == java.sql.Timestamp.class) {
return new java.sql.Timestamp(conf.getDateFormat().parse(str).getTime());
}
}
return null;
}
/**
* 指定されたobject型からString型へ変換し返却します。
*
* @param obj 変換を行うオブジェクト
* @param conf 固定長形式情報
* @return 文字列
*/
protected String convert(Object obj, FLTConfig conf) {
Class<?> type = obj.getClass();
if (type == String.class) {
return obj.toString();
} else if (type == int.class || type == Integer.class) {
return obj.toString();
} else if (type == double.class|| type == Double.class ) {
return obj.toString();
} else if (type == long.class || type == Long.class) {
return obj.toString();
} else if (type == float.class || type == Float.class) {
return obj.toString();
} else if (type == byte.class || type == Byte.class) {
return obj.toString();
} else if (type == char.class || type == Character.class) {
return obj.toString();
} else if (type == short.class || type == Short.class) {
return obj.toString();
} else if (type == java.util.Date.class || type == java.sql.Date.class || type == Calendar.class || type == java.sql.Timestamp.class) {
if (conf.getDateFormat() == null) {
throw new IllegalArgumentException("The conversion date format is not set.");
}
if (type == java.util.Date.class) {
return conf.getDateFormat().format(obj);
} else if (type == java.sql.Date.class) {
java.util.Date date = new java.util.Date(((java.sql.Date)obj).getTime());
return conf.getDateFormat().format(date);
} else if (type == Calendar.class) {
java.util.Date date = ((Calendar)obj).getTime();
return conf.getDateFormat().format(date);
} else if (type == java.sql.Timestamp.class) {
java.util.Date date = new java.util.Date(((java.sql.Timestamp)obj).getTime());
return conf.getDateFormat().format(date);
}
}
throw new IllegalArgumentException(String.format("Unknown convert type %s", type));
}
}
<file_sep>package com.black.fixedlength.format;
public interface PaddingFormat {
/**
* パディングのインタフェースです。
* 戻り値が既定の文字数(またはバイト数)でない場合エラーになります。
*
* @param param パディングを行う文字列
* @param length パディングが必要な文字数(バイト数の場合は穴埋めに必要な文字数)
* @return パディング済み文字列
*/
public String padding(String param, int length);
}
<file_sep>package com.black.fixedlength;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import com.black.fixedlength.manager.FLTEntityReader;
import com.black.fixedlength.manager.FLTEntityWriter;
/**
* 固定長ファイルの読み込み/書き込みを提供します。
*
*/
public class FLT {
/**
* 固定長ファイルを出力します。
* @param <T>
*
* @param conf 固定長形式情報
* @param outputPath 出力先ファイルパス
* @throws IOException
* @throws UnsupportedEncodingException
* @throws FileNotFoundException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static <T> void save(FLTConfig conf, Path outputPath, List<T> obj) throws FileNotFoundException, UnsupportedEncodingException, IOException, IllegalArgumentException, IllegalAccessException {
try (FLTEntityWriter entityWriter = new FLTEntityWriter(conf, outputPath)) {
for (T entity : obj) {
entityWriter.write(entity);
}
}
}
/**
* 固定長ファイルを読み込みます。
*
* @param conf 固定長形式情報
* @param clazz 格納先クラス
* @return 指定された{@code clazz}のインスタンスのList
* @throws IllegalAccessException 指定されたclazzが対応していない場合
* @throws InstantiationException 指定されたclazzが抽象クラス、インタフェース、配列クラス、プリミティブ型、またはvoidを表す場合、クラスが引数なしのコンストラクタを保持しない場合、あるいはインスタンスの生成がほかの理由で失敗した場合
* @throws IOException 入出力でエラーが発生した場合
* @throws ParseException 値の型変換に失敗した場合
*/
public static <T> List<T> load(FLTConfig conf,Path inputPath, Class<T> clazz)
throws InstantiationException, IllegalAccessException, IOException, ParseException {
List<T> ret = new ArrayList<T>();
try (FLTEntityReader<T> entityReader = new FLTEntityReader<>(conf, inputPath, clazz);) {
T line = null;
while ((line = entityReader.read()) != null) {
ret.add(line);
}
}
return ret;
}
/**
* 固定長ファイルを読み込みます。
*
* @param conf 固定長形式情報
* @param clazz 格納先クラス
* @return 指定された{@code clazz}のインスタンスのList
* @throws IllegalAccessException 指定されたclazzが対応していない場合
* @throws InstantiationException 指定されたclazzが抽象クラス、インタフェース、配列クラス、プリミティブ型、またはvoidを表す場合、クラスが引数なしのコンストラクタを保持しない場合、あるいはインスタンスの生成がほかの理由で失敗した場合
* @throws IOException 入出力でエラーが発生した場合
* @throws ParseException 値の型変換に失敗した場合
*/
public static <T> List<Object> load(FLTConfig conf,Path inputPath, Class<T> clazz, Class<?> headerClazz, Class<?> trailerClazz)
throws InstantiationException, IllegalAccessException, IOException, ParseException {
List<Object> ret = new ArrayList<Object>();
try (FLTEntityReader<T> entityReader = new FLTEntityReader<>(conf, inputPath, clazz);) {
T line = null;
if (headerClazz != null) {
Object obj = entityReader.getHeader(headerClazz);
if (obj == null) {
throw new IllegalArgumentException("Header does not exist.");
}
ret.add(obj);
}
while ((line = entityReader.read()) != null) {
ret.add(line);
}
if (trailerClazz != null) {
Object obj = entityReader.getTrailer(trailerClazz);
if (obj == null) {
throw new IllegalArgumentException("Trailer does not exist.");
}
ret.add(obj);
}
}
return ret;
}
}
<file_sep>package com.black.fixedlength.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 固定長文字列レコード定義
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface Record {
/**
* ヘッダ、データ、トレーラレコードかの判定に使用します。(前方一致)
*
* 指定されていない場合、判定を行いません。
* @return
*/
String recordCodeNum() default "";
}
<file_sep>package com.black.fixedlength.exception;
import java.io.IOException;
public class FixedLengthFormatException extends IOException {
public FixedLengthFormatException(String msg){
super(msg);
}
public FixedLengthFormatException(Throwable cause) {
super(cause);
}
public FixedLengthFormatException(String message, Throwable cause) {
super(message, cause);
}
}
<file_sep>package com.black.fixedlength.type;
/**
* 固定長の読み取り形式
*
*/
public enum FLTType {
/**
* バイト数
*/
BYTE
/**
* 文字数(桁数)
*/
, STRING
}
<file_sep>package com.black.fixedlength.format;
public class DefaultZeroPaddingFormatter implements PaddingFormat {
@Override
public String padding(String param, int length) {
return length == 0 ? param : String.format("%" + length + "s", param).replace(" ", "0");
}
}
<file_sep>package com.black.fixedlength.manager;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import com.black.fixedlength.FLTConfig;
public class FLTEntityWriter implements AutoCloseable {
private FLTConfig conf;
private FLTWriter writer;
private FLTAnnotationManager annotationManager;
/**
* 指定された固定長形式情報を使用して、構築するコンストラクタです。
*
* @param conf 固定長形式情報
* @param inputPath 読み込み先ファイルパス
* @param clazz データレコード格納先クラス
* @return 指定された{@code clazz}のインスタンス
* @throws FileNotFoundException ファイルが存在しないか、通常ファイルではなくディレクトリであるか、またはなんらかの理由で開くことができない場合。
* @throws UnsupportedEncodingException 指定された文字セットがサポートされていない場合
*/
public FLTEntityWriter(FLTConfig conf, Path outputPath)
throws FileNotFoundException, UnsupportedEncodingException {
this.conf = conf;
annotationManager = new FLTAnnotationManager();
// 指定された固定長形式情報を使用して、インスタンスを構築します。
writer = new FLTWriter(conf, outputPath);
}
/**
* 指定されたエンティティをファイルに固定長として書き込みます。
*
* @param entity 固定長として出力するエンティティクラス
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws IOException
*/
public <T> void write(T entity) throws IOException, IllegalArgumentException, IllegalAccessException {
if (entity == null) {
throw new IllegalArgumentException("Invalid argument specified.");
}
String fixedlength = annotationManager.convertToFixedlength(conf, entity);
writer.write(fixedlength, FLTAnnotationManager.getRecordSize(entity.getClass()));
}
/**
* 書き込み後の終了処理です。
* @throws IOException
*
*/
@Override
public void close() throws IOException {
writer.close();
}
}
<file_sep>package com.black.fixedlength.manager;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import com.black.fixedlength.FLTConfig;
import com.black.fixedlength.exception.FixedLengthFormatException;
public class FLTWriter implements AutoCloseable {
private FLTConfig conf;
private BufferedWriter writer;
/**
* 指定された固定長形式情報を使用して、構築するコンストラクタです。
*
* @param conf 固定長形式情報
* @param inputPath 書き込み先ファイルパス
* @throws FileNotFoundException ファイルが存在しないか、通常ファイルではなくディレクトリであるか、またはなんらかの理由で開くことができない場合。
* @throws UnsupportedEncodingException 指定された文字セットがサポートされていない場合
*/
public FLTWriter(FLTConfig conf, Path outputPath) throws FileNotFoundException, UnsupportedEncodingException {
if (conf == null || outputPath == null) {
throw new IllegalArgumentException("Invalid argument specified.");
}
this.conf = conf;
FileOutputStream input = new FileOutputStream(outputPath.toFile());
OutputStreamWriter stream = new OutputStreamWriter(input,conf.getCharCode());
this.writer = new BufferedWriter(stream);
}
/**
* 指定された固定長形式情報を使用して、構築するコンストラクタです。
*
* @param writer 書き込み用クラス
* @param conf 固定長形式情報
* @param inputPath 書き込み先ファイルパス
* @throws FileNotFoundException ファイルが存在しないか、通常ファイルではなくディレクトリであるか、またはなんらかの理由で開くことができない場合。
* @throws UnsupportedEncodingException 指定された文字セットがサポートされていない場合
*/
public FLTWriter(BufferedWriter writer, FLTConfig conf, Path outputPath) throws FileNotFoundException, UnsupportedEncodingException {
if (conf == null || outputPath == null) {
throw new IllegalArgumentException("Invalid argument specified.");
}
this.conf = conf;
this.writer = writer;
}
/**
* 指定された一行を書き込みます。
* 指定されているrecordSizeより数値が一致しない場合はIOExceptionをスローします。
*
* @throws IOException 入出力でエラーが発生した場合
*/
public void write(String str, int recordSize) throws IOException {
if (writer == null) {
throw new IllegalStateException("it is already closed.");
}
switch (conf.getFltType()) {
case BYTE :
byte[] byt = str.getBytes(conf.getCharCode());
if (byt.length != recordSize) {
throw new FixedLengthFormatException("The number of bytes in the record is not met.");
}
break;
case STRING :
default:
if (str.length() != recordSize) {
throw new FixedLengthFormatException("The number of characters in the record is not satisfied.");
}
break;
}
writer.write(str);
writer.newLine();
}
/**
* 書き込み後の終了処理です。
* @throws IOException 入出力でエラーが発生した場合
*/
@Override
public void close() throws IOException {
if (writer != null) {
writer.close();
writer = null;
}
}
}
| 08e87a9989c32f2fca05c583761a95338f068b97 | [
"Java"
] | 9 | Java | brackk/black-fixedlength | 57fce60cfc4ea8d4a454ff692b2e3de2a7efd41c | e2538a08c50ee9ccf648b5f5f82169a03806099b | |
refs/heads/master | <repo_name>VisualGMQ/Android<file_sep>/ContainerProvider/app/src/main/java/com/example/visualgmq/containerprovider/MainActivity.java
package com.example.visualgmq.containerprovider;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button diabutton = (Button)findViewById(R.id.dialbutton);
diabutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(MainActivity.this,"android.permission.CALL_PHONE") != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this,new String[]{"android.permission.CALL_PHONE"},1);
else
call();
}
});
}
private void call(){
try {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:17355481727"));
startActivity(intent);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String[] permission,int[] grantResults){
if(requestCode == 1)
if(permission.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
call();
}else{
Toast.makeText(MainActivity.this,"the permission haven't got",Toast.LENGTH_LONG);
}
}
}
<file_sep>/BoardCast/app/src/main/java/com/example/visualgmq/boardcast/MainActivity.java
package com.example.visualgmq.boardcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter1,intentFilter2;
private NetworkChangeBC networkChangeBC;
private SelfReceiver selfReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("com.self.action.SELF_BC");
sendBroadcast(intent);
}
});
networkChangeBC = new NetworkChangeBC();
intentFilter1 = new IntentFilter();
intentFilter1.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkChangeBC,intentFilter1);
intentFilter2 = new IntentFilter();
intentFilter2.addAction("com.self.action.SELF_BC");
selfReceiver = new SelfReceiver();
registerReceiver(selfReceiver,intentFilter2);
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(networkChangeBC);
unregisterReceiver(selfReceiver);
}
class NetworkChangeBC extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
ConnectivityManager connectionManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectionManager.getActiveNetworkInfo();
if(networkinfo!=null)
if(networkinfo.isAvailable())
Toast.makeText(context,"the Network is available!",Toast.LENGTH_SHORT).show();
else
Toast.makeText(context,"the Network is not avaliable!",Toast.LENGTH_SHORT).show();
}
}
class SelfReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context,"I have received the BroadCast",Toast.LENGTH_LONG).show();
}
}
}
<file_sep>/FileIO/app/src/main/java/com/example/visualgmq/fileio/MainActivity.java
package com.example.visualgmq.fileio;
import android.content.SharedPreferences.Editor;
import android.content.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
import java.io.*;
import java.sql.BatchUpdateException;
import java.util.*;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
private FileOutputStream fos;
private FileInputStream ios;
private BufferedWriter bw;
private BufferedReader br;
private String text;
@Override
//use simple file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button obutton1 = (Button)findViewById(R.id.obutton1);
obutton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
ios = openFileInput("test.txt");
br = new BufferedReader(new InputStreamReader(ios));
Toast.makeText(MainActivity.this,br.readLine(),Toast.LENGTH_LONG).show();
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
});
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
bw = new BufferedWriter(new OutputStreamWriter(fos));
EditText et = (EditText)findViewById(R.id.edittext);
text = et.getText().toString();
bw.write(text);
bw.close();
Toast.makeText(MainActivity.this,"the text has saved",Toast.LENGTH_SHORT).show();
}catch(IOException e){
e.printStackTrace();
}
}
});
Button bnext = (Button)findViewById(R.id.buttonnext);
bnext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,PrepActivity.class);
startActivity(intent);
}
});
}
} | 7e2fae1be4bbe8aa050488e67f6e6d86be79aa83 | [
"Java"
] | 3 | Java | VisualGMQ/Android | 536dc431396f70e710f3e7a298a2e0733eb52325 | 15403f59b692dc5a736cb9d8646401eb3d4d88d3 | |
refs/heads/master | <repo_name>Piper616/SaludRapanui-master<file_sep>/home/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.inicio, name='inicio'),
path('nosotros/', views.nosotros, name='nosotros'),
path('campañas/', views.campañas, name='campañas'),
path('contacto/', views.contacto, name='contacto'),
path('prueba/', views.prueba, name='prueba'),
]<file_sep>/home/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
def inicio(request):
return render(request,'home/inicio.html')
def nosotros(request):
return render(request,'home/nosotros.html')
def campañas(request):
return render(request,'home/campañas.html')
def contacto(request):
return render(request,'home/contacto.html')
def prueba(request):
return render(request,'home/prueba.html')
| 42cbf0ab81ff09a178bba67435734437a29fa7cb | [
"Python"
] | 2 | Python | Piper616/SaludRapanui-master | 5092c772289a4e26d543135441d924276d7be06b | 3f634189f72eb5ba55e95b94c4337b5c2264b70b | |
refs/heads/master | <repo_name>localidata/SPARQL-Interceptor<file_sep>/SPARQLInterceptor/src/tests/GenericTest.java
package tests;
import java.util.Collection;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.localidata.interceptor.Utils;
import com.localidata.queries.ListOfQueries;
import com.localidata.queries.QueryBean;
@RunWith(Parameterized.class)
public class GenericTest {
private QueryBean bean;
@Before
public void method() {
// set up method
}
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
// load the files as you want from the directory
// System.out.println("Parameters");
Utils.logConfLoad("log4j.properties");
ListOfQueries list = new ListOfQueries();
return Utils.generateData(list);
}
public GenericTest(QueryBean input) {
// constructor
this.bean = input;
}
@Test
public void test() {
// test
Utils.realTest(bean);
}
@After
public void tearDown() {
}
}<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/TaskConfig.java
package com.localidata.interceptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
public class TaskConfig {
private static Logger log = Logger.getLogger(TaskConfig.class);
private int time;
private ArrayList<Query> queryList;
private String usuario;
private String password;
private String destinos;
private String endpoint;
private String timelimit;
private String timeout;
private String petitionsBeforeReport;
public String getPetitionsBeforeReport() {
return petitionsBeforeReport;
}
public void setPetitionsBeforeReport(String petitionsBeforeReport) {
this.petitionsBeforeReport = petitionsBeforeReport;
}
public String getTimelimit() {
return timelimit;
}
public void setTimelimit(String timelimit) {
this.timelimit = timelimit;
}
public String getTimeout() {
return timeout;
}
public void setTimeout(String timeout) {
this.timeout = timeout;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public ArrayList<Query> getQueryList() {
return queryList;
}
public void setQueryList(ArrayList<Query> queryList) {
this.queryList = queryList;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getDestinos() {
return destinos;
}
public void setDestinos(String destinos) {
this.destinos = destinos;
}
public TaskConfig(ServletContextEvent evt) {
try {
Properties p = null;
JSONObject o = null;
if (evt==null){
p = Utils.leerProperties("conf.properties");
o = Utils.leerJSONFile("queries.json");
}else{
p = Utils.leerProperties(evt.getServletContext().getRealPath("/") + "/WEB-INF/conf.properties");
o = Utils.leerJSONFile(evt.getServletContext().getRealPath("/") + "/WEB-INF/queries.json");
}
time = Integer.parseInt(p.getProperty("time"));
usuario = p.getProperty("user");
password = <PASSWORD>("<PASSWORD>");
destinos = p.getProperty("emails");
endpoint = p.getProperty("endpoint");
timelimit=p.getProperty("timelimit");
timeout=p.getProperty("timeout");
petitionsBeforeReport=p.getProperty("petitionsBeforeReport");
JSONArray queries = (JSONArray) o.get("queries");
queryList = new ArrayList<Query>();
for (int i = 0; i < queries.size(); i++) {
JSONObject queryTemp = (JSONObject) queries.get(i);
Query q = new Query();
if (queryTemp != null) {
if (queryTemp.get("query") != null) {
q.setQuery((String) queryTemp.get("query"));
}
if (queryTemp.get("name") != null) {
q.setName((String) queryTemp.get("name"));
}
if (queryTemp.get("type") != null) {
q.setType(((Long) queryTemp.get("type")).longValue());
}
if (queryTemp.get("active") != null) {
q.setActive(((Long) queryTemp.get("active")).longValue());
}
queryList.add(q);
}
}
log.info("Config Loaded");
} catch (Exception e) {
log.error("Error loading configuration", e);
}
}
}
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/TaskMethod.java
package com.localidata.interceptor;
import java.util.ArrayList;
import org.apache.log4j.Logger;
public class TaskMethod {
private static Logger log = Logger.getLogger(TaskMethod.class);
private TaskConfig config;
private ArrayList<ResponseQuery> responseList;
private int petitionsOK;
private int timelimit;
private int petitionsBeforeReport;
private SendMailSSL emailSender;
public TaskConfig getConfig() {
return config;
}
public void setConfig(TaskConfig config) {
this.config = config;
}
public ArrayList<ResponseQuery> getResponseList() {
return responseList;
}
public void setResponseList(ArrayList<ResponseQuery> responseList) {
this.responseList = responseList;
}
public int getPetitionsOK() {
return petitionsOK;
}
public void setPetitionsOK(int petitionsOK) {
this.petitionsOK = petitionsOK;
}
public int getTimelimit() {
return timelimit;
}
public void setTimelimit(int timelimit) {
this.timelimit = timelimit;
}
public int getPetitionsBeforeReport() {
return petitionsBeforeReport;
}
public void setPetitionsBeforeReport(int petitionsBeforeReport) {
this.petitionsBeforeReport = petitionsBeforeReport;
}
public SendMailSSL getEmailSender() {
return emailSender;
}
public void setEmailSender(SendMailSSL emailSender) {
this.emailSender = emailSender;
}
public void testQueries() {
for (Query q : config.getQueryList()) {
if (q.getActive() == 1) {
long startTime = System.currentTimeMillis();
log.info("Throw " + q.getName());
int size = 0;
if (q.getType() == 1)
size = SPARQLQuery.Query(q.getQuery(), config.getEndpoint());
else
size = SPARQLQuery.URIQuery(config.getEndpoint() + "?" + q.getQuery());
long endTime = System.currentTimeMillis();
double duration = (endTime - startTime);
duration = duration / 1000.0;
responseList.add(new ResponseQuery(duration, size, q.getName()));
}
}
ArrayList<ResponseQuery> errors = new ArrayList<ResponseQuery>();
for (ResponseQuery rq : responseList) {
if ((rq.getSize() <= 0) || rq.getTime() > timelimit) {
errors.add(rq);
}
}
if (errors.size() > 0) {
petitionsOK = 0;
String bodyMail = "There are errors in the next Query/ies" + System.getProperty("line.separator");
bodyMail += System.getProperty("line.separator");
bodyMail += Utils.responseArrayToString(errors);
// log.info(bodyMail);
emailSender.send(config.getUsuario(), config.getPassword(), config.getDestinos(), "Some of the queries do not work", bodyMail);
} else {
petitionsOK++;
if (petitionsOK == petitionsBeforeReport + 1) {
petitionsOK = 0;
String bodyMail = "There aren't errors after " + petitionsBeforeReport + " times" + System.getProperty("line.separator");
bodyMail += System.getProperty("line.separator");
bodyMail += "The last test are theses: " + System.getProperty("line.separator");
bodyMail += System.getProperty("line.separator");
bodyMail += Utils.responseArrayToString(responseList);
// log.info(bodyMail);
emailSender.send(config.getUsuario(), config.getPassword(), config.getDestinos(), "The queries work fine", bodyMail);
}
log.info(Utils.responseArrayToString(responseList));
log.info(petitionsOK + " tests passed");
}
errors.clear();
responseList.clear();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
<file_sep>/README.md
SPARQL Interceptor
=================
This is a simple Web-based tool where you can test and monitor SPARQL queries over a set of SPARQL endpoints. The tool executes a set of queries periodically over a SPARQL endpoint. All these parameters (queries, SPARQL endpoint, periodicity of evaluations) can be configured, as explained below.
If any query fails (that is, it provides a timeout or zero results), it will send an e-mail, using a Google account to the e-mail account that is also specified in the configuration file. This may be improved in the feature to look for specific results.
When the whole process of testing queries is OK for all queries, a counter increases. When the counter is equal to a value (that can be also configured) the tool sends an e-mail with a report of the last execution time.
The tool is developed in Java, as a Java Application and as a Web Application (without a graphic enviroment).
The queries.json file is a deprecated version of the unit test file, as it was initially used when Jenkins was not used for this purpose. It is maintained in the repository for provenance reasons.
#JUnit Test of SPARQL queries
We added a new funcionality, with junit tests (mvn test) you can execute queries and test the number of rows that the query return match with a specific number.
If you want to add a query, you must create a file inside the "queries" directory with this format:
\# Description: A description of the query
\# Result: number of results
Query line 1
Query line 2
....
Query line n
## Example
```
# Description: Venues with no cell associated to them. It should be zero.
# Result: 0
SELECT ?venue (COUNT(DISTINCT ?cell) AS ?numberCells)
WHERE
{
?venue a dul:Place .
?venue locationOnt:cell ?cell
} GROUP BY ?venue HAVING (COUNT(DISTINCT ?cell) = 0)
```
## Be carefull with Jena
Jena execute these queries, you must test your queries in Jena first, maybe you put a 0 but Jena return -1, or the query is ok in Virtuoso but fails here.
# Deploy on Jenkins
Here I describe the steps to desploy this project without use any source control.
Usually the Jenkins home is: /var/lib/jenkins
When you are on Jenkins, you must add a new Item:
- Add the name of the project
- Select Maven project and click the "ok" button
Then you must do this steps:
- Build the Project at least once, (it will fail), but Jenkins will create the structure jenkins/workspace/PROJECTNAME/
- Copy the project files to jenkins/workspace/PROJECTNAME/
- Build again and configure appropriately
Back to the Jenkins project configuration:
In Build Triggers:
- Check Build periodically and write in the Schedule a cron expression to configure it. For example: "H/30 * * * *"
In Build:
- Root POM: must be "pom.xml"
- Goals and options: I write "clean package test"
And that´s enought.
With this configuration, Jenkins will run the test every 30 minutes.
#Configuration
This tool has three configuration files:
##log4j.properties
The log configuration, you can see this [tutorial](http://www.tutorialspoint.com/log4j/log4j_configuration.htm) to learn how to configure it.
##conf.properties
This file has the following attributes to configure:
####time
The periodicity of every query execution cycle.
Example: 3600000
####emails
List of email address of the people that you want to send an e-mail for errors or reports.
Example: <EMAIL>, <EMAIL>, <EMAIL>
####user
The Google account used to send e-mails.
Example: <EMAIL>
####password
The Google account password.
Example: <PASSWORD>
####endpoint
The SPARQL Endpoint where the queries will be executed.
Example: http://dev.3cixty.com/sparql
####timeout
The max-time for a timeout error, expressed in milliseconds.
Example: 60000
####timelimit
The max-time for an alert via e-mail, in seconds.
Example: 30
####petitionsBeforeReport
The number of OK petitions before sending a report with the last execution time.
Example: 24
##queries.json
Here you configure all the queries that you want to test. The file is an array that contains all the queries.
Each query has four attributes:
####type
The type can be 1 or 2.
The type 1 uses "the JENA parser" and only works when the query is standard. If you use fucntions like "bif:intersect” from Virtuoso you cannot use this type.
The type 2 uses the URL to send the query. You must begin with que "query" parameter, and the output format must be "json".
####active
Active can be 0 or 1. The query is only executed if active is set to 1.
####name
The name of the query
####query
That is the query.
If the type is 1 you must write the query as follows:
select distinct ?Concept where {[] a ?Concept} LIMIT 100
If the type is 2 you must write it as follows:
query=select+distinct+%3FConcept+where+{[]+a+%3FConcept}+LIMIT+100&format=json&timeout=0&debug=on
Be carefull with the double quote, here it must be a single quote.
#Running
##JAR
You can run the jar with this command:
java -jar SPARQLInterceptor.jar
You can stop pressing CONTROL + C.
If you are on LINUX you can add the " &" at the end of the command to run it in background:
java -jar SPARQLInterceptor.jar &
You can stop it with a kill command:
kill -9 pid
But you need to know the PID of the process. With this command you can obtain the pids of all Java processes
jps
##WAR
You can run SPARQL Interceptor deploying the war on servlet container.
Where the webapp is deployed you can edit the configuration files inside the WEB-INF folder.
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/TaskProcess.java
package com.localidata.interceptor;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class TaskProcess {
private static Logger log = Logger.getLogger(TaskProcess.class);
private static Timer timer;
private static TimerTask timerTask;
private static int timelimit=30;
private TaskConfig config;
private ArrayList<ResponseQuery> responseList;
private SendMailSSL emailSender = new SendMailSSL();
private int petitionsOK=0;
private int petitionsBeforeReport=100;
private TaskMethod method;
public TaskProcess()
{
responseList=new ArrayList <ResponseQuery>();
config=new TaskConfig(null);
SPARQLQuery.timeOut=Integer.parseInt(config.getTimeout());
timelimit=Integer.parseInt(config.getTimelimit().trim());
petitionsBeforeReport=Integer.parseInt(config.getPetitionsBeforeReport().trim());
method=new TaskMethod();
method.setConfig(config);
method.setEmailSender(emailSender);
method.setPetitionsBeforeReport(petitionsBeforeReport);
method.setPetitionsOK(petitionsOK);
method.setResponseList(responseList);
method.setTimelimit(timelimit);
}
public void init()
{
timerTask = new TimerTask() {
public void run() {
log.info("Init process");
method.testQueries();
log.info("End proccess");
}
};
timer = new Timer();
// timer.schedule(this, 0, 10*60*1000); // 10 minutes
timer.schedule(timerTask, 0, config.getTime());
}
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
TaskProcess t=new TaskProcess();
t.init();
}
}
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/Utils.java
package com.localidata.interceptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.localidata.queries.ListOfQueries;
import com.localidata.queries.QueryBean;
public class Utils {
private static Logger log = Logger.getLogger(Utils.class);
public static Properties leerProperties(String ruta) throws FileNotFoundException, IOException {
Properties propiedades = new Properties();
propiedades.load(new FileInputStream(ruta));
return propiedades;
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject leerJSONFile(String file) throws IOException, ParseException {
FileInputStream fis = new FileInputStream(file);
BufferedReader rd = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONParser parser = new JSONParser();
JSONObject obj = null;
obj = (JSONObject) parser.parse(jsonText);
return obj;
}
public static String procesaURL(String urlCadena, int timeout) throws IOException,MalformedURLException {
URL url = new URL(urlCadena);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(timeout);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
StringBuffer contenidoURL=new StringBuffer("");
BufferedReader in = null;
//Volcamos lo recibido al buffer
in = new BufferedReader(new InputStreamReader(huc.getInputStream()));
// Transformamos el contenido del buffer a texto
String inputLine;
if (in!=null){
while ((inputLine = in.readLine()) != null)
{
contenidoURL.append(inputLine+"\n");
}
in.close();
}
return contenidoURL.toString();
}
public static String responseArrayToString(ArrayList<ResponseQuery> errors) {
String body="";
for (ResponseQuery rq:errors)
{
body+= rq.getName()+":"+System.getProperty("line.separator");
body+= "\tNumber of results: "+rq.getSize()+System.getProperty("line.separator");
body+= "\tExecution time: "+rq.getTime()+ " seconds"+System.getProperty("line.separator");
body+= System.getProperty("line.separator");
}
return body;
}
public static String getQueryFromGitHub(String url) {
StringBuffer sb = new StringBuffer();
HttpURLConnection httpConnection =null;
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
String output;
while ((output = responseBuffer.readLine()) != null) {
sb.append(output + System.getProperty("line.separator"));
}
} catch (MalformedURLException e) {
log.error("Error with the URI: " + url );
log.error(e);
} catch (IOException e) {
log.error("IOError: " + url);
log.error(e);
}finally{
httpConnection.disconnect();
}
return sb.toString();
}
public static boolean logConfLoad(String path) {
File logProperties = new File(path);
if (!logProperties.exists()) {
System.out.println("log4j.properties not found. Please generate a log4j.properties.");
return false;
} else {
PropertyConfigurator.configure(path);
return true;
}
}
public static String readFile(String file) throws IOException {
FileInputStream fis = new FileInputStream(file);
BufferedReader rd = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return jsonText;
}
public static void realTest(QueryBean bean) {
if (bean.getCompareType().equals(QueryBean.EQUAL)) {
if (bean.getExpectedResult() != bean.getResultSize()) {
writeData(bean);
}
assertEquals(bean.getExpectedResult(), bean.getResultSize());
}else if (bean.getCompareType().equals(QueryBean.GREATER)) {
if (bean.getResultSize() <= bean.getExpectedResult()) {
writeData(bean);
}
assertTrue( bean.getResultSize() > bean.getExpectedResult());
}else if (bean.getCompareType().equals(QueryBean.LESS)) {
if (bean.getResultSize() >= bean.getExpectedResult()) {
writeData(bean);
}
assertTrue( bean.getResultSize() < bean.getExpectedResult());
}
}
public static void writeData(QueryBean bean) {
System.out.println(bean.getDescription());
System.out.println("");
System.out.println("Http Query:");
System.out.println("");
System.out.println(bean.getHttpQuery());
System.out.println("");
System.out.println("Query:");
System.out.println("");
System.out.println(bean.getQuery());
}
public static Collection<Object[]> generateData(ListOfQueries list) {
Collection<Object[]> data = new ArrayList<Object[]>();
for (QueryBean bean : list.getQueryList()) {
Object[] arg1 = new Object[] { bean };
data.add(arg1);
}
return data;
}
public static boolean checkURL(String url) {
HttpURLConnection connection;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
return false;
}
} catch (Exception e) {
//log.error("Error testing URL",e);
return false;
}
return true;
}
public static String watch(String url) {
StopWatch watch = new StopWatch();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String r=dateFormat.format(new Date());
boolean ok=false;
try {
watch.start();
ok=checkURL(url);
} catch (Exception e) {
e.printStackTrace();
} finally {
watch.stop();
}
if (ok)
r+=","+watch.getTime();
else
r+=",0";
return r;
}
public static void main(String[] args) {
String json="http://jsonpdataproxy.appspot.com/?url=http://sandbox-ckan.localidata.com/dataset/e5b37d9a-f551-4375-872e-a9fad5be6c8b/resource/dcae2eab-7ea5-4966-850b-7695979e7c69/download/recurso.csv";
System.out.println(watch(json));
}
}
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/Task.java
package com.localidata.interceptor;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.File;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.Timer;
public class Task implements ServletContextListener {
private static Logger log = Logger.getLogger(Task.class);
private static Timer timer;
private static TimerTask timerTask;
private static int timelimit=30;
private TaskConfig config;
private ArrayList<ResponseQuery> responseList;
private SendMailSSL emailSender = new SendMailSSL();
private int petitionsOK=0;
private int petitionsBeforeReport=100;
private TaskMethod method;
private void initLogs(ServletContextEvent evt) {
String log4jLocation = evt.getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "log4j.properties";
ServletContext sc = evt.getServletContext();
File ficheroLogProperties = new File(log4jLocation);
if (ficheroLogProperties.exists()) {
System.out.println("Initializing log4j with: " + log4jLocation);
PropertyConfigurator.configure(log4jLocation);
responseList=new ArrayList <ResponseQuery>();
} else {
System.err.println("*** " + log4jLocation + " file not found, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}
}
public void contextInitialized(final ServletContextEvent evt) {
initLogs(evt);
config=new TaskConfig(evt);
SPARQLQuery.timeOut=Integer.parseInt(config.getTimeout());
timelimit=Integer.parseInt(config.getTimelimit().trim());
petitionsBeforeReport=Integer.parseInt(config.getPetitionsBeforeReport().trim());
method=new TaskMethod();
method.setConfig(config);
method.setEmailSender(emailSender);
method.setPetitionsBeforeReport(petitionsBeforeReport);
method.setPetitionsOK(petitionsOK);
method.setResponseList(responseList);
method.setTimelimit(timelimit);
timerTask = new TimerTask() {
public void run() {
log.info("Init process");
method.testQueries();
log.info("End proccess");
}
};
timer = new Timer();
// timer.schedule(this, 0, 10*60*1000); // 10 minutes
timer.schedule(timerTask, 0, config.getTime());
}
public void contextDestroyed(ServletContextEvent evt) {
timer.cancel();
}
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
log.info("Ready to rock");
}
} | 8531fb733a22f60d5a8ba9735547ce8d5747921a | [
"Markdown",
"Java"
] | 7 | Java | localidata/SPARQL-Interceptor | 763e26f3ca8bb8145290d1c7ecc0c62abd45f8de | e8df9502190b34ed6ba37534d434b6c1f13573c2 | |
refs/heads/master | <file_sep>import time
import board
import adafruit_lis3dh
#altered to show alt readings
# Software I2C setup:
import bitbangio
i2c = bitbangio.I2C(board.SCL, board.SDA)
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c)
# Set range of accelerometer (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G).
lis3dh.range = adafruit_lis3dh.RANGE_2_G
# Loop forever printing accelerometer values
while True:
# Read accelerometer values (in m / s ^ 2). Returns a 3-tuple of x, y,
# z axis values.
x, y, z = lis3dh.acceleration
print('x = {}G, y = {}G, z = {}G'.format(1-(x / 9.806), 1-(y / 9.806), 1-(z / 9.806))
# Small delay to keep things responsive but give time for interrupt processing.
time.sleep(0.1)<file_sep>set pswd = mangonada
sudo chown quintosol2 /dev/ttyUSB0 $pswd
<file_sep>//network config
#include "config.h"
AdafruitIO_Feed *input = io.feed("state");
//analog acc reqs
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>
//for software SPI
#define LIS3DH_CLK 13
#define LIS3DH_MISO 12
#define LIS3DH_MOSI 11
//for hardware & software SPI
#define LIS3DH_CS 10
Adafruit_LIS3DH lis = Adafruit_LIS3DH();
#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif
//variables for three axis
int io; int state;
int ax; int ay; int az;
int bx; int by; int bz;
int nAn; int fox; int rabbit; int duck; int dinner;
void setup() {
// start the serial connection
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(115200);
while (!Serial);
if (! lis.begin(0x18)) { // change this to 0x19 for alternative i2c address
Serial.println("Couldnt start");
while (1);
}
//connect to net
Serial.println("Connecting to Adafruit IO");
io.connect();
Serial.println();
// wait for a connection
while(io.status() < AIO_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println(io.statusText());
//setting range for sensor, reccomend 2G at first
lis.setRange(LIS3DH_RANGE_4_G); // 2, 4, 8 or 16 G!
Serial.print("Range = "); Serial.print(2 << lis.getRange());
Serial.println("G");
}
void loop(){
io.run();
nAn = 200;
io = 0;
while (io < 10){
// grab the one state of the acc
lis.read();
state = 0;
//input ->save(state);
ax = lis.x; ay = lis.y; az = lis.z;
//get new number to be compared against
delay(250);
lis.read();
bx = lis.x; by = lis.y; bz = lis.z;
//FOX FOX FOX FOX FOX FOX FOX FOX FOX FOX FOX FOX
if(abs(bx - ax) <= nAn){
fox = 0; //not moving
}
else{
fox = 1; //still moving
}
//DUCK DUCK DUCK DUCK DUCK DUCK DUCK DUCK DUCK DUCK
if(abs(bx - ax) <= nAn){
fox = 0; //not moving
}
else{
fox = 1; //still moving
}
//RABBIT RABBIT RABBIT RABBIT RABBIT RABBIT RABBIT
if(abs(bx - ax) <= nAn){
fox = 0; //not moving
}
else{
fox = 1; //still moving
}
dinner = fox + rabbit + duck;
//DINNER DINNER DINNER DINNER DINNER DINNER DINNER DINNER DINNER DINNER
if (dinner > 0){
io =0;
// Serial.println("Counter: ");
Serial.println(io);
}
else{
io++;
// Serial.println("Counter: ");
Serial.println(io);
}
io = abs(io);
delay(500);
}
if(io >= 10){
Serial.println("The Laundry is Done!!!");
SaveState(1);
return;
}
delay(1000);
SaveState(0);
}
void SaveState(int state){
input->save(state);
}
Boolean Movement(int r1, int r2){
return (abs(r2 -r1) <= nAn);
}
<file_sep>Washer Machine Remote Monitoring 2016/17
This project has been developed for being able to use an Adafruit Huzzah Microcontroller along with an 3-axis accelerometer
I developed this after being frustrated with living in the fourth floor of my university dorm room and going downstairs to realize that my laundry had not finished only
The way it functions is by taking readings from the LIS3DH Accelerometer Module during a set interval of measure
After the entire wash cycle has completed the board will compare the data to previous measurments and determine if it is done
Once the Microcontroller has determined that the wash is done it will transmit to the io.adafruit website where there is a feed that monitors the output of the board
The method I decided to go with notifying the user that the laundry is done is by integrating an IFTTT applet that monitor that feed and from there an array of things can be triggered to notify the user such as sms message, google/apple calendar integration
| 076e2f6101c61eabaa5809686a3fc126d69ac224 | [
"Markdown",
"C",
"Python",
"C++"
] | 4 | Python | jaimeprojects/w1 | 9c15cf427dc9ffac623b64f1c0cf974295e0db0b | 88ebdd22a06e55edf152b98eadfee5e64ee56b8b | |
refs/heads/master | <repo_name>Shrinks99/tomesh2<file_sep>/build.md
---
layout: mkdownpage
title: Build A Node
parent: Get Involved
order: 1
---
The following instructions will help you set up an encrypted mesh network on Raspberry Pi's. It takes about 15 minutes to set up a node with the Pi 3. Obviously, to have a mesh you will need more than one node.
Many models of Orange Pi hardware running [Armbian](https://www.armbian.com/) are also supported. The same installation steps can be followed, except you would flash the SD card with Armbian instead of Raspbian. See [Hardware Table](#hardware-table) for the full list of supported hardware.
## Set Up
1. Make sure you have the following items:
* Raspberry Pi Zero, 1, 2, 3 (Pi 3 recommended), or for advanced users other [compatible hardware](#hardware-table)
* An SD card that works with the Pi
- * **Optional:** A USB WiFi adapter with [802.11s Mesh Point](https://github.com/o11s/open80211s/wiki/HOWTO) support, such as the [TP-LINK TL-WN722N](http://www.tp-link.com/en/products/details/TL-WN722N.html) or [Toplinkst TOP-GS07](https://github.com/tomeshnet/documents/blob/master/technical/20170208_mesh-point-with-topgs07-rt5572.md)
1. Flash the SD card with [Raspbian Stretch Lite](https://www.raspberrypi.org/downloads/raspbian/).
1. Create an empty file named **ssh** to enable SSH when the Pi boots:
```
$ touch /path/to/sd/boot/ssh
```
1. Plug the SD card and USB WiFi adapter into the Pi.
1. Plug the Pi into your router, so it has connectivity to the Internet. SSH into the Pi with `ssh <EMAIL>` and password **<PASSWORD>**.
**Optional:** There are other ways to connect, such as connecting the Pi to your computer and sharing Internet to it. Or if you have multiple Pi's connected to your router, find its IP with `nmap -sn 192.168.X.0/24` (where 192.168.X is your subnet) and SSH to the local IP assigned to the Pi you want to address `ssh [email protected]`.
1. In your SSH session, run `passwd` and change your login password. It is very important to choose a strong password so others cannot remotely access your Pi.
1. Run the following, then let the installation complete. After about 5 minutes the Pi will reboot:
```
$ wget https://raw.githubusercontent.com/tomeshnet/prototype-cjdns-pi/master/scripts/install && chmod +x install && ./install
```
The installation script can also install many optional features such as distributed applications and network analysis tools that are useful but non-essential to run a node. You can use flags to selectively enable them, or use the following command to install all optional features:
```
$ wget https://raw.githubusercontent.com/tomeshnet/prototype-cjdns-pi/master/scripts/install && chmod +x install && WITH_MESH_POINT=true WITH_WIFI_AP=true WITH_IPFS=true WITH_PROMETHEUS_NODE_EXPORTER=true WITH_PROMETHEUS_SERVER=true WITH_GRAFANA=true WITH_H_DNS=true WITH_H_NTP=true WITH_FAKE_HWCLOCK=true WITH_EXTRA_TOOLS=true ./install
```
## Optional Features
| Feature Flag | HTTP Service Port | Description |
| :------------------------------ | :--------------------------------------------- | :---------- |
| `WITH_MESH_POINT` | None | Set to `true` if you have a suitable USB WiFi adapter and want to configure it as a 802.11s Mesh Point interface. |
| `WITH_WIFI_AP` | None | Set to `true` if you have a Raspberry Pi 3 and want to configure the on-board WiFi as an Access Point. The default configuration routes all traffic to the Ethernet port `eth0`. |
| `WITH_IPFS` | **80**: HTTP-to-IPFS gateway at `/ipfs/HASH` | Set to `true` if you want to install [IPFS](https://ipfs.io). |
| `WITH_PROMETHEUS_NODE_EXPORTER` | **9100**: Node Exporter UI | Set to `true` if you want to install [Prometheus Node Exporter](https://github.com/prometheus/node_exporter) to report network metrics. |
| `WITH_PROMETHEUS_SERVER` | **9090**: Prometheus Server UI | Set to `true` if you want to install [Prometheus Server](https://github.com/prometheus/prometheus) to collect network metrics. *Requires Prometheus Node Exporter.* |
| `WITH_GRAFANA` | **3000**: Grafana UI (login: admin/admin) | Set to `true` if you want to install [Grafana](https://grafana.com) to display network metrics. *Requires Prometheus Server.* |
| `WITH_H_DNS` | None | Set to `true` if you want to use Hyperboria-compatible DNS servers: `fc4d:c8e5:9efe:9ac2:8e72:fcf7:6ce8:39dc` and `fc6e:691e:dfaa:b992:a10a:7b49:5a1a:5e09` |
| `WITH_H_NTP` | None | Set to `true` if you want to use a Hyperboria-compatible NTP server: `fc4d:c8e5:9efe:9ac2:8e72:fcf7:6ce8:39dc` |
| `WITH_FAKE_HWCLOCK` | None | Set to `true` if you want to force hwclock to store its time every 5 minutes. |
| `WITH_EXTRA_TOOLS` | None | Set to `true` if you want to install non-essential tools useful for network analysis: vim socat oping bmon iperf3 |
If you are connected to the WiFi Access Point, all HTTP services are available via `http://10.0.0.1:PORT` as well as the cjdns IPv6. To connect with the cjdns address, first note your node's fc00::/8 address from `status`, then navigate to `http://[fcaa:bbbb:cccc:dddd:eeee:0000:1111:2222]:PORT` from your browser.
## Check Status
1. Give the Pi about 15 seconds to reboot and SSH back into it. You should find the status of your mesh node automatically printed. You can also print this anytime by running `status`.
1. Verify that **cjdns Service** is active, and **Mesh Interface** (if applicable). The **NODE** section should display a single IPv6 address, that's the identity of your Pi in the cjdns mesh. The **PEERS** section should indicate a list of IPv6 addresses that are active peers to your node. This list will be empty, until you have another nearby node with the same set up.
## Network Benchmark
You can benchmark the network throughput with more than one node. Let's name our two Pi's **Hillary** and **Friend**.
1. SSH to Friend and note its IPv6.
1. Run `iperf3 -s` to start listening. Do not end the SSH session.
1. In another Terminal session, SSH to Hillary and run `iperf3 -c FRIEND_IPV6`. You should start seeing Hillary sending encrypted packets to her Friend. See [phillymesh/cjdns-optimizations](https://github.com/phillymesh/cjdns-optimizations) for expected throughput.
## Update & Uninstall
To uninstall the services, run `./prototype-cjdns-pi/scripts/uninstall`.
If you are updating, run the same uninstall script, but keep all configuration files and data directories when prompted, remove the **prototype-cjdns-pi** directory along with the **install** script, then repeat the last installation step.
## Experimental Support for Orange Pi
We are adding support for [Orange Pi](http://www.orangepi.org/) boards and have tested with the [Orange Pi Zero (Armbian nightly)](https://dl.armbian.com/orangepizero/nightly/), [Orange Pi One (Armbian nightly)](https://dl.armbian.com/orangepione/nightly/), and [Orange Pi Lite (Armbian nightly)](https://dl.armbian.com/orangepilite/nightly/). Instead of flashing Raspbian, start with the Armbian nightly images linked above, then follow the same installation steps as the Raspberry Pi.
## Hardware Table
List of tested hardware:
| Hardware | Base OS | [CJDNS Benchmark](https://github.com/phillymesh/cjdns-optimizations) (salsa20/poly1305, switching) | USB | Ethernet | Notes |
| :-------------------------|:----------------|:---------------------------------------------------------------------------------------------------|:----|:---------|:---------|
| Raspberry Pi 3 | [Raspbian Lite](https://www.raspberrypi.org/downloads/raspbian/) | 350k, 100k | 2 | 10/100 | |
| Raspberry Pi 2 | [Raspbian Lite](https://www.raspberrypi.org/downloads/raspbian/) | 150k, 50k | 2 | 10/100 | |
| Raspberry Pi 1 A+ | [Raspbian Lite](https://www.raspberrypi.org/downloads/raspbian/) | 35k, - | 1 | None | |
| Raspberry Pi 1 B+ | [Raspbian Lite](https://www.raspberrypi.org/downloads/raspbian/) | 35k, - | 2 | 10/100 | |
| Raspberry Pi Zero | [Raspbian Lite](https://www.raspberrypi.org/downloads/raspbian/) | 68k, 30k | 1* | None | *Need OTG Cable |
| Orange Pi Lite | [Armbian Nightly](https://dl.armbian.com/orangepilite/nightly/) | 198k, 76k | 2 | None | |
| Orange Pi One | [Armbian Nightly](https://dl.armbian.com/orangepione/nightly/) | 198k, 76k | 1 | 10/100 | |
| Orange Pi Zero | [Armbian Nightly](https://dl.armbian.com/orangepizero/nightly/) | 148k, 56k | 1 (+2*) | 10/100 | *Additional USB available via headers |
| Orange Pi Zero Plus 2 H5 | [Armbian Nightly](https://dl.armbian.com/orangepizeroplus2-h5/nightly/) | 142k, 92K | 0 (+2*) | None | *USB available via headers |
## Development
You can install from a specific tag or branch, such as `develop`, with:
```
$ wget https://raw.githubusercontent.com/tomeshnet/prototype-cjdns-pi/develop/scripts/install && chmod +x install && TAG_PROTOTYPE_CJDNS_PI=develop ./install
```
If you are developing on a forked repository, such as `me/prototype-cjdns-pi`, then:
```
$ wget https://raw.githubusercontent.com/me/prototype-cjdns-pi/develop/scripts/install && chmod +x install && GIT_PROTOTYPE_CJDNS_PI="https://github.com/me/prototype-cjdns-pi.git" TAG_PROTOTYPE_CJDNS_PI=develop ./install
```
To add a new module, use **scripts/ipfs/** as an example to:
* Create a `WITH_NEW_MODULE` tag
* Create **scripts/new-module/install** and **scripts/new-module/uninstall**
* Make corresponding references in the main **install**, **install2**, **status**, **uninstall** files
## Notes
* Your computer can be a node too! It will mesh with the Pi's over your router. See the [cjdns repository](https://github.com/cjdelisle/cjdns) on how to set this up.
* Original plan for this repository and early benchmark results are available in [the doc folder](https://github.com/tomeshnet/prototype-cjdns-pi/blob/master/docs/).
<file_sep>/js/map.js
var map = null;
var infowindow = null;
var markers = [];
var currentNodeListURL;
var circle = null;
function initialize() {
//Current Node URL with random bits to make sure it doesnt get cached
currentNodeListURL = document.getElementById('nodeURL').value + '?ramd=' + new Date();
//Set options based on check box positions
var filterActive = document.getElementById('chkActive').checked;
var filterProposed = document.getElementById('chkProposed').checked;
var zoomGroup = document.getElementById('chkGroup').checked;
//Prepare default view and create map
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(43.698136, -79.397593),
mapTypeId: google.maps.MapTypeId.ROADMAP,
fullscreenControl: false,
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
}
};
infowindow = new google.maps.InfoWindow({
content: 'holding...'
});
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
//Reset markers array
markers = undefined;
markers = [];
//Pull and process node url
$.getJSON(currentNodeListURL, function (data) {
var nodeVisible;
//loop through each node
for (var key in data) {
var results = data[key];
//console.log(results);
nodeVisible = 1; //Default all nodes to visible
//Adjust visibility based on value and option variable
if (results['status'] == 'active' && !filterActive) nodeVisible = 0;
if (results['status'] == 'proposed' && !filterProposed) nodeVisible = 0;
if (nodeVisible) {
//prepare location point
var lat = results['latitude'];
var lng = results['longitude'];
var myNodeLatLng = new google.maps.LatLng(lat, lng);
var myNodeName = results['name'];
//Call function to create (or update) marker
var newNode = addMarker(map, results, myNodeName, myNodeLatLng);
//If new node was created (rather then updated) add it to the marker array
if (newNode)
markers.push(newNode);
}
}
//Clustering code to group markers that are very close together untill you zoom in (if option enabled)
if (zoomGroup) {
var mcOptions = {
gridSize: 20,
maxZoom: 15,
imagePath: '/images/map/m'
};
var mc = new MarkerClusterer(map, markers, mcOptions);
}
});
}
//Find a marker witth a specific lat lng and dir combo. Used so that we dont create a new marker but rather add info to the existing one.
function findMarker(lat, lng, dir) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].position.lat() == lat &&
markers[i].position.lng() == lng &&
markers[i].direction == dir) {
return markers[i];
}
}
return undefined;
}
//Tries to find marker that already exists and updates it otherwise creates a new one
function addMarker(map, nodeResult, name, location) {
//Specify the colour of the marker based on the status
var nodeColor;
if (nodeResult['status'] == 'active') {
nodeColor = 'green';
}
if (nodeResult['status'] == 'proposed') {
nodeColor = 'grey';
}
//Default to OMNI icon if no direction is given
var ArrowDirection = 'omni';
//If direction is given set it to the correct direction
if (nodeResult['cardinalDirection'] != null) ArrowDirection = nodeResult['cardinalDirection'];
if (nodeResult['cardinalDirectionAntenna'] != null) ArrowDirection = nodeResult['cardinalDirectionAntenna'];
//Return formatted date for display
var formattedDate = function () {
var date = new Date(nodeResult['dateAdded']);
var options = { year: 'numeric', month: 'long', day: 'numeric' };
return date.toLocaleDateString('en-US', options);
};
var nodeStatus = nodeResult['status'].charAt(0).toUpperCase() + nodeResult['status'].slice(1);
//Prepare the detail information for the marker
var Description = '';
Description = '<div class="markerPop">';
Description += '<h1>' + name + '</h1>';
Description += '<p>Status: ' + nodeStatus + '</p>';
if (nodeResult['cardinalDirection']) Description += '<p>Direction: ' + nodeResult['cardinalDirection'] + '</p>';
if (nodeResult['cardinalDirectionAntenna']) Description += '<p>Antenna Direction: ' + nodeResult['cardinalDirectionAntenna'] + '</p>';
if (nodeResult['floor']) Description += '<p>Floor: ' + nodeResult['floor'] + '</p>';
if (nodeResult['IPV6Address']) Description += '<p>IPV6: ' + nodeResult['IPV6Address'] + '</p>';
Description += '<p>Added: ' + formattedDate() + '</p>';
Description += '</div>';
//Check to see if the currenty direction,lat,lng combo exists
var marker = findMarker(location.lat(), location.lng(), ArrowDirection);
//Prepare the image used to display the direction arrow and node color
var IMG = '/images/map/arrow-' + ArrowDirection.toLowerCase().replace(' ', '') + '-' + nodeColor + '.png';
//If marker does not exists in position and direction, create it
if (marker == undefined) {
//Establish anchor point based on direction of arrow so arrow images dont overlap each other so that they dont fully overlap
var x = 16;
var y = 16;
switch (ArrowDirection) {
case 'North':
case 'North East':
case 'North West':
y = 32;
break;
case 'South':
case 'South East':
case 'South West':
y = 0;
break;
}
switch (ArrowDirection) {
case 'East':
case 'North East':
case 'South East':
x = 0;
break;
case 'West':
case 'North West':
case 'South West':
x = 32;
break;
}
var imageAnchor = new google.maps.Point(x, y);
//Create a new marker
marker = new google.maps.Marker({
position: location,
map: map,
title: name,
icon: {
url: IMG,
anchor: imageAnchor
},
direction: ArrowDirection,
html: Description
});
//Add listener to the marker for click
google.maps.event.addListener(marker, 'click', function () {
//Code adds a circle to identiy selected marker and
//Maybe even present a possible range
if (typeof infowindow != 'undefined') infowindow.close();
infowindow.setContent(this.html);
infowindow.open(map, this);
if (circle) {
circle.setMap(null);
}
// Add circle overlay and bind to marker
circle = new google.maps.Circle({
map: map,
radius: 40, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
});
//listeer to close window
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
});
//Returns marker to identify it was created not modified
return marker;
//If marker already exists in direction and position, just add more information to the existing one.
} else {
if (marker.icon.url != IMG) {
//Promot Scacked Marker is new node is better then the previous
//IE: if inactive and active in same macker make sure node color is green
//Update marker color if an active node exists in the "stack"
var markerLevel = 0;
if (marker.icon.url.search('-red.png') > 0) markerLevel = 1;
if (marker.icon.url.search('-green.png') > 0) markerLevel = 2;
var requestLevel = 0;
if (IMG.search('-red.png') > 0) requestLevel = 1;
if (IMG.search('-green.png') > 0) requestLevel = 2;
if (requestLevel > markerLevel) {
marker.icon.url = IMG;
}
}
//Update marker
marker.html = marker.html + Description;
return undefined;
}
}
/*******************
Custom Marker Code
********************
Functions that deal with dialog box interaction
including GeoCoding and JSON Generation
*/
var customMarker = undefined;
//Plot new marker from entered coordinates
function addCustomMarker() {
var lng = document.getElementById('customMarkerLng').value;
var lat = document.getElementById('customMarkerLat').value;
if (customMarker) {
customMarker.setPosition(new google.maps.LatLng(lat, lng));
} else {
var location = new google.maps.LatLng(lat, lng);
customMarker = new google.maps.Marker({
position: location,
map: map,
title: 'New Location',
draggable: true
});
//Event for marker after it has been dropped (end of drag and drop)
google.maps.event.addListener(customMarker, 'dragend', function () {
document.getElementById('customMarkerLng').value = customMarker.getPosition().lng();
document.getElementById('customMarkerLat').value = customMarker.getPosition().lat();
customMarkerGenerateJSON(); //Regenerate json data in case your looking at the json screen
});
}
map.setCenter(new google.maps.LatLng(lat, lng));
}
//Attempt to GeoCode the marker based on an address
function customMarkerGeoCode() {
var address = document.getElementById('customMarkerAddress').value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == 'OK') {
document.getElementById('customMarkerLng').value = results[0].geometry.location.lng();
document.getElementById('customMarkerLat').value = results[0].geometry.location.lat();
map.setCenter(results[0].geometry.location);
addCustomMarker(document.getElementById('customMarkerLat').value, document.getElementById('customMarkerLng').value);
$('div#customMarkerGeoCodeDiv').hide();
$('div#customMarkerLocationDiv').show();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function customMarkerShowJsonDialog() {
$('div#customMarkerJSONDiv').show();
$('div#customMarkerLocationDiv').hide();
customMarkerGenerateJSON();
}
//Updates the text for the JSON data on the JSON screen
function customMarkerGenerateJSON() {
var lng = document.getElementById('customMarkerLng').value;
var lat = document.getElementById('customMarkerLat').value;
var floor = document.getElementById('customMarkerFloor').value;
var dir = document.getElementById('customMarkerDirection').value;
var name = document.getElementById('customMarkerName').value;
var currentJSONDate = (new Date()).toJSON();
var sJSON = '<div class="box-header"><h2>JSON for node</h2></div><pre style="white-space: pre;margin-bottom:10px;"> {\n' +
' "name": "' + name + '",\n' +
' "latitude": ' + lat + ',\n' +
' "longitude":' + lng + ',\n' +
' "cardinalDirection": "' + dir + '",\n' +
' "floor": ' + floor + ',\n' +
' "status": "proposed",\n' +
' "dateAdded": "' + currentJSONDate + '"\n' +
' }\n</pre>';
document.getElementById('customMarkerJSONDiv').innerHTML = sJSON + '<input type="button" value="Start Over" onclick="clearWindows();" />';
}
function GeoLocationBrowser() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showGeoLocatedPosition);
} else {
alert('Geolocation is not supported by this browser.');
}
}
function showGeoLocatedPosition(position) {
document.getElementById('customMarkerLng').value = position.coords.longitude;
document.getElementById('customMarkerLat').value = position.coords.latitude;
addCustomMarker();
}
function clearWindows() {
//$("div.customMarker").hide();
$('div#customMarkerLocationDiv').hide();
$('div#customMarkerJSONDiv').hide();
$('div#customMarkerGeoCodeDiv').show();
$('div#customMarkerAddress').show();
document.getElementById('customMarkerLng').value = -79.397593;
document.getElementById('customMarkerLat').value = 43.678136;
document.getElementById('customMarkerFloor').value = '';
document.getElementById('customMarkerDirection').value = '';
}
//Option Window Code
function ShowAdvanced(what) {
if (what.innerHTML=='+Show Advanced') {
$('div#customAdvacned').show();
what.innerHTML='-Hide Advanced';
} else {
$('div#customAdvacned').hide();
what.innerHTML='+Show Advanced';
}
}
//Expand Option Window For Mobile
function optionExpand() {
if ($('#mapOptions').hasClass('FullHeight')) {
$('#mapOptions').removeClass('FullHeight');
} else {
$('#mapOptions').addClass('FullHeight');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<file_sep>/js/mapstyle.js
var mapStyle = [
{
"elementType": "geometry.fill",
"stylers": [
{
"weight": 2
}
]
},
{
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#9c9c9c"
}
]
},
{
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
},
{
"elementType": "labels.text",
"stylers": [
{
"color": "#120b2c"
},
{
"visibility": "on"
},
{
"weight": 0.5
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#120b2c"
}
]
},
{
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#ffffff"
}
]
},
{
"featureType": "administrative",
"elementType": "geometry",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative.neighborhood",
"stylers": [
{
"color": "#ffffff"
},
{
"visibility": "off"
}
]
},
{
"featureType": "administrative.neighborhood",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#00ffff"
},
{
"visibility": "off"
}
]
},
{
"featureType": "landscape",
"stylers": [
{
"color": "#f2f2f2"
}
]
},
{
"featureType": "landscape",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#fffbe9"
}
]
},
{
"featureType": "poi",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"stylers": [
{
"saturation": -100
},
{
"lightness": 45
}
]
},
{
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#ec948b"
},
{
"weight": 1
}
]
},
{
"featureType": "road",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#292343"
}
]
},
{
"featureType": "road",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#fffbe9"
},
{
"weight": 1.5
}
]
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit.line",
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit.line",
"elementType": "labels.text",
"stylers": [
{
"weight": 0.5
}
]
},
{
"featureType": "water",
"stylers": [
{
"color": "#46bcec"
},
{
"visibility": "on"
}
]
},
{
"featureType": "water",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#9fd8d0"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#070707"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#ffffff"
}
]
}
];
<file_sep>/news.md
---
title: News
layout: mkdownpage
---
# Ubiquiti Winter Test
#### 2017-12-16
The test was to place a short-term permanent link between two balconies through the cold winter season to test the resilience of the node and gather data.
## Deployment on 16 December 2017
Two Ubiquiti LBE-5AC-23 devices were placed on balconies with direct line-of-sight between them:
The distance between the two nodes is approximately **375 m**. At that distance the antennas are almost not visible to the naked eye. This made pointing the antennas a bit of a guessing game. A signal strength of about **-40 dBm** was established.

## Node Construction
The radios were mounted on an ABS pipe stuck to a cinder block for support:


Each Ubiquiti device had an Orange Pi Zero with a 5 GHz TOP-GS07 radio as a companion cjdns device. These devices were connected to the Ubiquiti device via ethernet cable. The Ubiqiti was configured as PTP with network set to Bridge mode.
On one end of the link, the Orange Pi Zero and PoE connector were placed inside the apartment with the flat ethernet cable sliding under the balcony weather stripping and door, while the Ubiquiti device was left outside.
One the other side of the link, the Orange Pi Zero was placed in a dollar store tupperware container plugged into outdoor power outlets. The cables came out the bottom of the container, and the container was taped shut with the opening angled downward.

The latter node meshed over WiFi and cjdns to another node located indoors. That indoor node in turn meshed with an Internet-enabled Atom computer with WiFi capabilities. This provided a path to Hyperborea and the Internet.
## Orange Pi Zero Node-to-node Speed Test
At signal strength of about -40 dBm, the following speeds were obtained from iperf3 tests:
### Clear IPv4
```
[ ID] Interval Transfer Bandwidth Retr
[ 4] 0.00-60.00 sec 661 MBytes 92.5 Mbits/sec 106 sender
[ 4] 0.00-60.00 sec 661 MBytes 92.4 Mbits/sec receiver
```
### cjdns
```
[ ID] Interval Transfer Bandwidth Retr
[ 4] 0.00-10.00 sec 61.1 MBytes 51.3 Mbits/sec 94 sender
[ 4] 0.00-10.00 sec 60.5 MBytes 50.7 Mbits/sec receiver
```
## Ubiquiti Radio-to-radio Speed Test
Tests between the pair of Ubiquiti devices alone showed speeds of **275 Mbps**. This is faster than tests involving the Orange Pi Zero's 10/100 ethernet and cjdns overheads. The speed measured here is consistent with results from earlier tests with the Ubiquiti devices, which are ~300 Mbps as well.
## Things Learned
* Both Ubiquiti antennas were set to the same LAN IP address of 192.168.1.20, which created an IP conflict on the bridged interface, so one was changed to 192.168.1.21
* A bad power brick for the Orange Pi Zero would prevent the WiFi and Mesh Point from working, and rebooting would bring it up for a very short period of time
* So far the outdoor node performed fairly well with outside temperatures dropping to -10 C, but node core temp never dropped below +8 C
* ABS tubing is not very riget and bend fairly easily, making the antenna sway slightly in windy conditions
* Wireless link through a balcony door and screen has a decent signal strength but horrible throughput
## Poor Performance Between Outdoor and Indoor Nodes
Very poor speeds were observed between an outdoor node with the first indoor node. Note that this occurs in the part of the network outside of the Ubiquiti devices, involving only the TOP-GS07 devices over Mesh Point:
```
[ 4] local fc5e:44cd:6af4:4afc:cc4e:a75c:89a5:8d23 port 48622 connected to fc04:8b29:9889:cf83:88c:80fc:9e3b:78b4 port 5201
[ ID] Interval Transfer Bandwidth Retr Cwnd
[ 4] 0.00-1.00 sec 244 KBytes 2.00 Mbits/sec 12 13.2 KBytes
....
[ 4] 58.00-59.00 sec 125 KBytes 1.02 Mbits/sec 1 21.7 KBytes
[ 4] 59.00-60.00 sec 250 KBytes 2.05 Mbits/sec 1 20.5 KBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval Transfer Bandwidth Retr
[ 4] 0.00-60.00 sec 9.12 MBytes 1.28 Mbits/sec 252 sender
[ 4] 0.00-60.00 sec 8.98 MBytes 1.26 Mbits/sec receiver
```
The following steps were attempted to diagnose the issue:
* Replaced inside node with new node and TP-LINK TL-WN722N adapter (no improvement)
* Moved inside node outside (no improvement)
* Moved node inside (slight improvement to 3-4 Mbps)
* Removed top of tupperware container (no improvement)
* Signal strength during this whole time has been above -55 dBm
* Speed test against different node slightly farther registered 15 Mbps
* Suspecting of bad radio, replaced USB radio with new module (issue remains)
* Suspecting of bad power brick, replaced power brick (issue remains)
* Change one of the inside nodes to a "low-profile cased fanless" Orange Pi Zero with TP-LINK TL-WN722N WiFi adapter but kept the SD card to preserve settings (issue remains)
Notes:
* On 16 December 2017, patched a Node Exporter hack to collect Ubiquiti data from SNMP using the Orange Pi Zero nodes
* On 20 December 2017, moved the Orange Pi Zero node inside, link quality improved and metrics started recording correctly
* On 22 December 2017, further tests found that there may be an issue with the 3D-printed cases... when hardware is outside the case, speeds reach 30 Mbps, and placing it back in the case drops the speeds to 5 Mbps
* On 23 December 2017, moved one of the receivers down to below the balcony line so the signal is going _through_ the balcony glass, signal degraded minimally and speeds remained consistent
# Gigabit Link Field Test
#### 2016-10-15
## Test Setup & Objectives
A pair of Ubiquiti LiteBeam ac each powered by a ChargeTech 27 Ah portable battery through the PoE injector that the radios ship with. The LAN port of the injector is connected through an ethernet cable to an Ethernet-to-Thunderbolt gigabit adapter to a Mac. These two fully portable setups are largely symmetric. The LiteBeam ac's run AirOS and the Mac's run OS X with cjdns and other networking tools installed. On one of the ChargeTech batteries, we have attached a Kill-a-watt to measure the power draw of the LiteBeam ac units while idling and transmitting.
The objective of this exercise is to determine feasibility of using the LiteBeam ac to establish point-to-point, or perhaps point-to-multipoint, links for tomesh. We are primarily interested in the bandwidth and range performance of the unit, and secondary to that: power requirements, ease of set up, effects on obstructions by different objects in its line-of-sight path, and compatibility with cjdns.
On an early Saturday morning, the group met at a coffee shop near <NAME> Park, where there is a somewhat straight section of a few kilometres of flat land, which unfortunately does not have elevated points, but is a reasonable site for this first test. There we powered up the LiteBeams for the very first time.
## Initial Findings
- The Mac clients need to manually assign an IP to itself, with the router IP at its default **192.168.1.20**
- Connect with the AirOS web interface at **http://192.168.1.20**
- Switching one of the LiteBeams to **Router Mode** from the default **Bridge Mode** made it impossible to connect to again, this is probably due to our general infamiliarity with AirOS, but we had to reset that LiteBeam, and the reset button was damn hard to reach
- One LiteBeam was in **Station Mode** and the other in **Client Mode**, I don't recall if that was reverted and not reconfigured after the reset
- We changed one LiteBeam's IP to **192.168.1.19**, and once the link is established, only one of the two IPs become reachable from the Macs
- We initially had trouble having the Macs (each with a unique IP in the **192.168.1.0/24** subnet) ping each other over the LiteBeam link, but eventually that started working after the resets and assigning different IPs to each LiteBeam
- Using `iperf3` while the LiteBeams were sitting right beside each other, the link was about 370 Mbps
- We expected cjdns running on the Mac to automatically bind to the point-to-point interface and automatically establish autopeering over the cjdns `ETHInterface`, but that didn't happen, neither did AirOS show cjdns' `tun0` as an interface
- We manually forced cjdns to bind to the point-to-point interface by changing `"bind": "all"` to `"bind": "x"`, where _x_ is `en3` on one Mac and `en5` which we found from `ifconfig`, after that the two Mac nodes autopeered over ethernet and we are able to ping each other through their cjdns addresses
- The cjdns link `iperf3` at only 20 Mbps, which remains a mystery because the underlying link is 370 Mbps, and I have seen these Macs do at least 50 Mbps through the `UDPInterface`, limited only by my home Internet speeds, and based on `cjdroute --bench` results I'd expect the Macs to saturate the raw link
- Since we are primarily interested in the LiteBeam performance over distance, this is when we moved on to <NAME>
## Range Testing
We had one group mount a LiteBeam at about 8 ft on a pole at (43.645771, -79.320951), while the other group moved away from it and stopped at various distances.
#### Test Point A, 227 m away at (43.643781,-79.321583)
```
$ ping 192.168.1.25
PING 192.168.1.25 (192.168.1.25): 56 data bytes
64 bytes from 192.168.1.25: icmp_seq=0 ttl=64 time=1.263 ms
64 bytes from 192.168.1.25: icmp_seq=1 ttl=64 time=1.363 ms
64 bytes from 192.168.1.25: icmp_seq=2 ttl=64 time=2.432 ms
64 bytes from 192.168.1.25: icmp_seq=3 ttl=64 time=2.972 ms
64 bytes from 192.168.1.25: icmp_seq=4 ttl=64 time=1.273 ms
64 bytes from 192.168.1.25: icmp_seq=5 ttl=64 time=1.322 ms
64 bytes from 192.168.1.25: icmp_seq=6 ttl=64 time=1.345 ms
64 bytes from 192.168.1.25: icmp_seq=7 ttl=64 time=2.797 ms
^C
--- 192.168.1.25 ping statistics ---
8 packets transmitted, 8 packets received, 0.0% packet loss
```
```
$ iperf3 -c 192.168.1.25
Connecting to host 192.168.1.25, port 5201
[ 4] local 192.168.1.21 port 51076 connected to 192.168.1.25 port 5201
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-1.00 sec 45.2 MBytes 379 Mbits/sec
[ 4] 1.00-2.00 sec 45.1 MBytes 378 Mbits/sec
[ 4] 2.00-3.00 sec 42.4 MBytes 355 Mbits/sec
[ 4] 3.00-4.00 sec 43.9 MBytes 368 Mbits/sec
[ 4] 4.00-5.00 sec 41.2 MBytes 346 Mbits/sec
[ 4] 5.00-6.00 sec 41.0 MBytes 343 Mbits/sec
[ 4] 6.00-7.00 sec 44.6 MBytes 374 Mbits/sec
[ 4] 7.00-8.00 sec 43.7 MBytes 366 Mbits/sec
[ 4] 8.00-9.00 sec 44.3 MBytes 371 Mbits/sec
[ 4] 9.00-10.00 sec 42.4 MBytes 356 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-10.00 sec 434 MBytes 364 Mbits/sec sender
[ 4] 0.00-10.00 sec 434 MBytes 364 Mbits/sec receiver
```
**Obstruction one foot in front of one LiteBeam:**
```
$ iperf3 -c 192.168.1.25
Connecting to host 192.168.1.25, port 5201
[ 4] local 192.168.1.21 port 51170 connected to 192.168.1.25 port 5201
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-1.00 sec 44.1 MBytes 370 Mbits/sec
[ 4] 1.00-2.00 sec 39.4 MBytes 329 Mbits/sec
[ 4] 2.00-3.00 sec 9.90 MBytes 83.4 Mbits/sec
[ 4] 3.00-4.00 sec 37.0 MBytes 310 Mbits/sec
[ 4] 4.00-5.00 sec 41.6 MBytes 349 Mbits/sec
[ 4] 5.00-6.00 sec 34.1 MBytes 286 Mbits/sec
[ 4] 6.00-7.01 sec 7.67 MBytes 64.0 Mbits/sec
[ 4] 7.01-8.00 sec 29.3 MBytes 247 Mbits/sec
[ 4] 8.00-9.00 sec 15.9 MBytes 133 Mbits/sec
[ 4] 9.00-10.00 sec 34.9 MBytes 293 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-10.00 sec 294 MBytes 246 Mbits/sec sender
[ 4] 0.00-10.00 sec 293 MBytes 246 Mbits/sec receiver
```
**Over cjdns:**
```
$ iperf3 -c fcfd:cce:14ab:57de:64f7:32e3:19f3:ebdf
Connecting to host fcfd:cce:14ab:57de:64f7:32e3:19f3:ebdf, port 5201
[ 4] local fcaf:c9e1:bfff:73a3:c08c:51aa:3711:2ccc port 51316 connected to fcfd:cce:14ab:57de:64f7:32e3:19f3:ebdf port 5201
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-1.01 sec 2.49 MBytes 20.8 Mbits/sec
[ 4] 1.01-2.00 sec 2.04 MBytes 17.2 Mbits/sec
[ 4] 2.00-3.00 sec 2.68 MBytes 22.5 Mbits/sec
[ 4] 3.00-4.01 sec 1.41 MBytes 11.8 Mbits/sec
[ 4] 4.01-5.00 sec 2.58 MBytes 21.8 Mbits/sec
[ 4] 5.00-6.00 sec 3.12 MBytes 26.2 Mbits/sec
[ 4] 6.00-7.00 sec 3.06 MBytes 25.7 Mbits/sec
[ 4] 7.00-8.00 sec 3.01 MBytes 25.3 Mbits/sec
[ 4] 8.00-9.00 sec 3.10 MBytes 26.0 Mbits/sec
[ 4] 9.00-10.00 sec 3.37 MBytes 28.3 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-10.00 sec 26.9 MBytes 22.5 Mbits/sec sender
[ 4] 0.00-10.00 sec 26.7 MBytes 22.4 Mbits/sec receiver
```
**Notes:**
- If we introduced a misalignment of about 20 degrees, speed drops to < 100 mbps
- There were points when we had to restart `cjdroute` for things to work
#### Test Point B, 596 m away at (43.641396, -79.322121)
```
$ iperf3 -c 192.168.1.22
Connecting to host 192.168.1.22, port 5201
[ 4] local 192.168.1.21 port 53527 connected to 192.168.1.22 port 5201
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-1.00 sec 43.5 MBytes 365 Mbits/sec
[ 4] 1.00-2.00 sec 47.2 MBytes 395 Mbits/sec
[ 4] 2.00-3.00 sec 45.3 MBytes 380 Mbits/sec
[ 4] 3.00-4.00 sec 45.8 MBytes 384 Mbits/sec
[ 4] 4.00-5.00 sec 44.5 MBytes 373 Mbits/sec
[ 4] 5.00-6.00 sec 45.3 MBytes 380 Mbits/sec
[ 4] 6.00-7.00 sec 47.6 MBytes 399 Mbits/sec
[ 4] 7.00-8.00 sec 47.5 MBytes 399 Mbits/sec
[ 4] 8.00-9.00 sec 45.4 MBytes 381 Mbits/sec
[ 4] 9.00-10.00 sec 45.9 MBytes 385 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-10.00 sec 458 MBytes 384 Mbits/sec sender
[ 4] 0.00-10.00 sec 457 MBytes 384 Mbits/sec receiver
```
**180 degree offset (lol wut? bc we can):**
```
$ iperf3 -c 192.168.1.22
Connecting to host 192.168.1.22, port 5201
[ 4] local 192.168.1.21 port 53533 connected to 192.168.1.22 port 5201
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-1.00 sec 9.66 MBytes 81.0 Mbits/sec
[ 4] 1.00-2.00 sec 10.9 MBytes 91.9 Mbits/sec
[ 4] 2.00-3.00 sec 9.76 MBytes 81.9 Mbits/sec
[ 4] 3.00-4.00 sec 8.12 MBytes 68.2 Mbits/sec
[ 4] 4.00-5.00 sec 7.92 MBytes 66.4 Mbits/sec
[ 4] 5.00-6.00 sec 8.79 MBytes 73.8 Mbits/sec
[ 4] 6.00-7.01 sec 5.63 MBytes 47.0 Mbits/sec
[ 4] 7.01-8.00 sec 8.05 MBytes 67.9 Mbits/sec
[ 4] 8.00-9.00 sec 7.90 MBytes 66.1 Mbits/sec
[ 4] 9.00-10.00 sec 4.96 MBytes 41.7 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval Transfer Bandwidth
[ 4] 0.00-10.00 sec 81.7 MBytes 68.6 Mbits/sec sender
[ 4] 0.00-10.00 sec 81.7 MBytes 68.6 Mbits/sec receiver
```
#### Test Point C, 863 m away at (43.638118, -79.322729)
- No line-of-sight, blocked by a bunch of trees, Fresnel zone probably cuts deep into the ground because the antennas are at ground level
- A few kbps intermittenly, signal dropping all the time
- Tried changing polarization but that made no difference
- AirOS web interface on one site does not load, consistent with our belief that once linked, only one LiteBeam is routing while the other one is just bridging
<file_sep>/_posts/2016-04-06-civic-tech-meetup2.md
---
title: Another Civic Tech Meetup
text: Join us at Civic Tech Toronto's weekly Tuesday meetup.
location: Civic Tech TO, Connected Lab, 370 King St W
locationLink: http://osm.org/go/ZX6Bjwlll?m=
attendees: 8
date: 2016-04-06
startTime: '20:10'
endTime: '21:00'
---
Join Toronto Mesh at [Civic Tech Toronto](http://civictech.ca) on Tuesday at 6:30pm.
A recap of what we discussed is available in the [{{ page.date | date: '%B %d, %Y' }} meeting notes](https://github.com/tomeshnet/documents/blob/master/meeting_notes/{{ page.date | date: "%Y%m%d" }}_meeting-notes.md).
<file_sep>/about.md
---
layout: mkdownpage
title: About
descriptiveTitle: About Toronto Mesh
order: 1
permalink: about
---
Based in Toronto, we are a grassroots and decentralized group of volunteers who started Toronto Mesh at [CivicTechTO](http://civictech.ca) in early 2016. Through building community-owned infrastructure using off-the-shelf hardware and open-source technology, we are hoping to address barriers to internet access in our city. There are many ways that people can [be involved]({{ site.baseurl }}/events).
## Our Efforts
Since January 2016, Toronto Mesh has been working to build a community network using peer-to-peer, decentralized mesh network technology.
A mesh network consists of routers (or ‘nodes’) spread throughout the city with no single internet service provider or central servers. All nodes cooperate in the distribution of data, serving as a separate and redundant network (description via [NYCmesh](https://nycmesh.net/)).
## Vision
The primary driver for Toronto Mesh is to empower people to create spaces in which they can make decisions about the way they access and share information. For many of us, managing our online privacy means compromising it; the apps we download, the websites we visit, the operating systems we use, and even the infrastructure which carries our data around the world are implicated and leveraged by practices of surveillance for profit and social control. Internet access in general is sold in a 'black box'; meaning that the buyer doesn't know what it does or how it works. We believe this approach is at odds with the understanding of the internet as a place where people are empowered to act. Community-owned networks ask users to understand the technologies they use and to make decisions based on their community needs, rather than those of corporations.
As citizens, we cannot simply create our own parallel internet by pulling fibre optic cabling through the ground and the sea, or building data centres and switching stations. What we do have access to are the tools and devices through which countless wireless networks are already substantiated. In our project we are using familiar routers and antennas, we draw on lessons from existing projects worldwide in order to help us bring together residents, business owners, technologists, and others, to provide internet access in their neighbourhoods and cities. Building a mesh will be another way to connect people and spaces in this city to each other.
## Contact
Twitter: [@tomeshnet](https://twitter.com/tomeshnet)
Riot: [#tomesh:tomesh.net](https://chat.tomesh.net/#/room/#tomesh:tomesh.net)
Email: [<EMAIL>](mailto:<EMAIL>)
Github: [tomeshnet](https://github.com/tomeshnet)
| c28b2698c6f7b4831bb881a78f123b381eb5c003 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | Shrinks99/tomesh2 | 51d34fac0e5f4d55a66e3301f63a16f3c1118b13 | 146de557351178ac64e4a005bfba0533ab29ed51 | |
refs/heads/master | <repo_name>Muhammadk28/cv<file_sep>/skills.js
var skills = [
{
technology: 'Html',
projects: '30+',
exeperiences: '2+',
rating: 8,
},
{
technology: 'Css',
projects: '30+',
exeperiences: '2+',
rating: 8,
},
{
technology: 'JS',
projects: '20+',
exeperiences: '2+',
rating: 8,
},
{
technology: 'jQuery',
projects: '20+',
exeperiences: '2+',
rating: 8,
},
{
technology: 'PHP',
projects: '10+',
exeperiences: '1+',
rating: 7,
},
{
technology: 'MySql',
projects: '10+',
exeperiences: '1+',
rating: 7,
},
{
technology: 'Laravel',
projects: '3',
exeperiences: '1+',
rating: 6,
},
{
technology: 'WordPress',
projects: '10+',
exeperiences: '1+',
rating: 7,
},
]
| 2bc89764da0495c59f46deba585e33527cc7a21c | [
"JavaScript"
] | 1 | JavaScript | Muhammadk28/cv | 6ef6d6c87de6dc3b1e1356e361ccb3c0e35109cc | e73c9a385fddd09a60c66cb2b83c4c1cf7dbbc9b | |
refs/heads/master | <file_sep>var start = null;
var quickestTime = null;
function resizeGame() {
var center = document.getElementsByClassName("game-bounds").item(0);
center.style.width = (document.body.clientWidth - 50) + "px";
center.style.height = (document.body.clientHeight - 50) + "px";
}
resizeGame();
if (window.attachEvent) {
window.attachEvent('onresize', function () {
resizeGame();
});
} else if (window.addEventListener) {
window.addEventListener('resize', function () {
resizeGame();
});
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split(''),
color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var shape = document.getElementById('shape');
var top = Math.random() * 400,
left = Math.random() * 400,
size = (Math.random() * 200) + 10;
shape.style.display = "block";
shape.style.top = top + "px";
shape.style.left = left + "px";
shape.style.width = size + "px";
shape.style.height = size + "px";
shape.style.backgroundColor = getRandomColor();
if (Math.random() > 0.5) {
shape.style.borderRadius = "50%";
} else {
shape.style.borderRadius = "0%";
}
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, Math.random() * 2000); // Max Length 2 Seconds
}
document.getElementById('shape').onclick = function () {
var end = new Date().getTime(),
timeTaken = (end - start);
document.getElementById('shape').style.display = "none";
document.getElementById('time-taken').innerHTML = timeTaken / 1000 + 's';
if (quickestTime) {
if ((end - start) < quickestTime) {
quickestTime = timeTaken;
}
} else {
quickestTime = timeTaken;
}
document.getElementById('quickest-time').innerHTML = quickestTime / 1000 + 's';
appearAfterDelay();
};
appearAfterDelay();
<file_sep>function FrequencyConverter() {
this.values = {
"hertz": 0.001,
"kilohertz": 1,
"megahertz": 1000,
"gigahertz": 1000000
};
this.convert = function (From, To, Value) {
return (Value * this.values[From]) / this.values[To];
}
}<file_sep>function SpeedConverter() {
// Units in Foot Per Second
this.values = {
"miles-per-hour": 1.46667,
"foot-per-second": 1,
"meter-per-second": 3.28084,
"kilometer-per-hour": 0.911344,
"knot": 1.68781
};
this.convert = function(From, To, Value ) {
return (Value * this.values[From]) / this.values[To];
}
}<file_sep>function AreaConverter () {
// Units in Square Inch
this.values = {
"square-kilometer": 1550003100,
"square-meter": 1550,
"square-mile": 4014489600,
"square-yard": 1296,
"square-foot": 144,
"square-inch": 1,
"hectare": 15500031,
"acre": 6272640
};
this.convert = function(From, To, Value) {
return (Value * this.values[From]) / this.values[To]
}
}<file_sep>function LengthConverter() {
// Units in Nanometer
this.values = {
"kilometer": 1000000000000,
"meter": 1000000000,
"decimeter": 100000000,
"centimeter": 10000000,
"millimeter": 1000000,
"micrometer": 1000,
"nanometer": 1,
"mile": 1609344000000,
"yard": 914400000,
"foot": 304800000,
"inch": 25400000,
"nautical-mile": 1852000000000,
"light-year": 9460730472580800000000000
};
this.convert = function (From, To, Value) {
return (Value * this.values[From]) / this.values[To]
}
}
<file_sep>function TemperatureConverter() {
TemperatureTypeEnum = {
FAHRENHEIT: "fahrenheit",
CELSIUS: "celsius",
KELVIN: "kelvin"
};
this.convert = function(From, To, Value) {
switch(From) {
case TemperatureTypeEnum.FAHRENHEIT:
if (To == TemperatureTypeEnum.CELSIUS) {
return ((Value - 32) * 5) / 9;
} else {
return (Value + 459.67) * (5 / 9);
}
break;
case TemperatureTypeEnum.CELSIUS:
if (To == TemperatureTypeEnum.FAHRENHEIT) {
return (Value * (9 / 5)) + 32;
} else {
return Value + 273.15;
}
break;
case TemperatureTypeEnum.KELVIN:
if (To == TemperatureTypeEnum.CELSIUS) {
return Value - 273.15;
} else {
return (Value * (9 / 5)) -459.67;
}
break;
}
}
}<file_sep>function TimeConverter () {
// Units in Nanosecond
this.values = {
"nanosecond": 1,
"microsecond": 1000,
"millisecond": 1000000,
"second": 1000000000,
"minute": 60000000000,
"hour": 3600000000000,
"day": 86400000000000,
"week": 604800000000000,
"month": 2629746000000000,
"year": 31556952000000000,
"decade": 315360000000000000,
"century": 3153599999996478000
};
this.convert = function(From, To, Value) {
return (Value * this.values[From]) / this.values[To]
}
}<file_sep> $(document).ready(function () {
var toggleAffix = function (affixElement, scrollElement, wrapper) {
var height = affixElement.outerHeight(),
top = wrapper.offset().top;
if (scrollElement.scrollTop() >= top) {
wrapper.height(height);
affixElement.addClass("affix");
toggleNavbarSchema(false);
} else {
affixElement.removeClass("affix");
wrapper.height('auto');
toggleNavbarSchema(true);
}
};
$('[data-toggle="affix"]').each(function () {
var ele = $(this),wrapper = $('<div></div>');
ele.before(wrapper);
$(window).on('scroll resize', function () {
toggleAffix(ele, $(this), wrapper);
});
// init
toggleAffix(ele, $(window), wrapper);
});
// toggle between 'navbar-light' and 'navbar-inverse'
function toggleNavbarSchema(light) {
if (light) {
$("nav").addClass("navbar-light");
$("nav").removeClass("navbar-inverse");
} else {
$("nav").addClass("navbar-inverse");
$("nav").removeClass("navbar-light");
}
}
});
| cbf431bfa77ec5feadb61ee3a2d004a28e333ee5 | [
"JavaScript"
] | 8 | JavaScript | ChrisStayte/chrisstayte | b199eea7b8e0b14b6b3563a22c3bf002d96acdc8 | 5db645ece95ca2a021e6e0145b1d0ca4b9167a53 | |
refs/heads/master | <file_sep>package org.pw.GA.func;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Random;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.pw.compare.CompareIndex0;
import org.pw.compare.CompareIndex1;
import org.pw.dto.Agent;
import org.pw.dto.CellObj;
import org.pw.dto.DeptObj;
import org.pw.dto.FuncObj;
import org.pw.dto.FuncNodeObj;
public class GAFuncPanel extends JPanel implements ActionListener{
String STATUS="";
ArrayList<FuncNodeObj>funcNodeObjList;
ArrayList<FuncObj>funcObjList;
ArrayList<CellObj>cellObjList;
ArrayList<CellObj>interCellObjList;
ArrayList<GeneralPath>interPathList;
ArrayList<Integer>interIdList;
ArrayList<CellObj>periCellObjList;
ArrayList<GeneralPath>periPathList;
ArrayList<Integer>periIdList;
ArrayList<CellObj>genCellObjList;
ArrayList<GeneralPath>genPathList;
ArrayList<Integer>genIdList;
ArrayList<DeptObj>deptObjList;
HashMap<String,Double> mapArea;
double scaleX,scaleY,translateX, translateY;
double fitness_peri, fitness_cells_used_peri_limit;
double fitness_cells_used_inter, fitness_inter, fitness_defi;
double fitness_cells_used_gen, fitness_gen;
int entryclicksize=10;
Timer timer;
Random rnd;
Agent agent;
boolean showGrid=false;
public GAFuncPanel(ArrayList<FuncNodeObj>graphNodeList,
ArrayList<CellObj>GLOBAL_CellObjList){
timer=new Timer(100,this);
timer.start();
rnd=new Random();
funcNodeObjList=new ArrayList<FuncNodeObj>();
funcNodeObjList.clear();
funcNodeObjList.addAll(graphNodeList);
funcObjList=new ArrayList<FuncObj>();
funcObjList.clear();
cellObjList=new ArrayList<CellObj>();
cellObjList.addAll(GLOBAL_CellObjList);
periCellObjList=new ArrayList<CellObj>();
periPathList=new ArrayList<GeneralPath>();
interCellObjList=new ArrayList<CellObj>();
interPathList=new ArrayList<GeneralPath>();
genCellObjList=new ArrayList<CellObj>();
genPathList=new ArrayList<GeneralPath>();
deptObjList=new ArrayList<DeptObj>();
scaleX=1;
scaleY=1;
translateX=0;
translateY=0;
fitness_peri=0;
fitness_cells_used_peri_limit=0;
fitness_cells_used_inter=0;
fitness_inter=0;
fitness_cells_used_gen=0;
fitness_gen=0;
agent=new Agent(3);
double ar_cells=0;
for(int i=0; i<cellObjList.size(); i++){
CellObj cellobj = cellObjList.get(i);
double ar=cellobj.getNumericalArea();
ar_cells+=ar;
}
//System.out.println("total ar of cells : " +ar_cells);
/*
* departments
*/
deptObjList.clear();
ArrayList<String>dept_names=new ArrayList<String>();
for(int i=0; i<funcNodeObjList.size(); i++){
FuncNodeObj obj=funcNodeObjList.get(i);
String dept0=obj.getDeparment().toLowerCase();
int sum=0;
for(int j=0; j<dept_names.size();j++){
String dept1=dept_names.get(j).toLowerCase();
if(dept0.equals(dept1)){
sum++;
}
}
if(sum==0){
dept_names.add(dept0);
}
}
//System.out.println("number of depts = "+dept_names.size());
//System.out.println("name of depts = "+dept_names);
for(int i=0; i<dept_names.size(); i++){
String s=dept_names.get(i).toLowerCase();
double ar_sum=0;
for(int j=0; j<funcNodeObjList.size();j++){
FuncNodeObj obj=funcNodeObjList.get(j);
String name=obj.getDeparment().toLowerCase();
double qnty=obj.getQnty();
double ar=qnty*obj.getAr_each();
if(s.equals(name)){
ar_sum+=ar;
}
}
DeptObj deptobj=new DeptObj(s, ar_sum);
deptObjList.add(deptobj);
}
for(int i=0; i<deptObjList.size(); i++){
DeptObj obj=deptObjList.get(i);
//System.out.println(obj.getName() + "," +obj.getArea());
}
}
public void Update(double sx, double sy, double tx, double ty){
scaleX=sx;
scaleY=sy;
translateX=tx;
translateY=ty;
}
public void getPeriCells(){
periCellObjList.clear();
int idx=1;
for(int i=0; i<cellObjList.size(); i++){
CellObj c=cellObjList.get(i);
int id=c.getId();
String zone=c.getZone();
if(zone.equals("peripheral")){// || zone.equals("corner")){
c.setId(idx);
c.nullNumUsed();
periCellObjList.add(c);
}
}
periCellObjList.trimToSize();
// CLEAR ALL CELLS
for(int i=0; i<cellObjList.size(); i++){
CellObj c=cellObjList.get(i);
c.setFilled(false);
}
}
public void getInterCells(){
interCellObjList.clear();
interPathList.clear();
int idx=0;
for(int i=0; i<cellObjList.size(); i++){
CellObj obj=cellObjList.get(i);
if(obj.getZone().equals("interstitial")){
interCellObjList.add(obj);
obj.setFilled(false);
obj.nullNumUsed();
obj.setId(idx);
idx++;
}
}
}
public void getGeneralCells(){
genCellObjList.clear();
int idx=0;
for(int i=0; i<cellObjList.size(); i++){
CellObj obj=cellObjList.get(i);
if(obj.getZone().equals("general")){
obj.setFilled(false);
obj.nullNumUsed();
obj.setId(idx);
genCellObjList.add(obj);
idx++;
}
}
}
public void updateCells(ArrayList<CellObj>req_cell_list,
GeneralPath path, String node_name){
Area ar=new Area(path);
for(int i=0; i<req_cell_list.size(); i++){
CellObj c=req_cell_list.get(i);
double x=c.getMidPt()[0];
double y=c.getMidPt()[1];
boolean t=ar.contains(x,y);
int sum=0;
double[] verX=c.getVerX();
double[] verY=c.getVerY();
for(int j=0; j<verX.length; j++){
if(ar.contains(verX[j], verY[j])==true){
sum++;
}
}
if(sum>0 || t==true){
c.setName(node_name);
c.setFilled(true);
c.addNumUsed();
}
/*
if(t==true){
c.setName(node_name);
c.setFilled(true);
c.addNumUsed();
}
*/
}
}
public String getCellId(ArrayList<CellObj>req_cell_list,
GeneralPath path, boolean refine,
int num_vertices_occupied){
String s="";
for(int i=0; i<req_cell_list.size(); i++){
CellObj c=req_cell_list.get(i);
if(c.getFilled()==false){
int id=c.getId();
double x=c.getMidPt()[0];
double y=c.getMidPt()[1];
Area a=new Area(path);
boolean t=a.contains(x, y);
int sum=0;
if(refine==true){
double[] verX=c.getVerX();
double[] verY=c.getVerY();
for(int j=0; j<verX.length; j++){
if(a.contains(verX[j], verY[j])==true){
sum++;
}
}
if(sum>=num_vertices_occupied){
s+=id+",";
}
}else{
if(t==true){
s+=id+",";
}
}
}
}
return s;
}
public double checkAr_cellsOcc(ArrayList<CellObj>req_cell_list,
double ar, String id_str){
int n=id_str.split(",").length;
double ar_sum=0;
for(int i=0; i<n; i++){
CellObj c=req_cell_list.get(i);
double arX=c.getNumericalArea();
ar_sum+=arX;
}
double diff=ar_sum/ar;
return diff;
}
public void plottedCells(boolean rotate){
//System.out.println("--------CHECK PLOTTED -------");
STATUS+="--------CHECK PLOTTED -------/n";
//System.out.println("Total plotted cells : "+funcObjList.size());
STATUS+="Total plotted cells : "+funcObjList.size()+"\n";
for(int i=0; i<funcObjList.size(); i++){
FuncObj funcobj=funcObjList.get(i);
String name =funcobj.getName();
String zone=funcobj.getZone();
double ar=funcobj.getNumerical_area();
//System.out.println(i +"> "+ name+" , "+zone+" , "+ar);
STATUS+=i +"> "+ name+" , "+zone+" , "+ar+"\n";
}
/*
* CHECK FOR DEFICIT AND SEND IT FOR ACCOMMODATION
*/
//System.out.println("--------DEFICIT PLOTTED -------");
STATUS+="--------DEFICIT PLOTTED -------\n";
for(int i=0; i<funcNodeObjList.size(); i++){
FuncNodeObj nodeObj=funcNodeObjList.get(i);
int nodeObj_id=nodeObj.getId();
int req_num=(int)(nodeObj.getQnty());
int sum=0;
for(int j=0; j<funcObjList.size(); j++){
FuncObj plotObj=funcObjList.get(j);
int plotObj_id=plotObj.getId();
if(plotObj.getId()==nodeObj_id){
sum++;
}
}
int deficit_num=req_num-sum;
double ar=nodeObj.getAr_each();
String name=nodeObj.getName();
int id=nodeObj.getId();
int[] rgb=nodeObj.getRgb();
double[] asp_=nodeObj.getAspectRatio();
int sumX=0;
for(int j=0; j<deficit_num; j++){
sumX++;
allocateDeficitFunction(deficit_num, ar, name, id, rgb, asp_, rotate);
}
//System.out.println("deficit : "+id + name+","+sumX);
STATUS+="deficit : "+id + name+","+sumX +"\n";
}
}
public void allocatePeripheralFunction(int node_num, double node_ar,
String node_name, int node_id_, int[] rgb_, double[] asp_){
periPathList.clear();
/*
* LOGIC FOR OCCUPYING
*/
if(periCellObjList.size()>0){
int i=0;
int counter=0;
//System.out.println(node_name+","+node_num+","+node_ar);
while(counter<(node_num) && i<periCellObjList.size()){
int idx=i;
CellObj obj=periCellObjList.get(idx);
if(obj.getNumUsed()==0 && obj.getFilled()==false){
double ar=node_ar;
GeneralPath path=obj.getPeripheralGeo(ar);
String id_str=getCellId(periCellObjList, path, true, 4);
double ar_fit=checkAr_cellsOcc(periCellObjList, ar, id_str);
boolean intX=checkIntXPath(periCellObjList, path);
if(ar_fit>fitness_peri && !id_str.isEmpty() && intX==true){
FuncObj funcobj=new FuncObj(path, ar,id_str, node_name,
"peripheral", node_id_, rgb_, asp_);
funcObjList.add(funcobj);
periPathList.add(path);
updateCells(periCellObjList, path, node_name);
counter++;
}
}
i++;
}
}
/*
* GET THE FITNESS FOR PERIPHERAL
*/
double sumN_peri=0;
double sumI_peri=0;
for(int i=0; i<periCellObjList.size(); i++){
CellObj c=periCellObjList.get(i);
boolean t=c.getFilled();
if(c.getZone().equals("peripheral")){
if(t==true){
int n=c.getNumUsed();
sumI_peri+=n; //number of times this cell was used
sumN_peri++;
}
}
}
double f_overlap_peri=sumN_peri/(sumN_peri+Math.abs(sumN_peri-sumI_peri));
fitness_peri=f_overlap_peri;
}
public boolean checkIntXPath(ArrayList<CellObj>tempCell,GeneralPath path0){
Area ar0=new Area(path0);
ArrayList<String>path0_pts=new ArrayList<String>();
path0_pts.addAll(getPathPoints(path0));
int sum=0;
for(int i=0; i<tempCell.size(); i++){
CellObj obj=tempCell.get(i);
int num=obj.getNumUsed();
if(obj.getFilled()==true){
double x=obj.getMidPt()[0];
double y=obj.getMidPt()[1];
if(ar0.contains(x,y)==true){
sum++;
}
}
}
System.out.println("sum is "+sum);
if(sum<1){
return true;
}else{
return false;
}
}
public boolean periPathIntX(ArrayList<GeneralPath>tempPath, GeneralPath path0){
Area ar0=new Area(path0);
int sum=0;
for(int i=0; i<tempPath.size(); i++){
GeneralPath path=tempPath.get(i);
ArrayList<String>path_str=getPathPoints(path);
for(int j=0; j<path_str.size(); j++){
double x=Double.parseDouble(path_str.get(j).split(",")[0]);
double y=Double.parseDouble(path_str.get(j).split(",")[1]);
boolean t=ar0.contains(x,y);
if(t==true){
sum++;
}
}
}
if(sum<1){
return true;
}else{
return false;
}
}
public void allocateInterstitialFunction(int node_num, double node_ar,
String node_name, int node_id_, int[] rgb_, double[] asp_){
interPathList.clear();
if(interCellObjList.size()>0){
int i=0;
int counter=0;
while(counter<node_num && i<interCellObjList.size()){
int idx=i;
CellObj obj=interCellObjList.get(idx);
//System.out.println(node_name+","+node_num+","+node_ar);
if(obj.getNumUsed()==0 && obj.getFilled()==false){
double ar=node_ar;
GeneralPath path=obj.getGeneralGeo(ar, asp_, false);
String id_str=getCellId(interCellObjList, path, false, 4);
double ar_fit=checkAr_cellsOcc(interCellObjList, ar, id_str);
boolean intX=checkIntXPath(interCellObjList, path);
if(ar_fit>fitness_inter && !id_str.isEmpty() && intX==true){
updateCells(interCellObjList, path, node_name);
FuncObj funcobj=new FuncObj(path, ar,id_str, node_name, "interstitial", node_id_, rgb_, asp_);
funcObjList.add(funcobj);
counter++;
}
}
i++;
}
}
/*
* GET THE FITNESS FOR INTERSTITIAL
*/
double sumN_inter=0;
double sumI_inter=0;
for(int i=0; i<cellObjList.size(); i++){
CellObj c=cellObjList.get(i);
boolean t=c.getFilled();
if(c.getZone().equals("interstitial")){
if(t==true){
int n=c.getNumUsed();
sumI_inter+=n; //number of times this cell was used
sumN_inter++;
}
}
}
double f_overlap_inter=sumN_inter/(sumN_inter+Math.abs(sumN_inter-sumI_inter));
fitness_inter=f_overlap_inter;
}
public void allocateGeneralFunction(int node_num, double node_ar,
String node_name, int node_id_, int[]rgb_, double[] asp_){
genPathList.clear();
if(genCellObjList.size()>0){
int i=0;
int counter=0;
//System.out.println(node_name+","+node_num+","+node_ar);
while(counter<node_num && i<genCellObjList.size()){
int idx=i;
CellObj obj=genCellObjList.get(idx);
if(obj.getNumUsed()==0 && obj.getFilled()==false){
double ar=node_ar;
/*
* based on the side of the cell we derive rect path for the area
* getCellId() : refined placement : true; check for vertices & number of vertices to occupy
*/
GeneralPath ar_path=obj.getGeneralGeo(ar,asp_,false);
String id_str=getCellId(genCellObjList, ar_path, true, 4);
double ar_fit=checkAr_cellsOcc(genCellObjList, ar, id_str);
boolean intX=checkIntXPath(genCellObjList, ar_path);
if(ar_fit>fitness_gen && !id_str.isEmpty() && intX==true){
updateCells(genCellObjList, ar_path, node_name);
FuncObj funcobj=new FuncObj(ar_path, ar,id_str, node_name, "general", node_id_, rgb_, asp_);
funcObjList.add(funcobj);
counter++;
}
}
i++;
}
}
/*
* GET THE FITNESS FOR GENERAL
*/
double sumN_gen=0;
double sumI_gen=0;
for(int i=0; i<genCellObjList.size(); i++){
CellObj c=genCellObjList.get(i);
boolean t=c.getFilled();
if(c.getZone().equals("general")){
if(t==true){
int n=c.getNumUsed();
sumI_gen+=n; //number of times this cell was used
sumN_gen++;
}
}
}
double f_overlap_gen=sumN_gen/(sumN_gen+Math.abs(sumN_gen-sumI_gen));
fitness_gen=f_overlap_gen;
}
public void allocateDeficitFunction(int node_num, double node_ar, String
node_name, int node_id_, int[]rgb_, double[] asp_, boolean rotate){
int i=0;
int counter=0;
/*
* use every possible cell
*/
while(counter<node_num && i<cellObjList.size()){
int idx=i;
CellObj obj=cellObjList.get(idx);
if(obj.getNumUsed()==0 && obj.getFilled()==false){
double ar=node_ar;
/*
* based on the side of the cell we derive rect path for the area
* getCellId() : refined placement : true; check for vertices &
* number of vertices to occupy
*
*/
GeneralPath ar_path=obj.getGeneralGeo(ar,asp_,false);
String id_str=getCellId(cellObjList, ar_path, true, 2);
double ar_fit=checkAr_cellsOcc(cellObjList, ar, id_str);
boolean intX=checkIntXPath(cellObjList, ar_path);
if(ar_fit>fitness_defi && !id_str.isEmpty() && intX==true){
genPathList.add(ar_path);
updateCells(cellObjList, ar_path, node_name);
if(rotate==true){
//System.out.println("rotated in deficit function");
STATUS+="rotated in deficit function/n";
}
FuncObj funcobj=new FuncObj(ar_path, ar,id_str, node_name,
"general", node_id_, rgb_, asp_);
funcObjList.add(funcobj);
System.out.println("added : "+node_name);
STATUS+="added : "+node_name+"/n";
counter++;
}
}
i++;
}
/*
* GET THE FITNESS
*/
double sumN_gen=0;
double sumI_gen=0;
for(int j=0; j<cellObjList.size(); j++){
CellObj c=cellObjList.get(j);
boolean t=c.getFilled();
if(c.getZone().equals("general")){
if(t==true){
int n=c.getNumUsed();
sumI_gen+=n; //number of times this cell was used
sumN_gen++;
}
}
}
double f_overlap_gen=sumN_gen/(sumN_gen+Math.abs(sumN_gen-sumI_gen));
fitness_cells_used_gen=f_overlap_gen;
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d= (Graphics2D) g.create();
g2d.setColor(new Color(255,255,255));
g2d.fill(new Rectangle2D.Double(0,0,1000,1000));
g2d.scale(scaleX, scaleY);
g2d.translate(translateX, translateY);
/*
* PLOT ALL CELLS
*/
if(showGrid==false){
g2d.setColor(new Color(0,0,0));
for(int i=0; i<cellObjList.size(); i++){
CellObj c=cellObjList.get(i);
GeneralPath path=c.genPath();
String zone=c.getZone();
g2d.setStroke(new BasicStroke(0.25F));
g2d.setColor(new Color(0,0,0,50));
g2d.draw(path);
}
for(int i=0; i<cellObjList.size(); i++){
CellObj c= cellObjList.get(i);
boolean t=c.getFilled();
GeneralPath p=c.genPath();
if(t==true){
g2d.setColor(new Color(200,255,200,150));
g2d.fill(p);
}
int n=c.getNumUsed();
if(n>1){
//g2d.setColor(new Color(255,0,0));
//g2d.fill(p);
}
}
}
/*
* PLOT THE FUNCTIONS ALLOCATED
*/
for(int i=0; i<funcObjList.size(); i++){
FuncObj obj=funcObjList.get(i);
String name=obj.getName();
//System.out.println(obj.getCellsOccupied());
int[] rgb=obj.getRgb();
int id=obj.getId();
GeneralPath path=obj.getPath();
g2d.setStroke(new BasicStroke(0.70F));
g2d.setColor(new Color(0,0,0));
g2d.draw(path);
g2d.setColor(new Color(rgb[0],rgb[1],rgb[2]));
g2d.fill(path);
/*
* GET CELLS ID
* GET PATH
* ADD AREA
*/
String[] cellsId=obj.getCellsOccupied().split(",");
int req_id0=Integer.parseInt(cellsId[0]);
CellObj cell0=cellObjList.get(req_id0);
GeneralPath path0=cell0.genPath();
Area a0=new Area(path0);
for(int j=0; j<cellsId.length; j++){
int req_id=Integer.parseInt(cellsId[j]);
CellObj cell=cellObjList.get(req_id);
GeneralPath path1=cell.genPath();
Area a1=new Area(path1);
a0.add(a1);
}
/*
* INDEXING
*/
int mpx=(int)(describePath(path)[0]);
int mpy=(int)(describePath(path)[1]);
g2d.setColor(new Color(255,255,255,150));
double r=5;
g2d.fill(new Rectangle2D.Double(mpx-r/2, mpy-r*2/3, r, r));
g2d.setColor(new Color(0,0,0));
Font font1=new Font("Consolas", Font.PLAIN, 3);
g2d.setFont(font1);
g2d.drawString(""+id,(int)(mpx-r/5),(int)mpy);
}
/*
for(int i=0; i<periCellObjList.size(); i++){
GeneralPath p=periCellObjList.get(i).genPath();
g2d.setColor(new Color(255,0,0,100));
g2d.fill(p);
}
*/
repaint();
}
public double[] describePath(GeneralPath path){
PathIterator pi=path.getPathIterator(null);
ArrayList<String> bb=new ArrayList<String>();
bb.clear();
String s="";
while(pi.isDone()==false){
double[] coor=new double[2];
int type=pi.currentSegment(coor);
switch(type){
case PathIterator.SEG_MOVETO:
s=coor[0]+","+coor[1];
bb.add(s);
break;
case PathIterator.SEG_LINETO:
s=coor[0]+","+coor[1];
bb.add(s);
break;
default:
break;
}
pi.next();
}
Collections.sort(bb,new CompareIndex0());
double minX=Double.parseDouble(bb.get(0).split(",")[0]);
double maxX=Double.parseDouble(bb.get(bb.size()-1).split(",")[0]);
Collections.sort(bb,new CompareIndex1());
double minY=Double.parseDouble(bb.get(0).split(",")[1]);
double maxY=Double.parseDouble(bb.get(bb.size()-1).split(",")[1]);
double mpx=(minX+maxX)/2;
double mpy=(minY+maxY)/2;
double[] mp={mpx,mpy};
return mp;
}
public ArrayList<String> getPathPoints(GeneralPath path){
PathIterator pi=path.getPathIterator(null);
ArrayList<String> bb=new ArrayList<String>();
bb.clear();
String s="";
while(pi.isDone()==false){
double[] coor=new double[2];
int type=pi.currentSegment(coor);
switch(type){
case PathIterator.SEG_MOVETO:
s=coor[0]+","+coor[1];
bb.add(s);
break;
case PathIterator.SEG_LINETO:
s=coor[0]+","+coor[1];
bb.add(s);
break;
default:
break;
}
pi.next();
}
return bb;
}
public double dis(double x0, double y0, double x1, double y1){
double d=Math.sqrt((x0-x1)*(x0-x1) + (y0-y1)*(y0-y1));
return d;
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
<file_sep>package org.pw.GA.func;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.Timer;
import org.pw.dto.CellObj;
import org.pw.dto.FuncNodeObj;
public class GAFuncFrame extends JFrame implements ActionListener{
JLabel jlblScale, jlblTranslate,jlblalgoname, jlblDept, jlblDeptFit,
jlblOverlapFit_peri, jlblOverlapFitnessSize_peri, jlblOverlap_peri,
jlblOverlapFit_inter, jlblOverlap_inter,jlblOverlapFitnessSize_inter,
jlblOverlap_gen,jlblOverlapFit_gen,jlblOverlapFitnessSize_gen,
jlblDeficit_gen, jlblDeficitFit_gen, jlblDeficitFitnessSize_gen,
jlblFitnessFields, jlblFitnessReturned,jlblGrid;
JTextField jtfScale, jtfTranslate, jtfentry;
JButton jbtnTransform, jbtnRunAlgo, jbtnEntry, jbtnDept;
JSlider jsliderOverlapLim_peri, jsliderOverlapLim_inter,jsliderOverlapLim_gen,
jsliderDeficit,jsliderDept;
GAFuncPanel pnl;
JCheckBox gridOn;
Timer timer;
ArrayList<FuncNodeObj>funcNodeObjList;
public GAFuncFrame(ArrayList<FuncNodeObj>graphNodeList,
ArrayList<CellObj>GLOBAL_CellObjList){
setLocation(430,0);
setSize(1500,1000);
setTitle("Demonstration of Genetic Algorithm");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
/*
* GLOBAL VARIABLES
*/
funcNodeObjList=new ArrayList<FuncNodeObj>();
funcNodeObjList.clear();
funcNodeObjList.addAll(graphNodeList);
timer=new Timer(150,this);
timer.start();
/*
* TRANFORMATION
*/
jlblScale=new JLabel("Scale");
jlblScale.setBounds(1025,20,100,40);
jtfScale=new JTextField("3,3");
jtfScale.setBounds(1150,20,100,40);
jlblTranslate= new JLabel("Translate");
jlblTranslate.setBounds(1025,70,100,40);
jtfTranslate=new JTextField("-20,0");
jtfTranslate.setBounds(1150,70,100,40);
jbtnTransform=new JButton("Transform");
jbtnTransform.setBounds(1275,40,175,50);
/*
* PLACE DEPARTMENTS
*/
jlblDept=new JLabel("O R G A N I Z E F U N C T I O N S");
jlblDept.setBounds(1025,770,250,40);
jlblDeptFit=new JLabel("20");
jlblDeptFit.setBounds(1225,820,250,40);
jsliderDept=new JSlider(50,100,75);
jsliderDept.setBounds(1025,820,175,40);
jbtnDept=new JButton("Organize");
jbtnDept.setBounds(1275,800,175,50);
/*
* RUN ALGORITHM
*/
jlblalgoname=new JLabel("R U N A L G O R I T H M");
jlblalgoname.setBounds(1025,630,175,40);
jbtnRunAlgo=new JButton("run Algorithm");
jbtnRunAlgo.setBounds(1275,625,175,50);
/*
* FITNESS LABELS
*/
jlblFitnessFields=new JLabel("S E T F I T N E S S L I M I T S : ");
jlblFitnessFields.setBounds(1025,150,180,40);
jlblFitnessReturned=new JLabel(" R E T U R N E D");
jlblFitnessReturned.setBounds(1300,150,175,40);
/*
* PERIPHERAL ZONE
*/
jlblOverlap_peri=new JLabel("1. Fitness of overlap in peripheral zone");
jlblOverlap_peri.setBounds(1025,200,400,40);
jlblOverlapFit_peri=new JLabel("<-- peripheral fitness -->");
jlblOverlapFit_peri.setBounds(1275,245,250,40);
jlblOverlapFitnessSize_peri=new JLabel("20");
jlblOverlapFitnessSize_peri.setBounds(1225,245,50,40);
jsliderOverlapLim_peri=new JSlider(50,100,75);
jsliderOverlapLim_peri.setBounds(1025,245,175,40);
/*
* INTERSTITIAL ZONE
*/
jlblOverlap_inter=new JLabel("2. Fitness of overlap in interstitial zone");
jlblOverlap_inter.setBounds(1025,300,400,40);
jlblOverlapFit_inter=new JLabel("<-- interstitial fitness -->");
jlblOverlapFit_inter.setBounds(1275,345,250,40);
jlblOverlapFitnessSize_inter=new JLabel("20");
jlblOverlapFitnessSize_inter.setBounds(1225,345,50,40);
jsliderOverlapLim_inter=new JSlider(50,100,75);
jsliderOverlapLim_inter.setBounds(1025,345,175,40);
/*
* GENERAL ZONE
*/
jlblOverlap_gen=new JLabel("3. Fitness of overlap in general zone");
jlblOverlap_gen.setBounds(1025,400,400,40);
jlblOverlapFit_gen=new JLabel("<-- general fitness -->");
jlblOverlapFit_gen.setBounds(1275,445,250,40);
jlblOverlapFitnessSize_gen=new JLabel("20");
jlblOverlapFitnessSize_gen.setBounds(1225,445,50,40);
jsliderOverlapLim_gen=new JSlider(50,100,75);
jsliderOverlapLim_gen.setBounds(1025,445,175,40);
/*
* DEFICIT ZONE
*/
jlblDeficit_gen=new JLabel("4. Fitness of overlap in deficit zone");
jlblDeficit_gen.setBounds(1025,500,400,40);
jlblDeficitFit_gen=new JLabel("<-- deficit fitness -->");
jlblDeficitFit_gen.setBounds(1275,545,250,40);
jlblDeficitFitnessSize_gen=new JLabel("20");
jlblDeficitFitnessSize_gen.setBounds(1225,545,50,40);
jsliderDeficit=new JSlider(50,100,75);
jsliderDeficit.setBounds(1025,545,175,40);
/*
* Grid On
*/
gridOn=new JCheckBox(" G R I D S W I T C H");
gridOn.setBounds(1175,700,500,40);
gridOn.setSelected(true);
jlblGrid=new JLabel(" Switch the grid on or off");
jlblGrid.setBounds(1025,700,150,40);
/*
* ADD THE PANEL
*/
pnl=new GAFuncPanel(graphNodeList, GLOBAL_CellObjList);
pnl.setBounds(0,0,1000,1000);
setLayout(null);
add(pnl);
add(jlblScale);
add(jlblTranslate);
add(jtfScale);
add(jtfTranslate);
add(jbtnTransform);
add(jlblDept);
add(jsliderDept);
add(jlblDeptFit);
add(jbtnDept);
add(jlblalgoname);
add(jbtnRunAlgo);
add(jlblOverlapFit_peri);
add(jsliderOverlapLim_peri);
add(jlblOverlapFitnessSize_peri);
add(jlblOverlap_peri);
add(jsliderOverlapLim_inter);
add(jlblOverlapFitnessSize_inter);
add(jlblOverlapFit_inter);
add(jlblOverlap_inter);
add(jlblOverlap_gen);
add(jlblOverlapFit_gen);
add(jlblOverlapFitnessSize_gen);
add(jsliderOverlapLim_gen);
add(jlblFitnessFields);
add(jlblFitnessReturned);
add(jlblDeficit_gen);
add(jlblDeficitFit_gen);
add(jlblDeficitFitnessSize_gen);
add(jsliderDeficit);
add(gridOn);
add(jlblGrid);
gridOn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(gridOn.isSelected()==true){
pnl.showGrid=false;
}else{
pnl.showGrid=true;
}
}
});
jbtnTransform.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
double scaleX=Double.parseDouble(jtfScale.getText().split(",")[0]);
double scaleY=Double.parseDouble(jtfScale.getText().split(",")[1]);
double translateX=Double.parseDouble(jtfTranslate.getText().split(",")[0]);
double translateY=Double.parseDouble(jtfTranslate.getText().split(",")[1]);
pnl.scaleX=scaleX;
pnl.scaleY=scaleY;
pnl.translateX=translateX;
pnl.translateY=translateY;
pnl.Update(scaleX,scaleY,translateX,translateY);
}
});
jbtnRunAlgo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
constructCells();
}
});
}
public void constructCells(){
pnl.fitness_peri=0;
pnl.fitness_cells_used_inter=0;
pnl.fitness_cells_used_gen=0;
pnl.funcObjList.clear();
pnl.periCellObjList.clear();
pnl.periPathList.clear();
pnl.interCellObjList.clear();
pnl.interPathList.clear();
pnl.genPathList.clear();
pnl.genCellObjList.clear();
pnl.getPeriCells();
pnl.getInterCells();
pnl.getGeneralCells();
double sc=1.0;
for(int i=0; i<funcNodeObjList.size(); i++){
FuncNodeObj node_obj=funcNodeObjList.get(i);
String node_loc=node_obj.getLocation().toLowerCase();
int node_num=(int)node_obj.getQnty();
double node_ar=node_obj.getAr_each()/sc;
String node_name=node_obj.getName();
int node_id=node_obj.getId();
int[] node_rgb=node_obj.getRgb();
double[] aspect=node_obj.getAspectRatio();
if(node_loc.equals("peripheral")){
pnl.allocatePeripheralFunction(node_num, node_ar,
node_name, node_id, node_rgb, aspect);
}else if(node_loc.equals("interstitial")){
pnl.allocateInterstitialFunction(node_num, node_ar,node_name,
node_id,node_rgb,aspect);
}else{
pnl.allocateGeneralFunction(node_num, node_ar,node_name,
node_id,node_rgb,aspect);
}
}
pnl.plottedCells(false);
//pnl.plottedCells(true);
}
@Override
public void actionPerformed(ActionEvent e) {
/*
* PERIPHERAL SLIDER VALUE
*/
double peri_sliderVal=(double)jsliderOverlapLim_peri.getValue()/100;
String peri_sliderValStr=String.valueOf(peri_sliderVal);
jlblOverlapFitnessSize_peri.setText(""+peri_sliderValStr);
/*
* OVERLAP PERIPHERAL FITNESS
*/
pnl.fitness_peri=Double.parseDouble(jlblOverlapFitnessSize_peri.getText());
/*
* INTERSTITIAL SLIDER VALUE
*/
double inter_sliderVal=(double)jsliderOverlapLim_inter.getValue()/100;
String inter_sliderValStr=String.valueOf(inter_sliderVal);
jlblOverlapFitnessSize_inter.setText(""+inter_sliderValStr);
/*
* OVERLAP INTERSTITIAL FITNESS
*/
pnl.fitness_inter=Double.parseDouble(jlblOverlapFitnessSize_inter.getText());
/*
* GENERAL SLIDER VALUE
*/
double gen_sliderVal=(double)jsliderOverlapLim_gen.getValue()/100;
String gen_sliderValStr=String.valueOf(gen_sliderVal);
jlblOverlapFitnessSize_gen.setText(""+gen_sliderValStr);
/*
* OVERLAP GENERAL FITNESS
*/
pnl.fitness_gen=Double.parseDouble(jlblOverlapFitnessSize_gen.getText());
/*
* DEFICIT SLIDER VALUE
*/
double defi_sliderVal=(double)jsliderDeficit.getValue()/100;
String defi_sliderValStr=String.valueOf(defi_sliderVal);
jlblDeficitFitnessSize_gen.setText(""+defi_sliderValStr);
/*
* OVERLAP GENERAL FITNESS
*/
pnl.fitness_defi=defi_sliderVal;
repaint();
}
}
<file_sep>package org.pw.dto;
import java.awt.geom.Area;
import java.util.ArrayList;
public class FuncNodeObj {
int id;
String rel_id;
String name;
double qnty;
double ar_each;
double dim;
double xPos;
double yPos;
double weight;
int[] rgb;
String adj_to;
boolean selected=false;
String zone;
double[] aspect_ratio;
String location;
String department;
ArrayList<Area>graphArea;
public FuncNodeObj(double xPos_, double yPos_){
xPos=xPos_;
yPos=yPos_;
}
public FuncNodeObj(int id_, String name_, double qnty_, double ar_each_, double dim_,
String adj_to_, int[] rgb_, String loc_, String zone_, String dept_,
double[] asp_r_){
id=id_;
name=name_;
qnty=qnty_;
ar_each=ar_each_;
dim=dim_;
adj_to=adj_to_;
rgb=new int[3];
for(int i=0; i<rgb_.length; i++){
rgb[i]=rgb_[i];
}
location=loc_;
rel_id="0";
graphArea=new ArrayList<Area>();
zone=zone_;
aspect_ratio=asp_r_;
department=dept_;
weight=qnty*ar_each;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getRel_id() {
return rel_id;
}
public void setRel_id(String rel_id) {
this.rel_id = rel_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getQnty() {
return qnty;
}
public void setQnty(double qnty) {
this.qnty = qnty;
}
public double getAr_each() {
return ar_each;
}
public void setAr_each(double ar_each) {
this.ar_each = ar_each;
}
public double getDim() {
return dim;
}
public void setDim(double dim) {
this.dim = dim;
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
this.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
this.yPos = yPos;
}
public int[] getRgb() {
return rgb;
}
public void setRgb(int[] rgb) {
this.rgb = rgb;
}
public String getAdj_to() {
return adj_to;
}
public void setAdj_to(String adj_to) {
this.adj_to = adj_to;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getLocation() {
return location;
}
public void setLocation(String loc_) {
this.location = location;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public ArrayList<Area> getGraphNodeArea() {
return graphArea;
}
public void setGraphNodeArea(ArrayList<Area> graphicArea) {
this.graphArea = graphicArea;
}
public String getDeparment(){
return department;
}
public void setDepartment(String s){
department=s;
}
public double[] getAspectRatio(){
return aspect_ratio;
}
public void setAspectRatio(double[] asp_){
aspect_ratio=asp_;
}
public String returnInfo(){
double asp0=aspect_ratio[0];
double asp1=aspect_ratio[1];
String asp_rat=asp0+","+asp1;
String s=("id:"+id+"|- name "+name+"|- dept "+department+"|- zone "+zone+"|-qnty" + qnty+
"|- area(each)"+ar_each + "|- aspect "+asp_rat);
return s;
}
}
| dfcd7a2ace7be826fa73abb0a5feab7625898edf | [
"Java"
] | 3 | Java | nirvik00/spg2.0_today | 98f45a0e7d6f4965202ef9d860a4d3559a21d495 | 504592d3915b259fee650d4b2db6dde3ed55aa19 | |
refs/heads/master | <repo_name>opensafely/emis-smoke-tests<file_sep>/analysis/study_definition.py
from cohortextractor import StudyDefinition, patients, codelist_from_csv
asthma_dx_codes = codelist_from_csv(
"codelists/primis-covid19-vacc-uptake-ast.csv", system="snomed", column="code"
)
asthma_rx_codes = codelist_from_csv(
"codelists/primis-covid19-vacc-uptake-astrx.csv", system="snomed", column="code"
)
study = StudyDefinition(
index_date="2021-01-20", # Third Wednesday in January
population=patients.satisfying("registered = 1 AND NOT has_died"),
registered=patients.registered_as_of(
"index_date",
return_expectations={
"incidence": 0.95,
"date": {"earliest": "2000-01-01", "latest": "2099-12-31"},
},
),
has_died=patients.died_from_any_cause(
on_or_before="index_date",
return_expectations={
"incidence": 0.95,
"date": {"earliest": "2000-01-01", "latest": "2099-12-31"},
},
),
asthma_dx_today=patients.with_these_clinical_events(
asthma_dx_codes,
between=["index_date", "index_date"],
return_expectations={
"incidence": 0.05,
"date": {"earliest": "2000-01-01", "latest": "2099-12-31"},
},
),
asthma_rx_today=patients.with_these_medications(
asthma_rx_codes,
between=["index_date", "index_date"],
return_expectations={
"incidence": 0.05,
"date": {"earliest": "2000-01-01", "latest": "2099-12-31"},
},
),
)
<file_sep>/analysis/count_occurrences.py
import csv
import json
with open("output/input.csv") as f:
reader = csv.reader(f)
headers = next(reader)
asthma_dx_ix = headers.index("asthma_dx_today")
asthma_rx_ix = headers.index("asthma_rx_today")
asthma_dx_today = 0
asthma_rx_today = 0
for row in reader:
if row[asthma_dx_ix] == "1":
asthma_dx_today += 1
if row[asthma_rx_ix] == "1":
asthma_rx_today += 1
output = {"asthma_dx_today": asthma_dx_today, "asthma_rx_today": asthma_rx_today}
with open("output/counts.json", "w") as f:
json.dump(output, f, indent=2)
| 76d49283b26556d48336a930b5da314604ee4703 | [
"Python"
] | 2 | Python | opensafely/emis-smoke-tests | 4f4f2b9df3abccc5fe0c214f1abdf102d172b4cf | ec0720ebfdbad0dca28bdddaf5591be98735bc61 | |
refs/heads/main | <repo_name>arcrozier/HAL<file_sep>/chatbot/consumers.py
import json
import logging
import re
from typing import Final
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.exceptions import StopConsumer
class MessageConsumer(AsyncWebsocketConsumer):
placeholder: Final = "I don't understand"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.model = None
self.on = False
self.conversation = ''
async def connect(self):
await self.accept()
async def disconnect(self, close_code):
raise StopConsumer()
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
category = text_data_json['type']
if category == "status":
if message == "on":
# imports necessary dependencies - won't need to be imported later
import tensorflow.compat.v1 as tf
from .gpt2.src import model, sample, encoder
from tensorflow.python.framework.errors_impl import InvalidArgumentError
logging.getLogger(__name__).info('Dependencies loaded')
self.on = True
await self.send(json.dumps({ # tells webpage that the model is ready
'type': 'status',
'message': 'on'
}))
elif message == "off":
self.on = False
if category == "message" and self.on:
# todo doesn't send immediately, waits until all messages are ready to be sent
await self.send(json.dumps({
'type': 'status',
'message': 'typing',
}))
print('awaiting typing status')
self.conversation = '\n'.join([self.conversation, message])
sample = await self.interact_model(self.conversation)
find_eot = re.match(r'.+?(?=<\|endoftext\|>|$)', sample, re.DOTALL)
find_sentence = re.match(r'(?:.+?[.!?][ \n]){2}', sample, re.DOTALL | re.MULTILINE)
print(find_eot, find_sentence)
if find_eot is not None and find_sentence is not None:
reply = find_eot if len(find_eot.group(0)) < len(find_sentence.group(0)) else find_sentence
else:
reply = find_eot if find_eot is not None else find_sentence
if reply is None:
reply = self.placeholder
else:
reply = reply.group(0)
self.conversation = '\n'.join([self.conversation, reply])
await self.send(json.dumps({
'type': 'reply',
'message': reply,
}))
await self.send(json.dumps({
'type': 'status',
'message': 'done typing',
}))
def make_response(self, prompt: str):
# this is where hyper parameter tuning would go
self.interact_model(prompt, length=1, top_k=40, top_p=0.9)
@staticmethod
async def interact_model(
prompt: str,
model_name: str = '117M',
seed: int = None,
length: int = None,
temperature: float = 1,
top_k: int = 0,
top_p: float = 0.0
):
"""
Interactively run the model
:prompt : String, the prompt for the model to generate with
:model_name=117M : String, which model to use
:seed=None : Integer seed for random number generators, fix seed to reproduce
results
:length=None : Number of tokens in generated text, if None (default), is
determined by model hyperparameters
:temperature=1 : Float value controlling randomness in boltzmann
distribution. Lower temperature results in less random completions. As the
temperature approaches zero, the model will become deterministic and
repetitive. Higher temperature results in more random completions.
:top_k=0 : Integer value controlling diversity. 1 means only 1 word is
considered for each step (token), resulting in deterministic completions,
while 40 means 40 words are considered at each step. 0 (default) is a
special setting meaning no restrictions. 40 generally is a good value.
:top_p=0.0 : Float value controlling diversity. Implements nucleus sampling,
overriding top_k if set to a value > 0. A good setting is 0.9.
"""
import numpy as np
import os
import tensorflow.compat.v1 as tf
from .gpt2.src import model, sample, encoder
from tensorflow.python.framework.errors_impl import InvalidArgumentError
batch_size = 1
enc = encoder.get_encoder(model_name)
hparams = model.default_hparams()
with open(os.path.join(os.path.dirname(__file__), 'gpt2', 'src', 'models', model_name, 'hparams.json')) as f:
dict2 = json.load(f)
for key, value in hparams.items():
hparams[key] = dict2[key]
if length is None:
length = hparams['n_ctx'] // 2
elif length > hparams['n_ctx']:
raise ValueError("Can't get samples longer than window size: %s" % hparams['n_ctx'])
with tf.Session(graph=tf.Graph()) as sess:
context = tf.placeholder(tf.int32, [batch_size, None])
np.random.seed(seed)
tf.set_random_seed(seed)
output = sample.sample_sequence(
hparams=hparams, length=length,
context=context,
batch_size=batch_size,
temperature=temperature, top_k=top_k, top_p=top_p
)
saver = tf.train.Saver()
ckpt = tf.train.latest_checkpoint(os.path.join(os.path.dirname(__file__), 'gpt2', 'src', 'models',
model_name))
saver.restore(sess, ckpt)
context_tokens = enc.encode(prompt)
for _ in range(0, 2):
try:
out = sess.run(output, feed_dict={
context: [context_tokens]
})[:, len(context_tokens):]
text = enc.decode(out[0])
print("=" * 40 + " SAMPLE " + "=" * 40)
print(text)
return text
except InvalidArgumentError as e:
print(str(e))
<file_sep>/requirements.txt
channels
Django
numpy
tensorflow-gpu
regex
tqdm
requests
websockets
Twisted[tls,http2]
python-dotenv
daphne
<file_sep>/start.sh
#!/bin/bash
cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P
{ .venv/bin/daphne --b localhost -p 8001 hal.asgi:application; } >> hal.log 2>&1
<file_sep>/hal/asgi.py
"""
ASGI config for hal project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import sys
print(sys.path)
import os
from dotenv import load_dotenv
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application
import django
from chatbot import routing
load_dotenv()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hal.settings')
os.environ['DJANGO_ALLOW_ASYNC_UNSAFE'] = "true"
django.setup()
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns,
)
)})
<file_sep>/chatbot/urls.py
from django.urls import path
from chatbot import views
urlpatterns = [
path('', views.home, name='background'),
path('bot/', views.bot, name='chatbot'),
]
<file_sep>/README.md
# HAL
A chatbot to emulate HAL from *2001: A Space Odyssey*
## Installing Dependencies
This project requires
[Python](https://www.python.org/downloads/).
From your command line, `cd` into the repo. Once there, run
`pip install -r requirements.txt`. If that doesn't work, you can also try
`pip3 install -r requirements.txt`,
`python -m pip install -r requirements.txt`, or
`python3 -m pip install -r requirements.txt`. If that doesn't work,
ensure Python is installed and on your PATH.
## Quickstart Guide
Once you've cloned the repo, all you need to do is `cd` into the repo
from your command line and run `python manage.py runserver`. If it doesn't
work, please ensure Python is on your PATH or try
`python3 manage.py runserver`.
You can then interact with HAL at http://localhost:8000. If port 8000 is in use,
call `runserver` with a port argument: `python3 manage.py runserver <port>`.
Running without specifying a port is the same as `python3 manage.py runserver 8000`.
If you use a different port, make sure you access the site with that port:
http://localhost:<port>
<file_sep>/chatbot/views.py
from django.shortcuts import render
def home(request):
return render(request, 'chatbot/background.html')
def bot(request):
return render(request, 'chatbot/HAL.html')
<file_sep>/chatbot/routing.py
from django.urls import re_path
from chatbot import consumers
websocket_urlpatterns = [
re_path(r'input/$', consumers.MessageConsumer.as_asgi()),
]
| 72ceeb1ebeb0110f05652ba16031726a94ea222e | [
"Markdown",
"Python",
"Text",
"Shell"
] | 8 | Python | arcrozier/HAL | 64609fdf152eb35ca3f34ea30bf5d9c7e3e09de5 | 420972793a6a61c518a748bca23526f54ecfa4bc | |
refs/heads/master | <file_sep>export const THEMES_NAMES = {
light: "light",
dark_grey: "dark_grey",
green: "green",
purpule: "purpule",
rainbow: "rainbow",
};
export const REFRESH_RATE_MS = 500;
export const SETTINGS_FILE_NAME = "settings.json";
export const MUSIC_FOLDER = "/Music/";
<file_sep>// See the Electron documentation for details on how to use preload scripts:
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts
// eslint-disable-next-line import/no-extraneous-dependencies
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
getMusicFiles: (folderPath) =>
ipcRenderer.invoke("getMusicFiles", folderPath),
networkInterfaces: () => ipcRenderer.invoke("networkInterfaces"),
isLinux: () => ipcRenderer.invoke("isLinux"),
startParameters: () => ipcRenderer.invoke("startParameters"),
minimize: () => ipcRenderer.invoke("minimize"),
close: () => ipcRenderer.invoke("close"),
appVersion: () => ipcRenderer.invoke("appVersion"),
getUserDataPath: () => ipcRenderer.invoke("getUserDataPath"),
profileStartTime: () => ipcRenderer.invoke("profileStartTime"),
bufferFrom: () => ipcRenderer.invoke("bufferFrom"),
listSerialPorts: () => ipcRenderer.invoke("listSerialPorts"),
pathJoin: (args = []) => ipcRenderer.invoke("pathJoin", args),
pathDirname: (filePath) => ipcRenderer.invoke("pathDirname", filePath),
existsSync: (stringPath = "") => ipcRenderer.invoke("existsSync", stringPath),
readFileSync: (stringPath = "") =>
ipcRenderer.invoke("readFileSync", stringPath),
writeFileSync: (args) => ipcRenderer.invoke("writeFileSync", args),
writeFile: (args) => ipcRenderer.invoke("writeFile", args),
CPUtemp: () => ipcRenderer.invoke("CPUtemp"),
getSong: (filePath) => ipcRenderer.invoke("getSong", filePath),
getWifiSSID: () => ipcRenderer.invoke("getWifiSSID"),
getListOfAvailableNetworks: () =>
ipcRenderer.invoke("getListOfAvailableNetworks"),
disconnectFromWifi: () => ipcRenderer.invoke("disconnectFromWifi"),
connectToWifiNetwork: () => ipcRenderer.invoke("connectToWifiNetwork"),
onCAN: (callback) => ipcRenderer.on("fromCAN", callback),
sendMsgToCAN: (data) => ipcRenderer.invoke("sendMsgToCAN", data),
});
<file_sep>import { BrowserWindow } from "electron";
import { wrtieIBUSdataToFile } from "./utils";
const { IbusDevices } = require("ibus");
// config
export function sendAllData(data) {
// id, from, to, message, message hex, analyzing, description
return `${data.id} | ${IbusDevices.getDeviceName(
data.src
)} | ${IbusDevices.getDeviceName(data.dst)} |
${data.msg} |
${data}`;
}
export default function initIBUSinMain(ibusInterface) {
// disables logs from ibus (lots of colorfull spam, "ibus" is using "debug" package)
// const debug = require("debug");
// debug.disable();
// Configure your device location
function init() {
try {
ibusInterface.startup();
} catch (error) {
console.log(error);
}
}
// main start
// if (window.appData.isLinux) {
init();
// }
// Message structure:
// 1. Transmitter address (8 bit Source ID)
// 2. Length of data (number of following message bytes)
// 3. Receiver address (8 bit Destination ID)
// 4. Detailed description of message (maximum 32 bytes of data)
// 5. Summary of transmitted information (check sum)
// | Source ID | Length | Dest ID | Message Data | Checksum |
// |-----------|--------|---------|--------------|----------|
// | | | Length |
// Add an event listener on the ibus interface output stream.
function onIbusDataHandler(data) {
console.log(data)
const msgDescryption = "";
const buffMsg = Buffer.from(data.msg);
const buffMsgHex = buffMsg.toString("hex").toLowerCase();
const output = {
name: null,
data: null,
};
function sendToRenderer(dataTosend) {
BrowserWindow.getFocusedWindow().webContents.send("fromCAN", dataTosend);
}
// remove empty data, like: from BodyModule - 0 to BodyModule - 0
// tre for less data from CAN, for les noise in debuging (only knowns comands?)
if (true) {
if ((data.src === "0" && data.dst === "0") || data.src === "a4") {
// end this round of data
}
if (data.src === "3b" && data.dst === "80" && buffMsgHex === "410701") {
// filters this: id: 1588784831880 | GraphicsNavigationDriver - 3b | InstrumentClusterElectronics - 80 Message: A | 410701 | [object Object] |
}
}
// from: MultiFunctionSteeringWheel && to: Radio or Telephone ('c8')
if (data.src === "50" && (data.dst === "68" || data.dst === "c8")) {
// volume down steering wheel
if (data.msg === Buffer.from([50, 16]).toString("ascii")) {
// Volume down button steering wheel
output.name = "volDown";
sendToRenderer(output);
}
// volume up steering wheel
if (data.msg === Buffer.from([50, 17]).toString("ascii")) {
// Volume up button steering wheel
output.name = "volUp";
sendToRenderer(output);
}
// previous track steering wheel
if (data.msg === Buffer.from([59, 8]).toString("ascii")) {
// Arrow up? button steering wheel
output.name = "steeringWheelArrowDown";
sendToRenderer(output);
}
// next song stearing wheel
if (data.msg === Buffer.from([59, 1]).toString("ascii")) {
// Arrow up button steering wheel
output.name = "steeringWheelArrowUp";
sendToRenderer(output);
}
}
// from: MultiFunctionSteeringWheel
if (data.src === "50") {
// face button steering wheel
if (buffMsgHex === "3b40") {
// Face button steering wheel
output.name = "pauseAudio";
sendToRenderer(output);
}
// RT button steering wheel
if (buffMsgHex === "3b80") {
// RT button steering wheel
output.name = "muteAudio";
sendToRenderer(output);
}
}
// egz WHOLE message: 80 0a ff 24 03 00 2b 31 32 2e 35 61 80 0f ff 24 02 00 31 30 2e 31 31 2e 32 30 31 39 5d 80 05 bf 18 00 06 24
// or WHOLE message: Buffer(36) [128, 10, 255, 36, 3, 0, 43, 49, 50, 46, 53, 97, 128, 15, 255, 36, 2, 0, 49, 48, 46, 49, 49, 46, 50, 48, 49, 57, 93, 128, 5, 191, 24, 0, 6, 36]
// 80 source, 0a length, ff destenation, 2b 31 32 2e 35 actual temperature, there is allso time later in string
if (
data.src === "80" &&
data.dst === "ff" &&
buffMsgHex.substring(0, 4) === "2403"
) {
// outside temperature
output.name = "tempOutside";
output.data = buffMsgHex.substring(6, 16);
sendToRenderer(output);
}
// time from instrument cluster not GPS
// data.msg -> first 3 parts in buffer describe is it time ([36, 1, 0]) in hex: 24010031373a30392020
if (
data.src === "80" &&
data.dst === "ff" &&
buffMsgHex.substring(0, 6) === "240100"
) {
// remove 3 first parts from buffer and remove 2 parts from end -> this give time in format HH:MM egz 12:45 (12h or 24h?)
output.name = "timeFromInstrumentCluster";
output.data = buffMsg.slice(3, 9).toString("utf-8");
sendToRenderer(output);
}
// temperature outside and coolant temperature
// from: InstrumentClusterElectronics - 80 to: GlobalBroadcastAddress - bf msg: 19154b00
if (
data.src === "80" &&
data.dst === "bf" &&
buffMsgHex.substring(0, 2) === "19"
) {
// first hex in message indicates temperature outside and coolant temperatur message
// to decimal conversion
// in Celsius
// CHECK IF ITS OK
output.data.tempOutside = parseInt(buffMsgHex.substring(2, 4), 16);
output.data.coolantTemp = parseInt(buffMsgHex.substring(4, 6), 16);
output.name = "tempOutsideAndCoolantTemp";
sendToRenderer(output);
}
if (data.src === "80" && data.dst === "ff") {
// if (buffMsg.slice(1, 1).toString('hex') === '04') {
if (data.msg[1] === "04") {
// fuel consumption 1
output.name = "fuleConsumption1";
output.data = data.msg
.slice(3, 14)
.toString("utf-8")
.replace(".", ",")
.trim();
sendToRenderer(output);
}
if (buffMsgHex.slice(0, 4) === "2405") {
// if (data.msg[1] === '05') {
// fuel consumption 2
// src: "80";
// len: "9";
// dst: "ff";
// msg: {"type":"Buffer","data":[36,5,0,32,56,46,52]};
// 24050020382e34
// crc: "55";
output.name = "fuleConsumption2";
output.data = buffMsgHex
.slice(6, 14)
.toString("utf-8")
.replace(".", ",")
.trim();
sendToRenderer(output);
}
if (buffMsgHex.slice(0, 4) === "2406") {
output.name = "range";
output.data = buffMsgHex.slice(6, 14).toString("utf-8").trim();
sendToRenderer(output);
}
if (data.msg[1] === "07") {
// window.CANdata.distance
output.name = "distance";
output.data = data.msg.slice(3, 14).toString("hex");
sendToRenderer(output);
}
if (data.msg[1] === "09") {
output.name = "speedLimit";
output.data = data.msg.slice(3, 14).toString("hex");
sendToRenderer(output);
}
if (buffMsgHex.slice(0, 6) === "240a00") {
output.data = buffMsgHex.slice(6, 14);
output.name = "avgSpeed";
sendToRenderer(output);
}
}
// if from NavigationEurope 7f
if (data.src === "7f") {
// Town from NavModule GPS
// data.msg -> third part ("1") in buffer msg describe is it town ([164, 0, 1])
if (buffMsgHex.slice(0, 6) === "a40001") {
output.data = buffMsg
.slice(3, buffMsg.indexOf("0", 5))
.toString("utf-8");
output.name = "navTownName";
}
// Street from NavModule GPS
// data.msg -> third part ("2") in buffer msg describe is it street ([164, 0, 2])
if (buffMsgHex.slice(0, 6) === "a40002") {
output.data = buffMsg
.slice(3, buffMsg.indexOf("0", 5))
.toString("utf-8");
output.name = "navStreetName";
}
// GPS cords, time, altitude
// data.msg -> first 3 parts in buffer describe is it GPS position ([162, 1, 0]) -> 'a20100' -- maybe only one part?? [162] - > 'a2', it can be ([162, 0, 0])
if (buffMsgHex.slice(0, 6) === "a20100") {
// buffer egxample: [162, 1, 0, 81, 64, 82, 80, 0, 32, 87, 65, 144, 1, 16, 0, 16, 71, 73] -> hex -> a2 01 00 51 40 52 50 00 20 57 41 90 01 10 00 10 47 49
// first 3 can be erased (a20100) -> 514052500020574190011000104749
// from nav encoder: 2019-10-13 10:25:49.105||NAV |TEL |Current position|GPS fix; 51°40'52.5"N 20°57'41.9"E; Alt 111m; UTC 08:25:49
// 51 (stopnie) 40 (minuty) 52 (sekundy) 50 (połowki sekundy N?) 00 (separator?) 20 (stopnie) 57 (minuty) 41 (sekundy) 90 (połowki sekundy E?) 01 10 00 (wysokość 111m, traktować jak stringi i połączyć? wtedy 01 + 10 + 00 daje 011000 -> 110m?) 10 (UTC godzina)47 (UTC minuty) 49 (UTC sekundy)
output.name = "navLatLngTimeLatitiude";
output.data.lat = buffMsg.slice(3, 7).toString("hex");
output.data.lng = buffMsg.slice(8, 12).toString("hex");
output.data.altitude = parseInt(buffMsgHex.slice(24, 28), 10);
output.data.utcTime = buffMsg.slice(15, 18).toString("hex");
sendToRenderer(output);
}
}
// light dimmer
// data.msg -> hex -> 5C FF FC FF 00 -> lights on?
// data.msg -> hex -> 5c ff c9 ff 00 -> lights on?
if (data.src === "d0" && data.dst === "bf" && buffMsgHex === "5cff3fff00") {
output.data = "day";
output.name = "lightSensor";
sendToRenderer(output);
}
if (data.src === "d0" && data.dst === "bf" && buffMsgHex === "5cfe3fff00") {
output.data = "night";
output.name = "lightSensor";
sendToRenderer(output);
}
// debugLog('[app] Analyzing: ', Buffer.from(data), '\n');
const msgDate = new Date();
wrtieIBUSdataToFile(
msgDate.getHours(),
":",
msgDate.getMinutes(),
":",
msgDate.getSeconds(),
":",
msgDate.getMilliseconds(),
" | id: ",
data.id,
" | src: ",
IbusDevices.getDeviceName(data.src),
"| dst: ",
IbusDevices.getDeviceName(data.dst),
"| msg:",
data.msg,
"| buffMsgHex:",
buffMsgHex,
"| data: ",
JSON.stringify(data),
"| msgDescryption: ",
msgDescryption
);
sendToRenderer(output); // null
}
// Cleanup and close the device when exiting.
function onSignalInt() {
ibusInterface.shutdown(() => {
process.exit();
});
}
// events
ibusInterface.on("data", onIbusDataHandler);
// implementation
// process.on('SIGINT', onSignalInt);
process.on("exit", onSignalInt);
}
<file_sep>// const { fs } = require("fs");
// export default function debugLog(...args) {
// // let args = arguments;
// let output = "";
// if (window.appData.debugMode === true) {
// args.forEach((arg) => {
// if (typeof arg === "object") {
// // console.log(JSON.stringify(arg, null, 4));
// Object.keys(arg).forEach((property) => {
// output += `${property}: ${JSON.stringify(arg[property])};\n`;
// });
// console.log(output);
// } else if (args.lastIndexOf("colorGREEN") >= 0) {
// args.pop();
// console.log("%c%s", "background: green;", arg);
// } else if (args.lastIndexOf("colorOwindow.CANdata.range") >= 0) {
// args.pop();
// console.log(
// "%c%s",
// "background: owindow.CANdata.range; color: black;",
// arg
// );
// } else {
// console.log(arg);
// }
// });
// }
// }
export default function debugLog(...args) {
if (window.appData.debugMode) {
// eslint-disable-next-line prefer-spread
console.log.apply(console, args);
}
}
export function hexToAscii(str) {
if (str === " " || str.length < 7) {
return null;
}
const hex = str.toString();
let output = "";
for (let n = 0; n < hex.length; n += 2) {
output += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return output;
}
export function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
export function clampNumbers(value, min, max) {
return Math.min(Math.max(value, min), max);
}
<file_sep>// SERIAL PORT MOCKING
//
const { MockBinding } = require("@serialport/binding-mock");
const { SerialPortStream } = require("@serialport/stream");
const { ReadlineParser } = require("@serialport/parser-readline");
// Create a port and enable the echo and recording.
MockBinding.createPort("/dev/ROBOT", { echo: true, record: true });
const port = new SerialPortStream({
binding: MockBinding,
path: "/dev/ROBOT",
baudRate: 9600,
});
/* Add some action for incoming data. For example,
** print each incoming line in uppercase */
const parser = new ReadlineParser({ length: 8 });
port.pipe(parser).on("data", (line) => {
console.log(line);
console.log(line.toString());
});
// wait for port to open...
port.on("open", () => {
// ...then test by simulating incoming data
setInterval(() => {
console.log("emitingData");
port.port.emitData("\x50\x04\x68\x3B\x21\xA6");
}, 1000);
});
/* Expected output:
HELLO, WORLD!
*/
<file_sep>/**
* This file will automatically be loaded by webpack and run in the "renderer" context.
* To learn more about the differences between the "main" and the "renderer" context in
* Electron, visit:
*
* https://electronjs.org/docs/tutorial/application-architecture#main-and-renderer-processes
*
* By default, Node.js integration in this file is disabled. When enabling Node.js integration
* in a renderer process, please be aware of potential security implications. You can read
* more about security risks here:
*
* https://electronjs.org/docs/tutorial/security
*
* To enable Node.js integration in this file, open up `main.js` and enable the `nodeIntegration`
* flag:
*
* ```
* // Create the browser window.
* mainWindow = new BrowserWindow({
* width: 800,
* height: 600,
* webPreferences: {
* nodeIntegration: true
* }
* });
* ```
*/
import "./css/index.css";
import { settingsInit } from "./js/settings";
import Keyboard from "./js/keyboard";
import "./js/bluetooth";
import { getWifiInfo } from "./js/wifi";
import "./js/translation";
import dialogCloseHandler, {
dialogShowHandler,
modalClasses,
} from "./js/modal";
import playAudio, {
pauseAudio,
muteAudio,
volUp,
volDown,
shuffl,
nextSong,
previousSong,
musicEventRegister,
} from "./js/music-player";
import {
guiUpdateData,
dateAndTimeSetInHTML,
getIPs,
} from "./js/htmlRefreshers";
import updateTimeCANfromInput, { asksCANforNewData } from "./js/canUpdaters";
import { switchTheme } from "./js/themes";
import { menuHideToggle } from "./js/menu";
console.log(
'👋 This message is being logged by "renderer.js", included via webpack'
);
function timeSetModal() {
const elemModal = window.appData.modalTemplateEl.modalTwoInputs;
const modalTime = document.createElement("div");
modalTime.id = "timeModalSet";
modalTime.classList = `${modalClasses[0]} ${modalClasses[1]}`;
modalTime.innerHTML = elemModal;
document.body.appendChild(modalTime);
// add attribute "onclick" to template file
// fire chnage time CAN fucntion
document.querySelector("#timeModalSet dialog .confirm").onclick =
updateTimeCANfromInput();
// second init, for inputs in modal that was created
Keyboard.reinitForInputs();
// set focus on first input to show keyboard
document.querySelector("#timeModalSet dialog input").focus();
}
function fuelConsResetModal() {
// show dialog
const dialogEl = document.getElementById("modalConfirm");
dialogShowHandler(dialogEl);
// after confirm send reset
dialogEl.querySelector(".confirm").addEventListener("click", () => {
// TODO: add reset fuel consumption function
});
}
window.electronAPI.listSerialPorts();
window.addEventListener("DOMContentLoaded", () => {
window.CANdata = {};
window.appData = {
...window.appData,
switchTheme,
timeSetModal,
fuelConsResetModal,
};
// const path = require("path");
window.electronAPI.isLinux().then((data) => {
window.appData.isLinux = data;
});
window.appData.debugMode = true;
// const settings = require('./js/settings.js');
window.electronAPI.startParameters().then((startParameters) => {
if (
startParameters.includes("debug") ||
startParameters.includes("remote-debugging-port=8315")
) {
window.appData.debugMode = true;
}
});
const isTouchDevice = () =>
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0;
if (!isTouchDevice()) {
document.body.style.cursor = "auto";
}
document.getElementById("loader-wrapper").style.display = "none";
document.getElementById("app").classList.remove("hidden");
window.appData.audio = {
...window.appData.audio,
audio: {},
methods: {
playAudio,
pauseAudio,
muteAudio,
volUp,
volDown,
shuffl,
nextSong,
previousSong,
},
};
window.appData.dialogs = {
dialogCloseHandler,
};
window.menuHideToggle = menuHideToggle;
document.getElementById("settings-main-nav").addEventListener("click", () => {
getIPs();
getWifiInfo();
});
// minimizing and closing
document.getElementById("minimize").addEventListener("click", () => {
window.electronAPI.minimize();
});
document.getElementById("closeApp").addEventListener("click", () => {
window.electronAPI.close();
});
//
// bluetooth
document.getElementById("bluetooth").addEventListener("click", () => {
// show/hide bluetooth settings
document
.querySelector("#bluetooth-settings-modal")
.classList.toggle("hide");
});
document.getElementById("btClose").addEventListener("click", () => {
document
.querySelector("#.bluetooth-settings-modal")
.classList.toggle("hide");
});
// display app version from package.json
window.electronAPI.appVersion().then((data) => {
document.getElementById("app_version").innerText = `Version: ${data}`;
});
// do settings file stuff
settingsInit().then(() => {
// initiall start
window.electronAPI
.getMusicFiles(window.appData.settingsFile.musicFolder)
.then((data) => {
window.appData.songsObj = data;
// create audio object
window.appData.audio.audio = new Audio();
musicEventRegister();
playAudio(data[0]);
});
setTimeout(getIPs, 4000);
setTimeout(getWifiInfo, 4000);
asksCANforNewData();
// and repeate checking and asking if necessery every x miliseconds
setInterval(asksCANforNewData, 500);
dateAndTimeSetInHTML();
setInterval(dateAndTimeSetInHTML, 1000);
guiUpdateData();
setInterval(guiUpdateData, 1000);
window.electronAPI.networkInterfaces();
});
});
<file_sep>// https://www.youtube.com/watch?v=N3cq0BHDMOY
const Keyboard = {
elements: {
main: null,
keysContainer: null,
keys: [],
},
eventHandlers: {
oninput: null,
onclose: null,
},
properties: {
value: "",
capsLock: false,
keyboard_type: "",
},
init() {
// Create main elements
this.elements.main = document.createElement("div");
this.elements.keysContainer = document.createElement("div");
// Setup main elements
this.elements.main.classList.add("keyboard", "keyboard--hidden");
this.elements.keysContainer.classList.add("keyboard__keys");
this.elements.keysContainer.appendChild(this.createKeys());
this.elements.keys =
this.elements.keysContainer.querySelectorAll(".keyboard__key");
// Add to DOM
this.elements.main.appendChild(this.elements.keysContainer);
document.body.appendChild(this.elements.main);
// Automatically use keyboard for elements with input
document.querySelectorAll("input:not(.nokeyboard)").forEach((element) => {
this.properties.keyboard_type = element.type;
element.addEventListener("focus", () => {
this.show(element.value);
});
});
document.getElementById("yt-view").addEventListener("click", (e) => {
if (e.path[0].localName !== "input" && e.currentTarget !== "#keyboard") {
Keyboard.close();
Keyboard.triggerEvent("onclose");
}
});
// hide keyboard after focus is lost on input element - for modal
document.querySelectorAll(".backgrounddialog").forEach((element) => {
element.addEventListener("click", (e) => {
if (
e.path[0].localName !== "input" &&
e.currentTarget !== "div#keyboard"
) {
Keyboard.close();
Keyboard.triggerEvent("onclose");
}
});
});
},
// when new input element is created 'Keyboard' dont see them, 'Keyboard' needs to be reinitialized
reinitForInputs() {
// Automatically use keyboard for elements with input
document.querySelectorAll("input:not(.nokeyboard)").forEach((element) => {
this.properties.keyboard_type = element.type;
element.addEventListener("focus", () => {
this.show(element.value);
});
});
// hide in youtube section
// not working
document.getElementById("yt-view").addEventListener("click", (e) => {
if (e.path[0].localName !== "input" && e.currentTarget !== "#keyboard") {
Keyboard.close();
Keyboard.triggerEvent("onclose");
}
});
// hide keyboard after focus is lost on input element - for modal
document.querySelectorAll(".backgrounddialog").forEach((element) => {
element.addEventListener("click", (e) => {
if (
e.path[0].localName !== "input" &&
e.currentTarget !== "div#keyboard"
) {
Keyboard.close();
Keyboard.triggerEvent("onclose");
}
});
});
},
createKeys() {
const fragmentText = document.createDocumentFragment();
const fragmentNumeric = document.createDocumentFragment();
let keyLayoutText = [];
let keyLayoutNumeric = [];
keyLayoutNumeric = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"backspace",
"space",
"enter",
"TEXT",
];
keyLayoutText = [
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"caps",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
"enter",
"done",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"?",
"space",
"backspace",
"NUM",
];
// Creates HTML for an icon
const createIconHTML = (iconName) => `<i class="fas fa-${iconName}"></i>`;
keyLayoutText.forEach((key) => {
const keyElement = document.createElement("button");
// Add attributes/classes
keyElement.setAttribute("type", "button");
keyElement.classList.add("keyboard__key");
switch (key) {
case "backspace":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = createIconHTML("backspace");
keyElement.addEventListener("click", () => {
this.properties.value = this.properties.value.substring(
0,
this.properties.value.length - 1
);
this.triggerEvent("oninput");
});
break;
case "caps":
keyElement.classList.add(
"keyboard__key--wide",
"keyboard__key--activatable"
);
keyElement.innerHTML = createIconHTML("arrow-up");
keyElement.addEventListener("click", () => {
this.toggleCapsLock();
keyElement.classList.toggle(
"keyboard__key--active",
this.properties.capsLock
);
});
break;
case "enter":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = "enter";
keyElement.addEventListener("click", () => {
this.properties.value += "\n";
this.triggerEvent("oninput");
// pig hack for youtube
// update webview adress with values from transprent input
document.querySelector(
"#yt-view"
).src = `https://www.youtube.com/results?search_query=${document
.getElementById("input-for-yt")
.value.replace(" ", "+")}`;
// cleare input
document.getElementById("input-for-yt").value = "";
// end of pig hack
});
break;
case "space":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = "___";
keyElement.addEventListener("click", () => {
this.properties.value += " ";
this.triggerEvent("oninput");
});
break;
case "done":
keyElement.classList.add(
"keyboard__key--wide",
"keyboard__key--dark"
);
keyElement.innerHTML = "hide";
keyElement.addEventListener("click", () => {
this.close();
this.triggerEvent("onclose");
});
break;
case "NUM":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = key;
keyElement.addEventListener("click", () => {
this.toggleNumericAndTextKeyborad("number");
});
break;
default:
keyElement.textContent = key.toLowerCase();
keyElement.addEventListener("click", () => {
this.properties.value += this.properties.capsLock
? key.toUpperCase()
: key.toLowerCase();
this.triggerEvent("oninput");
});
break;
}
fragmentText.appendChild(keyElement);
});
keyLayoutNumeric.forEach((key) => {
const keyElement = document.createElement("button");
// Add attributes/classes
keyElement.setAttribute("type", "button");
keyElement.classList.add("keyboard__key");
switch (key) {
case "backspace":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = createIconHTML("backspace");
keyElement.addEventListener("click", () => {
this.properties.value = this.properties.value.substring(
0,
this.properties.value.length - 1
);
this.triggerEvent("oninput");
});
break;
case "caps":
keyElement.classList.add(
"keyboard__key--wide",
"keyboard__key--activatable"
);
keyElement.innerHTML = createIconHTML("arrow-up");
keyElement.addEventListener("click", () => {
this.toggleCapsLock();
keyElement.classList.toggle(
"keyboard__key--active",
this.properties.capsLock
);
});
break;
case "enter":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = "enter";
keyElement.addEventListener("click", () => {
this.properties.value += "\n";
this.triggerEvent("oninput");
// pig hack for youtube
// update webview adress with values from transprent input
document.querySelector(
"#yt-view"
).src = `https://www.youtube.com/results?search_query=${document
.getElementById("input-for-yt")
.value.replace(" ", "+")}`;
// cleare input
document.getElementById("input-for-yt").value = "";
// end of pig hack
});
break;
case "space":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = "___";
keyElement.addEventListener("click", () => {
this.properties.value += " ";
this.triggerEvent("oninput");
});
break;
case "done":
keyElement.classList.add(
"keyboard__key--wide",
"keyboard__key--dark"
);
keyElement.innerHTML = "hide";
keyElement.addEventListener("click", () => {
this.close();
this.triggerEvent("onclose");
});
break;
case "TEXT":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = key;
keyElement.addEventListener("click", () => {
this.toggleNumericAndTextKeyborad("password");
});
break;
default:
keyElement.textContent = key.toLowerCase();
keyElement.addEventListener("click", () => {
this.properties.value += this.properties.capsLock
? key.toUpperCase()
: key.toLowerCase();
this.triggerEvent("oninput");
});
break;
}
fragmentNumeric.appendChild(keyElement);
});
const fragmentResult = document.createDocumentFragment();
const textWrapper = document.createElement("div");
textWrapper.appendChild(fragmentText);
fragmentResult.appendChild(textWrapper);
const numericWrapper = document.createElement("div");
numericWrapper.appendChild(fragmentNumeric);
fragmentResult.appendChild(numericWrapper);
return fragmentResult;
},
triggerEvent(handlerName) {
if (typeof this.eventHandlers[handlerName] === "function") {
this.eventHandlers[handlerName](this.properties.value);
}
},
toggleCapsLock() {
this.properties.capsLock = !this.properties.capsLock;
this.elements.keys.forEach((key, index) => {
if (key.childElementCount === 0) {
this.elements.keys[index].textContent = this.properties.capsLock
? key.textContent.toUpperCase()
: key.textContent.toLowerCase();
}
});
},
show(initialValue) {
this.properties.value = initialValue || "";
this.elements.main.classList.remove("keyboard--hidden");
this.toggleNumericAndTextKeyborad();
},
close() {
this.properties.value = "";
this.elements.main.classList.add("keyboard--hidden");
},
toggleNumericAndTextKeyborad(manual) {
const firstkeyboard = this.elements.main.querySelector(
".keyboard__keys > div:first-child"
);
if (this.properties.keyboard_type === "number" || manual === "number") {
firstkeyboard.style.left = "-100%";
this.elements.main.querySelector(
".keyboard__keys > div:last-child"
).style.left = "0";
}
if (this.properties.keyboard_type === "password" || manual === "password") {
firstkeyboard.style.left = "0%";
this.elements.main.querySelector(
".keyboard__keys > div:last-child"
).style.left = "100%";
}
},
};
window.addEventListener("DOMContentLoaded", () => {
Keyboard.init();
});
export default Keyboard;
<file_sep>import debugLog, { clampNumbers } from "./utils";
export default async function playAudio(songObj = {}) {
console.log("playAudio");
const { audio } = window.appData.audio;
const { path } = songObj;
if (!path) return;
window.electronAPI.getSong(path).then((data) => {
// window.appData.audio.audio.currentTime = 0;
// window.appData.audio.audio.pause();
audio.src = data;
audio.load();
window.appData.currentSongId = songObj.id;
});
}
export function pauseAudio() {
if (!window.appData.audio.audio.paused) {
window.appData.audio.audio.pause();
}
}
export function muteAudio() {
// works only for "music"
const muteButton = document.querySelector("#music-player .mute.button");
if (window.appData.audio.audio.muted === true) {
window.appData.audio.audio.muted = false;
debugLog("audio unmuted");
// remove class
muteButton.classList.toggle("active");
// hide mute icon on tom of nav element
document.querySelector(
"#notifications-persistant .mute-icon"
).style.opacity = 0;
} else {
window.appData.audio.audio.muted = true;
debugLog("audio muted");
// remove class
muteButton.classList.toggle("active");
// show mute icon on tom of nav element
document.querySelector(
"#notifications-persistant .mute-icon"
).style.opacity = 1;
}
}
export function volUp() {
window.appData.audio.audio.volume = clampNumbers(
(window.appData.audio.audio.volume + 0.1).toFixed(2),
0,
1
);
debugLog("volUp");
}
export function volDown() {
window.appData.audio.audio.volume = clampNumbers(
(window.appData.audio.audio.volume - 0.1).toFixed(2),
0,
1
);
debugLog("volDown");
}
export function shuffl() {
console.log("TODO");
}
export function currentVolume() {
console.log("currentVolume");
const sliVmValue = window.appData.sliderVolumeMusicEl.valueAsNumber;
// update slider value
// set window.appData.audio.audio volume "globaly", value from slider value
window.appData.audio.audio.volume = sliVmValue;
// debugLog(window.appData.audio.audio.volume.toFixed(2));
// debugLog("sliderVolMusicValue: " + sliderVolMusicValue);
}
export function updateThreeSongsInHTML() {
const previousSongHTMLObject = document.getElementById("previousSong");
const currentSongHTMLObject = document.getElementById("currentSong");
const nextSongHTMLObject = document.getElementById("nextSong");
const currentSongID =
window.appData.currentSongId || window.appData.songsObj[0].id;
if (currentSongID < 0) return;
const currentSongIndex = window.appData.songsObj.findIndex(
(obj) => obj.id === currentSongID
);
let nextSongIndex = currentSongIndex + 1;
// if this is last song then go to first
if (nextSongIndex === window.appData.songsObj.length) {
nextSongIndex = 0;
}
let prevSongIndex = currentSongIndex - 1;
// if this is first song then go to last song
if (prevSongIndex < 0) {
prevSongIndex = window.appData.songsObj.length - 1;
}
// update HTML with songs
nextSongHTMLObject.innerText = window.appData.songsObj[nextSongIndex].name
? window.appData.songsObj[nextSongIndex].name
: "";
currentSongHTMLObject.innerText = window.appData.songsObj[currentSongIndex]
.name
? window.appData.songsObj[currentSongIndex].name
: "";
previousSongHTMLObject.innerText = window.appData.songsObj[prevSongIndex].name
? window.appData.songsObj[prevSongIndex].name
: "";
}
export function nextSong() {
const currentSongID = window.appData.currentSongId;
const currentSongIndex = window.window.appData.songsObj.findIndex(
(obj) => obj.id === currentSongID
);
let nextSongIndex = currentSongIndex + 1;
if (window.appData.songsObj[0]) {
// if this is last song then go to first
if (nextSongIndex >= window.window.appData.songsObj.length) {
nextSongIndex = 0;
}
window.appData.currentSongId = window.appData.songsObj[nextSongIndex].id;
window.appData.audio.audio.pause();
playAudio(window.appData.songsObj[nextSongIndex]);
debugLog("next song");
}
}
export function previousSong() {
const currentSongID = window.appData.currentSongId;
const currentSongIndex = window.window.appData.songsObj.findIndex(
(obj) => obj.id === currentSongID
);
let prevSongIndex = currentSongIndex - 1;
if (window.appData.songsObj[0]) {
// if this is first song then go to last song
if (prevSongIndex < 0) {
prevSongIndex = window.appData.songsObj.length - 1;
}
debugLog(
`previous song - prevSongIndex: ${prevSongIndex}, currentSongIndex: ${currentSongIndex}`
);
playAudio(window.appData.songsObj[prevSongIndex]);
}
}
export function musicEventRegister() {
const plyButon = document.querySelector("#music-player .play.button");
const pauseButon = document.querySelector("#music-player .pause.button");
// setting sliders values to default window.appData.audio.audio value (at start they are different)
window.appData.sliderVolumeMusicEl =
document.getElementById("volume-music-bar");
window.appData.sliderVolumeMusicEl.value = window.appData.audio.audio.volume;
window.appData.sliderVolumeMusicEl.setAttribute(
"value",
window.appData.sliderVolumeMusicEl.value
);
// second time as above
// on every volume change update slider as well
window.appData.audio.audio.onvolumechange = function () {
window.appData.sliderVolumeMusicEl.value =
window.appData.audio.audio.volume;
window.appData.sliderVolumeMusicEl.setAttribute(
"value",
window.appData.sliderVolumeMusicEl.value
);
};
// hook to play event and manage DOM classes
window.appData.audio.audio.addEventListener("play", () => {
if (!window.appData.hasFirstPlayStarted) {
window.appData.hasFirstPlayStarted = true;
// start time messure
window.electronAPI.profileStartTime().then((startTime) => {
console.log(
"app start time (to play event): ",
(Date.now() - startTime) / 1000,
" s"
);
});
}
//
debugLog("event PLAY occured");
// add classes for Play button
plyButon.classList.add("playing");
plyButon.classList.add("active");
// remove class for pause button
pauseButon.classList.remove("active");
});
window.appData.audio.audio.addEventListener("canplaythrough", () => {
window.appData.audio.audio
.play()
.then(() => {
updateThreeSongsInHTML();
console.log("playing currentSongId: ", window.appData.currentSongId);
})
.catch((err) => {
console.error(err);
window.appData.currentSongId = 0;
});
});
// hook to pause event and manage DOM classes
window.appData.audio.audio.onpause = function () {
debugLog("event PAUSE occured");
// remove classes for play button
plyButon.classList.remove("playing");
plyButon.classList.remove("active");
// add class for pause button
pauseButon.classList.add("active");
};
window.appData.audio.audio.onended = function () {
// start new song when "current" song ends
debugLog("audio event ENDED occured");
nextSong();
};
window.appData.sliderVolumeMusicEl.addEventListener("input", () =>
currentVolume()
);
}
<file_sep>// {
// // var exec = require('child_process').exec;
// const bt = require("bluetoothctl");
// const btConnectedTo = (btAvailableDevices = "");
// const selectedMAC = "";
// window.addEventListener("DOMContentLoaded", () => {
// document.getElementById("bluetooth").addEventListener("click", () => {
// // bluetoothctl init
// try {
// bt.Bluetooth();
// const btConnectedDevicesDOM = document.querySelector(
// ".settings .bluetooth .pairedDevices .devices"
// );
// bt.on(bt.bluetoothEvents.ScaningEnded, () => {
// debugLog("ScaningEnded");
// btAvailableDevices = bt.devices;
// const btScanedDevicesDOM = document.querySelector(
// ".settings .bluetooth .scanedDevices .devices"
// );
// // clear DOM element for new data after scanning
// btScanedDevicesDOM.innerHTML = "";
// for (let i = 0, l = btAvailableDevices.length; i < l; i++) {
// btScanedDevicesDOM.innerHTML +=
// `<div class="device" onclick="markDeviceToPair(this)"><div class="name">${
// btAvailableDevices[i].name
// }</div><div class="mac">${
// btAvailableDevices[i].mac
// }</div></div>`;
// }
// debugLog("btAvailableDevices: ", btAvailableDevices);
// });
// bt.on(bt.bluetoothEvents.PassKey, (passkey) => {
// debugLog(`Confirm passkey:${ passkey}`);
// bt.confirmPassKey(true);
// });
// bt.on(bt.bluetoothEvents.Connected, () => {
// debugLog("Connected");
// // clear DOM element for new data after scanning
// btConnectedDevicesDOM.innerHTML = "";
// btConnectedTo = bt.devices.filter(
// (element) => element.connected === "yes"
// );
// btConnectedTo.forEach((element) => {
// btConnectedDevicesDOM.innerHTML +=
// `<div class="device"><div class="name">${
// element.name
// }</div><div class="mac">${
// element.mac
// }</div></div>`;
// });
// });
// bt.on(bt.bluetoothEvents.Device, () => {
// debugLog("Event Device");
// // clear DOM element for new data after scanning
// btConnectedDevicesDOM.innerHTML = "";
// btConnectedTo = bt.devices.filter(
// (element) => element.connected === "yes"
// );
// btConnectedTo.forEach((element) => {
// btConnectedDevicesDOM.innerHTML +=
// `<div class="device"><div class="name">${
// element.name
// }</div><div class="mac">${
// element.mac
// }</div></div>`;
// });
// });
// } catch (error) {
// console.log("Bluetooth error:", error);
// }
// });
// document.getElementById("btScan").addEventListener("click", () => {
// btScan();
// });
// document.getElementById("btClose").addEventListener("click", () => {
// bt.close;
// });
// document.getElementById("btPair").addEventListener("click", () => {
// const macAdresSelectedDevice = document.querySelector(
// ".settings .bluetooth .scanedDevices .devices .device.selected .mac"
// );
// bt.pair(macAdresSelectedDevice.innerText);
// debugLog(
// `macAdresSelectedDevice.innerText: ${ macAdresSelectedDevice.innerText}`
// );
// });
// document
// .getElementById("btDisconnect")
// .addEventListener("click", () => {
// bt.disconnect(
// document.querySelector(
// ".settings .bluetooth .pairedDevices .devices .device .mac"
// ).innerText
// );
// });
// });
// function btScan() {
// // check if bluetooth is ready, exist and it's not scaning curently
// if (
// bt.isBluetoothReady === true &&
// bt.isBluetoothControlExists === true &&
// bt.isScanning === false
// ) {
// // start scaning
// bt.scan(true);
// debugLog("bluetoooth scaning...");
// // stop scaning after 7sec
// setTimeout(() => {
// debugLog("stopping scan");
// bt.scan(false);
// }, 5000);
// }
// }
// function btConnect(MAC) {
// bt.pair(MAC);
// }
// function markDeviceToPair(element) {
// // remove class from already selected element
// const alreadySelected = document.querySelector(
// ".settings .bluetooth .scanedDevices .devices .device.selected"
// );
// if (alreadySelected) {
// alreadySelected.classList.toggle("selected");
// }
// element.classList.toggle("selected");
// }
// }
<file_sep>const { readdirSync, statSync } = require("fs");
const path = require("path");
module.exports.findMusicFilesRecursivly = (folderPath) => {
// get files recursivly (with sub folders)
// https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j
// add record in songsObj for each audio file in musicFolder
const songs = [];
try {
// read files and directoryes in current directory
const files = readdirSync(folderPath);
files.forEach((file, index) => {
// for each file or directory
// check if it's file or directory
// file = path.join(initailPath, file).toLowerCase();
const fileFullPath = path.join(folderPath, file);
const stat = statSync(fileFullPath); // file info
if (stat && stat.isDirectory()) {
// it is directory
// Recurse into a subdirectory for curent path/directory
this.findMusicFilesRecursivly(fileFullPath);
}
// Is a file
// get only .mp3 audio files
if (
fileFullPath.split(".").pop() === "mp3" ||
fileFullPath.split(".").pop() === "MP3"
) {
songs.push({
id: index,
name: fileFullPath.split("\\").pop().split("/").pop(),
length: "",
path: fileFullPath,
});
}
});
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
}
return songs;
};
<file_sep>import dialogCloseHandler from "./modal";
export default function updateTimeCANfromInput(event) {
const el = document.getElementById("modalTwoInputs");
const hour = el.querySelector("input.hour.time").value;
const minutes = el.querySelector("input.minutes.time").value;
if (
hour.match(/^[0-9][0-9]$/) != null &&
minutes.match(/^[0-9][0-9]$/) != null
) {
window.electronAPI.sendMsgToCAN("update-time", hour, minutes);
dialogCloseHandler(event.target);
}
}
export function asksCANforNewData() {
// checks if variable is empty, if soo then ask CAN for new data
if (!window.CANdata.fuelConsumption1) {
window.electronAPI.sendMsgToCAN("fuelConsumption1");
}
if (!window.CANdata.fuelConsumption2) {
window.electronAPI.sendMsgToCAN("fuelConsumption2");
}
if (!window.CANdata.tempOutside) {
window.electronAPI.sendMsgToCAN("tempOutside");
}
if (!window.CANdata.distance) {
window.electronAPI.sendMsgToCAN("distance");
}
if (!window.CANdata.range) {
window.electronAPI.sendMsgToCAN("range");
}
if (!window.CANdata.avgSpeed) {
window.electronAPI.sendMsgToCAN("avgSpeed");
}
if (!window.CANdata.timeFromInstrumentCluster) {
window.electronAPI.sendMsgToCAN("time");
}
}
<file_sep>import Keyboard from "./keyboard";
import dialogCloseHandler from "./modal";
import debugLog from "./utils";
// var exec = require("child_process").exec;
const currentWifi = "";
// executing OS commands
function executeCommand(command) {
debugLog(`executeCommand: ${command}`);
// exec(command, function (error, stdout, stderr) {
// callback(stdout);
// });
}
export function getWifiInfo() {
debugLog("Getting wifi info");
window.electronAPI.getWifiSSID().then((data) => {
const SSID = data.replace(/SSID:\s+|\n|\s+/g, "");
console.log(SSID);
document.querySelector(
"#wifi-modal-with-settings .currentNetwork"
).innerHTML = `<p>Connected to: ${currentWifi}</p>`;
});
window.electronAPI
.getListOfAvailableNetworks()
.then((data) => {
const wifiNetworkList = data
.trimRight()
.replace(/\s+ESSID:"/g, "")
.split('"');
// clear
document.querySelector(
"#wifi-modal-with-settings .availableNetworks .data"
).innerHTML = "";
// populate
wifiNetworkList.forEach((element) => {
document.querySelector(
"#wifi-modal-with-settings .availableNetworks .data"
).innerHTML += `<div class="ssid" onclick="selectedWiFitoConnect(this);">${element}</div>`;
});
})
.catch((err) => {
document.querySelector(
"#wifi-modal-with-settings .availableNetworks .data"
).innerHTML = err;
});
}
function wifiDisconnect() {
if (window.appData.isLinux) {
// Linux
// nop
} else {
// Windows
window.electronAPI
.disconnectFromWifi()
.then((data) => debugLog("disconnected from wifi", data));
}
}
export default function wifiConnect() {
const selectedWiFitoConnectEl = document.querySelector(
"#settings .wifi .data .ssid.selectedWiFi"
);
let wifiPasswordDialog;
if (window.appData.isLinux) {
// Linux
try {
// connect to WiFi network
// https://unix.stackexchange.com/questions/92799/connecting-to-wifi-network-through-command-line
// using wpa_cli
// first get network id, wpa_cli add_network
executeCommand("wpa_cli add_network", (outputNetworkId) => {
const networkId = outputNetworkId.match(/^\d/m)[0];
debugLog(networkId);
// connect to selected WiFi
//
executeCommand(
`wpa_cli set_network ${networkId} ssid '"${selectedWiFitoConnectEl.innerText}"' psk '"${wifiPasswordDialog}"'`,
(outputWpaCli) => {
debugLog(`output_wpa_cli: ${outputWpaCli}`);
document.querySelector(
"#settings .wifi .currentNetwork"
).innerHTML = `<p>Connected to: ${currentWifi}</p>`;
debugLog(
`conected to Wi-Fi network: ${selectedWiFitoConnectEl.innerText}`
);
}
);
});
} catch (error) {
debugLog(error);
}
} else {
// Windows
try {
// connect to WiFi network
executeCommand(
`netsh wlan connect name="${selectedWiFitoConnectEl.innerText}"`,
(output) => {
document.querySelector(
"#settings .wifi .currentNetwork"
).innerHTML = `<p>Connected to: ${currentWifi}</p>`;
debugLog(
`conected to Wi-Fi network: ${selectedWiFitoConnectEl.innerText}`
);
const stringHelper = `There is no profile "${selectedWiFitoConnectEl.innerText}" assigned to the specified interface.`;
const outputTrimed = output.trimRight();
debugLog(outputTrimed);
// no password, show password input
if (outputTrimed === stringHelper && !wifiPasswordDialog) {
showWifiDialog();
// document.getElementById('wifiPasswordDialog').classList.toggle('hide');
document.querySelector("#wifiPasswordDialog input").focus();
debugLog("Enter wifi password");
}
}
);
} catch (error) {
debugLog(error);
}
}
}
// for marking purposes
function selectedWiFitoConnect(element) {
document
.querySelectorAll("#settings .wifi .availableNetworks .data .selectedWiFi")
.forEach((ele) => {
ele.classList.remove("selectedWiFi");
});
element.classList.toggle("selectedWiFi");
}
export function showWifiDialog() {
document.getElementById("wifiPasswordDialog").showModal();
// for modal popup, after entering password
document.querySelector("#wifiPasswordDialog .wifipassconnect").onclick =
function () {
wifiConnect();
};
// second init, for inputs in modal that was created
Keyboard.reinitForInputs();
}
function showWifiNetworkListModal() {
document.getElementById("wifi-modal-with-settings").showModal();
}
window.addEventListener("DOMContentLoaded", () => {
document
.getElementById("show-wifi-settings-dialog")
.addEventListener("click", showWifiNetworkListModal);
document.getElementById("wifiClose").addEventListener("click", (e) => {
dialogCloseHandler(e.target);
});
document.getElementById("wifiDisconnect").addEventListener("click", () => {
wifiDisconnect();
});
document.getElementById("wifiConnect").addEventListener("click", () => {
wifiConnect();
});
document.getElementById("wifiRefreshList").addEventListener("click", () => {
getWifiInfo();
});
});
<file_sep>import path from "path";
const fs = require("fs");
export function wrtieIBUSdataToFile(...args) {
return new Promise((resolve, reject) => {
const pipFilePath = path.join(
__dirname,
`DATA_FROM_IBUS_${new Date().toISOString().split("T")[0]}.txt`
);
const outputFile = fs.createWriteStream(pipFilePath, { flags: "a" });
outputFile.on("error", (error) => {
console.error(error);
});
outputFile.write(`${args.join(", ")}\n`);
outputFile.end();
outputFile.on("finish", () => {
outputFile.close(() => {
resolve(`IBUS data saved to: ${pipFilePath}`);
});
});
outputFile.on("error", (err) => {
fs.unlink(pipFilePath);
reject(err);
});
});
}
export const some = true;
<file_sep>This aplication and hardware was designed to replace default/stock navigation/radio provided by BMW in my x3 e83 (2004).<br>
Not ready yet :)
for serialport:
rm -f node_modules/@serialport
npm install serialport --build-from-source
### How it looks
#### Dashboard GUI
<img src="src/for_readme/img/stearing_fox_dashboard_GUI_1.jpg" width="300">
<img src="src/for_readme/img/stearing_fox_dashboard_GUI_2.jpg" width="300">
#### Music GUI
<img src="src/for_readme/img/stearing_fox_music_GUI.png" width="300">
`more to come`
<h3>Hardware:</h3>
<ol>
<li><del>Raspbery pi 3B+</del> - heart of hardware, in short Raspberry sucks, a better alternative is Rock Pi 4 Model B 1GB (cost about this same, and have a lot more features, for example can run on 12V (this will eliminate need steepdown DC converter usage, and eMMC disk can be installed))</li>
<li>Resler USB IBUS interface (I encourage you to try other solutions, cheaper ones @aliexpres :) )</li>
<li>DAC plus soundcard (raspberry pi hat), DYKB PCM5122 Raspberry pi B+ 2/3B HIFI DAC + Sound Card Digital Audio Module</li>
<li>12v step down DC converter with output set around 5,7V</li>
<li>Bluetooth dongle</li>
<li>Cables (for speakers, HDMI, USB extender 5m+, comon USB extender)</li>
<li>Few realeys (10A will do)</li>
<li>6,5 inch touchscreen with control board PCB800099-V.9.</li>
<li>Revers camera</li>
<li>GPIO Extension Expansion Board Module for Raspberry pi 3B+</li>
</ol>
#### Wiring diargam/schematics
<img src="src/for_readme/img/Instalation_schema_raspberry_pi_BMW_x3_e83.png" width="300">
<h3>Software:</h3>
<ol>
<li>Raspbian</li>
<li>Node.JS</li>
<li>Electron</li>
<li>more in package.json ;)</li>
</ol>
<h3>Few facts:</h3>
<ol>
<li>GUI was designed for 6,5 inch screen (800 x 480 px)</li>
<li>Image from revers camera is handled by PCB control board (when revers gear is on then revers camera is on and signal send to control board)</li>
</ol>
<h3>Aplication can:</h3>
<ol>
<li>Displays diffrent data from car CAN network like (temperature outside, fuel consumption, avarage speed, altitude, time and more</li>
<li>Play mp3 from disk (USB to do?)</li>
<li>Play YouTube</li>
<li>Displays google map (navigation on to do list)</li>
<li>Manage Wi-Fi connections</li>
<li>Manage Bluetooth conections/devices</li>
<li>Play music via ADSP (egz. music from phone)</li>
<li>Be controlled from steering wheel controls</li>
<li>Allows to do phone calls (to do)</li>
</ol>
### Usage
First install all dependencies:
```
npm install
```
Start application without debug logs, logs can be later turn on by setting: `debugMode = true`
```
npm start
```
Start application with debug logs
```
npm run debug
```
Rebuild application
```
npm run prepare
```
Build application for Raspberry pi 3B+ (linux)
```
npm run build-linux-arm
```
### Settings
More logs can be show by setting:
```
lessInfoFromCAN=false
```
### OS settings
#### Auto shutdown script
This Python script is monitoring PIN 33 status when it's changes it will run `sudo shutdown -h now` command and close Linux OS
Code:
```
from time import sleep
import RPi.GPIO as GPIO
import os
GPIO.setmode(GPIO.BOARD)
pin=33
GPIO.setup(pin,GPIO.IN,pull_up_down=GPIO.PUD_UP)
while(1):
if GPIO.input(pin)==1:
print "Shuting down - ACC power (switched) off"
os.system("sudo shutdown -h now")
sleep(.1)
```
To auto start script: `sudo nano /etc/rc.local`
and at the end add:
`sudo python /path_to_your_script_file/script.py &`
### Deployment
Github actions need tag to be present in order to compile release
First update version in package.json:
```
git commit -am 1.0.0
```
Tag your commit:
```
git tag 1.0.0
```
Push your changes to GitHub:
```
git push && git push --tags
```
<file_sep>const rules = require("./webpack.rules");
rules.push({
test: /\.css$/,
use: [
{ loader: "style-loader" },
{
loader: "css-loader",
options: {
importLoaders: 1,
},
},
{
loader: "postcss-loader",
},
],
});
module.exports = {
// Put your normal webpack config below here
module: {
rules,
},
experiments: {
topLevelAwait: true,
},
// externals: {
// serialport: "serialport", // Ref: https://copyprogramming.com/howto/electron-and-serial-ports
// },
};
<file_sep>const fs = require("fs");
const path = require("path");
const svg_folder = "./svg/";
let result = "";
fs.readdir(svg_folder, (error, files) => {
if (error) {
console.error(error);
return;
}
files.forEach((file) => {
try {
let data = fs.readFileSync(path.join(svg_folder, file), "utf8");
data = data.replace(
/(style|stroke|stroke\-linecap|stroke\-linejoin|fill)\=\"(.*?)"/gm,
""
);
result += data
.replace("<svg", `<svg id="${file.slice(0, -4)}_svg"`)
.replace('<?xml version="1.0" encoding="UTF-8"?>', "");
} catch (error) {
console.log(error);
return;
}
console.log(`${file} - done`);
});
fs.writeFileSync(path.join("./tools/", "output.txt"), result);
});
<file_sep>export default function sendMsgToCAN(
requestName,
ibusInterface,
arg1,
arg2,
arg3
) {
if (Object.keys(ibusInterface) === 0) {
// ibus not initialised
return;
}
switch (requestName) {
// request for fuel consumption 1
case "fuelConsumption1":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x04, 0x01]),
// 3B 05 80 41 04 01
});
break;
// request for fuel consumption 2
case "fuelConsumption2":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x05, 0x01]),
// 3B 05 80 41 05 01
});
break;
// request for outside temperature
case "tempOutside":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x03, 0x01]),
});
break;
// request for total kilometers
// Odometer request
case "distance":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x07, 0x01]),
});
break;
// request window.CANdata.range
case "range":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x06, 0x01]),
});
break;
// request avg speed
case "avgSpeed":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x0a, 0x01]),
});
break;
// request obc
case "obc":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x19]),
});
break;
// set DSP
case "dsp-on-concert-hall":
ibusInterface.sendMessage({
src: 0x68,
dst: 0x6a,
msg: Buffer.from([0x34, 0x09]),
});
break;
// request time
case "time":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x41, 0x01, 0x01]),
});
break;
// update time
// arg1->Hours, arg2->minutes
case "updateTime":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x40, 0x01, arg1, arg2]),
});
break;
// update date
// arg1->day, arg2->month, arg3->year
case "update-date":
ibusInterface.sendMessage({
src: 0x3b,
dst: 0x80,
msg: Buffer.from([0x40, 0x02, arg1, arg2, arg3]),
});
break;
default:
break;
}
}
<file_sep>import debugLog from "./utils";
import { SETTINGS_FILE_NAME } from "./var";
export function getUserPath() {
// eslint-disable-next-line no-return-await
return window.electronAPI
.getUserDataPath()
.then((userPath) =>
window.electronAPI
.pathJoin([userPath, SETTINGS_FILE_NAME])
.then((path) => path)
);
}
export function saveSettingsToFile() {
let contentObject = {};
let themeOption = "";
try {
debugLog("Saving settings to file");
const musiFolderPathEl = document.getElementById("music-folder-path");
const { musicFolder } = window.appData.settingsFile;
window.electronAPI
.pathDirname(musiFolderPathEl?.files[0]?.path || musicFolder)
.then((response) => {
console.log(`saveSettingsToFile response: `, response);
window.appData.settingsFile.musicFolder = response;
const themeElement = document.querySelector("#settings .themeOption");
// check if egzist
if (themeElement.length > 0) {
themeOption = themeElement.selectedOptions[0].value;
}
const fuel_1_ele = document.querySelector("#main .fuel_cons1 .data");
if (fuel_1_ele.innerText) {
contentObject.lastFuel1Con = fuel_1_ele.innerText.replace(
/^\s+|\n|-|\s+$/gm,
""
);
}
// adding options to object
contentObject.musicFolder = window.appData.settingsFile.musicFolder;
contentObject.theme = themeOption;
contentObject.audioVolume = window.appData.audio.audio.volume;
// converting object to string
contentObject = JSON.stringify(contentObject);
debugLog(`musicFolder: ${window.appData.settingsFile.musicFolder}`);
debugLog(`SETTINGS_FILE_NAME: ${SETTINGS_FILE_NAME}`);
debugLog(`contentObject: ${contentObject}`);
try {
window.electronAPI
.writeFile([window.appData.userPath, contentObject])
.then(() => {
console.log(
`The file has been saved! ${window.appData.userPath}`
);
window.appData.settingsFile = JSON.parse(contentObject);
});
} catch (e) {
debugLog(`FAILD to save setting file ${e}`);
}
});
} catch (err) {
console.error(err);
}
}
export function updateGUIwithSettings(settingsObj) {
// update GUI
const themeElement = document.querySelector("#settings .themeOption");
const musicFolderEl = document.querySelector("#settings .item .filepath");
musicFolderEl.innerText = settingsObj.musicFolder;
themeElement.value = settingsObj.theme;
const event = new Event("change");
themeElement.dispatchEvent(event);
window.appData.audio.audio.volume = settingsObj.audioVolume;
}
export function settingsFileContentHandler(fileContentObject) {
// if settings file contain folderPath (and it's not empty string) then use it in var musicFolder else use "/Music/"
if (!fileContentObject) return;
debugLog("Settings file, loading content...");
try {
if (!("musicFolder" in fileContentObject)) {
console.log("invalid content - not JSON");
return;
}
window.appData.settingsFile = fileContentObject;
updateGUIwithSettings(window.appData.settingsFile);
//
// TODO
// switchTheme();
} catch (error) {
console.error(error);
}
}
export function checkForSettingsFileCreate() {
// check if settings.json file dose not egzist in app folder
// if it's not there then create it that file with default data
// try {
return window.electronAPI
.existsSync(window.appData.userPath)
.then((exist) => {
if (exist) {
return window.electronAPI
.readFileSync(window.appData.userPath)
.then((settingsFileContent) => {
// file exist and no error
const parsed = JSON.parse(settingsFileContent);
window.appData.settingsFile = parsed;
debugLog("Settings file exist");
settingsFileContentHandler(parsed);
return parsed;
});
}
// file not exist or empty
debugLog("Settings file not exist or empty, creating...");
const defaultSettingsFileContent = {
musicFolder: "",
theme: "light",
audioVolume: 0.5,
};
return window.electronAPI.writeFileSync([
window.appData.userPath,
JSON.stringify(defaultSettingsFileContent),
]);
});
// } catch (err) {
// console.error(`Setting file: ${err}`);
// }
}
export function listenForUIchanges() {
// add events listners responsible for saving when user interacts with UI
const elToWatch = document.querySelectorAll(".settings-watcher");
elToWatch.forEach((el) => {
el.addEventListener(
"change",
() => {
console.log(`listenForUIchanges`);
saveSettingsToFile();
},
false
);
});
window.appData.audio.audio.onvolumechange = () => {
console.log(`volumechange`);
};
// theme and language chages and saves to settings file are handled in elements on click functions
}
export function settingsInit() {
return getUserPath().then((userPath) => {
window.appData.userPath = userPath;
listenForUIchanges();
return checkForSettingsFileCreate();
});
}
<file_sep>import { THEMES_NAMES } from "./var";
export function setHTMLtheme(themeName = "") {
document.querySelector("html").setAttribute("data-theme", themeName);
}
export function switchTheme(ele) {
if (!ele) return;
// update css in html
// based on select drop down change OR from setting file
const theme =
ele.options[ele.options.selectedIndex].value ||
window.appData.settingsFile.theme;
// save settings to file - changed theme
console.log(`switchTheme`);
setHTMLtheme(theme);
}
export function setDarkTheme() {
setHTMLtheme(THEMES_NAMES.dark_grey);
}
export function setPreviousTheme() {
// TODO
// switchTheme();
}
<file_sep>const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const os = require("os");
const {
existsSync,
readFileSync,
writeFileSync,
writeFile,
lstatSync,
readFile,
} = require("fs");
const { SerialPort } = require("serialport");
const { spawn, exec } = require("child_process");
const { findMusicFilesRecursivly } = require("../main-music-utils");
const { default: sendMsgToCAN } = require("./ibus-senders");
const convertSong = (filePath) => {
const songPromise = new Promise((resolve, reject) => {
if (typeof filePath !== "string") reject();
readFile(filePath, "base64", (err, data) => {
if (err) {
reject(err);
}
resolve(`data:audio/mp3;base64,${data}`);
});
});
return songPromise;
};
function currentWifiSSID() {
const cmd =
process.platform === "linux"
? "iw wlan0 link | grep SSID"
: "netsh wlan show interfaces";
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log("Error on BE while getting WIFI SSID");
console.warn(error);
reject(error);
}
resolve(stdout || stderr);
});
});
}
function getListOfAvailableNetworks() {
const cmd =
process.platform === "linux"
? "iwlist wlan0 scan | grep ESSID"
: "netsh wlan show networks mode=Bssid";
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log("Error on BE while getting WIFI list");
console.warn(error);
reject(error);
}
resolve(stdout || stderr);
});
});
}
function disconnectFromWifi() {
const cmd = process.platform === "linux" ? "" : "netsh wlan disconnect";
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log("Error on BE while disconnecting from wifi");
console.warn(error);
reject(error);
}
resolve(stdout || stderr);
});
});
}
function connectToWifiNetwork() {
const cmd = process.platform === "linux" ? "" : "";
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log("Error on BE while connecting to wifi");
console.warn(error);
reject(error);
}
resolve(stdout || stderr);
});
});
}
const mainIpcs = (profileStartTime, ibusInstance) => {
ipcMain.handle("getMusicFiles", (event, folderPath) =>
findMusicFilesRecursivly(folderPath)
);
ipcMain.handle("networkInterfaces", () => os.networkInterfaces());
ipcMain.handle("isLinux", () => process.platform === "linux");
ipcMain.handle("startParameters", () => process.argv.slice(2));
ipcMain.handle("minimize", () => BrowserWindow.getFocusedWindow().minimize());
ipcMain.handle("close", () => BrowserWindow.getFocusedWindow().close());
ipcMain.handle("appVersion", () => app.getVersion());
ipcMain.handle("getUserDataPath", () => app.getPath("userData"));
ipcMain.handle("profileStartTime", () => profileStartTime);
ipcMain.handle("bufferFrom", (event, arg) => Buffer.from(arg));
ipcMain.handle("pathJoin", (event, argArray) => {
if (argArray.length > 0) {
return path.join(...argArray);
}
return null;
});
ipcMain.handle("pathDirname", (event, arg) => {
if (!existsSync(arg)) return null;
if (lstatSync(arg).isDirectory()) {
return arg;
}
const parentFolder = path.dirname(arg);
return parentFolder;
});
ipcMain.handle("listSerialPorts", async () => {
await SerialPort.list()
.then((ports, err) => {
if (err) {
// eslint-disable-next-line no-console
console.log(`serialPort list error`, err);
return null;
}
// eslint-disable-next-line no-console
console.log("ports: ", ports);
return ports;
})
// eslint-disable-next-line no-console
.catch((err) => console.log("listSerialPorts error: ", err));
});
ipcMain.handle("existsSync", (event, arg) => existsSync(arg));
ipcMain.handle(
"readFileSync",
(event, arg) => arg && readFileSync(arg, { encoding: "utf8" })
);
ipcMain.handle("writeFileSync", (event, args) => writeFileSync(...args));
ipcMain.handle("writeFile", (event, args) => {
writeFile(...args, (err) => {
// eslint-disable-next-line no-console
if (err) console.log(err);
else {
// eslint-disable-next-line no-console
console.log("writeFile callback: File written successfully");
}
});
});
ipcMain.handle(
"CPUtemp",
() =>
new Promise((resolve, reject) => {
const temp = spawn("cat", ["/sys/class/thermal/thermal_zone0/temp"]);
temp.stdout.on("data", async (data) => resolve(Number(data) / 1000));
temp.stdout.on("error", async (err) => reject(err));
})
);
ipcMain.handle("getSong", (event, filePath) => convertSong(filePath));
ipcMain.handle("getWifiSSID", currentWifiSSID);
ipcMain.handle("getListOfAvailableNetworks", getListOfAvailableNetworks);
ipcMain.handle("disconnectFromWifi", disconnectFromWifi);
ipcMain.handle("connectToWifiNetwork", connectToWifiNetwork);
ipcMain.handle("sendMsgToCAN", (event, data) => {
sendMsgToCAN(data, ibusInstance);
});
};
module.exports = mainIpcs;
<file_sep>import debugLog, { hexToAscii } from "./utils";
export function dateAndTimeSetInHTML() {
const dateObj = new Date();
const date = dateObj.toLocaleDateString("pl-PL").replace(/\./g, "-");
const time = dateObj.toLocaleTimeString("pl-PL").substring(0, 5);
const timeDateElement = document.querySelector("#main #info .curent_time");
// get time from instrument claster (CAN)
if (window.CANdata.timeFromInstrumentCluster) {
// get time from instrument claster (CAN)
timeDateElement.innerHTML =
`<span class="time">${window.CANdata.timeFromInstrumentCluster}</span>` +
`<span class="date">${date}</span>`;
// to do
// set time and date (on OS) from CAN/car?
} else {
timeDateElement.innerHTML = `<span class="time">${time}</span><span class="date">${date}</span>`;
}
/// / if 'window.CANdata.gps_utc_time' have data then get time from gps
// if (window.CANdata.gps_utc_time) {
// // current time from GPS
// window.CANdata.gps_utc_time = parseInt(window.CANdata.gps_utc_time.substring(0, 2)) + 1 + ':' + window.CANdata.gps_utc_time.substring(2, 4) + ':' + window.CANdata.gps_utc_time.substring(4, 6);
// }
}
export function CPUtemp() {
if (window.appData.isLinux) {
try {
window.electronAPI.CPUtemp().then((data) => {
// return data/1000;
document.querySelector(
"#info .cpu_temp .data"
).innerHTML = `${Math.round(
data / 1000
)}<div class="small text">\xB0C</div>`;
});
} catch (error) {
debugLog(error);
}
} else {
document.querySelector(
"#info .cpu_temp .data"
).innerHTML = `-<div class="small text">\xB0C</div>`;
}
}
export function guiUpdateData() {
// neerest town
if (window.CANdata.townNav) {
// document.querySelector('.grid-cell.nearest_town .data').innerText = window.CANdata.townNav;
}
// alltitude, with conversion
if (window.CANdata.altitude) {
document.querySelector(
".grid-cell.altitude .data"
).innerHTML = `${window.CANdata.altitude}<div class="small text">m</div>`;
}
// Temperature outside
if (window.CANdata.tempOutside) {
window.CANdata.tempOutside =
window.CANdata.tempOutside.length > 7
? hexToAscii(window.CANdata.tempOutside)
: window.CANdata.tempOutside;
// to string conversion
window.CANdata.tempOutside += "";
if (window.CANdata.tempOutside.includes(" ")) {
window.CANdata.tempOutside = window.CANdata.tempOutside.trim();
} else if (
window.CANdata.tempOutside.includes("+") ||
window.CANdata.tempOutside.includes("-")
) {
window.CANdata.tempOutside = window.CANdata.tempOutside.replace(
"+",
"+ "
);
window.CANdata.tempOutside = window.CANdata.tempOutside.replace(
"-",
"- "
);
window.CANdata.tempOutside = window.CANdata.tempOutside.replace(".", ",");
document.querySelector(
".grid-cell.temp_outside_car .data"
).innerText = `${window.CANdata.tempOutside} \xB0C`;
}
}
if (window.CANdata.coolantTemp) {
document.querySelector(
".grid-cell.coolant_temp .data"
).innerText = `${window.CANdata.coolantTemp} \xB0C`;
}
// fuel consumption 1
if (window.CANdata.fuelConsumption1) {
document.querySelector(
"#main .fuel_cons1 .data"
).innerHTML = `<div class="data1">${window.CANdata.fuelConsumption1}</div><div class="small text">l/100km</div>`;
}
// fuel consumption 2
if (window.CANdata.fuelConsumption2) {
document.querySelector(
".grid-cell.fuel_cons2 .data"
).innerHTML = `${window.CANdata.fuelConsumption2}<div class="small text">l/100km</div>`;
}
// light sensor in place of weather forecast
if (window.CANdata.lightSensor) {
document.querySelector(".grid-cell.weather_forecast").innerText =
window.CANdata.lightSensor;
}
// window.CANdata.range
if (window.CANdata.range) {
document.querySelector(
".grid-cell.range .data"
).innerHTML = `${window.CANdata.range}<div class="small text">km</div>`;
}
// window.CANdata.avgSpeed
if (window.CANdata.avgSpeed) {
document.querySelector(
".grid-cell.avg_speed .data"
).innerHTML = `${window.CANdata.avgSpeed}<div class="small text">km/h</div>`;
}
CPUtemp();
}
export function getIPs() {
// clear DOM
document.getElementById("ipslist").innerHTML = "";
window.electronAPI.networkInterfaces().then((data) => {
Object.keys(data).forEach((ifname) => {
let alias = 0;
data[ifname].forEach((iface) => {
if (iface.family !== "IPv4" || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
debugLog(`${ifname}:${alias}`, iface.address);
document.getElementById(
"ipslist"
).innerHTML += `<span class="ip">${ifname}: ${alias} ${iface.address}</span>`;
} else {
// this interface has only one ipv4 adress
debugLog(`${ifname}: ${iface.address}`);
document.getElementById(
"ipslist"
).innerHTML += `<span class="ip">${ifname}: ${iface.address}</span>`;
}
alias += 1;
});
});
});
}
<file_sep>export const modalClasses = ["background", "modal"];
export default function dialogCloseHandler(element) {
element.closest("dialog").close();
}
export function dialogShowHandler(element) {
element.closest("dialog").showModal();
}<file_sep>module.exports = {
plugins: [
[
"postcss-preset-env",
{
stage: 2,
features: {
"nesting-rules": true,
"custom-media-queries": true,
"custom-properties": true,
"custom-selectors": true,
clamp: true,
"cascade-layers": true,
"nested-calc": true,
"not-pseudo-class": true,
"is-pseudo-class": true
},
},
],
],
};
<file_sep>// mesuure start time
const profileStartTime = Date.now();
require("log-node")();
// Modules to control application life and create native browser window
// eslint-disable-next-line import/no-extraneous-dependencies
const { app, BrowserWindow } = require("electron");
const IbusInterface = require("ibus/src/IbusInterface");
const { SerialPort } = require("serialport");
const mainIpcs = require("./js/mainProcess/ipcs");
const {
default: handleSquirrelEvent,
} = require("./js/main-squirel-events-handler");
const { default: initUpdates } = require("./js/main-updates");
const { default: initIBUSinMain } = require("./js/mainProcess/ibus");
require("update-electron-app")({
updateInterval: "1 hour",
notifyUser: true,
});
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// eslint-disable-next-line global-require
if (require("electron-squirrel-startup")) {
app.quit();
}
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
const createWindow = () => {
// Create the browser window.
let mainWindow = new BrowserWindow({
width: 800,
height: 480,
frame: !app.isPackaged,
icon: "./build/icons/icon.ico",
webPreferences: {
// eslint-disable-next-line no-undef
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
// nodeIntegration: true,
},
fullscreen: app.isPackaged,
backgroundColor: "#2c2c2c",
});
if (!app.isPackaged) {
// dev mode - kind off, not packed
// Open the DevTools.
mainWindow.webContents.openDevTools();
} else {
// production only
mainWindow.maximize();
}
// and load the index.html of the app.
// eslint-disable-next-line no-undef
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
// mainWindow.loadFile(
// "F:/Repozytoria/my-app/src/index.html"
// );
// Emitted when the window is closed.
mainWindow.on("closed", () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", () => {
createWindow();
// let ibusInterface = {};
SerialPort.list().then((ports, err) => {
if (err) {
// eslint-disable-next-line no-console
console.log(`serialPort list error`, err);
return;
}
// eslint-disable-next-line no-console
console.log("ports: ", ports);
// setup interface
// const device = "/dev/ttyUSB0"; // for linux
const ibusInterface = new IbusInterface(
app.isPackaged ? ports[0].path : "/dev/ROBOT"
);
try {
initIBUSinMain(ibusInterface);
} catch (error) {
console.log(error);
}
// API
mainIpcs(profileStartTime, ibusInterface);
});
if (handleSquirrelEvent() === "firstrun") {
setTimeout(initUpdates, 30000);
} else {
initUpdates();
}
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
// DOMException: play() failed because the user didn't interact with the document first.
// allow to play audio without intereaction with document
app.commandLine.appendSwitch("--autoplay-policy", "no-user-gesture-required");
// console.log(powerSaveBlocker.isStarted(id))
// app.whenReady().then(() => {});
| 17ea3cb0580cc173e19a11fd30ae8ef75083aa7c | [
"JavaScript",
"Markdown"
] | 24 | JavaScript | miroslawlis/steering-fox | 77341e3cfab8c42fb41e1adde8bd199f32dba33f | 1a618a2e3d7c236c5ccaebe3518fed0c60438876 | |
refs/heads/master | <repo_name>Sobiash/SASS-Project<file_sep>/gulp/tasks/build.js
const gulp = require("gulp"),
usemin = require("gulp-usemin"),
rev = require("gulp-rev"),
del = require ("del");
gulp.task("deleteDistFolder", function(){
return del(["dist/styles/*.css", "./dist/img/**", "./dist/*.html"]);
});
gulp.task("usemin", function(done){
return gulp.src("./app/*.html")
.pipe(usemin({
css: [ rev() ]
}))
.pipe(gulp.dest("./dist/"));
done();
});
gulp.task("build", gulp.series("deleteDistFolder", "sass", "images", "usemin"));<file_sep>/gulp/tasks/styles.js
const gulp = require("gulp"),
sass = require("gulp-sass"),
autoprefixer = require("autoprefixer"),
sourcemaps = require ("gulp-sourcemaps"),
postcss = require ("gulp-postcss"),
cssnano = require ("cssnano");
const paths = {
styles: {
src: "./app/scss/**/*.scss",
dest: "./app/dest/css/"
}
}
gulp.task("sass", function(done){
gulp.src(paths.styles.src)
.pipe(sourcemaps.init())
.pipe(sass().on("error", sass.logError))
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(paths.styles.dest));
done();
});
<file_sep>/README.md
# SASS-Project
In this project, I have made a sass project with the help of sass plugins and gulp task-runner. This project is made to show my sass skills and only is about frontend web design made with flexbox.
| 5a7a570eb55a8a36a7e4325bc64a29435ecedd68 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Sobiash/SASS-Project | 7fb5b9cb05b9f10f89068498154b9010bd08c180 | 484d07f5486c7a778edf888ff1f9b93e3035d15c | |
refs/heads/master | <repo_name>Eragoneq/Lumium_Mod<file_sep>/java/com/eragon_skill/lumium/items/ExplosionRod.java
package com.eragon_skill.lumium.items;
import java.util.Set;
import com.eragon_skill.lumium.entities.EntityThrownTNT;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class ExplosionRod extends ItemTool{
private static final Set SET = Sets.newHashSet(new Block[] {Blocks.air});
public ExplosionRod(ToolMaterial material) {
super(material, SET);
this.setUnlocalizedName("explosion_rod");
ItemStack stack = new ItemStack(ModItems.explosion_rod);
this.setCreativeTab(CreativeTabs.tabCombat);
GameRegistry.registerItem(this, "explosion_rod");
}
@Override
public boolean onBlockDestroyed(ItemStack stack, World worldIn, IBlockState blockIn, BlockPos pos, EntityLivingBase entityLiving) {
return false;
}
@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) {
world.playSound(player, player.getPosition(), SoundEvents.item_firecharge_use, SoundCategory.NEUTRAL, 0.7F, 0.9F);
if(!world.isRemote){
EntityThrownTNT eTT = new EntityThrownTNT(world, player);
eTT.func_184538_a(player, player.rotationPitch, player.rotationYaw, 0.0F, 1.5F, 1.0F);
world.spawnEntityInWorld(eTT);
stack.damageItem(1, player);
}
return super.onItemRightClick(stack, world, player, hand);
}
}
<file_sep>/java/com/eragon_skill/lumium/crafting/AltarCraftingManager.java
package com.eragon_skill.lumium.crafting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.BlockStone;
import net.minecraft.block.BlockStoneSlab;
import net.minecraft.block.BlockStoneSlabNew;
import net.minecraft.block.BlockWall;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.RecipeBookCloning;
import net.minecraft.item.crafting.RecipeFireworks;
import net.minecraft.item.crafting.RecipeRepairItem;
import net.minecraft.item.crafting.RecipeTippedArrow;
import net.minecraft.item.crafting.RecipesArmor;
import net.minecraft.item.crafting.RecipesArmorDyes;
import net.minecraft.item.crafting.RecipesBanners;
import net.minecraft.item.crafting.RecipesCrafting;
import net.minecraft.item.crafting.RecipesDyes;
import net.minecraft.item.crafting.RecipesFood;
import net.minecraft.item.crafting.RecipesIngots;
import net.minecraft.item.crafting.RecipesMapCloning;
import net.minecraft.item.crafting.RecipesMapExtending;
import net.minecraft.item.crafting.RecipesTools;
import net.minecraft.item.crafting.RecipesWeapons;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraft.item.crafting.ShieldRecipes;
import net.minecraft.world.World;
import com.eragon_skill.lumium.items.ModItems;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class AltarCraftingManager {
/** The static instance of this class */
private static final AltarCraftingManager instance = new AltarCraftingManager();
private final List<IRecipe> recipes = Lists.<IRecipe>newArrayList();
/**
* Returns the static instance of this class
*/
public static AltarCraftingManager getInstance()
{
/** The static instance of this class */
return instance;
}
private AltarCraftingManager(){
this.addRecipe(new ItemStack(ModItems.explosion_rod), new Object[]{" IO", " RI", "R ", 'I', ModItems.ignisium_ingot, 'R', Items.blaze_rod, 'O', Items.diamond});
Collections.sort(this.recipes, new AltarCraftingComparator(this));
}
public AltarShapedRecipes addRecipe(ItemStack stack, Object... recipeComponents)
{
String s = "";
int i = 0;
int j = 0;
int k = 0;
if (recipeComponents[i] instanceof String[])
{
String[] astring = (String[])((String[])recipeComponents[i++]);
for (int l = 0; l < astring.length; ++l)
{
String s2 = astring[l];
++k;
j = s2.length();
s = s + s2;
}
}
else
{
while (recipeComponents[i] instanceof String)
{
String s1 = (String)recipeComponents[i++];
++k;
j = s1.length();
s = s + s1;
}
}
Map<Character, ItemStack> map;
for (map = Maps.<Character, ItemStack>newHashMap(); i < recipeComponents.length; i += 2)
{
Character character = (Character)recipeComponents[i];
ItemStack itemstack = null;
if (recipeComponents[i + 1] instanceof Item)
{
itemstack = new ItemStack((Item)recipeComponents[i + 1]);
}
else if (recipeComponents[i + 1] instanceof Block)
{
itemstack = new ItemStack((Block)recipeComponents[i + 1], 1, 32767);
}
else if (recipeComponents[i + 1] instanceof ItemStack)
{
itemstack = (ItemStack)recipeComponents[i + 1];
}
map.put(character, itemstack);
}
ItemStack[] aitemstack = new ItemStack[j * k];
for (int i1 = 0; i1 < j * k; ++i1)
{
char c0 = s.charAt(i1);
if (map.containsKey(Character.valueOf(c0)))
{
aitemstack[i1] = ((ItemStack)map.get(Character.valueOf(c0))).copy();
}
else
{
aitemstack[i1] = null;
}
}
AltarShapedRecipes shapedrecipes = new AltarShapedRecipes(j, k, aitemstack, stack);
this.recipes.add(shapedrecipes);
return shapedrecipes;
}
/**
* Adds a shapeless crafting recipe to the the game.
*/
public void addShapelessRecipe(ItemStack stack, Object... recipeComponents)
{
List<ItemStack> list = Lists.<ItemStack>newArrayList();
for (Object object : recipeComponents)
{
if (object instanceof ItemStack)
{
list.add(((ItemStack)object).copy());
}
else if (object instanceof Item)
{
list.add(new ItemStack((Item)object));
}
else
{
if (!(object instanceof Block))
{
throw new IllegalArgumentException("Invalid shapeless recipe: unknown type " + object.getClass().getName() + "!");
}
list.add(new ItemStack((Block)object));
}
}
this.recipes.add(new AltarShapelessRecipes(stack, list));
}
/**
* Adds an IRecipe to the list of crafting recipes.
*/
public void addRecipe(IRecipe recipe)
{
this.recipes.add(recipe);
}
/**
* Retrieves an ItemStack that has multiple recipes for it.
*/
public ItemStack findMatchingRecipe(InventoryCrafting p_82787_1_, World worldIn)
{
for (IRecipe irecipe : this.recipes)
{
if (irecipe.matches(p_82787_1_, worldIn))
{
return irecipe.getCraftingResult(p_82787_1_);
}
}
return null;
}
public ItemStack[] func_180303_b(InventoryCrafting p_180303_1_, World worldIn)
{
for (IRecipe irecipe : this.recipes)
{
if (irecipe.matches(p_180303_1_, worldIn))
{
return irecipe.getRemainingItems(p_180303_1_);
}
}
ItemStack[] aitemstack = new ItemStack[p_180303_1_.getSizeInventory()];
for (int i = 0; i < aitemstack.length; ++i)
{
aitemstack[i] = p_180303_1_.getStackInSlot(i);
}
return aitemstack;
}
public List<IRecipe> getRecipeList()
{
return this.recipes;
}
}
<file_sep>/java/com/eragon_skill/lumium/blocks/ModBlocks.java
package com.eragon_skill.lumium.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import com.eragon_skill.lumium.LumiumMod;
import com.eragon_skill.lumium.utils.CustomBlock;
import com.eragon_skill.lumium.utils.CustomBlock.HarvestLevelEnum;
import com.eragon_skill.lumium.utils.CustomBlock.HarvestToolEnum;
public class ModBlocks {
//Blocks
public static CustomBlock lumium_ore;
public static CustomBlock ignisium_ore;
//
public static CraftingAltar crafting_altar;
public static final int guiIDCraftingAltar = 1;
public static void initBlocks(){
lumium_ore = new CustomBlock(Material.rock, "lumium_ore", 3.0F, 5.0F, HarvestToolEnum.PICKAXE, HarvestLevelEnum.IRON, CreativeTabs.tabBlock, 1, 3, 8, 15, 5, 60, new Block[]{Blocks.stone}, new Block[]{Blocks.lava, Blocks.diamond_ore}, 3, true, false, false);
ignisium_ore = new CustomBlock(Material.rock, "ignisium_ore", 7.0F, 10.0F, HarvestToolEnum.PICKAXE, HarvestLevelEnum.LUMIUM, CreativeTabs.tabBlock, 1, 3, 4, 100, 0, 255, new Block[]{Blocks.netherrack}, new Block[]{Blocks.netherrack}, 0, false, true, false);
crafting_altar = new CraftingAltar();
}
}
<file_sep>/java/com/eragon_skill/lumium/items/ItemModPickaxe.java
package com.eragon_skill.lumium.items;
import java.util.List;
import com.eragon_skill.lumium.Reference;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class ItemModPickaxe extends ItemPickaxe{
public ItemModPickaxe(ToolMaterial material, String name) {
super(material);
this.setUnlocalizedName(name);
this.setCreativeTab(CreativeTabs.tabTools);
GameRegistry.registerItem(this, name);
}
public void RegisterRenderer(String modelName)
{
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(this, 0, new ModelResourceLocation(Reference.MOD_ID+":"+modelName, "inventory"));
}
}
<file_sep>/java/com/eragon_skill/lumium/entities/ModEntities.java
package com.eragon_skill.lumium.entities;
import net.minecraft.entity.EntityList;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import com.eragon_skill.lumium.LumiumMod;
public class ModEntities {
public static EntityThrownTNT thrown_tnt;
public static void initEntities(){
createEntity(EntityThrownTNT.class, "thrown_tnt");
}
public static void createEntity(Class classId, String name){
int id = EntityRegistry.findGlobalUniqueEntityId();
EntityRegistry.registerGlobalEntityID(classId, name, id);
EntityRegistry.registerModEntity(classId, name, id, LumiumMod.instance, 80, 10, true);
}
public static void createEntity(Class classId, String name, int solidColor, int spotColor){
int id = EntityRegistry.findGlobalUniqueEntityId();
EntityRegistry.registerGlobalEntityID(classId, name, id);
EntityRegistry.registerModEntity(classId, name, id, LumiumMod.instance, 80, 10, true);
EntityRegistry.registerEgg(classId, solidColor, spotColor);
}
}
<file_sep>/java/com/eragon_skill/lumium/inventory/InventoryCoreSlot.java
package com.eragon_skill.lumium.inventory;
import com.eragon_skill.lumium.items.ModItems;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
public class InventoryCoreSlot implements IInventory{
private ItemStack[] stackCore = new ItemStack[1];
@Override
public String getName() {
return "Player Core Slot";
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public ITextComponent getDisplayName() {
return (ITextComponent)(this.hasCustomName() ? new TextComponentString(this.getName()) : new TextComponentTranslation(this.getName(), new Object[0]));
}
@Override
public int getSizeInventory() {
return 1;
}
@Override
public ItemStack getStackInSlot(int index) {
return this.stackCore[0];
}
@Override
public ItemStack decrStackSize(int index, int count) {
return ItemStackHelper.func_188383_a(this.stackCore, 0);
}
@Override
public ItemStack removeStackFromSlot(int index) {
return ItemStackHelper.func_188383_a(this.stackCore, 0);
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
this.stackCore[0] = stack;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public void markDirty() {
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return true;
}
@Override
public void openInventory(EntityPlayer player) {
}
@Override
public void closeInventory(EntityPlayer player) {
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return false;
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {
}
@Override
public int getFieldCount() {
return 0;
}
@Override
public void clear() {
this.stackCore[0]=null;
}
}
<file_sep>/java/com/eragon_skill/lumium/items/ItemModShovel.java
package com.eragon_skill.lumium.items;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemSpade;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.eragon_skill.lumium.Reference;
public class ItemModShovel extends ItemSpade{
public ItemModShovel(ToolMaterial material, String name) {
super(material);
this.setUnlocalizedName(name);
this.setCreativeTab(CreativeTabs.tabTools);
GameRegistry.registerItem(this, name);
}
}
<file_sep>/java/com/eragon_skill/lumium/proxy/CommonProxy.java
package com.eragon_skill.lumium.proxy;
import com.eragon_skill.lumium.LumiumMod;
import com.eragon_skill.lumium.blocks.ModBlocks;
import com.eragon_skill.lumium.entities.ModEntities;
import com.eragon_skill.lumium.handlers.CraftingHandler;
import com.eragon_skill.lumium.items.ModItems;
import com.eragon_skill.lumium.utils.CustomBlock;
import com.eragon_skill.lumium.utils.CustomItem;
import com.eragon_skill.lumium.utils.CustomBlock.HarvestLevelEnum;
import com.eragon_skill.lumium.utils.CustomBlock.HarvestToolEnum;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
public class CommonProxy
{
public void preInit(FMLPreInitializationEvent e)
{
}
public void init(FMLInitializationEvent e)
{
ModItems.initItems();
ModBlocks.initBlocks();
ModEntities.initEntities();
CraftingHandler.registerCraftingRecipes();
CraftingHandler.registerSmeltingRecipes();
}
public void postInit(FMLPostInitializationEvent e)
{
}
}
<file_sep>/java/com/eragon_skill/lumium/renderers/ModBlockRenderer.java
package com.eragon_skill.lumium.renderers;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import com.eragon_skill.lumium.Reference;
import com.eragon_skill.lumium.blocks.ModBlocks;
public class ModBlockRenderer {
public static void registerBlockRenderers(){
reg(ModBlocks.ignisium_ore);
reg(ModBlocks.lumium_ore);
reg(ModBlocks.crafting_altar);
}
public static void reg(Block block)
{
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), 0, new ModelResourceLocation(Reference.MOD_ID+":"+block.getUnlocalizedName().substring(5), "inventory"));
}
}
| 177b55ebc77f1350b3ee4ffcfdc70f6d4cb39a05 | [
"Java"
] | 9 | Java | Eragoneq/Lumium_Mod | 50de19e1b4bc745fe9e451cca7a5dc23ab503f15 | 2971f9a6de05fb0c36dca1d72b945b6c8a34bc8c | |
refs/heads/master | <repo_name>LataB/cmpe273-projectPhase1<file_sep>/src/main/java/edu/sjsu/cmpe/dropbox/dto/FileDto.java
package edu.sjsu.cmpe.dropbox.dto;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import edu.sjsu.cmpe.dropbox.domain.File;
import edu.sjsu.cmpe.dropbox.domain.Review;
@JsonPropertyOrder(alphabetic = true)
public class FileDto extends LinksDto {
private File file;
/**
* @param book
*/
public FileDto(File file) {
super();
this.setFile(file);
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
<file_sep>/src/main/java/edu/sjsu/cmpe/dropbox/dto/FilesDto.java
package edu.sjsu.cmpe.dropbox.dto;
import java.util.ArrayList;
import edu.sjsu.cmpe.dropbox.domain.File;
public class FilesDto extends LinksDto {
private ArrayList<File> Files = new ArrayList<File>();
/**
* @param book
*/
public FilesDto(ArrayList<File> Files) {
super();
this.setFiles(Files);
}
public ArrayList<File> getFiles() {
return Files;
}
public void setFiles(ArrayList<File> Files) {
this.Files = Files;
}
}
<file_sep>/src/main/java/edu/sjsu/cmpe/dropbox/api/resources/DropboxResource.java
package edu.sjsu.cmpe.dropbox.api.resources;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.yammer.metrics.annotation.Timed;
import edu.sjsu.cmpe.dropbox.domain.File;
import edu.sjsu.cmpe.dropbox.domain.User;
import edu.sjsu.cmpe.dropbox.dto.UserDto;
import edu.sjsu.cmpe.dropbox.dto.LinkDto;
import edu.sjsu.cmpe.dropbox.dto.LinksDto;
import edu.sjsu.cmpe.dropbox.dto.FileDto;
import edu.sjsu.cmpe.dropbox.dto.FilesDto;
@Path("/v1/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DropboxResource {
private static HashMap<String,User> users=new HashMap<String,User>();
private static int fileNum =1;
private MongoClient mongoClient;
private DB db;
private DBCollection colluser,colldocument;
public DropboxResource() {
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
db = mongoClient.getDB( "test" );
colluser = db.getCollection("user");
colldocument = db.getCollection("document");
}
@GET
@Path("/{email}")
@Timed(name = "view-user")
public Response getUserByEmail(@PathParam("email") String email) {
// FIXME - Dummy code
/* User user = new User();
user=users.get(email);
UserDto userResponse = new UserDto(user);
userResponse.addLink(new LinkDto("view-user", "/users/" + email,
"GET"));
userResponse.addLink(new LinkDto("update-user",
"/users/" + email, "PUT"));
userResponse.addLink(new LinkDto("delete-user",
"/users/" + email, "DELETE"));
userResponse.addLink(new LinkDto("create-file",
"/users/" + email +"/files", "POST"));
if (user.getmyFiles().size()>0){
userResponse.addLink(new LinkDto("view-all-files",
"/users/" + email + "/files", "GET"));
}*/
DBCursor cursor = colluser.find(new BasicDBObject().append("email",email));
String output = "";
while(cursor.hasNext()) {
output +=cursor.next();
}
return Response.status(200).entity(output).build();
// add more links
// return user;
}
@POST
@Timed(name = "create-user")
public Response setUserByEmail(User user) {
// FIXME - Dummy code
// users.put(user.getEmail(), user);
BasicDBObject ob = new BasicDBObject();
ob.append("firstName", user.getFirstName());
ob.append("lastName", user.getLastName());
ob.append("password", <PASSWORD>());
ob.append("email", user.getEmail());
ob.append("status", user.getStatus());
ob.append("designation", user.getDesignation());
ob.append("myFiles",new ArrayList<String>());
ob.append("filesShared",new ArrayList<String>());
colluser.insert(ob);
LinksDto links = new LinksDto();
links.addLink(new LinkDto("view-user", "/users/" + user.getEmail(),
"GET"));
links.addLink(new LinkDto("update-user",
"/users/" + user.getEmail(), "PUT"));
links.addLink(new LinkDto("update-user",
"/users/" + user.getEmail(), "POST"));
links.addLink(new LinkDto("delete-user",
"/users/" + user.getEmail(), "DELETE"));
links.addLink(new LinkDto("create-file",
"/users/" + user.getEmail() +"/files", "POST"));
return Response.status(201).entity(links).build();
}
@DELETE
@Path("/{email}")
@Timed(name = "delete-user")
public LinkDto deleteUserByEmail(@PathParam("email") String email) {
// FIXME - Dummy code
BasicDBObject document = new BasicDBObject();
document.put("email", email);
colluser.remove(document);
// users.remove(email);
return new LinkDto("create-user", "/users","POST");
}
@PUT
@Path("/{email}")
@Timed(name = "update-user")
public LinksDto updateUserByEmail(@PathParam("email") String email,@QueryParam("status") String status) {
// FIXME - Dummy code
users.get(email).setStatus(status);
LinksDto userResponse = new LinksDto();
userResponse.addLink(new LinkDto("view-user", "/users/" + email,
"GET"));
userResponse.addLink(new LinkDto("update-user",
"/users/" + email, "PUT"));
userResponse.addLink(new LinkDto("update-user",
"/users/" + email, "POST"));
userResponse.addLink(new LinkDto("delete-user",
"/users/" + email, "DELETE"));
userResponse.addLink(new LinkDto("create-file",
"/users/" + email +"/files", "POST"));
if (users.get(email).getmyFiles().size()>0){
userResponse.addLink(new LinkDto("view-all-files",
"/users/" + email + "/files", "GET"));
}
return userResponse;
}
@POST
@Path("/{email}/files")
@Timed(name = "create-file")
public Response createUserFileByEmail(@PathParam("email") String email, File file) {
// FIXME - Dummy code
// users.get(email).getmyFiles().add(file);
file.setFileID(fileNum);
BasicDBObject ob = new BasicDBObject();
ob.append("name", file.getName());
ob.append("fileID", fileNum);
ob.append("owner", file.getOwner());
ob.append("accessType", file.getAccessType());
ob.append("sharedWith", new ArrayList<String>());
colldocument.insert(ob);
BasicDBObject query = new BasicDBObject().append("email", email);
// BasicDBObject newDoc = new BasicDBObject().append("$set", new BasicDBObject().append("myFiles", file.getName()));
// colluser.update(query,newDoc );
BasicDBObject newDoc = new BasicDBObject().append("$push", new BasicDBObject().append("myFiles", file.getFileID()));
colluser.update(query,newDoc );
LinkDto link = new LinkDto("view-file", "/users/" + email + "/files/ " + file.getFileID(),"GET");
fileNum++;
return Response.status(201).entity(link).build();
}
@PUT
@Path("/{email}/files/{id}")
@Timed(name = "update-files")
public void updateFileByEmail(@PathParam("email") String email,@PathParam("id") int id,@QueryParam("sharedWith") String sharedWith) {
// FIXME - Dummy code
/* users.get(email).setStatus(status);
LinksDto userResponse = new LinksDto();
userResponse.addLink(new LinkDto("view-user", "/users/" + email,
"GET"));
userResponse.addLink(new LinkDto("update-user",
"/users/" + email, "PUT"));
userResponse.addLink(new LinkDto("update-user",
"/users/" + email, "POST"));
userResponse.addLink(new LinkDto("delete-user",
"/users/" + email, "DELETE"));
userResponse.addLink(new LinkDto("create-file",
"/users/" + email +"/files", "POST"));
if (users.get(email).getmyFiles().size()>0){
userResponse.addLink(new LinkDto("view-all-files",
"/users/" + email + "/files", "GET"));
}
*/ BasicDBObject query = new BasicDBObject().append("email", sharedWith);
BasicDBObject newDoc = new BasicDBObject().append("$push", new BasicDBObject().append("filesShared", id));
colluser.update(query,newDoc );
BasicDBObject query2 = new BasicDBObject().append("fileID", id);
BasicDBObject newDoc2 = new BasicDBObject().append("$push", new BasicDBObject().append("sharedWith", sharedWith));
colldocument.update(query2,newDoc2);
}
@GET
@Path("/{email}/files/{id}")
@Timed(name = "view-file")
public Response getFileByEmailById(@PathParam("email") String email, @PathParam("id") int id) {
// FIXME - Dummy code
// File file = users.get(email).getmyFiles().get(id-1);
// FileDto fileResponse = new FileDto(file);
// fileResponse.addLink(new LinkDto("view-file", "/users/" + email + "/files/" + id,
// "GET"));
// add more links
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("fileID", id));
obj.add(new BasicDBObject("owner", email));
andQuery.put("$and", obj);
DBCursor cursor = colldocument.find(andQuery);
String output = "";
while(cursor.hasNext()) {
output +=cursor.next();
}
return Response.status(200).entity(output).build();
// return fileResponse;
}
@DELETE
@Path("/{email}/files/{id}")
@Timed(name = "delete-file")
public LinkDto deleteFileByEmailAndId(@PathParam("email") String email, @PathParam("id") Integer id) {
// FIXME - Dummy code
users.get(email).getmyFiles().remove(id);
return new LinkDto("create-file", "/users/" + email,"POST");
}
@GET
@Path("/{email}/files")
@Timed(name = "view-all-files")
public Response getAllFilesByEmail(@PathParam("email") String email) {
// FIXME - Dummy code
// ArrayList<File> files = users.get(email).getmyFiles();
// FilesDto filesResponse = new FilesDto(files);
DBCursor cursor = colldocument.find(new BasicDBObject().append("owner",email));
String output = "";
while(cursor.hasNext()) {
output +=cursor.next();
}
// filesResponse.addLink(null);
// add more links
return Response.status(200).entity(output).build();
}
/*
@POST
@Path("/{email}/filesShared")
@Timed(name = "create-file")
public Response createUserFileSharedByEmail(@PathParam("email") String email, File file) {
// FIXME - Dummy code
// users.get(email).getFilesShared().add(file);
BasicDBObject query = new BasicDBObject().append("email", email);
BasicDBObject newDoc = new BasicDBObject().append("$push", new BasicDBObject().append("filesShared", file.getFileID()));
colluser.update(query,newDoc );
LinkDto link = new LinkDto("view-file", "/users/" + email + "/filesShared/ " + file.getFileID(),"GET");
return Response.status(201).entity(link).build();
}
*/
@GET
@Path("/{email}/filesShared/{id}")
@Timed(name = "view-filesShared")
public Response getFilesSharedByEmailById(@PathParam("email") String email, @PathParam("id") int id) {
// FIXME - Dummy code
// File file = users.get(email).getFilesShared().get(id-1);
// FileDto fileResponse = new FileDto(file);
// fileResponse.addLink(new LinkDto("view-filesShared", "/users/" + email + "/filesShared/" + id,
// "GET"));
// add more links
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("fileID", id));
obj.add(new BasicDBObject("sharedWith", email));
andQuery.put("$and", obj);
DBCursor cursor = colldocument.find(andQuery);
String output = "";
while(cursor.hasNext()) {
output +=cursor.next();
}
return Response.status(200).entity(output).build();
}
@DELETE
@Path("/{email}/filesShared/{id}")
@Timed(name = "delete-fileShared")
public LinkDto deleteFileSharedByEmailAndId(@PathParam("email") String email, @PathParam("id") Integer id) {
// FIXME - Dummy code
users.get(email).getFilesShared().remove(id);
return new LinkDto("create-fileShared", "/users/" + email + "/filesShared/","POST");
}
@GET
@Path("/{email}/filesShared")
@Timed(name = "view-all-filesShared")
public Response getAllFilesSharedsByEmail(@PathParam("email") String email) {
// FIXME - Dummy code
// ArrayList<File> filesShared = users.get(email).getFilesShared();
// FilesDto filesSharedResponse = new FilesDto(filesShared);
// filesSharedResponse.addLink(null);
// add more links
BasicDBObject query = new BasicDBObject().append("email",email);
BasicDBObject fields = new BasicDBObject();
fields.put("filesShared", 1);
DBCursor cursor = colluser.find(query, fields);
String output = "";
while(cursor.hasNext()) {
output +=cursor.next();
}
// add more links
return Response.status(200).entity(output).build();
// return filesSharedResponse;
}
}
| 17593914e00a7d2d0dd9d3e267b3a05392b012a2 | [
"Java"
] | 3 | Java | LataB/cmpe273-projectPhase1 | 1431e87a97af33253ff9d188661695cda9b441f1 | c0f6577bf29cfd3dd1c868dce5a713941bdf1366 | |
refs/heads/master | <repo_name>downneck/prometheus-kubernetes<file_sep>/remove.sh
#!/bin/bash
kubectl delete -f ./k8s/grafana
kubectl delete -f ./k8s/ingress
kubectl delete -R -f ./k8s/prometheus
kubectl delete -f ./k8s/kube-state-metrics
kubectl delete -f ./k8s/rbac
kubectl delete ns monitoring
<file_sep>/cleanup.sh
git checkout k8s/ingress/01-basic-auth.secret.yaml
git checkout k8s/prometheus/01-prometheus.configmap.yaml
git checkout k8s/prometheus/02-prometheus.svc.statefulset.yaml
git checkout k8s/prometheus/03-alertmanager.configmap.yaml
git checkout k8s/prometheus/04-alertmanager.svc.deployment.yaml
git checkout k8s/prometheus/05-node-exporter.svc.daemonset.yaml
git checkout k8s/grafana/grafana.svc.deployment.yaml
git checkout grafana/Dockerfile
rm auth
| ea4b11a99408a3bd906fbb8f9e0b078e677ad32b | [
"Shell"
] | 2 | Shell | downneck/prometheus-kubernetes | 913b3fff358e3c26b96b60c340c8028b2921c272 | b4ce50c9fc8c116ead62b3498688a619ea17f2bb | |
refs/heads/master | <file_sep>REST_PAGINAACTUAL = 0;
$(document).ready(init);
function init(){
cargarFront();
}
function cargarFront(){
$.ajax({
url: 'ajax/selectPlatos.php',
type: 'POST',
data: 'pagina='+REST_PAGINAACTUAL,
success: function(datos){
mostrarGaleria(datos);
},
error: function (){
alert("adios");
}
});
}
function mostrarGaleria(datos){
var galeria = $("#galeria-platos");
galeria.empty();
for (var i=0 in datos.platos) {
$("<div class='plato-principal plato1'><div class='foto-plato' style='background-image: url(imagenes/"+datos.platos[i].fotos[0]+")'></div><div class='info-plato'><h3>"+datos.platos[i].nombre+"</h3><p>"+datos.platos[i].descripcion+" a un precio de "+datos.platos[i].precio+"€</p></div></div>").appendTo(galeria);
}
$(".paginacion").remove();
var tr = document.createElement("div");
var td = document.createElement("div");
/*td.setAttribute("colspan", 5);*/
td.classList.add("paginacion");
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.inicio + "'><<</a> ";
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.anterior + "'><</a> ";
if (datos.paginas.primero !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.primero + "'>" + (parseInt(datos.paginas.primero) + 1) + "</a> ";
if (datos.paginas.segundo !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.segundo + "'>" + (parseInt(datos.paginas.segundo) + 1) + "</a> ";
if (datos.paginas.actual !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.actual + "'>" + (parseInt(datos.paginas.actual) + 1) + "</a> ";
if (datos.paginas.cuarto !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.cuarto + "'>" + (parseInt(datos.paginas.cuarto) + 1) + "</a> ";
if (datos.paginas.quinto !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.quinto + "'>" + (parseInt(datos.paginas.quinto) + 1) + "</a> ";
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.siguiente + "'>></a> ";
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.ultimo + "'>>></a> ";
tr.appendChild(td);
galeria.after(tr);
$(".enlace").unbind("click");
$(".enlace").on("click", cambiarPagina);
}
function cambiarPagina(){
REST_PAGINAACTUAL = $(this).data("href");
cargarFront();
}
<file_sep><?php
header("Content-Type: application/json");
require '../require/comun.php';
$bd = new BaseDatos();
$modelo = new modeloPlato($bd);
$id = Leer::post("id");
if($id==null){
echo "{'error':-1}";
exit();
}
$plato = $modelo->get($id);
echo $plato->getJSON();
$bd->closeConexion();
<file_sep><?php
header("Content-Type: application/json");
require '../require/comun.php';
$bd = new BaseDatos();
$modelo = new modeloPlato($bd);
$idplato = Leer::post("idplato");
$nombre = Leer::post("nombre");
if($idplato==null){
echo '{"error": -1}';
exit();
}
$r = $modelo->deleteFoto($idplato, $nombre);
echo '{"error": '.$r.'}';
$bd->closeConexion();
<file_sep># restaurante
Carta web de un restaurante con AJAX
<file_sep>var REST_PAGINAACTUAL=0;
$(document).ready(init);
function init(){
$(".cerrar-ventana").on("click", function(){
cerrarVentana();
});
$("#btn-confirmar").on("click", llamadaPlatos);
document.getElementById('archivos').addEventListener('change', handleFileSelect, false);
$("#btn-insertar").on("click", function(){
mostrarPanelVacio();
})
$("#btn-login").on("click", procesarLogin);
$("#btn-salir").on("click", procesarSalir);
procesarLogin();
}
function procesarSalir(){
$.ajax({
url: '../ajax/logout.php',
type: 'GET',
success: function(datos){
portero(datos);
//alert(datos);
},
error: function (){
alert("adios");
}
});
}
function procesarLogin(){
$.ajax({
url: '../ajax/login.php',
type: 'POST',
data: 'login='+$("#login").val()+'&clave='+$("#clave").val(),
success: function(datos){
portero(datos);
//alert(datos);
},
error: function (){
alert("adios");
}
});
}
function portero(datos){
//alert(datos.estado);
if(datos.estado == "logueado"){
cargarPlatos(REST_PAGINAACTUAL);
cerrarLogin();
}else if(datos.estado == "noclave"){
$("#clave").next().text("Clave incorrecta");
$("#login").next().text("");
}else if(datos.estado == "noexiste"){
$("#clave").next().text("");
$("#login").next().text("Usuario incorrecto");
}else if(datos.estado == "logout"){
$("#tabla").remove();
$(".paginacion").remove();
mostrarLogin();
}
}
function cargarPlatos() {
$.ajax({
url: '../ajax/selectPlatos.php',
type: 'POST',
data: 'pagina='+REST_PAGINAACTUAL,
success: function(datos){
mostrarTabla(datos);
},
error: function (){
alert("adios");
}
});
}
function mostrarTabla(datos) {
var tabla = $("#tabla");
tabla.empty();
$("<tr><th>Nombre</th><th>Descripción</th><th>Precio</th><th>Editar</th><th>Borar</th></tr>").appendTo(tabla);
for (var i = 0 in datos.platos) {
var fila = $("<tr><td>" + datos.platos[i].nombre + "</td><td>" + datos.platos[i].descripcion + "</td><td>" + datos.platos[i].precio + "</td><td><a class='enlace-modificar' data-id='"+datos.platos[i].id+"'>Editar</a></td><td><a class='enlace-eliminar' data-id='"+datos.platos[i].id+"' data-nombre='"+datos.platos[i].nombre+"'>Borrar</a></td>");
tabla.append(fila);
}
$(".paginacion").remove();
var tr = document.createElement("div");
var td = document.createElement("div");
/*td.setAttribute("colspan", 5);*/
td.classList.add("paginacion");
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.inicio + "'><<</a> ";
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.anterior + "'><</a> ";
if (datos.paginas.primero !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.primero + "'>" + (parseInt(datos.paginas.primero) + 1) + "</a> ";
if (datos.paginas.segundo !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.segundo + "'>" + (parseInt(datos.paginas.segundo) + 1) + "</a> ";
if (datos.paginas.actual !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.actual + "'>" + (parseInt(datos.paginas.actual) + 1) + "</a> ";
if (datos.paginas.cuarto !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.cuarto + "'>" + (parseInt(datos.paginas.cuarto) + 1) + "</a> ";
if (datos.paginas.quinto !== -1)
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.quinto + "'>" + (parseInt(datos.paginas.quinto) + 1) + "</a> ";
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.siguiente + "'>></a> ";
td.innerHTML += "<a class='enlace' data-href='" + datos.paginas.ultimo + "'>>></a> ";
tr.appendChild(td);
tabla.after(tr);
$(".enlace").unbind("click");
$(".enlace").on("click", cambiarPagina);
$(".enlace-modificar").unbind("click");
$(".enlace-modificar").on("click", recogerPlato);
$("enlace-eliminar").unbind("click");
$(".enlace-eliminar").on("click", function(){
mostrarConfirm($(this));
});
}
function cambiarPagina(){
REST_PAGINAACTUAL = $(this).data("href");
cargarPlatos();
}
function recogerPlato(){
$.ajax({
url: '../ajax/selectPlato.php',
type: 'POST',
data: 'id='+$(this).data("id"),
beforeSend: function(){
$("#img-carga").removeClass("oculto");
},
complete: function(){
$("#img-carga").addClass("oculto");
},
success: function(datos){
mostrarPanel(datos);
},
error: function (){
alert("adios");
}
});
}
function modificarPlatos(){
if($(".minifoto").length<3){
return false;
}
datosform = new FormData($("#formulario")[0]);
$.ajax({
url: '../ajax/updatePlato.php',
type: 'POST',
data: datosform,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$("#img-carga").removeClass("oculto");
},
complete: function(){
$("#img-carga").addClass("oculto");
},
success: function(datos){
cargarPlatos();
cerrarVentana();
},
error: function (datos){
alert("fallo");
}
});
}
function insertarPlato() {
var imagenes = document.getElementById("archivos");
imagenes = imagenes.files.length;
/*imagenes = $(".minifoto").length;*/
if(imagenes<3){
alert("minimo de fotos: 3");
return false;
}
datosform = new FormData($("#formulario")[0]);
$.ajax({
url: '../ajax/insertPlato.php',
type: 'POST',
data: datosform,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$("#img-carga").removeClass("oculto");
},
complete: function(){
$("#img-carga").addClass("oculto");
},
success: function (datos) {
cargarPlatos();
cerrarVentana();
},
error: function (e, a) {
// alert(a);
}
});
}
function llamadaPlatos(){
if($("#in-id").val()==""){
insertarPlato();
}else{
modificarPlatos();
}
}
function borrarPlato(x){
//alert(x.data("nombre"));
$.ajax({
url: '../ajax/deletePlato.php',
type: 'POST',
data: 'id='+x.data("id"),
beforeSend: function(){
$("#img-carga").removeClass("oculto");
},
complete: function(){
$("#img-carga").addClass("oculto");
},
success: function(datos){
cargarPlatos();
//alert(datos.error);
},
error: function (){
alert("adios");
}
});
}
function borrarFoto(){
//alert("ok");
$.ajax({
url: '../ajax/deleteFoto.php',
type: 'POST',
data: 'idplato='+$(this).data("idplato")+'&nombre='+$(this).data("nombre"),
beforeSend: function(){
$("#img-carga").removeClass("oculto");
},
complete: function(){
$("#img-carga").addClass("oculto");
},
success: function(datos){
cargarPlatos();
//alert(datos.error);
},
error: function (){
alert("adios");
}
});
}
/*************************************************************************************************************
****************************************** gestion de ventanas ***********************************************
*************************************************************************************************************/
function cerrarVentana(){
$("#superposicion").addClass("oculto");
$("#in-id").val("");
$("#in-nombre").val("");
$("#in-descripcion").val("");
$("#in-precio").val("");
$("#panel-gestion").addClass("borrado");
$("#mensaje-confirm").text("");
$("#confirmacion").addClass("borrado");
var archivador = $('#archivos');
archivador.replaceWith(archivador.clone(true));
document.getElementById('archivos').addEventListener('change', handleFileSelect, false);
$("#list").empty();
$("#galeria").empty();
}
function mostrarConfirm(x){
$("#mensaje-confirm").text("¿Desea borrar '"+x.data("nombre")+"' y sus fotos");
$("#superposicion").removeClass("oculto");
$("#confirmacion").removeClass("borrado");
$("#btn-ok").unbind("click");
$("#btn-ok").on("click", function(){
borrarPlato(x);
cerrarVentana();
});
}
function cerrarConfirm(){
$("#mensaje-confirm").text("");
$("#superposicion").addClass("oculto");
$("#panel-gestion").removeClass("borrado");
$("#confirmacion").addClass("borrado");
}
function mostrarPanel(datos){
if(datos.id==""){
alert("No se ha encontrado el plato solicitado, pruebe de nuevo");
return;
}
$("#superposicion").removeClass("oculto");
$("#panel-gestion").removeClass("borrado");
$("#in-id").val(datos.id);
$("#in-nombre").val(datos.nombre);
$("#in-descripcion").val(datos.descripcion);
$("#in-precio").val(datos.precio);
for(var i=0; i<datos.fotos.length; i++){
$("#galeria").append($("<img src='../imagenes/"+datos.fotos[i]+"' data-idplato='"+datos.id+"' data-nombre='"+datos.fotos[i]+"' class='minifoto'>"));
}
$(".minifoto").unbind("click");
$(".minifoto").on("click", borrarFoto);
}
function mostrarPanelVacio(){
$("#superposicion").removeClass("oculto");
$("#panel-gestion").removeClass("borrado");
}
function cerrarLogin(){
$("#login").text("");
$("#clave").text("");
$("#formulario-login").addClass("borrado");
$("#clave").next().text("");
$("#login").next().text("");
$("#superposicion").addClass("oculto");
$("#btn-salir").removeClass("oculto");
}
function mostrarLogin(){
$("#login").text("");
$("#clave").text("");
$("#formulario-login").removeClass("borrado");
$("#clave").next().text("");
$("#login").next().text("");
$("#superposicion").removeClass("oculto");
$("#btn-salir").addClass("oculto");
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
document.getElementById('list').innerHTML = "";
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="minifoto" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
<file_sep><?php
header("Content-Type: application/json");
//header("Content-Type: txt/plain");
require '../require/comun.php';
$sesion = new Sesion();
$sesion->salir();
echo '{"estado": "logout"}';
<file_sep><?php
class Configuracion {
const PERMISOS = 777;
const SERVIDOR = "localhost";
const BASEDATOS = "rest2";
const USUARIO = "root";
const CLAVE = "";
const PEZARANA = "<NAME>";
const ORIGENGMAIL = "<EMAIL>";
const CLAVEGMAIL = "*******";
const RPP = 4;
const TIMEOUT = 1800;
}<file_sep><?php
header("Content-Type: application/json");
//header("Content-Type: txt/plain");
require '../require/comun.php';
$sesion = new Sesion();
$bd = new BaseDatos();
$modelo = new modeloUsuario($bd);
$login = Leer::post("login");
$clave = Leer::post("clave");
if($login == "" || $clave == ""){
if($sesion->isAutentificado()){
echo '{"estado": "logueado"}';
exit();
}else{
echo '{"estado": "pedir"}';
exit();
}
}
if(Validar::isCorreo($login)){
$param['email']=$login;
$filas = $modelo->getList("email=:email", $param);
if(sizeof($filas)>0){
$login = $filas[0]->getLogin();
}
}
$objeto = $modelo->get($login);
if($objeto->getLogin() == null || !$objeto->getIsactivo()){
echo '{"estado": "noexiste"}';
exit();
}
if(!Util::isPass($clave, $objeto->getClave())){
echo '{"estado": "noclave"}';
exit();
}
$sesion->setAutentificado(true);
$modelo->setFechaLogin($login);
$sesion->setUsuario($objeto);
echo '{"estado": "logueado"}';
<file_sep><?php
/**
* Description of modeloPlato
*
* @author Javier
*/
class modeloPlato {
private $bd, $tabla="platos", $tablafotos="fotos";
function __construct(BaseDatos $bd) {
$this->bd = $bd;
}
function add(Plato $plato){
$sql = "INSERT INTO $this->tabla VALUES (null, :nombre, :descripcion, :precio)";
$param['nombre'] = $plato->getNombre();
$param['descripcion'] = $plato->getDescripcion();
$param['precio'] = $plato->getPrecio();
$r=$this->bd->setConsulta($sql, $param);
if(!$r){
return -1;
}
return $this->bd->getAutonumerico();
}
function addFoto(Plato $objeto){
$sql = "INSERT INTO $this->tablafotos VALUES(null, :idplato, :nombre)";
$arrayfotos = $objeto->getFotos();
$error=0;
foreach($arrayfotos as $key => $foto){
$param['idplato']=$objeto->getId();
$param['nombre']=$foto;
$r=$this->bd->setConsulta($sql, $param);
if(!$r){
$error=-1;
}
}
//devuelve -1 si alguna inserción falló
return $error;
}
function delete($id){
$nombres = $this->getNombreFotos($id);
foreach ($nombres as $nombre){
unlink("../imagenes/".$nombre);
}
$sql = "DELETE FROM $this->tabla WHERE id=:id";
$param['id'] = $id;
$r=$this->bd->setConsulta($sql, $param);
if(!$r){
return -1;
}
return $this->bd->getNumeroFilas();
}
function deleteFoto($idplato, $nombre){
unlink("../imagenes/".$nombre);
$sql = "DELETE FROM $this->tablafotos WHERE idplato=:idplato and nombre=:nombre";
$param['idplato'] = $idplato;
$param['nombre'] = $nombre;
$r=$this->bd->setConsulta($sql, $param);
if(!$r){
return -1;
}
return $this->bd->getNumeroFilas();
}
function update(Plato $plato){
$sql = "UPDATE $this->tabla SET nombre=:nombre, descripcion=:descripcion, precio=:precio WHERE id=:id";
$param['id'] = $plato->getId();
$param['nombre'] = $plato->getNombre();
$param['descripcion'] = $plato->getDescripcion();
$param['precio'] = $plato->getPrecio();
$r=$this->bd->setConsulta($sql, $param);
if(!$r){
return -1;
}
return $this->bd->getNumeroFilas();
}
function count($condicion = "1=1", $parametros = array()) {
$sql = "select count(*) from $this->tabla where $condicion";
$r = $this->bd->setConsulta($sql, $parametros);
if ($r) {
$x = $this->bd->getFila();
return $x[0];
}
return -1;
}
function get($id){
$sql = "SELECT * FROM $this->tabla where id=:id";
$param['id']=$id;
$r=$this->bd->setConsulta($sql, $param);
if($r){
$plato = new Plato();
$plato->set($this->bd->getFila());
$plato->setFotos($this->getNombreFotos($id));
return $plato;
}
return null;
}
/********************************************************************************************/
private function getNombreFotos($id){
$list = array();
$sql = "select * from $this->tablafotos where idplato=:idplato";
$param['idplato']=$id;
$r = $this->bd->setConsulta($sql, $param);
if($r){
while($fila = $this->bd->getFila()){
$list[] = $fila[2];
}
}else{
return null;
}
return $list;
}
/********************************************************************************************/
function getList($condicion="1=1", $parametro=array(), $orderby = "1"){
$list = array();
$sql = "select * from $this->tabla where $condicion order by $orderby";
$r = $this->bd->setConsulta($sql, $parametro);
if($r){
while($fila = $this->bd->getFila()){
$plato = new Plato();
$plato->set($fila);
$plato->setFotos($this->getNombreFotos($id));
$list[] = $plato;
}
}else{
return null;
}
return $list;
}
function getListJSON($pagina=0, $rpp=3, $condicion="1=1", $parametro=array(), $orderby = "1"){
$principio = $pagina*$rpp;
$sql = "select * from $this->tabla where $condicion order by $orderby limit $principio,$rpp";
/*$sql = "select * from $this->tabla p "
. "left join fotos f "
. "on p.id = f.idplato "
. "where $condicion order by $orderby limit $principio,$rpp";*/
$this->bd->setConsulta($sql, $parametro);
/*$foto = array();*/
$r = "[ ";
while($fila = $this->bd->getFila()){
$bd2 = new BaseDatos();
$modelo2 = new modeloPlato($bd2);
$plato = new Plato();
$plato->set($fila);
$fotos = $modelo2->getNombreFotos($plato->getId());
$plato->setFotos($fotos);
$r .= $plato->getJSON() . ",";
}
$r = substr($r, 0, -1)."]";
return $r;
}
}
<file_sep>
create table platos (
id tinyint(4) not null primary key auto_increment,
nombre varchar(200) not null,
descripcion varchar(400) not null,
precio decimal(10,2) not null
) engine=innodb charset=utf8 collate=utf8_unicode_ci;
create table fotos (
id tinyint(5) not null primary key auto_increment,
idplato tinyint(4) not null,
nombre varchar(50) not null,
CONSTRAINT fotos_fk FOREIGN KEY (idplato) REFERENCES platos (id) ON DELETE CASCADE
) engine=innodb charset=utf8 collate=utf8_unicode_ci;
create table usuario(
login varchar(20) not null primary key,
clave varchar(40) not null,
nombre varchar (60) not null,
apellidos varchar(60) not null,
email varchar(40) not null,
fechaalta date not null,
isactivo tinyint(1) not null default 0,
isroot tinyint(1) not null default 0,
rol enum('administrador', 'usuario', 'vendedor') not null default 'usuario',
fechalogin datetime
) engine=innodb charset=utf8 collate=utf8_unicode_ci<file_sep>window.addEventListener("load", function(){
var pos = new google.maps.LatLng(37.176817, -3.589867);
var mapaconfig = {
zoom: 10,
center: new google.maps.LatLng(37.176817, -3.589867),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapa = new google.maps.Map(document.getElementById('mapa'), mapaconfig);
var marker = new google.maps.Marker({
position: pos,
title:"Hello World!"
});
marker.setMap(mapa);
var boton = document.getElementById("boton-js");
var menu = document.querySelector("nav ul");
boton.addEventListener("click", function(){
this.classList.toggle("menu-abierto");
menu.classList.toggle("abrir");
});
});<file_sep><?php
header("Content-Type: application/json");
require '../require/comun.php';
$bd = new BaseDatos();
$modelo = new modeloPlato($bd);
$nombre = Leer::post("nombre");
$descripcion = Leer::post("descripcion");
$precio = Leer::post("precio");
$subir = new SubirMultiple("archivos");
$subir->addExtension("jpg");
$subir->addExtension("png");
$subir->addTipo("image/jpeg");
$subir->addTipo("image/png");
$subir->setNuevoNombre(time());
$subir->setAcccion(1);
$subir->setAccionExcede(1);
$subir->setTamanio(1024*1024*5);
$subir->setCantidadMaxima(10);
$subir->setCrearCarpeta(true);
$subir->setDestino("../imagenes");
$subir->subir();
$fotos = $subir->getNombres();
$plato = new Plato(null, $nombre, $descripcion, $precio, $fotos);
$r = $modelo->add($plato);
$plato->setId($r);
$s = $modelo->addFoto($plato);
echo $plato->getJSON();
$bd->closeConexion(); | 4dcf5f3ee8b95549250933a75c0dcbbcc2666622 | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 12 | JavaScript | jgallegoweb/restaurante | 91063fbd6aa88568cd799548a3a285ed952c9c55 | 53a5fb49be5802bc95180ffd82f1a4f3f00185f5 | |
refs/heads/master | <repo_name>scatterbrain/wave<file_sep>/lib/wave.rb
require 'gitlab_git'
require 'rugged'
module Wave
extend self
REPO_PATH='/tmp/example/example.git'
BLOB_PATH="document.md"
def gitdo(msg)
case msg["cmd"]
when "commit"
reply = commit(msg, repo())
when "read"
reply = read(repo())
end
end
def read(repo)
begin
commit = Gitlab::Git::Commit.last(repo)
blob = Gitlab::Git::Blob.find(repo, commit.sha, BLOB_PATH)
ok({:doc => blob.data, :author => commit.raw_commit.author, :message => commit.message })
rescue Exception => ex
{ :result => 1, :error => ex.message, :bt => ex.backtrace.join("\n") }
end
end
def commit(msg, repo)
#GitLab::Git doesn't have support for commits so we use the raw rugged repo
repo = repo.rugged
oid = repo.write(msg["doc"]["text"], :blob)
index = repo.index
begin
index.read_tree(repo.head.target.tree)
rescue
end
index.add(:path => BLOB_PATH, :oid => oid, :mode => 0100644)
options = {}
options[:tree] = index.write_tree(repo)
options[:author] = { :email => "<EMAIL>", :name => 'Mikko', :time => Time.now }
options[:committer] = { :email => "<EMAIL>", :name => 'Mikko', :time => Time.now }
options[:message] ||= "It's a commit!"
options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
options[:update_ref] = 'HEAD'
Rugged::Commit.create(repo, options)
#index.write()
ok
end
def repo()
begin
Gitlab::Git::Repository.new(REPO_PATH)
rescue
Rugged::Repository.init_at(REPO_PATH, :bare)
Gitlab::Git::Repository.new(REPO_PATH)
end
end
def ok(opts = {})
{ :result => 0}.merge(opts)
end
end
<file_sep>/workers/git_processor.rb
require 'sneakers'
require 'json'
require_relative '../lib/wave'
class GitProcessor
include Sneakers::Worker
include Wave
from_queue "doc.request",
env: nil, #Env nil tells not to mangle the name to doc.request_development
:durable => true
#from_queue 'downloads',
# :durable => false,
# :ack => true,
# :threads => 50,
# :prefetch => 50,
# :timeout_job_after => 1,
# :exchange => 'dummy',
# :heartbeat => 5
Sneakers.configure({})
# Sneakers.configure(:handler => Sneakers::Handlers::Maxretry,
# :workers => 1,
# :threads => 1,
# :prefetch => 1,
# :exchange => 'sneakers',
# :exchange_type => 'topic', ##NOTE WE CAN MAKE A TOPIC
# EXCHANGE!
# :routing_key => ['#', 'something'],
# :durable => true,
# )
Sneakers.logger.level = Logger::INFO
def work_with_params(msg, delivery_info, metadata)
msg = JSON.parse(msg)
reply = gitdo(msg)
#Reply to delivery_info channel
exchange = delivery_info.channel.default_exchange
exchange.publish(reply.to_json, :routing_key => metadata.reply_to, :correlation_id => metadata.correlation_id)
ack!
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'sneakers', '~> 1.0.1'
gem 'gitlab_git', '~> 7.0.0.rc12'
| 5764912e1189e8d024995a59d565273596f1f9ec | [
"Ruby"
] | 3 | Ruby | scatterbrain/wave | ec2f63894acbec4ddf04e8908416722ab207d7f3 | 70221b6169932edc1eab77ac3862df73fa4c099e | |
refs/heads/master | <file_sep>---
title: 0.2.0 - Usernames
date: 2015-03-10
layout: post
---
Just deployed version 0.2.0 of the SceneVR server. It now supports usernames! [Claim a username](//login.scenevr.com/users/sign_up) now at login.scenevr.com.
## Behind the scenes
I've been thinking about authentication for scenevr for a long time. Initially I thought of just letting people name themselves whatever they want, with name collisions, and no promise that the person is who they say they are, but I didn't like that idea, because I wanted to be able to do authentication on names (eg, if `player.name=='bnolan'` then they can do god-mode stuff to the scene). So I had a hack at doing an authentication server using oauth or openid, but to be honest, they're just so fucking complicated, and didn't have good support for automatically granting tokens. So eventually I settled on a solution using [JSON Web Tokens](http://jwt.io/) which came together quickly and works well. I also updated the renderer so that if a `<player />` has their name attribute set, then they will have a name above them, and their name will show up in the chat logs.
<img src="/images/blog/usernames.png" class="screenshot" />
## Anonymity
I like [this post](https://highfidelity.com/blog/2014/03/identity-in-the-metaverse/) by high fidelity. Basically, you shouldn't be forced to display your username while you wander around scenes. Sure, in the [homeroom](//client.scenevr.com/) it's cool to have your name. But maybe if you're visiting /r/gentlemanboners, you're not so keen on everyone seeing you wander around the gallery.
That's why anonymity is built in to scenevr. You aren't required to log in to access scenes, and you can transition from authenticated (with a name over your avatar) to anonymous at any time, without leaving the room.
## Try it out!
So go try it out, just click the 'login' button in the top right of the [client](//client.scenevr.com) and you can sign up and then log in so that everybody in scenevr knows your name. It's like the bar in cheers. Talking of which, that'd make a good scene.
<img src="/images/blog/cheersbar.jpg" class="screenshot" /><file_sep>---
title: Box
primary_navigation: true
---
# Box
A box is a simple cube. It inherits from [Element](/element.html).
## Sample XML
```xml
<box id="cubey" position="1 2 3" scale="1 1 1" style="color: #f07" />
```
## Screenshot
<img src="/images/box.png" class="screenshot" />
## Styles
### color
The color of the box. Can be set using hexadecimal code or color names. For example to set every box to be red, use the following code.
```javascript
document.getElementsByTagName("box").forEach(function(box){
box.style.color = '#ff0000';
});
```
### texture-map
A texture map that is applied to the box. Texture-maps are lambertian shaded. Textures should be sized as a power of 2 (eg 256x256, 512x512).
```
style="texture-map: url(/images/crate.png)"`
```
### texture-repeat
How many times is the texture repeated in the U and V directions.
```
style="texture-map: url(/images/grid.png); texture-repeat: 100 100"
```
<file_sep>---
title: SceneVR downloadable IDE
date: 2015-11-30
layout: post
---
<div class="md"><p>Hi all, long time no post! I've been working on a downloadable version of SceneVR that has an installer and is a quick and easy way to let you start building Scenes, without having to install npm or understand how node.js works.</p>
<p><a href="http://i.imgur.com/a0BUlMT.png">This is how the editor looks</a>.</p>
<p>I'm working out the last few bugs today and hope to get it released. It will make it much much easier to create scenes on your own computer, and the installer also acts as a server, so people on your own LAN can connect to your server and walk around the scenes as you edit them.</p>
<p>I've also added google cardboard support to the client, so you can use your phone to load scenes.</p>
</div><br /><a href='https://www.reddit.com/r/scenevr/comments/3urgld/scenevr_downloadable_ide/'>Read comments on reddit...</a><file_sep>---
title: Update getting started instructions
date: 2015-04-02
layout: post
---
[@qster123](//github.com/qster123) pointed out that the getting started docs were incomplete for windows users, so I updated them to have better instructions. You don't require git to get started, and it explains that the server autorestarts when you make changes. :)<file_sep>---
title: Gamepad support and Deltas
date: 2015-03-02
tags: server
layout: post
---
Big news today. I merged in the Gamepad support pull request from @brodavi, so you can now walk around the scene using an xbox 360 controller. You need to click the `A` button before the gamepad will be recognized and the thumbsticks enabled.
Today I also committed the `deltas` branch.
### Before deltas
Before the delta branch, the scenevr server sent the state of *every single element in the scene* 5 times a second to every connected client.
### After deltas
Using a bunch of `object.observe` calls, the scenevr server now keeps track of what elements are changing (because they're animated, or responding to user behaviour) and only send those over the wire. This results in:
* Much lower CPU utilisation on the server
* Less network traffic
* Can support more concurrent users
* Simpler client side change detection
It's a big win, and although there are still a few bugs to iron out, it's deployed on scenevr.hosting and client.scenevr.com, so you can try it out now.
Note that this change requires that you upgrade your version of node to 0.12.0 (the latest release).
### Changed the face
@ujelleh had complained that the face was too creepy. So I replaced it with the look of disapproval face.
ಠ_ಠ<file_sep>---
title: Roadmap
primary_navigation: false
position: 5
---
# Roadmap
### Avatar customisation
Allow users to set girth, height and color of avatars. Make a scene for choosing a face. Render a face on the avatars.
### Friend list
Keep a list of your friends, be able to message them in game (voice message or text chat), and teleport to their location.
### Google Cardboard
Use the hmd polyfill to support google cardboard. Investigate navigation techniques that will work with the one bit 'magnet' input system. Probably look at the ground and click to teleport.
### Physics on the server
Use bullet physics on the server, with a fallback to cannon.js, add physical attributes to elements so they can be simulated on the server.
### \<group /\> element
Create a group element for nesting transforms, allows things like:
```xml
<group position="1 2 3">
<box />
</box>
```
### Break server into smaller modules
As per the npm philosophy, break the server into several smaller modules, so that people can re use the scenegraph/dom code for other purposes and projects.
### Persistence
Investigate and expose a persistence method for scenes, something like localStorage, or webSQL. Possibly use redis for this?
### Support convexpolyhedra collision meshes
Create a model format for representing polyhedra as collision meshes (possibly create hulls around .obj models), to allow collision models that aren't cube.
### Add \<sphere /\> element
Allow spheres, potentially with `subdivision` count as an attribute.
### Add \<light /\> element
Allow point lights and ambient light to be set as an element.
## Previous goals
These are things that used to be on the list but are on the back burner for now.
### Unity client
Investigate porting the web client to unity (c#), and measure the performance advantages. This is particularly with a goal to having a highly performant mobile client. Investigate opensource licenses that can be used with Unity projects and plugins. Find out how to render to texture for each platform (for the billboards).
### Gear VR
Try using the chrome webview, or the unity client, to create a gear vr + bluetooth controller mobile interface for SceneVR.
### Hosting
Create a hosting server that allows people to easily serve SceneVR scenes. Have some error handling (or provide integration with raygun.io) for reporting errors that occur in the scene.
### Blender exporter
Take the existing blender export code and make it work well, generating entire scene files with collision meshes and seperate .obj objects, keeps existing blender object names and converts them into `id` attribute.
## Performance
SceneVR is written in pure javascript at the moment, with a few node.js binary modules on platforms that support them. The client, server and scripts are all written in javascript. Earlier in the lifecycle of SceneVR, I wrote a server in c++, that embedded v8. And I have also worked on various native viewers for the SceneVR protocol. As the project progresses, there is no reason that parts of the client or server cannot be replaced by close-to-the-metal components, with a native fallback for cases where ultra-performance isn't required.
For example, cannon.js can be augmented with bullet. The websocket protocol can be augmented by raknet. The dom-lite implementation could be augmented with the dom implementation in webkit or firefox. The client can be rewritten in unity, unreal, jmonkeyengine or ogre. Some of these libraries already have node.js bindings, others would need new bindings written, but with node-gyp, it's relatively straightforward to create bindings to existing libraries. It would even be possible to write the entire server in c++, embedding v8, although this would prevent people extending their scenes with custom node modules.
In summary, there is a long path ahead for optimisations to SceneVR, but we won't be taking any steps until we are forced to by performance bottlenecks.
In the words of [<NAME>](http://c2.com/cgi/wiki?PrematureOptimization):
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil**. Yet we should not pass up our opportunities in that critical 3%."
<file_sep>---
layout: post
title: "Making a door"
date: 2015-04-13
---
I just put up a [gist of making a door](https://gist.github.com/bnolan/a740dccdde9c0d3cb5ad) using SceneQuery. There's a few things going on here. First up you'll need to download [scenequery](http://github.com/scenevr/scenequery) from github. Next up create two grey walls, and a pink door.
<img src="https://pbs.twimg.com/media/CCbX14DUAAAoaBX.png" class="screenshot" />
Then you need to add a `click` event handler to the door. We store the state of whether the door is opened or closed by using a css class. This doesn't actually have any effect on the display of the door, it's just a handy place to store some state.
Now, we could have the door open instantly, but its cooler if we take 1 second (1000 milliseconds) for the door to animate open. To do this, we use the `animate` method in SceneQuery. Note that at the moment you can only animate position and rotation. So we work out the state the door needs to move to, then animate the door. And boom! You have an animated dooor.
```html
<scene>
<spawn position="0 0 10" />
<box class="wall" style="color: #ccc" scale="10 4 0.2" position="-6 2 0" />
<box class="wall" style="color: #ccc" scale="10 4 0.2" position="6 2 0" />
<box class="door" style="color: #f07" scale="2 4 0.2" position="0 2 0" rotation="0 0 0" />
<script src="scripts/scenequery.js" />
<script>
var door = $('box.door').addClass('closed');
door.click(function (e) {
var endRotation, endPosition;
if (door.hasClass('closed')) {
// open door
endRotation = new Euler(0, -Math.PI / 2, 0);
endPosition = new Vector(1, 2, -1);
door.removeClass('closed');
} else {
// close door
endRotation = new Euler(0, 0, 0);
endPosition = new Vector(0, 2, 0);
door.addClass('closed');
}
door.animate({
rotation : endRotation,
position: endPosition
}, 1000);
});
</script>
</scene>
```
<file_sep>---
title: New Homeroom
date: 2015-02-28
tags: homeroom
layout: post
---
I released a new homeroom today. It is a gallery with several tall thin windows looking to the east, and corridors off to the three wings, the alien room (all hail our alien overlord), the reddit gallery room (make sure you click the portals to visit the galleries) and a room that is currently empty but will become a link to scenes that people submit to [/r/scenevr](//reddit.com/r/scenevr).
<img src="/images/blog/homeroom.png" class="screenshot" />
The scene was modelled originally in Sketchup (taking care to make sure the faces are facing the right way and deleting bits of geometry that you can't see from inside the scene). It was then exported to blender where I set up lighting, merged all the geometry together, and then baked the lights.
Because SceneVR doesn't support mesh collision at the moment, I had to create a seperate collision model for the homeroom.
```xml
<!-- Gallery model with collision disabled -->
<model src="/models/home.obj" position="0 0.01 0" style="collision: none; color: #555; light-map: url(/textures/home-lightmap.jpg)"/>
```
I did this by placing about 30 boxes around the walls and corridors. I then use our blender export script which outputs a bunch of invisible boxes that are used only for collision:
```xml
<!-- Collision -->
<box position="0.16626548767089844 -1.505699634552002 -0.6487710475921631" scale="80.0 2.0 200.0" rotation="0.0 0.0 0.0" style="color: #f0a; visibility: hidden;"/>
<box position="-3.6149256229400635 6.710185527801514 1.4967803955078125" scale="2.0 19.231510162353516 2.0" rotation="0.0 0.0 0.0" style="color: #f0a; visibility: hidden;"/>
<box position="5.27642822265625 6.710185527801514 1.4967803955078125" scale="2.0 19.231510162353516 2.0" rotation="0.0 0.0 0.0" style="color: #f0a; visibility: hidden;"/>
```
The rest of the elements were then placed manually around the scene, as well as an elevator and some sliding panels that hide links to reddit galleries. The galleries are auto-generated using the script in [scene-scripts](https://github.com/bnolan/scene-scripts).
The new homeroom has been posted a few places around the internet, so there have been people joining the room every few minutes all day - it's been great chatting with you all!<file_sep>---
layout: post
title: "An open virtual world"
date: 2015-04-17
---
I didn't start SceneVR because I wanted to build the eponymous virtual world.
I built it because I want there to be an opensource, open natured virtual world, that everyone can contribute to and be in. I don't want a hundred different virtual worlds that don't interoperate. I want to be able to walk from one room to another room, scene to scene, world to world, without leaving your browser or client.
## JanusVR
James and I have been talking for a while. During a chat last week, we got to understand each other a bit better, and I mocked up a proxy that allowed Janus to connect to SceneVR worlds. After that demo, James blew my mind by adding support for Scene markup to Janus.
The thing with Janus, is that James invented most of this shit.
* Portals. James invented them.
* Rooms with html-like markup. James invented that.
* A white floor with a grid on it and a skybox in the distance? Well, the matrix invented that, but James reintroduced it to the conscience. ;)
## Altspace and Convrge
Altspace and Convrge are doing awesome stuff in the VR space. They have nice clients and altspace has a javascript API coming out.
But they're all seperate worlds.
What is the point of making a bunch of worlds that don't interoperate?
I really want us to work together to make it so you can walk from one world to another. That doesn't mean that I want everyone to build their worlds in Scene, but I really want is to make a way that you can walk straight from Janus to Scene to Altspace to Convrge.
Let's make it happen.<file_sep>---
title: Billboard
primary_navigation: true
---
# Billboard
A billboard is a white box that has an html page as a texture on the front face. It inherits from [Element](/element.html).
## Sample XML
```xml
<billboard id="hello" position="0 1 0" scale="2 2 0.2"><![CDATA[
<h1>Hello world</h1>
<br />
<center>
<img src="images/smiley.png" />
</center>
]]></billboard>
```
## Screenshot
<img src="/images/billboard.png" class="screenshot" />
## Scripting
You can change the content of a billboard `cdata` node by assigning to the `data` attribute. This will cause the billboard to be re-generated (for doing a scoreboard, or other dynamic data). Note that re-generating billboards can be expensive, try and not do it more than once per second.
```javascript
document.getElementById("hello").firstChild.data = '<h1>It has all changed</h1>';
```
## Notes
The html content inside a billboard must be enclosed in a `<![CDATA[ ... ]]>` block. This is so that the scene parser doesn't have to try and parse all the html on the server, but can instead send it straight to the client, where the client renders it.
## Limitations
Because of [limitations](https://code.google.com/p/chromium/issues/detail?id=294129) in some browsers, scenevr cannot render the html directly to a texture, but instead uses [html2canvas](http://html2canvas.hertzen.com/) to convert the html into a texture. This means that scenevr only supports a subset of html. You cannot use `form`, `iframe`, `embed` or many other things. Also note that the html is only rendered once and you cannot interact with it. So you can't click on links embedded in the html, nor will animated gifs work correctly.
These are some pretty serious limitations, but the goal for billboards, is to have an easy way to render text, images and tables, which html is great for. Although it is possible to use css3 to embed fully interactive web pages in a scenevr scene, that has many limitations (it doesnt work in rift mode, depth sorting gets broken) and is extremely slow. Over time we expect more html features to be rendered correctly, and it would be cool to be able to interact with forms, but for now, just use billboards to render static text and images.
Billboards have a physical body, so you can collide with them. Most of the galleries just use plain billboards.<file_sep>---
title: Scene client can now be loaded from other domains
date: 2015-05-04
layout: post
---
<div class="md"><p>I just published the scene-client 1.0.2. This is part of my goal to make SceneVR work so that you can include scenes on your own websites, by just including a script tag and a bit of javascript. This release.</p>
<p>Similair to the way the google maps api lets people embed maps on their own site the scene client will eventually be usable so you can have scenes embedded on your site.</p>
<p>There will probably be some limitations to this initially, like you will be anonymous, and if you enter a portal that takes you elsewhere on the internet, you'll be redirected to the full scenevr client (as scenevr.com), but it'll be a great way for putting your content on your own server.</p>
<p>This is all part of upgrading scenevr.com with the new server i'm working on, that interoperates with the rest of the internet a lot better, and makes Scene less of an island and more a part of the web.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34sc3g/sceneclient_102_scene_client_can_now_be_loaded/'>Read comments on reddit...</a><file_sep>require 'json'
require 'open-uri'
require 'date'
require 'htmlentities'
json = JSON.parse(open('https://www.reddit.com/r/scenevr.json').readlines.join)
json['data']['children'].each do |child|
child = child['data']
next unless child['selftext_html']
next unless child['author'] == 'captainbenis'
date = DateTime.strptime(child['created'].to_s,'%s').strftime('%Y-%m-%d')
title = child['title'].gsub(/:/,' ')
slug = date + '-' + title.downcase.gsub(/[^a-z]+/,'-').slice(0,50).sub(/^-+/,'').sub(/-+$/,'') + '.md'
html = HTMLEntities.new.decode(child['selftext_html'])
html = html.gsub(/<!--.+?-->/,'')
html += "<br /><a href='#{child['url']}'>Read comments on reddit...</a>"
post = "---\ntitle: #{title}\ndate: #{date}\nlayout: post\n---\n" + html
next if File.exists?('source/posts/' + slug)
File.open('source/posts/' + slug, 'w') { |f| f.write(post) }
puts slug
end
<file_sep>---
title: Replacing logins with something else...
date: 2015-05-01
layout: post
---
<div class="md"><p>I've decided that running a login server, with username / password / captchas / email reset / etc isn't a key component of what we're trying to do with Scene.</p>
<p>The biggest problem is the friends list. When you log into scene, your friends should be highlighted in a different color, and you should be able to see which Scene they are in, and teleport straight to them to join them. To do this requires a social graph, and there are two options:</p>
<p><strong>Create a social graph</strong>, this would mean creating a way to add friends in Scene, and start to build up a network. This would be fun to code up, and valuable for Scene the company to own, but it'd be a massive pain the ass, and how many people can be bothered re-adding all their friends to a new social network.</p>
<p><strong>Use an existing social graph</strong>. This is my preferred option. If you facebook login and instantly you can see where all your friends are in Scene, I think this is a big win.</p>
<p>Real names. In the first iteration of this functionality, I'm going to get rid of handles, and when you're in Scene you'll appear with just your first name to identify you. This isn't going to be a long term solution, and nicknames will probably come back, but this is just a first cut to get things moving.</p>
<p>I'll also make it easier to switch between logged in and anonymous mode, so that if you want to go into bobs-porn-den, that won't show up on your friends radar. The radar app, that shows where your friends are and lets you warp to them will probably be a little node.js app that I'll put on github and anyone can run.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34gpfj/replacing_logins_with_something_else/'>Read comments on reddit...</a><file_sep>---
title: Protocol
primary_navigation: true
---
# SceneVR Protocol
This document describes the SceneVR wire protocol. This document is mostly of interest to people build alternative SceneVR clients or servers.
## Overview
A SceneVR client connects to the server over websockets. As soon as a client connects, the server will send xml packets describing the scene.
## Websockets
To connect to a scene, connect to the url specified in the location bar, with a websocket connection on port 8080. So for example this url:
http://client.scenevr.com/?connect=chess.scenevr.hosting/chess.xml
You would establish a websocket connection to:
ws://chess.scenevr.hosting:8080/chess.xml
You can also connect to port 80 for websockets, except some ISPs block websocket upgrade requests on port 80, so use 8080.
The `protocol` parameter of the websocket should be `scenevr`.
```javascript
var socket = new WebSocket("ws://chess.scenevr.hosting:8080/hello.xml", "scenevr");
```
## Packets
The first packet a client will recieve is the `ready` event. This will tell the client what UUID has been assigned for the player. This allows the client to identify the `<player />` object that is their own avatar, and not render it.
```xml
<packet><event name="ready" uuid="6693fc3e-cfba-43cb-a0f4-1e3a980d63a3" /></packet>
````
A client is responsible for physics and movement of their own avatar, so can ignore `<player />` packets about their own uuid.
## Packet format
Packets are valid xml wrapped inside a `<packet />` element. At this stage, SceneVR doesn't support nested transforms, so all elements inside the packet can be added directly to the scene. Some elements have `CDATA` elements inside them. eg:
```xml
<billboard uuid="a6d25ec5-42f5-41a5-95f9-040474ed8804" position="-2 1 0" rotation="0 1.5700000000000003 0" scale="2 2 0.25"> <![CDATA[ <h1>Welcome to SceneVR</h1> <p> There are two boxes for you to enjoy. One is <span style="color:#f70">orange</span> and one is <span style="color: #0af">aqua</span>. </p> <p> There are also some little voxel men, courtesy of @mikeloverobots. </p> <center> Enjoy <span style="background: #333; padding: 5px; display: inline-block; color: #f70">VR</span> ! </center> ]]> </billboard>
```
The CData is used so that the clients don't have to decode html inside `<billboard />` tags twice, but can instead recieve it as text, then pass it onto a html renderer. (Due to browser security limitations, billboards cannot have iframes, inputs, embeds etc, they are best treated as a static texture).
## Create / update / delete
The server does not maintain a list of what elements the client has seen, but instead sends all changing elements to the client, whenever an element changes. So for example - the teapot in the [homeroom](http://client.scenevr.com/) has a `setInterval` that continuously rotates the teapot. This means that the `rotation` attribute of the `<model />` is constantly changing. That means that at 10hz (the current update frequency), the element is sent to all connected clients.
To process a packet, the client parses the packet, then for each child element, looks up first:
### Is it an element we have seen before?
```xml
<box uuid="7334d64b-3989-4ca5-bbc1-f05bc6704e6e" id="home" style="color: #555555" position="2.5 0.25 3.5" rotation="0 0 0" scale="1 0.5 1"></box>
```
If we look up the UUID and find this uuid in our local scenegraph, we need to make a decision. Have only the position and rotation of the element changed? If so, just interpolate the previous position and rotation to the new position and rotation (do the interpolation over the network timestep, currently 100ms, but in the future this will be server-definable).
To tell if only the position and rotation changed, you need to keep a copy of the parsed XML from when you created the object in your scenegraph. You can use a userData for this. For example (pseudocode):
```javascript
var packet = parseXML("<box uuid='1234...' position='1 1 1' style='color: #f0a' />");
var box = new OpenGL.Box()
box.position = StringToVector(packet.position);
box.setColor(packet.style..color)
box.userData = packet;
```
In this pseudocode, we can then do a test when we recieve a new packet. If only the `position` and `rotation` attribute have changed, then we can interpolate the existing element. If the style attribute has changed, then we need to destroy and regenerate the element, to apply the new styles.
The `if_substantial_change` then `destroy_and_regenerate` is a very naive way to make sure that the scenegraph reflects the current server state of an element, but it is the easiest way to get started. Feel free to optimise this step as you see fit.
### Is it an element we haven't seen before?
```xml
<box uuid="7334d64b-3989-4ca5-bbc1-f05bc6704e6e" id="home" style="color: #555555" position="2.5 0.25 3.5" rotation="0 0 0" scale="1 0.5 1"></box>
```
Using the uuid attribute, we look up to see if we have this element in our local scenegraph. If we don't, then we create the element and add it to our scenegraph with the uuid attribute so that we can look it up in the future. The attributes of an element are parsed as per their description in the relevent API docs on scenevr.com.
*The wire serialization of elements is identical to the markup used to define a scene*. The only addition is the uuid which is only used for wire serialization.
### Is it a `<dead />`?
```xml
<dead uuid="1234-1234-1234-1234" />
```
If it is a dead packet, look up the corresponding object in our local scenegraph by using the uuid attribute, and remove that object from the scenegraph. This is an instanteneous action, no need to fade out the object, just prune it from the scenegraph and the physics simulation.
### Is it an `<event />`?
```xml
<event name="ready" uuid="6693fc3e-cfba-43cb-a0f4-1e3a980d63a3" />
```
Events are basically remote procedure calls, and are treated seperately from other elements in the packet. See *events* below.
## Send player position
At the server update frequency (currently 5hz), the client should send the current position of the player. This packet is sent like this:
```xml
<packet><player position="1 2 3" rotation="0 1.571 0" /></packet>
```
Only the position and rotation attributes are considered by the server. There is no need to send the UUID with the player packet. To keep the load easier on the server, you should bundle together player updates with events that you are going to send, and send them all in one packet at the server update frequency (10hz).
## Send click events
If the player clicks on an element, send the click event, with the UUID of the element that was clicked:
```xml
<packet><event name="click" uuid="1234..." point="1 2 3" /></packet>
```
The point is a Vector that represents the point at which the player clicked on the element. This is important for the chessboard for example, to work out where on the board the player clicked.
## Send collide events
If the player collides with an element (touches it), send a collide event. You should only send a collide event every time the player touches a different object. If a player jumps off an object and lands on the same object, you should send another collide event, but throttled so that you don't send two collide events for the same UUID more than once every 500ms.
See `addPlayerBody` in client.js in the web client for more details on this.
The normal is a vector pointing from the object in the direction of the player, representing the direction the object is pushing against the player.
```xml
<packet><event name="collide" uuid="1234..." normal="-1 -2 -3" /></packet>
```
## Send chat events
To post a message to the chat channel for the current scene, send a chat element.
```xml
<packet><event name="chat" message="I love big butts and I cannot lie" /></packet>
```
Players are anonymous by default, so your chat messages will be posted anonymously. See authentication below.
## Receieve chat message
A chat message is recieved like this:
```xml
<packet><event name="chat" from="toastman" message="I love big butts and I cannot lie" /></packet>
```
## Recieve respawn event
If a player 'dies' (this event is usually triggered by game logic, eg when you collide with a ghost in puckman), you should `respawn` them, send them back to the spawn point, and add a message to the chat log saying why they died.
```xml
<packet><event name="respawn" reason="you touched a deadly ghost" /></packet>
```
## Restart event
If you are connected to a local scenevr server that is running in development mode (the default), then when the server detects a change to the scene files (because you pressed save in your editor), it sends a restart event to all connected clients.
```xml
<event name="restart" />
```
If the client recieves this message, it should disconnect from the server, remove all objects in the local scenegraph, then reconnect 1000ms later to the server. The player should stay where they are and not respawn (ignore the `<spawn />` element) but the scene should reload around the player.
## Authentication
Authentication is achieved by presenting a web surface (an iframe in the web client) that points at:
http://login.scenevr.com/
This is the scenevr login server. Once the player logs in, the login server uses postMessage to say that the player is now logged in and you can request an authentication token.
```html
<script>
window.parent.postMessage(JSON.stringify({
message : "auth"
}), "*");
</script>
```
You should write a hook that detects a call to `postMessage`, you can now trust that the player is logged in.
You need to save the session cookies set for the domain `login.scenevr.com`, these are used in the next step to get a token to authenticate with the current room.
Using the cookies, you can see if the user has logged in by resquesting:
http://login.scenevr.com/session/status.json
If you have set the cookies correctly and formed the request, this will return json like:
```javascript
{"name":"toastman","id":16}
```
Note that the login server currently doesn't use SSL, but SSL will be added and *required* soon.
## Get an authentication token
Using these cookies - do a `GET` request to this url:
http://login.scenevr.com/session/token.json?host=chess.scenevr.hosting
The server will respond like so:
```javascript
{"token":"<KEY>"}
```
This is a [json web token](http://jwt.io/) that is signed by the servers private key. All SceneVR servers have the login servers public key embedded in them, so can prove that this is a valid token for authenticating the user to this SceneVR server at this time. Tokens expire after a specified period, so you should get a new token every time you connect to a scene and want to authenticate the user.
## Sending tokens to the server
To authenticate the client - send the value of the token to the server:
```xml
<packet>
<event name="authenticate" token="<KEY> />
</packet>
```
The client should now be authenticated and you can post messages to the chat channel and you will appear as that player. You will also have your name above the pegman avatar when people see you.
## OpenTok
We use opentok / webrtc for voice chat. This section will be added later... Email ben to remind him to finish this if you need details.
<file_sep>---
title: SceneQuery
primary_navigation: false
---
# SceneQuery
Can you write a web page with jQuery? If you can, then you can create a Virtual Reality scene with SceneQuery, a version of jQuery for SceneVR.
First, a bit of an introduction to SceneVR.
The core of SceneVR
## Example
```xml
<scene>
<box id="door" position="0 1 0" scale="2 2 2" style="color: #555" />
</scene>
```
This is our door. We want to add
<file_sep>---
title: Chess
date: 2015-03-04
tags: scene
layout: post
---
I finished up a multiplayer version of chess tonight. It uses [chess.js](https://github.com/jhlywa/chess.js/) to handle the logic, and implements the interactivity and multiplayer using scenevr. [Try it out!](http://client.scenevr.com/?connect=chess.scenevr.hosting/chess.xml) You can see the [source code](http://chess.scenevr.hosting/chess.xml), it is about 180 lines of javascript.
<img src="/images/blog/chess.png" class="screenshot" />
It's been fantastic watching people play the game. Currently anyone can play, but what tends to happen is that people cluster at the viewing platform at each end, and one person jumps down and makes a move. It's a pretty fun emergent behaviour watching people play. There are a few bugs (castling, promotion doesn't work) that need fixing, I've added [issues for them on github](http://github.com/scenevr/chess/issues), if anyone wanted to have a crack at them that'd be awesome, but otherwise it's looking pretty good.
<file_sep>---
title: Script
primary_navigation: true
---
# Script
An inline, or externally referenced javascript block. These blocks are executed after the dom has been loaded.
## Notes
Even though the script block is evaluated on the server, by a node.js process, it is run in a sandbox, so you cannot access many of the node.js built ins. When scripting with SceneVR, you should refer only to documented attributes and methods of the elements. It may be possible to escape out of the sandbox, but use of SceneVR internals is not supported, and your scenes may break in future versions. Note that the node.js sandboxing doesn't prevent you from creating infinite loops. If you create an infinite loop, your server will grind to a halt.
Due to limitations in the way we parse the scenes at the moment, you may not get a correct line number when an error is reported. This will be improved in future versions.
All scripts run in the same context.
## Sample XML
```xml
<script src="scripts/chess.js"></script>
<script>
var game = new Chess;
console.log(game.gameOver());
</script>
```
NB: If you are embedding html in strings in your javascript, or using < and >, you need to wrap your script inside a cdata.
```
<script>
<![CDATA[
console.log("This is some <b>html</b>");
]]>
</script>
```
## Attributes
### src
If specified, the script will be synchronously loaded from an external file and evaluated. Scripts must be local, you cannot reference files over http.
## Global scope
The following members are in the global scope. See [scene.js](https://github.com/bnolan/scenevr/blob/master/elements/scene.js) for an up to date list of members exported to the global scope.
### document
The document object representing this scene. Access `document.scene` for the root level scene element.
### Vector
The [vector](/vector.html) class, derived from the three.js vector class.
### Euler
The euler class, derived from the three.js euler class, for rotations.
### XMLHttpRequest
The [XMLHTTPRequest](http://www.w3.org/TR/XMLHttpRequest/) class, an implementation of the w3c spec. It has no cross-domain restrictions.
### console
A minimal console, only has `console.log`. Logs as a chat message to connected clients, as well as to the server console.
### setTimeout
A proxied setTimeout that catches errors in user code without bringing down the server.
### setInterval
A proxied setInterval that catches errors in user code without bringing down the server.
<file_sep>---
title: Seperated scene-dom from the server
date: 2015-05-11
layout: post
---
<div class="md"><p>More sexy backend changes that no-one except Ben and Sam will see, but we've seperated the scene loading code from the server. The big goal here, is to make it so that you can load scene files directly in the client, and simulate them in the client.</p>
<p>This means that you can make Scenes without requiring a server. Sadly, these scenes will be single player only, but it makes it much easier for you to create scenes without having to install node.js and all that stuff. For example, we've forked <a href="http://glslb.in/">glslbin</a> and are going to make <a href="https://github.com/scenevr/bin">bin.scenevr.com</a>, which will let you quickly hack up scenes in the browser. And then once you've built something cool and want to put it online, you can deploy to heroku via one-click deploy.</p>
<p>I've also been working on the new web client, which uses all the same rendering code, but has way nicer web interaction, like when you paste a link to a scene to reddit, twitter or facebook, you will get a pre-rendered screenshot of what the scene looks like. We also put a little summary of the scene (all the html content and links in it) in a <noscript /> tag, so that google can index your scene and you can use google site search to search for a scene that you found on scenevr.</p>
<p>Finally, we're working on making the reddit galleries work for any reddit gallery, not just the 3 pre-defined ones.</p>
<p>So there's been a bunch of behind the scenes work, but this will all lead to some nice user-facing features in the next few weeks.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/35jlgl/seperated_scenedom_from_the_server/'>Read comments on reddit...</a><file_sep>---
title: Moving docs to docs.scenevr.com
date: 2015-05-04
layout: post
---
<div class="md"><p>The client.scenevr.com/?connect URL is needlessly complex, I'm going to put the scenevr world at <a href="http://www.scenevr.com">www.scenevr.com</a>, and move the docs and blog to docs.scenevr.com.</p>
<p>So now whenever someone goes to check out scenevr, they'll be launched straight into virtual reality, instead of having to click the 'try now' link.</p>
<p>This is also part of an effort to put more focus on VR in scenevr, so instead of having lots of web components, try and move as much into VR as possible. For example, the face configurator that I was working on, that's being redeveloped as a VR scene, instead of a seperate web page.</p>
<p>The UI is also going to undergo a bit of a redesign to make mobile and clients using VR (cardboard / rift) more of a first class citizen in the world, at the moment the VR experience works best for the pc master race, and I want everyone to be included.</p>
<p>Except for console (unless someone with a console development license wants to port the unity client to xbox / ps). :)</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34roh0/moving_docs_to_docsscenevrcom/'>Read comments on reddit...</a><file_sep>---
title: Puckman
date: 2015-03-14
layout: post
tags: game
---
I deployed puckman today, it's based on [pacman.js](https://github.com/daleharvey/pacman) by @daleharvey. It was pretty easy to convert to SceneVR.
<img class="screenshot" src="/images/blog/puckman.png" />
I first iterated over the pacman.map variable, and create a box for every wall in the map. Each box has a large dark blue box, and a small bright blue border around it. I then create all the little pills, which are set to `collision-response: false` which means that the script can detect touching them up, but walk straight through them. Then the ghosts are instantiated and simulated 10 times a second by the pacman.js code.
Then it's a simple case of adding a `<model />` for each ghost (pacman.js tells you what color to make them, pink or green etc, or blue when they're vulnerable, or grey when they're dead), and looking for collision events with the ghosts and killing the player, or eating the ghost.
View the [source here](http://puckman.scenevr.hosting/game.xml). <file_sep>---
title: Plane
primary_navigation: true
---
# Plane
A plane is a plane on the x-y axis, it's depth in the z dimension is 0. It inherits from [Element](/element.html). If you want a horizontal plane, rotate your plane by approximately `-1.5708` radians on the y axis as in the following example. Planes are finite, they will only be as large as the specified scale in the x and y dimensions.
## Sample XML
```xml
<plane style="texture-map: url(/images/stones.jpg); texture-repeat: 1000 1000;" scale="1000 1000 0" position="0 0.01 0" rotation="-1.5708 0 0" />
```
## Screenshot
<img src="/images/plane.png" class="screenshot" />
## Styles
### color
The color of the plane.
### texture-map
A texture map that is applied to the plane. Texture-maps are lambertian shaded.
```
style="texture-map: url(/images/crate.png)"`
```
### texture-repeat
How many times is the texture repeated in the U and V directions.
```
style="texture-map: url(/images/grid.png); texture-repeat: 100 100"
```
<file_sep>---
title: Lots of backend work
date: 2015-05-17
layout: post
---
<div class="md"><p>You might not have noticed a bunch of changes on the front of SceneVR lately, but we haven't been idle. We've been making a new frontend that can be indexed by google, so that your scenes get good search engine ranking, and when you paste a link to your scene, reddit, twitter and facebook (and anyone else that uses opengraph tags) can display a thumbnail of your scene to encourage people to try out your scene.</p>
<p>We've also been working on a large change to make it so that you can develop scenes in the browser without requiring a node.js server. Hopefully you'll start to see some of this come to fruition soon!</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/36aver/lots_of_backend_work/'>Read comments on reddit...</a><file_sep>---
title: Semistandard
date: 2015-03-30
layout: post
---
So today was a fun productive day on SceneVR. I spent the weekend at a great node conference in christchurch, and met <NAME>, substack, <NAME> and feross (amongst others), and after seeing all their great work, I got inspired to tidy up the source code to the SceneVR server.
So now the code is semistandard compliant (semistandard is a great code linter based on standard, but with semicolons, because I prefer them).
The server for scenevr was originally written in coffeescript, and about 2 months ago, I transpiled it all to javascript, and started coding purely in javascript. However, there were still a few coffeescript classes left around (in the specs), and the javascript was pretty ugly, using weird `for()` loops instead of nice clean .forEach. So today I set up the package to lint with `semistandard` and fixed up the whole server, deleted a bit of unused code, and removed pretty much all the ex-coffeescript grossness.
While I was at it, I ported the specs from jasmine to using [tape](https://github.com/substack/tape) by substack. It's a great testing library, and super lightweight. I found a few weird errors while fixing up the tests, but they're all fixed up, and now the tests pass yay!
I added a little badge to the readme that shows that SceneVR gets about 1000 downloads a month on NPM, which is cool.
## Future
In the future for scenevr, I'd like to break the code into some smaller modules that can be independently published to NPM. This might be handy for people that want to make alternative scenevr servers, or want to use the scenevr code to write intelligent agents that connect to scenevr clients.
I'd also like to get rid of the forked Vector, Euler and Dom-Lite classes, and instead use the original versions from NPM, and just extend them as necessary to add code to them, instead of hacking up the source code. I think I can probably do this now that we use `object.observe`.
I'd like to replace the current `dirtyNodes` code with something modelled on the [mutationobserver](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) API. That'd make the code a bit nicer, and I could release a nice module around that.
After talking with <NAME>, he gave me some ideas about how to more efficiently send updates over the wire, and how to send nested elements efficiently. I'm really keen to have a go at this, since grouped transforms would be really handy for scene creation.
I'd also like to remove the current UUID code and move to using `nodeid` instead, because that'll be more space efficient on the wire, and because all node ids are generated on the server, there's no need to use UUIDs.
Productive day!<file_sep>---
title: Big refactor for code cleanliness
date: 2015-03-31
layout: post
---
<div class="md"><p>The server code was getting pretty gross, so I did some work to get the tests passing, made the code pass the semistandard linter and made some effort to get rid of the forked libraries. I'd like to refactor the server into a bunch of small mode modules eventually.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/30z92o/big_refactor_for_code_cleanliness/'>Read comments on reddit...</a><file_sep>---
title: Working on general performance work and Safari / IE support
date: 2015-04-28
layout: post
---
<div class="md"><p>I've discovered that scene doesn't work very well on safari on Mac, and the keyboard controls aren't very good for IE either, so I'm working on polishing up those two platforms to make it easier to develop on those browsers :)</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/3437q0/working_on_general_performance_work_and_safari_ie/'>Read comments on reddit...</a><file_sep>---
title: Are all your blender models coming out as black?
date: 2015-05-26
layout: post
---
<div class="md"><p>Make sure you have clicked <a href="http://i.imgur.com/3Fd5nKi.png">write normals</a> in the blender export options.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/37b8bm/are_all_your_blender_models_coming_out_as_black/'>Read comments on reddit...</a><file_sep>---
title: .mtl support added!
date: 2015-04-09
layout: post
---
<div class="md"><p>You can now use .mtl files like this:</p>
<p><model obj="x.obj" mtl="x.mtl" /></p>
<p>If you link to images inside your mtls, you should use relative paths. This means you might need to open your .mtl file in a text editor and change the code like this:</p>
<p>newmtl armchair_part4</p>
<p>Ns 96.078431</p>
<p>Ka 0.000000 0.000000 0.000000</p>
<p>Kd 0.640000 0.640000 0.640000</p>
<p>Ks 0.500000 0.500000 0.500000</p>
<p>Ni 1.000000</p>
<p>d 1.000000</p>
<p>illum 2</p>
<p>map_Kd /textures/armchair_part4_d.jpg</p>
<p>This will load the textures from your /textures/ directory in your SceneVR scene.</p>
<p>This makes it way easier to create scenes with multiple materials in your .obj files. Check out the chairs in the homeroom, which now have fancy textures instead of just being a boring color.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/31zfrd/mtl_support_added/'>Read comments on reddit...</a><file_sep>---
title: Link
primary_navigation: true
---
# Link
A link is a floating globe that when clicked, turns into a portal to another scene. It inherits from [Element](/element.html).
## Sample XML
```xml
<link href="/challenge.xml" position="-0.8 1 2" rotation="0 1.57 0" />
```
## Screenshot
<img src="/images/link.png" class="screenshot" />
## Attributes
### rotation
The rotation of a link is important, because even though links are represented as spheres, when they are opened, they become a 2 dimensional circle, and players can only enter a portal by going into the sphere perpendicularly, so you must rotate the link to make it possible for players to run through it.
### href
This is the destination url. These urls are merged with the url of the current scene, so you can use relative urls like `/next-scene.xml` to link to another scene in the current scenes directory, or a complete url like `ws://home.scenevr.hosting/home.xml` to link to the home scene.
## Notes
When you go through a portal, a back link portal is generated at the spawn of the next scene, so you can go back to the previous scene. However, these portals go away if the page is reloaded. However, people can always use the back button to go back to a previous scene.<file_sep>---
title: Got server-side lightmap rendering partially working...
date: 2015-10-28
layout: post
---
<div class="md"><p>I can now edit a scene in the browser, and then run a command on the server to render that scene using lightmaps. I'm not working on having multiple types of blocks. I'll probably use the EGA color palette, with 16 flat colored diffuse blocks and 16 emissive blocks.</p>
</div><br /><a href='https://www.reddit.com/r/scenevr/comments/3qhqya/got_serverside_lightmap_rendering_partially/'>Read comments on reddit...</a><file_sep>---
title: Thinking of deprecating the hosting service...
date: 2015-04-30
layout: post
---
<div class="md"><p>Hey all,</p>
<p>I had a meet up with my advisors tonight @traskjd and @sminnee, and we talked through a bunch of stuff, and one of the things that I want to do is to turn off new signups for the hosting service, and instead make it way easier for people to deploy their scenes to heroku.</p>
<p>I've come to this decision because in using scenevr locally, I find the hosting service to be a bit of a pain, because it's not easy to just create a new scene, then type a few lines and deploy it, instead you have to drag and drop into the browser, and every time you change one file, you have to reupload the entire scene.</p>
<p>I could fix this, but I think a better option would be to use Heroku, because then I could just type <code>git push heroku</code> and the new version of the scene would be online. This is a great step forward in workflow for anyone who is regularly working on scenes, and I want to promote more people to work on scenes, instead of just hacking them up once and letting them fallow.</p>
<p>On the negative side, is that some people consider heroku quite a technical tool to get started with. This isn't true though! This evening I added a <a href="https://devcenter.heroku.com/articles/heroku-button">deploy to heroku</a> button to Puckman:</p>
<p><a href="https://github.com/scenevr/puckman#deploy-to-heroku">https://github.com/scenevr/puckman#deploy-to-heroku</a></p>
<p>There you go, just click that button and set up your own free instance of puckman on heroku. I let heroku create a hostname for me and it hosted it at:</p>
<p><a href="http://still-inlet-1130.herokuapp.com/">http://still-inlet-1130.herokuapp.com/</a></p>
<p>You can go there and try out puckman.</p>
<p>So what does this mean for the hosting app? Well, I still have to do some investigation before I am ready to unreservedly recommend heroku for scenevr hosting, but if all goes well, i'll turn off new sign ups for the hosting service. I won't turn off the scenevr hosting any time soon, so current users will have months to move their content off, but you can look forward to a bunch of tutorials and some work on the code to make deploying your scenes regularly much much easier!</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34e3o0/thinking_of_deprecating_the_hosting_service/'>Read comments on reddit...</a><file_sep>---
title: Working at a clients office this week...
date: 2015-09-23
layout: post
---
<div class="md"><p>So there probably won't be any releases. I'm concentrating on getting the voxel support, plus a public sandbox working. Had some fun making stairs the other day, it seems the peg man will happily run up stairs with a 20cm run and 10cm drop.</p>
</div><br /><a href='https://www.reddit.com/r/scenevr/comments/3lzij5/working_at_a_clients_office_this_week/'>Read comments on reddit...</a><file_sep>---
title: Reddit
---
# Reddit Galleries in Virtual Reality
SceneVR converts web content into virtual reality spaces that you can share with your friends. Enter
the name of your favourite subreddit below to turn it into a virtual reality scene. Share the URL
of your scene with your friends, and you will see them when they join the scene.
<form action="#" class="enter-destination">
<h3>Enter a subreddit:</h3>
<p>
Turn any reddit gallery into a virtual reality space that you can share with your friends.
</p>
<div>
/r/ <input type="text" id="sub" value="aww" /> <button type="submit">Enter VR</button>
</div>
</form>
## What will it look like?
Subreddit galleries will take any direct image
links and turn them into billboards that you can walk around and view. Galleries are viewed like
first person games if you are used to using them, where you use the WASD keys to move around,
and the mouse to look. If you are on mobile, you can navigate the galleries using two thumbpads.
<img src="/images/subreddit.png" class="screenshot" />
<cite>This is how subreddits appear in VR.</cite>
<img src="/images/friend.png" class="screenshot" />
<cite>This is how other people will appear in VR.</cite>
## How do I view it on my rift?
Oculus Rift support is currently being reworked to work better with the latest 0.6.0 driver release. We
will update this page when rift support is working.
## How do I view on google cardboard?
We currently don't have any google cardboard support, but we are working on it.
<script>
$('form').submit(function (e){
var sub = $('form #sub').val();
window.location = 'http://scenevr.com/wss/scene-reddit.herokuapp.com/gallery.xml?subreddit=' + sub;
e.preventDefault();
});
$('#sub').focus();
</script>
<file_sep>
all:
ruby autoblog.rb
middleman build
s3cmd sync --add-header='Cache-Control: public, max-age=43200' --recursive ./build/* s3://docs.scenevr.com/
| cf98d419ad26e08ae7cd9934ec8b21880eee71e2 | [
"Markdown",
"Ruby",
"Makefile"
] | 33 | Markdown | scenevr/docs | 9280436074ac704c7de9f1b4690c78343d65b0ba | 6d92f465219eed0888592d85ab48757bd993c34a | |
refs/heads/master | <file_sep>import {securityId, UserProfile} from '@loopback/security';
import {HttpErrors} from "@loopback/rest";
// import {TokenService} from '@loopback/authentication';
import {inject} from '@loopback/core';
import {promisify} from 'util';
import {UserRepository} from "@loopback/authentication-jwt";
import {TokenServiceBindings, UserServiceBindings} from '@loopback/authentication-jwt';
export interface TokenServiceInternal {
verifyToken(token: string): Promise<UserProfile>;
generateToken(userProfile: UserProfile): Promise<object>;
revokeToken?(token: string): Promise<boolean>;
decodeToken(refreshToken: string): Promise<object>;
}
const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);
export class JWTService implements TokenServiceInternal {
constructor(
@inject(TokenServiceBindings.TOKEN_SECRET) private jwtSecret: string,
@inject(TokenServiceBindings.TOKEN_EXPIRES_IN) private jwtExpiresIn: string,
@inject(UserServiceBindings.USER_REPOSITORY) private userRepository: UserRepository
) {}
async verifyToken(token: string): Promise<UserProfile> {
if (!token) {
throw new HttpErrors.Unauthorized(
`Error verifying token : 'token' is null`,
);
}
let userProfile: UserProfile;
try {
// decode user profile from token
const decodedToken = await verifyAsync(token, this.jwtSecret);
// don't copy over token field 'iat' and 'exp', nor 'email' to user profile
userProfile = Object.assign(
{[securityId]: '', name: ''},
{
[securityId]: decodedToken.id,
name: decodedToken.name,
id: decodedToken.id,
},
);
} catch (error) {
throw new HttpErrors.Unauthorized(
`Error verifying token : ${error.message}`,
);
}
return userProfile;
}
async generateToken(userProfile: UserProfile): Promise<object> {
if (!userProfile) {
throw new HttpErrors.Unauthorized(
'Error generating token : userProfile is null',
);
}
return this.createTokens(userProfile)
// const userInfoForToken = {
// id: userProfile[securityId],
// name: userProfile.name,
// email: userProfile.email,
// };
// const userInfoForRefreshToken = {
// id: userProfile[securityId]
// };
// // Generate a JSON Web Token
// let token: string;
// let refreshToken: string;
// try {
// token = await signAsync(userInfoForToken, this.jwtSecret, {
// expiresIn: Number(this.jwtExpiresIn),
// });
// // refreshToken is set to expire after 30 days - 30*24*60*60
// refreshToken = await signAsync(userInfoForRefreshToken, this.jwtSecret, {
// expiresIn: 2592000
// });
//
// } catch (error) {
// throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
// }
// return {
// token,
// refreshToken
// };
}
async decodeToken(refreshToken: string): Promise<object> {
const userProfile = await this.verifyToken(refreshToken)
return this.createTokens(userProfile);
// const userInfoForToken = {
// id: user['id'],
// name: user.name,
// email: user.email,
// };
// const userInfoForRefreshToken = {
// id: user["id"]
// };
//
// let token: string;
// let refreshTokenNew: string;
// try {
// token = await signAsync(userInfoForToken, this.jwtSecret, {
// expiresIn: Number(this.jwtExpiresIn),
// });
// // refreshToken is set to expire after 30 days - 30*24*60*60
// refreshTokenNew = await signAsync(userInfoForRefreshToken, this.jwtSecret, {
// expiresIn: 2592000
// });
//
// } catch (error) {
// throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
// }
// return {
// token,
// refreshToken: refreshTokenNew
// };
}
async createTokens(userProfile: UserProfile){
const userInfoForToken = {
id: userProfile[securityId],
name: userProfile.name,
email: userProfile.email,
};
const userInfoForRefreshToken = {
id: userProfile[securityId]
};
// Generate a JSON Web Token
let token: string;
let refreshToken: string;
try {
token = await signAsync(userInfoForToken, this.jwtSecret, {
expiresIn: Number(this.jwtExpiresIn),
});
// refreshToken is set to expire after 30 days - 30*24*60*60
refreshToken = await signAsync(userInfoForRefreshToken, this.jwtSecret, {
expiresIn: 2592000
});
} catch (error) {
throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
}
return {
token: token,
refreshToken: refreshToken
};
}
}
export type Token = {
token: string,
refreshToken: string
}
<file_sep>import { Todo } from '../models/index';
export declare function givenTodo(todo?: Partial<Todo>): Todo;
<file_sep>import { UserProfile } from '@loopback/security';
import { UserRepository } from "@loopback/authentication-jwt";
export interface TokenServiceInternal {
verifyToken(token: string): Promise<UserProfile>;
generateToken(userProfile: UserProfile): Promise<object>;
revokeToken?(token: string): Promise<boolean>;
decodeToken(refreshToken: string): Promise<object>;
}
export declare class JWTService implements TokenServiceInternal {
private jwtSecret;
private jwtExpiresIn;
private userRepository;
constructor(jwtSecret: string, jwtExpiresIn: string, userRepository: UserRepository);
verifyToken(token: string): Promise<UserProfile>;
generateToken(userProfile: UserProfile): Promise<object>;
decodeToken(refreshToken: string): Promise<object>;
createTokens(userProfile: UserProfile): Promise<{
token: string;
refreshToken: string;
}>;
}
export declare type Token = {
token: string;
refreshToken: string;
};
<file_sep>import { TokenServiceInternal } from '../services/token.service';
import { Credentials, MyUserService, User, UserRepository } from '@loopback/authentication-jwt';
import { UserProfile } from '@loopback/security';
export declare class NewUserRequest extends User {
password: string;
}
export declare const TokensRequestBody: {
description: string;
required: boolean;
content: {
'application/json': {
schema: {
type: string;
required: string[];
};
};
};
};
export declare const CredentialsRequestBody: {
description: string;
required: boolean;
content: {
'application/json': {
schema: {
type: string;
required: string[];
properties: {
email: {
type: string;
format: string;
};
password: {
type: string;
minLength: number;
};
};
};
};
};
};
export declare class UserController {
jwtService: TokenServiceInternal;
userService: MyUserService;
user: UserProfile;
protected userRepository: UserRepository;
constructor(jwtService: TokenServiceInternal, userService: MyUserService, user: UserProfile, userRepository: UserRepository);
login(credentials: Credentials): Promise<object>;
whoAmI(currentUserProfile: UserProfile): Promise<string>;
signUp(newUserRequest: NewUserRequest): Promise<User>;
refresh(token: string): Promise<object>;
}
| 4a664dd3c5b024c34fd36b3a0e452cf1cfd68156 | [
"TypeScript"
] | 4 | TypeScript | gopigof/lb_refresh_token | 1410da088fb84ee58bd61a123cc57afd60bb9c37 | 442df6a42ffbcff83502a649a9ee8a3cf7f69512 | |
refs/heads/master | <file_sep>import React, { useEffect } from 'react'
import styled, { keyframes, css } from 'styled-components'
import Portal from './Portal'
import { MdClose } from 'react-icons/md'
const fadeIn = keyframes`
0% {
opacity: 0
}
100% {
opacity: 1
}
`
const fadeOut = keyframes`
0% {
opacity: 1
}
100% {
opacity: 0
}
`
const ModalWrapper = styled.div`
box-sizing: border-box;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1000;
overflow: auto;
outline: 0;
visibility: ${(props) => (props.visible ? 'visible' : 'hidden')};
transition: visibility 1s linear;
${(props) => props.visible && css`animation: ${fadeIn} 1s`};
${(props) => !props.visible && css`animation: ${fadeOut} 1s`};
display: flex;
flex-flow: column nowrap;
& button#close {
margin: 0px;
padding: 20px;
align-self: flex-end;
transform: scale(1.2);
color: #fff;
transition: all .2s ease-out;
-webkit-appearance: none;
appearance: none;
background-color: transparent;
border: 0;
cursor: pointer;
outline: none;
position: absolute;
z-index: 4;
filter: drop-shadow(0 2px 2px #1a1a1a);
&:hover {
cursor:pointer;
color: #337ab7;
transform: scale(1.3);
}
& svg {
width: 36px;
height: 36px;
}
}
@media (max-width: 768px) {
button#close {
padding: 15px;
&:hover {
color: #fff;
transform: scale(1.2);
}
& svg {
width: 24px;
height: 24px;
}
}
@media (max-width: 480px) {
button#close {
padding: 10px;
& svg {
width: 16px;
height: 16px;
}
}
}
}
`
const ModalOverlay = styled.div`
box-sizing: border-box;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.9);
z-index: 999;
visibility: ${(props) => (props.visible ? 'visible' : 'hidden')};
transition: visibility 1s linear;
${(props) => props.visible && css`animation: ${fadeIn} 1s`};
${(props) => !props.visible && css`animation: ${fadeOut} 1s`};
`
function Modal (props) {
const handleClose = () => {
props.setFocus(false)
props.allowScroll()
}
useEffect(() => {
return () => {
handleClose()
}
})
return (
<Portal container='modal-root'>
<ModalOverlay visible={props.visible} />
<ModalWrapper visible={props.visible}>
<button id='close' onClick={handleClose}><MdClose /></button>
{props.children}
</ModalWrapper>
</Portal>
)
}
export default Modal
<file_sep>import React from 'react'
import styled from 'styled-components'
const StyledFooter = styled.header`
background-color: #dbdada;
color: #857e7a;
font-family: 'Roboto', sans-serif;
font-size: .6rem;
margin-top: auto;
padding: .8vh;
text-align: center;
`
function NavBar () {
return (
<StyledFooter>
Copyright 2021. Lee, <NAME>. All rights reserved.
</StyledFooter>
)
}
export default NavBar
<file_sep>import React, { useState, useEffect } from 'react'
import styled from 'styled-components'
import Fade from 'react-reveal/Fade'
const StyledContainer = styled.div`
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
height: 100vh;
width: 100%;
position: relative;
overflow: hidden;
background-image: url('../../assets/landing_0.jpg');
background-size: cover;
.bird {
background-image: url('../../assets/bird-cells-new.svg');
background-size: auto 100%;
width: 88px;
height: 125px;
will-change: background-position;
animation-name: fly-cycle;
animation-timing-function: steps(10);
animation-iteration-count: infinite;
&--one {
animation-duration: 1s;
animation-delay: -0.5s;
}
&--two {
animation-duration: 0.9s;
animation-delay: -0.75s;
}
&--three {
animation-duration: 1.25s;
animation-delay: -0.25s;
}
&--four {
animation-duration: 1.1s;
animation-delay: -0.5s;
}
}
.bird-container {
position: absolute;
top: 20%;
left: -10%;
transform: scale(1.5) translateX(-10vw);
will-change: transform;
@media (max-width: 600px) {
left: -20%;
}
animation-name: fly-right-one;
animation-timing-function: linear;
animation-iteration-count: infinite;
&--one {
animation-duration: 15s;
animation-delay: 0;
}
&--two {
animation-duration: 16s;
animation-delay: 1s;
}
&--three {
animation-duration: 14.6s;
animation-delay: 9.5s;
}
&--four {
animation-duration: 16s;
animation-delay: 10.25s;
}
}
@keyframes fly-cycle {
100% {
background-position: -900px 0;
}
}
@keyframes fly-right-one {
0% {
transform: scale(0.6) translateX(-10vw);
}
10% {
transform: translateY(2vh) translateX(10vw) scale(0.6);
}
20% {
transform: translateY(0vh) translateX(30vw) scale(0.6);
}
30% {
transform: translateY(4vh) translateX(50vw) scale(0.6);
}
40% {
transform: translateY(2vh) translateX(70vw) scale(0.5);
}
50% {
transform: translateY(0vh) translateX(90vw) scale(0.5);
}
60% {
transform: translateY(0vh) translateX(110vw) scale(0.4);
}
100% {
transform: translateY(0vh) translateX(110vw) scale(0.4);
}
}
@media (max-width: 600px) {
@keyframes fly-right-one {
0% {
transform: scale(0.3) translateX(-10vw);
}
10% {
transform: translateY(2vh) translateX(10vw) scale(0.3);
}
20% {
transform: translateY(0vh) translateX(30vw) scale(0.3);
}
30% {
transform: translateY(4vh) translateX(50vw) scale(0.3);
}
40% {
transform: translateY(2vh) translateX(70vw) scale(0.2);
}
50% {
transform: translateY(0vh) translateX(90vw) scale(0.2);
}
60% {
transform: translateY(0vh) translateX(110vw) scale(0.1);
}
100% {
transform: translateY(0vh) translateX(110vw) scale(0.1);
}
}
}
`
const StyledLogoWrapper = styled.div`
transform: translateY(${(props) => -props.offset/5}%);
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
`
const StyledLogo = styled.div`
margin-top: 3vh;
color: #443c36;
font-family: '<NAME>', cursive;
font-size: 5vh;
@media (max-width: 600px) {
font-size: 4vh;
}
`
const StyledLogoSub = styled.div`
color: #443c36;
font-family: 'WandohopeB';
font-size: 4vh;
@media (max-width: 600px) {
font-size: 3vh;
}
`
function Landing(props) {
const [offset, setOffset] = useState(0);
useEffect(() => {
window.onscroll = () => {
setOffset(window.pageYOffset)
}
}, []);
return (
<StyledContainer offset={offset}>
<div className="bird-container bird-container--one">
<div className="bird bird--one"></div>
</div>
<div className="bird-container bird-container--two">
<div className="bird bird--two"></div>
</div>
<div className="bird-container bird-container--three">
<div className="bird bird--three"></div>
</div>
<div className="bird-container bird-container--four">
<div className="bird bird--four"></div>
</div>
<StyledLogoWrapper offset={offset}>
<Fade In duration={5000} cascade>
<StyledLogo>EunGyeol</StyledLogo>
<StyledLogoSub>은결 이미선 한국화 갤러리</StyledLogoSub>
</Fade>
</StyledLogoWrapper>
</StyledContainer>
)
}
export default Landing
<file_sep># EunGyeol
## Link
http://eungyeol.com
## Description
70th birthday present for my mother's surprise :)
Could be an example of artist(painter) portfolio web page built with react.js.
## Blending two awesome libraries quite well
react-image-gallery(https://github.com/xiaolin/react-image-gallery)
react-photo-gallery(https://github.com/neptunian/react-photo-gallery)
Please check Arts component(Arts.js and Arts.css) about this.<file_sep>import React, { useState } from 'react'
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'
import styled from 'styled-components'
import NavBar from './components/NavBar'
import Footer from './components/Footer'
import About from './pages/About'
import Arts from './pages/Arts'
import Home from './pages/Home'
import Landing from './pages/Landing'
const StyledContainer = styled.div`
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: stretch;
min-height: inherit;
& main {
padding-top: 2vh;
padding-bottom: 2vh;
}
`
function App() {
const [lang, setLang] = useState('Korean')
return (
<BrowserRouter>
<Landing lang={lang} setLang={setLang} />
<StyledContainer>
<NavBar lang={lang} setLang={setLang} />
<main>
<Switch>
<Redirect from='/' to='/home' exact />
<Route path='/home'>
<Home lang={lang} setLang={setLang} />
</Route>
<Route path='/arts'>
<Arts />
</Route>
<Route path='/about'>
<About lang={lang} setLang={setLang} />
</Route>
</Switch>
</main>
<Footer />
</StyledContainer>
</BrowserRouter>
);
}
export default App;
<file_sep>import React from 'react'
import styled from 'styled-components'
import Fade from 'react-reveal/Fade'
const StyledAbout = styled.div`
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
font-family: 'Roboto', sans-serif;
overflow-x: hidden;
`
const StyledPhoto = styled.div`
margin: 0vh 10vh 0vh 10vh;
& img {
width: 300px;
height: 300px;
object-fit: cover;
border-radius: 50%;
@media (max-width: 900px) {
width: 200px;
height: 200px;
}
}
`
const StyledBio = styled.div`
color: #857e7a;
font-family: 'Cafe24Oneprettynight';
font-size: 1.2rem;
text-align: justify;
max-width: 600px;
min-height: 400px;
margin-top: 1vh;
@media (max-width: 600px) {
max-width: 300px;
font-size: 1rem;
}
`
function About(props) {
return (
<StyledAbout>
<StyledPhoto>
<Fade left>
<img src='/assets/portrait.jpg' alt='Portrait of EunGyeol'></img>
</Fade>
</StyledPhoto>
{ props.lang === 'Korean' && <StyledBio>
<Fade right cascade>
<div>
<p>
은결은 한국의 화가이다.
</p>
<p>
1952년 3월 23일 대한민국 경상북도 안동에서 출생하였으며 독실한 기독교 가정에서 자랐다.
어린 시절부터 자연 속 삶에 매료되어 13세 때에는 실제로 이를 직접 실행에 옮기기도 하였다.
</p>
<p>
경북대학교 사범대학을 졸업하여 화학 교사를 역임하였다.
이후 해외 주재원 생활을 하게 된 현재의 배우자와 결혼하여, 그를 따라 프랑스 벨포로 이주 후 그 곳에서 수년간의 해외 생활을 하였다.
그 시절 그녀는 유럽의 많은 나라들을 여행할 기회를 갖게 되었으며, 그 곳의 다양한 회화, 예술, 문화들은 그녀의 작품세계에도 적지 않은 영향을 끼치게 되었다.
</p>
<p>
그녀는 그녀의 전 생애에 걸쳐 그림을 그렸다.
현재 사랑받는 아내이며, 두 아들의 어머니이자 네 아이들의 할머니이기도 하다.
그리고 아직도 하나님의 사랑과 계획하심 안에 시골 어딘가에서 자유로운 삶을 살게되길 꿈꾸고 있다.
</p>
<p>
2021년은 그녀의 탄생 70주년이 되는 해이다.
</p>
</div>
</Fade>
</StyledBio> }
{ props.lang === 'English' && <StyledBio>
<Fade right cascade>
<div>
<p>
EunGyeol is contemporary Korean painting artist.
</p>
<p>
She was born in Andong, a small city placed in southern east area of South Korea, March 23, 1952.
She was raised in devout Christian family.
Since childhood, she was attracted by living in nature, and she actually tried it when she was thirteen.
</p>
<p>
She graduated Kyungpook National University as a chemistry teacher.
And married with present husband and moved to Belfort, France following him due to he was assigned as a expatriate.
At that time she had many opportunities to travel various European countries and there she influenced by paintings, arts and culture there.
</p>
<p>
She is painting through her whole life time.
Now she is beloved wife, mother of two son and grandmother of four kids.
And Still dreaming the life somewhere in countryside with the believe in the love of god and his plan.
</p>
<p>
2021 is the year of her 70th birth anniversary.
</p>
</div>
</Fade>
</StyledBio> }
</StyledAbout>
)
}
export default About
<file_sep>import { useMemo } from 'react'
import { createPortal } from 'react-dom'
function Portal (props) {
const container = useMemo(() => document.getElementById(props.container), [props.container])
return createPortal(props.children, container)
}
export default Portal<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import { createGlobalStyle } from "styled-components";
import App from './App';
import reportWebVitals from './reportWebVitals';
const GlobalStyle = createGlobalStyle`
@font-face {
font-family: 'WandohopeR';
src: local('WandohopeR'), url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/WandohopeR.woff') format('woff');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'WandohopeB';
src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/WandohopeB.woff') format('woff');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Cafe24Oneprettynight';
src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/Cafe24Oneprettynight.woff') format('woff');
font-weight: normal;
font-style: normal;
}
html, body, #root {
margin: 0px;
padding: 0px;
min-height: 100vh;
// /* Hide scrollbar for Chrome, Safari and Opera */
// ::-webkit-scrollbar {
// display: none;
// }
// -ms-overflow-style: none; /* IE and Edge */
// scrollbar-width: none; /* Firefox */
}
`
ReactDOM.render(
<>
<App />
<GlobalStyle />
</>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
| d33bb0107cddd3dcbcce6b303de9f027bb4f6d26 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | su79eu7k/eungyeol.art | 01f188345cecf489dab081f046b35b15bc0dc6ef | fa03205bf5c9ae1bacb5855b502a54050c63222f | |
refs/heads/master | <repo_name>ifricker/ifricker.github.io<file_sep>/game.js
// Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:
// Overall mission: Create a simple Casino War simulator
// Goals: Create simple card game
// Characters: Ask user for input using prompt, alert, and confirm
// Objects: deck of cards, player hand, dealer hand, and bank
// Functions: random card, compare to dealer
// Pseudocode
/*
Instruct the user of the rules of the game
create a deck of cards, 4 suits, 13 ranks
create function that creates a hand
set user bank to 1000
ask user what the want to bet and set to value
reveal user card and ask if they want to play the hand
if not hand is over
if they do show dealer hand
if win add bet to user bank
if loss subract bet to user bank
*/
// Initial Code
// Instructions
alert("\nWelcome to Ian\'s Casino War\n\nYou first place your bet and receive your card.\nYou than can double your bet if you like your card. \nOr you can fold to live another day.\nIf there is a tie, new hand will be played.\nYou will start with 1,000 tokens.\n\nGood luck!\n")
// Create 52 card deck
var deck = [];
// var suit = ["Spades", "Diamnods", "Clubs", "Hearts"]
var suit = ["\u2660","\u2661","\u2662","\u2663"];
// var rank = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"];
var rank = ["2","3","4","5","6","7","8","9","T","J","Q","K","A"]
suit.forEach(function (suit){
rank.forEach(function (rank) {
deck.push(rank + suit);
});
});
// console.log(deck);
// Create a hand(may be more complicated, was originally going to make a 3 card poker game but did not want to write all of the arguments for what hands beat what)
function createHand(){
var hand = [];
for (var i = 0; i <= 0; i += 1) {
hand.push(deck.splice(Math.floor(Math.random() * deck.length), 1));
};
hand = hand.join(" ");
return hand
};
// Create user tokens, create player object and dealer object.
var player = new Object();
player.token = 1000;
var dealer = new Object();
function bank(){
return "Player tokens: " + player.token.toString();
};
// Ask player if they want to play again
function playAgain() {
var again = confirm("Do you want to play again?");
if (again == false) {
alert("Thank you for playing. You finished with " + player.token + " tokens!")
};
if (again == true) {
playWar();
};
};
// Play game
function playWar(){
player.hand = createHand();
dealer.hand = createHand();
var bet = Number(prompt(bank() + "\nPlayer wager: "));
var play = confirm(bank() + "\nWager is " +bet +"\nDo you want to double your bet and play?\nOr do you want to surrender and forfeit your wager?\n" + "Player hand: " + player.hand);
if (play == false) {
player.token = player.token - bet
alert(bank());
playAgain();
};
if (play == true) {
if (player.hand[0] == dealer.hand[0]) {
alert("Player Hand: " + player.hand + "\nDealer Hand: " + dealer.hand + "\nIt's a tie!\n" + bank())
playAgain();
};
if (rank.indexOf(player.hand[0]) > rank.indexOf(dealer.hand[0])) {
player.token = player.token + (bet*2)
alert("Player Hand: " + player.hand + "\nDealer Hand: " + dealer.hand + "\nYou win " + (bet*2).toString() + " tokens!\n" + bank())
playAgain();
};
if (rank.indexOf(player.hand[0]) < rank.indexOf(dealer.hand[0])) {
player.token = player.token - (bet*2)
alert("Player Hand: " + player.hand + "\nDealer Hand: " + dealer.hand + "\nYou lose " + (bet*2).toString() + " tokens!\n" + bank())
playAgain();
};
};
};
// Run game
playWar();
// Reflection
/*
What was the most difficult part of this challenge?
At first I wanted to make a three card poker game or a pia gow until I realised I would have to created a list of every hand to be able to compair to the dealer. I switch to making my own version of caisno war. After running many test I was able to make the game do what I think is a decent version of war. The next issue I had was trying to make the game play on my website. I still have a lot to learn and after trying a few things I had to settle for the game to play with pop ups.
What did you learn about creating objects and functions that interact with one another?
After making my game I realised that I did not make any properties. I can make them for the user to will hold his card and his bank. I will do this if I have enough time. I created functions that call upon each other. Very similar to classes in ruby.
Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
I still wish the built in methods were more automatic for me but that will come with time. Overall the game is pretty simple.
How can you access and manipulate properties of objects?
You can call upon them with a period or bracket.
*/<file_sep>/blog/enumerable-methods.html
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Blog Enumerable Partition">
<title>Blog | Enumerable.partition Equals What?</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
<link rel="stylesheet" type="text/css" href="../stylesheets/blog.css">
<meta name="author" content="<NAME>">
</head>
<body>
<nav class="navbar">
<div id="nav-left">
<a href="http://ifricker.github.io/">Ian <span class="heavy">Fricker</span></a>
</div>
<div id="nav-right">
<a href="http://ifricker.github.io/#aboutme">About Me</a>
<a href="http://ifricker.github.io/#experience">Experience</a>
<a href="http://ifricker.github.io/#education">Education</a>
<a href="http://ifricker.github.io/#projects">Projects</a>
<a href="http://ifricker.github.io/blog">Blog</a>
<a href="http://ifricker.github.io/#contact">Contact</a>
</div>
</nav>
<div class="blog-post">
<div class="blog-entry">
<p id="blog-title">Enumerable.partition Equals What?</p>
<p id="blog-date">January 31, 2016</p>
<p id="blog-author">By <NAME></p>
<p id="blog-subtitle">How to work with partition</p>
<p id="blog-paragraph">So what is an enumerable anyway? An enumerable is a module that iterates over a collection and does whatever method you call upon it. It that sense it is very similar to <code>.each</code>. Some enumerable examples include <code>map</code>, <code>select</code>, <code>inject</code>, <code>any?</code>, <code>sort</code>, and <code>sort_by</code>, to name a few.</p>
<p id="blog-paragraph">I'm going to discuss an enumerable that I just learned that helped me complete my most recent assignment. This assignment had an input of an array that included both strings and integers. The output was to split this array and put all of the numbers into its own array and strings in another after. After doing some research I found <code>partition</code>.</p>
<br>
<p><code>array = ["red", "blue", 4, "banana", 14, "grapes", 6]</code><br><br><code>def split(source)</code><br><code><pre> strings, nums = source.partition {|x| x.is_a? String}</pre></code><code><pre> result = [nums] + [strings]</pre></code><code>end</code><br><br><code>split(array)</code><br><code>=> [[4, 14, 6], ["red", "blue", "banana", "grapes"]]</code></p>
<br>
<p id="blog-paragraph">In the example above you can see that I was given the array that includes some colors, numbers and even fruits. I called the partition method. I set two variables on the left side of the equal sign to strings, and nums. In the <code>.partition</code> method I have it looking at each item and seeing if it is a string with the <code>.is_a? String</code> method. If the argument is true it places the item in the array to the first variable. If the argument is false it places it into the second.</p>
<p id="blog-paragraph">Visit the Ruby Docs to find out all of the enumerables that exist. You will find them to make your coding more readable, shorter, and simpler. </p>
</div>
<div id="previous-button">
<a href="./online-security.html" id="resume-button">Previous</a>
</div>
<div id="next-button">
<a href="./index.html" id="resume-button">Next</a>
</div>
</div>
<footer class="footbar">
<a href="mailto:<EMAIL>"><img src="../imgs/email-white.png" onmouseover="this.src='../imgs/email-color.png'" onmouseout="this.src='../imgs/email-white.png'" alt="email" class="icon-style"></a>
<a href="https://www.linkedin.com/in/ianfricker"><img src="../imgs/linkedin-white.png" onmouseover="this.src='../imgs/linkedin-color.png'" onmouseout="this.src='../imgs/linkedin-white.png'" alt="linkedin" class="icon-style"></a>
<a href="https://github.com/ifricker"><img src="../imgs/github-white.png" onmouseover="this.src='../imgs/github-color.png'" onmouseout="this.src='../imgs/github-white.png'" alt="github" class="icon-style"></a>
<a href="https://www.instagram.com/ifricker/"><img src="../imgs/instagram-white.png" onmouseover="this.src='../imgs/instagram-color.png'" onmouseout="this.src='../imgs/instagram-white.png'" alt="instagram" class="icon-style"></a>
<h4>Copyright © <NAME> 2016</h4>
</footer>
</body>
</html><file_sep>/reflection.md
## 3.5 Your Website, Part 3
#### What did you learn about CSS padding, borders, and margin by doing this challenge?
Padding, borders, and margins are very important to developing the website's space. Margins is the blank space you want around your content. Borders are if you want some sore of style on the outside of the content. Padding is used to move content to where you want it on the page.
#### What did you learn about CSS positioning?
I learned that you need to take it one step at a time. I found myself not breaking it down to each area that I wanted on the page and had to go back to adjust things. You need to start with the overall size and then move to the content on the page.
#### What aspects of your design did you find easiest to implement? What was most difficult?
The easiest for me was probably to setup text fonts, text colors, and designing links. The most difficult was the overall spacing of different sections on the page.
#### What did you learn about adding and formatting elements with CSS in this challenge?
I learned a lot about formatting. At first I didn't really know the difference on when to use a class vs an ID. I was making redundant classes when you could use the same one as before. Overall its just getting comfortable with the spacing on the page.<file_sep>/README.md
# ifricker.github.io
| 01bd05937cf79dd974726f8c36e72e327ff78c6f | [
"JavaScript",
"HTML",
"Markdown"
] | 4 | JavaScript | ifricker/ifricker.github.io | ec9025d77be8548b922e4143dd375234412a02bb | 199c4f672e70dcea86add8977bffec8ab9176902 | |
refs/heads/master | <repo_name>Vamsi404/word-game-hangamn<file_sep>/README.md
# word-game-hangamn
using c++
<file_sep>/word.cpp
#include<iostream>
#include<conio.h >
#include<string.h>
#include<stdlib.h>
using namespace std;
const int maxlength=80;
const int maxtries=5;
const int maxrow=7;
int letterfill(char,char[],char[]);
void initunknown(char [],char[]);
int main()
{
int n;
char unknown[maxlength];
char letter;
int wrong=0;
char word[maxlength];
char words[][maxlength]={"india","pakistan","nepal","malaysia","philippines","australia","iran","ethiopia","oman","indonesia"};
n=rand()%10;
strcpy(word,words[n]);
initunknown(word,unknown);
cout<<"welcome to the guessing world"<<endl;
cout<<"each letter is represented by a star"<<endl;
cout<<"you have to type only one letter in one try"<<endl;
cout<<"you have "<<maxtries<<" tries to try and guess the word"<<endl;
while(wrong<maxtries)
{
cout<<endl<<unknown<<endl;
cout<<"guess a letter"<<endl;
cin>>letter;
if(letterfill(letter,word,unknown)==0)
{
cout<<endl<<" its a wrong guess"<<endl;
wrong++;
}
else
{
cout<<endl<<"amazing u made an correct choice"<<endl;
}
cout<<"you have "<<maxtries-wrong;
cout<<"guesses left"<<endl;
if(strcmp(word,unknown)==0)
{
cout<<word<<endl;
cout<<"yeah you got it"<<endl;
break;
}
}
if(wrong==maxtries)
{
cout<<"sorrt you have exceeded your limit"<<endl;
cout<<"the word was "<<word<<endl;
}
getch();
return 0;
}
int letterfill(char guess,char secretword[],char guessword[])
{
int i;
int matches=0;
for(i=0;secretword[i]!='\0';i++)
{
if(guess==guessword[i])
{
return 0;
}
if(guess==secretword[i])
{
guessword[i]=guess;
matches++;
}
}
return matches;
}
void initunknown(char word[],char unknown[])
{
int i;
int length=strlen(word);
for(i=0;i<length;i++)
{
unknown[i]='*';
}
unknown[i]='\0';
}
| 100381279a7e978083206954de594407c8ee59dc | [
"Markdown",
"C++"
] | 2 | Markdown | Vamsi404/word-game-hangamn | 1c39fa9b411fa7d318bfd481ebfa19a06e471f5b | 089969f13ccb630b340486870269185b4b6631f6 | |
refs/heads/master | <repo_name>tokarskimarcin/laravel-admin-ext-select-inline-create<file_sep>/resources/lang/pl/select.php
<?php
return [
'empty_option' => 'Opcja nie została dodana ze względu na brak etykiety.',
'entity_not_found' => 'Jednostka nie znaleziona z nieznanego powodu. Skontaktuj się z administratorem.'
];
<file_sep>/src/Form/SelectResponse.php
<?php
namespace Encore\SelectInlineCreate\Form;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
class SelectResponse
{
/**
* Get proper response for SelectInlineCreate field model request
* @param Model $entity
* @param \closure $callback
* @return JsonResponse
*/
public static function get(Model $entity, \closure $callback)
{
$response = [
'success' => false
];
if($entity){
$option = $callback($entity);
if(self::isEmpty($option)){
$response['message'] = trans('select-inline-create::select.empty_option');
}else{
$response['success'] = true;
$response['option'] = $option;
}
}else{
$response['message'] = trans('select-inline-create::select.entity_not_found');
}
return JsonResponse::create($response);
}
protected static function isEmpty($option){
return !isset($option['id'], $option['text']) || empty($option['id']) || empty($option['text']);
}
}
<file_sep>/resources/assets/js/select.js
$('.select-inline-button:not([data-has-event])').each((key, element)=>{
var $modalButton = $(element);
$modalButton.attr('data-has-event', true);
}).on('modelCreated', function (e) {
var $modalButton = $(e.target);
var $select = $modalButton.closest('.form-group').find('.select-inline-create');
var searchUrl = $select.data('model-search-url');
var createdModelId = $modalButton.data('model-id');
console.log(createdModelId, searchUrl);
if(createdModelId && searchUrl){
disable($modalButton);
$.ajax({
'url': searchUrl,
'method': 'GET',
'data': {
'id': createdModelId
}
}).error((jqXHR, textStatus, errorThrown)=>{
swal(jqXHR.status.toString(), errorThrown, 'error');})
.success((result)=>{
if(result.success){
var option = result.option;
// Set the value, creating a new option if necessary
if ($select.find("option[value='" + option.id + "']").length) {
$select.val(option.id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(option.text, option.id, true, true);
// Append it to the select
$select.append(newOption).trigger('change');
}
}else{
toastr.error(result.message);
}
})
.always(() => {
enable($modalButton);
})
}else{
console.warn("There is no model id in form response or there is no url of model searching.");
}
});
function disable($button){
switch ($button.prop('tagName')) {
case 'A':
$button.data('data-href', $button.attr('href'));
$button.attr('href', 'javascript:void(0)');
//intentional break statement missing
case 'BUTTON':
$button.attr('disabled', true);
break;
}
}
function enable($button) {
switch ($button.prop('tagName')) {
case 'A':
$button.attr('href', $button.data('data-href'));
$button.removeAttr('data-href');
//intentional break statement missing
case 'BUTTON':
$button.removeAttr('disabled');
break;
}
}
<file_sep>/src/SelectInlineCreateServiceProvider.php
<?php
namespace Encore\SelectInlineCreate;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
class SelectInlineCreateServiceProvider extends ServiceProvider
{
protected $commands = [
Console\PublishCommand::class
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'admin.select-inline-create.bootstrap' => Middleware\Bootstrap::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'admin' => [
'admin.select-inline-create.bootstrap',
],
];
/**
* {@inheritdoc}
*/
public function boot(SelectInlineCreate $extension)
{
if (! SelectInlineCreate::boot()) {
return ;
}
if ($views = $extension->views()) {
$this->loadViewsFrom($views, 'select-inline-create');
}
if ($this->app->runningInConsole() && $assets = $extension->assets()) {
$this->publishes(
[$assets => public_path('vendor/laravel-admin-ext/select-inline-create')],
'select-inline-create-assets'
);
}
if($translations = $extension->translations()){
$this->loadTranslationsFrom($translations, 'select-inline-create');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->commands($this->commands);
$this->registerRouteMiddleware();
}
public function registerRouteMiddleware(){
// register route middleware.
/**
* @var Router $router
*/
$router = app('router');
foreach ($this->routeMiddleware as $key => $middleware) {
$router->aliasMiddleware($key, $middleware);
}
// register middleware group.
foreach ($this->middlewareGroups as $key => $middleware) {
$middlewareGroups = $router->getMiddlewareGroups();
if(key_exists($key, $middlewareGroups)){
$groupMiddleware = $middlewareGroups[$key];
$middleware = array_merge($groupMiddleware, $middleware);
}
$router->middlewareGroup($key, $middleware);
}
}
}
<file_sep>/src/bootstrap.php
<?php
/**
* Extending Admin/Form with additional field
*/
\Encore\Admin\Form::extend('selectInlineCreate', \Encore\SelectInlineCreate\Form\SelectInlineCreate::class);
<file_sep>/src/Form/SelectInlineCreate.php
<?php
namespace Encore\SelectInlineCreate\Form;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field;
use Encore\Admin\Form\Field\Select;
use Encore\ModalForm\Form\ModalButton;
use Encore\SelectInlineCreate\Exceptions\ParameterMissingException;
use Illuminate\Database\Eloquent\Model;
class SelectInlineCreate extends Select
{
protected $view = 'select-inline-create::select';
/**
* @var string
*/
private $createUrl;
/**
* @var string
*/
protected $searchUrl = null;
/**
* @var ModalButton
*/
protected $modalButton;
public function __construct($column = '', $arguments = [])
{
parent::__construct($column, $arguments);
$this->createRoute(url()->current());
$this->modalButton = new ModalButton('+', $this->createUrl);
}
public function createRoute(string $createRoute)
{
$this->createUrl = $createRoute;
return $this;
}
/**
* Load options from ajax results.
*
* @param string $url
* @param string $idField
* @param string $textField
* @return SelectInlineCreate
*/
public function ajax($url, $idField = 'id', $textField = 'text')
{
$this->setSearchUrl($url);
return parent::ajax($url, $idField, $textField);
}
/**
* Sets only ajax url for pulling model information purpose.
* @param string $url
* @return $this
*/
public function setSearchUrl(string $url)
{
$this->searchUrl = $url;
return $this;
}
public function disable(): Field
{
$this->modalButton->disable();
return parent::disable();
}
public function render()
{
if (empty($this->searchUrl)) {
throw new ParameterMissingException(sprintf('`%s` missing from %s field. Use "setSearchUrl" or "ajax" method.',
'searchUrl', self::class));
}
$this->modalButton->setHref($this->createUrl);
$this->modalButton->setClass('btn btn-success select-inline-button');
$this->addVariables([
'modalButton' => $this->modalButton->render()
]);
Admin::script(file_get_contents(public_path('/vendor/laravel-admin-ext/select-inline-create/js/select.js')));
Admin::style(file_get_contents(public_path('/vendor/laravel-admin-ext/select-inline-create/css/select.css')));
$this->attribute('data-model-search-url', $this->searchUrl);
return parent::render();
}
/**
* @param Model $entity
* @param \closure $callback
*/
public static function response(Model $entity, \closure $callback){
return SelectResponse::get($entity, $callback);
}
}
<file_sep>/resources/lang/en/select.php
<?php
return [
'empty_option' => 'Option could not be added because of empty label.',
'entity_not_found' => 'Entity could not be found for not know reason. Contact with administrator.'
];
<file_sep>/src/Middleware/Bootstrap.php
<?php
namespace Encore\SelectInlineCreate\Middleware;
use Closure;
use Illuminate\Http\Request;
class Bootstrap
{
public function handle(Request $request, Closure $next)
{
//bootstraping
require $this->getBootstrapPath();
return $next($request);
}
/**
* @return string
*/
protected function getBootstrapPath(){
return __DIR__.'/../bootstrap.php';
}
}
<file_sep>/src/SelectInlineCreate.php
<?php
namespace Encore\SelectInlineCreate;
use Encore\Admin\Extension;
class SelectInlineCreate extends Extension
{
public $name = 'select-inline-create';
public $views = __DIR__.'/../resources/views';
public $assets = __DIR__.'/../resources/assets';
public $translations = __DIR__ . '/../resources/lang';
/**
* Get the path of translation files.
*
* @return string
*/
public function translations(){
return $this->translations;
}
}
<file_sep>/src/Exceptions/ParameterMissingException.php
<?php
namespace Encore\SelectInlineCreate\Exceptions;
class ParameterMissingException extends \Exception
{
}
<file_sep>/README.md
laravel-admin-ext/SelectInlineCreate
======

Use select field to create entity if not exists. Created entity is selected immediately.
## Requires
- "php": ">=7.2.0",
- "encore/laravel-admin": "~1.6"
- "tokarskimarcin/laravel-admin-ext-modal-form": "^0.1"
## Installation
### Publishing
Execute command below to publish package.
It will copy vendor resources to your application public directory.
~~~
php artisan admin:select-inline-create:publish
~~~
### Update
To update/overwrite assets of package add ```--force``` option to publishing command.
## Documentation
### Usage
SelectInlineCreate field can be used by executing method ```selectInlineCreate``` on Admin/Form.
```php
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
Admin::form(new Administrator(), function (Form $form){
$form->selectInlineCreate('manager', 'Manager');
...;
});
```
While entity is created it looks for the option by searching url with `id` parameter in query string.
Use `SelectResponse` class and static function `get` to return proper response.
```php
use Encore\SelectInlineCreate\Form\SelectResponse;
use Illuminate\Support\Facades\Request;
class SearchController{
public function search(){
$id = Request::offsetGet('id');
// SelectResponse::get($entity, $callback)
// $entity can be null, then SelectResponse will return suitable message
// in $callback return array with 'id' and 'text' keys.
// js will create an option based on this
return SelectResponse::get(
Administrator::query()->find($id),
function(Administrator $administrator){
return ['id' => $administrator->id, 'text' => $administrator->name];
});
}
}
```
### Methods
SelectInlineCreate has same methods as regular Select from Admin
#### 1. `setSearchUrl`
If `ajax(...)` function it's not used so `setSearchUrl` should be used.
```php
//Example
$form->selectInlineCrate(...)
->setSearchUrl(route('manager.search'))
->options(...);
```
If ```ajax(...)``` is used then `setSearchUrl` is executed inside of ajax and searching url is the same as ajax.
```php
$form->selectInlineCrate(...)
->ajax(route('manager.search'));
```
Search url can be overwritten if it's set by ajax function. To do that `setSearchUrl` must be executed after `ajax`.
```php
$form->selectInlineCrate(...)
->ajax(route('manager.search-by-query'))
->setSearchUrl(route('manager.search-by-id'));
```
| 8ed79a7463cc191dcfda6998ad812e5bffabdbb6 | [
"JavaScript",
"Markdown",
"PHP"
] | 11 | PHP | tokarskimarcin/laravel-admin-ext-select-inline-create | cbe6538c70aae686571ae146062e0ed00e3f9dbe | fe17f514b76c67ac80b8462224517fc1d5cdfafe | |
refs/heads/master | <file_sep># ShinyWookie
[](https://travis-ci.org/kvannotten/shiny_wookie)
ShinyWookie is a command line utility that generates documents with random data for you.
## Installation
Install via the command line:
$ gem install shiny_wookie
## Usage
After installation you can run ShinyWookie as follows:
$ shiny_wookie -a #_OF_DOCUMENTS_YOU_WANT_TO_GENERATE
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
<file_sep># coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'shiny_wookie/version'
Gem::Specification.new do |spec|
spec.name = "shiny_wookie"
spec.version = ShinyWookie::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.description = %q{A gem that generates random documents}
spec.summary = %q{This gem creates a specified amount documents, containing randomly generated text}
spec.homepage = "https://github.com/kvannotten/shiny_wookie"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.required_ruby_version = '>= 1.9'
# development dependencies
{"bundler" => "~> 1.3", "rake" => "> 0", "rspec" => "> 0", "simplecov" => "> 0"}.each do |gem_name, gem_version|
spec.add_development_dependency gem_name, gem_version
end
# runtime dependencies
["gabbler"].each do |gem_name|
spec.add_dependency gem_name
end
end
<file_sep>require 'simplecov'
SimpleCov.start
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'shiny_wookie'
require 'gabbler'
<file_sep>require 'spec_helper'
describe ShinyWookie do
it 'has a version number' do
ShinyWookie::VERSION.should_not be_nil
end
context "documents" do
it 'returns an array' do
documents = ShinyWookie.generate_documents
documents.should be_an_instance_of Array
end
it 'contains documents' do
documents = ShinyWookie.generate_documents
documents.first.should be_an_instance_of ShinyWookie::Document
end
end
it "has a gabbler" do
gabbler = ShinyWookie.gabbler
gabbler.should be_an_instance_of Gabbler
end
it "has one gabbler" do
gabbler = ShinyWookie.gabbler
gabbler2 = ShinyWookie.gabbler
gabbler.object_id.should eql gabbler2.object_id
end
end
<file_sep>require 'gabbler'
module ShinyWookie
class Document
attr_accessor :content
def initialize
@content = generate_content
end
def write_to_file *args
options = args.last.is_a?(Hash) ? args.last : {}
prefix = (options.member?(:prefix) ? options[:prefix] : "")
name = (options.member?(:name) ? options[:name] : nil)
suffix = (options.member?(:suffix) ? options[:suffix] : "")
extension = (options.member?(:extension) ? options[:extension] : "txt")
raise ArgumentError if name.nil?
File.open("#{prefix}#{name}#{suffix}.#{extension}", "w") { |f| f.write @content }
end
private
def generate_content
sentences = rand(10..100)
@content = ShinyWookie.gabbler.sentence
sentences.times { @content << ShinyWookie.gabbler.sentence << " " }
@content
end
end
end<file_sep>require 'spec_helper'
require 'shiny_wookie/document'
describe ShinyWookie::Document do
before :each do
@document = ShinyWookie::Document.new
end
subject { @document }
context :content do
it { should respond_to :content }
its(:content) { should_not be_empty }
it "is unique" do
doc2 = ShinyWookie::Document.new
@document.content.should_not eql doc2.content
end
end
context "write file" do
it "writes content" do
@document.write_to_file :prefix => "cv_", :name => "document", :extension => "txt"
IO.read("cv_document.txt").should eql @document.content
File.delete("cv_document.txt")
end
it "has a file name" do
expect { @document.write_to_file :prefix => "doc_" }.to raise_error ArgumentError
end
end
end<file_sep>#!/usr/bin/env ruby
require 'optparse'
require 'shiny_wookie'
$stdout.sync = true
amount = 1
file = ''
options = OptionParser.new do |o|
o.banner =
"Usage: shiny_wookie [options] \n\n"
o.on("-a", "--amount X", "generate X documents") do |k|
amount = k.to_i
end
o.on("-f", "--file FILE" , "learn this document to parse strings from") do |k|
file = k unless k.nil? or k.eql? ""
end
o.on('-h', "--help", "show this help") { puts o; exit }
end
begin
args = options.parse!
documents = ShinyWookie::generate_documents amount
documents.each_with_index do |document, index|
document.write_to_file :prefix => "cv_", :name => Time.now.strftime("%Y_%m_%d_%s"), :suffix => "_#{index}"
end
rescue OptionParser::MissingArgument
puts "I don't understand what you mean :-("
puts
puts options
end
<file_sep>require "shiny_wookie/version"
require "shiny_wookie/document"
module ShinyWookie
def self.generate_documents amount = 1
documents = []
return [] if amount.to_i < 1
1.upto amount.to_i do
documents << Document.new
end
documents
end
def self.gabbler
if @gabbler.nil?
@gabbler = Gabbler.new
story_file = File.join(File.dirname(File.expand_path(__FILE__)), '../resources/huckleberry.txt')
story = File.read(story_file)
gabbler.learn story
end
@gabbler
end
end
| dbc4b7cefbfccb6f0448407d7a76bc43421affb8 | [
"Markdown",
"Ruby"
] | 8 | Markdown | kvannotten/shiny_wookie | ec2e07aed1ee9ed0bdbc6c7f4354d0724ae227f6 | 2a80c4485b8cbdebe76c8148a2f8a196e8df54a4 | |
refs/heads/master | <file_sep>import isPlainObject from 'lodash/isPlainObject';
import { of as of$ } from 'rxjs/observable/of';
import { merge as merge$ } from 'rxjs/observable/merge';
import { concatMap as concatMap$ } from 'rxjs/operator/concatMap';
import { scan as scan$ } from 'rxjs/operator/scan';
import isObservable from './isObservable';
class Streamer {
constructor(defaults = {}) {
this._observables = [
of$(defaults),
];
}
_push(observable) {
this._observables.push(observable);
}
set(value, ...args) {
// (key, value)
if (typeof value === 'string') {
return this.setKey(value, args[0]);
}
// (plainObject)
if (isPlainObject(value)) {
return this.setPlainObject(value);
}
// (observable$, ...mapperFns)
if (isObservable(value)) {
return this.setObservable(value, ...args);
}
return this;
}
setKey(key, value) {
this._push(of$({
[key]: value
}));
return this;
}
setPlainObject(object) {
this._push(of$(object));
return this;
}
setObservable(object$, ...mappers) {
let mappedObject$ = object$;
mappers.forEach((mapperFn) => {
mappedObject$ = mappedObject$
::concatMap$((object) => {
const result = mapperFn(object);
if (isObservable(result)) {
return result;
}
return of$(result);
});
});
this._push(mappedObject$);
return this;
}
setDispatch(actions, store) {
const object = {};
Object.keys(actions)
.forEach((propKey) => {
const actionFn = actions[propKey];
object[propKey] = (...args) => {
return store.dispatch(actionFn(...args));
};
});
this._push(of$(object));
return this;
}
get$() {
return merge$(...this._observables)
::scan$((props, emitted) => {
return {
...props,
...emitted,
};
});
}
}
export default function streamProps(defaultProps = {}) {
return new Streamer(defaultProps);
}
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names, no-unused-expressions */
/* global describe, it, before, resetDOM */
import { expect } from 'chai';
import React from 'react';
import { shallow } from 'enzyme';
import { createApp } from 'frint';
import { MemoryRouterService } from 'frint-router';
import Route from './Route';
function createContext() {
const App = createApp({
name: 'TestRouterApp',
providers: [
{
name: 'router',
useFactory: function () {
return new MemoryRouterService();
},
cascade: true,
},
],
});
return {
app: new App()
};
}
function getAppInstance(wrapper) {
return wrapper.instance()._handler._appInstance;
}
describe('frint-route-react › Route', function () {
before(function () {
resetDOM();
});
it('renders nothing (null) when no app or component prop is passed', function () {
// exact and path
const wrapperPathExact = shallow(
<Route exact path="/about" />,
{ context: createContext() }
);
expect(wrapperPathExact.type()).to.be.null;
// only path
const wrapperPath = shallow(
<Route path="/about" />,
{ context: createContext() }
);
expect(wrapperPath.type()).to.be.null;
// only computedMatch
const wrapperComputedMatch = shallow(
<Route computedMatch={{ url: '/about' }} />,
{ context: createContext() }
);
expect(wrapperComputedMatch.type()).to.be.null;
});
it('renders component when route is matched not exactly', function () {
const Component = () => <div>Matched</div>;
const context = createContext();
const wrapper = shallow(
<Route component={Component} path="/about" />,
{ context }
);
context.app.get('router').push('/');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about');
expect(wrapper.type()).to.equal(Component);
context.app.get('router').push('/service');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about/contact');
expect(wrapper.type()).to.equal(Component);
});
it('renders stateless component, when route is matched not exactly', function () {
const context = createContext();
const wrapper = shallow(
<Route
path="/about"
render={function ({ match }) {
return (
<div>
<div className="url">{match.url}</div>
</div>
);
}}
/>,
{ context }
);
context.app.get('router').push('/');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about');
expect(wrapper.find('.url').text()).to.equal('/about');
context.app.get('router').push('/service');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about/contact');
expect(wrapper.find('.url').text()).to.equal('/about');
});
it('renders component when exact prop passed and route is matched exactly', function () {
const Component = () => <div>Matched</div>;
const context = createContext();
const wrapper = shallow(
<Route component={Component} exact path="/about" />,
{ context }
);
context.app.get('router').push('/');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about');
expect(wrapper.type()).to.equal(Component);
context.app.get('router').push('/service');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about/contact');
expect(wrapper.type()).to.be.null;
});
it('passes match from router to the component when it matches path', function () {
const Component = () => <div>Matched</div>;
const context = createContext();
const wrapper = shallow(
<Route component={Component} path="/about" />,
{ context }
);
context.app.get('router').push('/');
expect(wrapper.type()).to.be.null;
context.app.get('router').push('/about');
expect(wrapper.type()).to.equal(Component);
expect(wrapper.prop('match')).to.include({ url: '/about', isExact: true });
context.app.get('router').push('/about/contact');
expect(wrapper.type()).to.equal(Component);
expect(wrapper.prop('match')).to.include({ url: '/about', isExact: false });
});
it('renders component only when computedMatch is passed and passes computedMatch as prop.match to child', function () {
const Component = () => <div>Matched</div>;
const context = createContext();
const wrapper = shallow(
<Route component={Component} computedMatch={{ url: '/about' }} />,
{ context }
);
expect(wrapper.type()).to.equal(Component);
expect(wrapper.prop('match')).to.deep.equal({ url: '/about' });
wrapper.setProps({ computedMatch: undefined });
expect(wrapper.type()).to.be.null;
});
it('gives priority to computedMatch over path matching router url', function () {
const Component = () => <div>Matched</div>;
const context = createContext();
const wrapper = shallow(
<Route component={Component} computedMatch={{ url: '/computed' }} path="/about" />,
{ context }
);
context.app.get('router').push('/about');
expect(wrapper.prop('match')).to.include({ url: '/computed' });
wrapper.setProps({ computedMatch: undefined });
expect(wrapper.prop('match')).to.include({ url: '/about' });
wrapper.setProps({ computedMatch: { url: '/whatever' } });
expect(wrapper.prop('match')).to.include({ url: '/whatever' });
});
describe('registers app, renders its component and then destroys it', function () {
let beforeDestroyCallCount = 0;
const AboutApp = createApp({
name: 'AboutApp',
providers: [
{
name: 'component',
useValue: () => <article>About</article>,
},
],
beforeDestroy: () => {
beforeDestroyCallCount += 1;
}
});
const context = createContext();
const wrapper = shallow(
<Route app={AboutApp} path="/about" />,
{ context }
);
it('registers app with parent app from context', function () {
const aboutApp = getAppInstance(wrapper);
expect(aboutApp.getParentApp()).to.equal(context.app);
});
it('doesn\'t get rendered when path doesn\'t match', function () {
expect(wrapper.type()).to.be.null;
});
it('gets rendered when path matches', function () {
context.app.get('router').push('/about');
expect(wrapper.html()).to.equal('<article>About</article>');
expect(wrapper.prop('match')).to.include({ url: '/about' });
});
it('beforeDestroy is called on unmount', function () {
expect(beforeDestroyCallCount).to.equal(0);
wrapper.unmount();
expect(beforeDestroyCallCount).to.equal(1);
});
});
describe('renders components, apps, registers and destroys them during lifecycle when they are changes in props', function () {
const HomeComponent = () => <header>Home</header>;
let beforeDestroyAboutCallCount = 0;
const AboutApp = createApp({
name: 'AboutApp',
providers: [
{
name: 'component',
useValue: () => <article>About</article>,
},
],
beforeDestroy: () => {
beforeDestroyAboutCallCount += 1;
}
});
let beforeDestroyServicesCallCount = 0;
const ServicesApp = createApp({
name: 'ServicesApp',
providers: [
{
name: 'component',
useValue: () => <section>Services</section>,
},
],
beforeDestroy: () => {
beforeDestroyServicesCallCount += 1;
}
});
const context = createContext();
const wrapper = shallow(
<Route component={HomeComponent} path="/about" />,
{ context }
);
it('renders nothing then path doesn\'t match', function () {
expect(wrapper.type()).to.be.null;
});
it('renders HomeComponent when path matches', function () {
context.app.get('router').push('/about');
expect(wrapper.html()).to.equal('<header>Home</header>');
});
let aboutApp;
it('instantiates AboutApp and registers it with parent app from context', function () {
wrapper.setProps({ app: AboutApp, component: undefined });
aboutApp = getAppInstance(wrapper);
expect(aboutApp.getParentApp()).to.equal(context.app);
expect(wrapper.html()).to.equal('<article>About</article>');
});
it('doesn\'t destroy the app and doesn\'t reinitialise it when it\'s the same app', function () {
wrapper.setProps({ app: AboutApp });
expect(beforeDestroyAboutCallCount).to.equal(0);
expect(getAppInstance(wrapper)).to.equal(aboutApp);
});
it('calls beforeDestroy for AboutApp when app is changed', function () {
wrapper.setProps({ app: ServicesApp });
expect(beforeDestroyAboutCallCount).to.equal(1);
});
it('instantiates servicesApp and registers it with parent app from context', function () {
const servicesApp = getAppInstance(wrapper);
expect(servicesApp.getParentApp()).to.equal(context.app);
expect(servicesApp).to.not.equal(aboutApp);
});
it('renders ServicesApp', function () {
expect(wrapper.html()).to.equal('<section>Services</section>');
});
it('destroys ServicesApp when switching to component', function () {
expect(beforeDestroyServicesCallCount).to.equal(0);
wrapper.setProps({ app: undefined, component: HomeComponent });
expect(beforeDestroyServicesCallCount).to.equal(1);
expect(getAppInstance(wrapper)).to.be.null;
});
it('renders HomeComponent', function () {
expect(wrapper.html()).to.equal('<header>Home</header>');
});
it('unmounts nicely', function () {
wrapper.unmount();
});
});
});
<file_sep>---
title: Changelog
importContentFromRoot: CHANGELOG.md
sidebarPartial: docsSidebar
---
<file_sep>---
title: Maintainers guide
importContentFromRoot: MAINTAINERS.md
sidebarPartial: docsSidebar
---
<file_sep>---
title: frint-store
importContentFromPackage: frint-store
sidebarPartial: docsSidebar
---
<file_sep>/* eslint-disable no-console */
import isPlainObject from 'lodash/isPlainObject';
import padStart from 'lodash/padStart';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { map as map$ } from 'rxjs/operator/map';
import { switchMap as switchMap$ } from 'rxjs/operator/switchMap';
import { scan as scan$ } from 'rxjs/operator/scan';
import ActionsObservable from './ActionsObservable';
function Store(options = {}) {
this.options = {
initialState: undefined,
deps: null,
appendAction: false,
reducer: state => state,
epic: null,
enableLogger: true,
console: console,
...options,
};
this.internalState$ = new BehaviorSubject(this.options.initialState)
::scan$((previousState, action) => {
let updatedState;
const d = new Date();
const prettyDate = [
padStart(d.getHours(), 2, 0),
':',
padStart(d.getMinutes(), 2, 0),
':',
padStart(d.getSeconds(), 2, 0),
'.',
padStart(d.getMilliseconds(), 3, 0)
].join('');
try {
updatedState = this.options.reducer(previousState, action);
} catch (error) {
if (action && action.type) {
this.options.console.error(`Error processing @ ${prettyDate} ${action.type}:`);
}
this.options.console.error(error);
return previousState;
}
// logger in non-production mode only
if (process.env.NODE_ENV !== 'production') {
if (this.options.enableLogger === true) {
const groupName = `action @ ${prettyDate} ${action.type}`;
if (typeof this.options.console.group === 'function') {
this.options.console.group(groupName);
}
this.options.console.log('%cprevious state', 'color: #9e9e9e; font-weight: bold;', previousState);
this.options.console.log('%caction', 'color: #33c3f0; font-weight: bold;', action);
this.options.console.log('%ccurrent state', 'color: #4cAf50; font-weight: bold;', updatedState);
if (typeof this.options.console.groupEnd === 'function') {
this.options.console.groupEnd();
}
}
}
return updatedState;
});
this.exposedState$ = new BehaviorSubject();
this.cachedState = Object.assign({}, this.options.initialState);
this.subscription = this.internalState$
.subscribe((state) => {
this.cachedState = state;
this.exposedState$.next(state);
});
this.getState = this.getState.bind(this);
this.dispatch = this.dispatch.bind(this);
// for epic
this._input$ = null;
this._action$ = null;
this._epic$ = null;
this._epicSubscription = null;
if (this.options.epic) {
this._input$ = new Subject();
this._action$ = new ActionsObservable(this._input$);
this._epic$ = new Subject();
this._epicSubscription = this._epic$
::map$(epic => epic(this._action$, this, this.options.deps))
::switchMap$(output$ => output$)
.subscribe(this.dispatch);
this._epic$.next(this.options.epic);
}
this.dispatch({ type: '__FRINT_INIT__' });
}
Store.prototype.getState$ = function getState$() {
return this.exposedState$;
};
Store.prototype.getState = function getState() {
return this.cachedState;
};
Store.prototype.dispatch = function dispatch(action) {
if (typeof action === 'function') {
return action(
this.dispatch,
this.getState,
this.options.deps
);
}
const payload = (
this.options.appendAction &&
isPlainObject(this.options.appendAction)
)
? { ...this.options.appendAction, ...action }
: action;
const result = this.internalState$.next(payload);
if (this.options.epic) {
this._input$.next(payload);
}
return result;
};
Store.prototype.destroy = function destroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
if (this._epicSubscription) {
this._epicSubscription.unsubscribe();
}
};
export default Store;
<file_sep>---
title: REPL
layout: repl
---
Content here
<file_sep>import { jsdom } from 'jsdom';
export function resetDOM() {
global.document = jsdom('<html><body><div id="root"></div></body></html>');
global.window = global.document.defaultView;
global.location = global.window.location;
global.navigator = { userAgent: 'node.js' };
/*
Temporary fix for chai's expect(plainObject1).to.include(plainObject2) to work.
Until these are solved:
- https://github.com/chaijs/type-detect/pull/91
- https://github.com/chaijs/type-detect/issues/98
*/
global.HTMLElement = global.window.HTMLElement;
}
export function takeOverConsole(console) {
let hijackedFns = {};
function intercept(method, fn) {
const original = console[method];
console[method] = function () { // eslint-disable-line
fn((...args) => {
const [f] = args;
if (typeof f !== 'undefined') {
original.apply(console, args);
}
}, arguments); // eslint-disable-line
};
return original;
}
['log', 'warn', 'error'].forEach((method) => {
hijackedFns[method] = intercept(method, (through, [firstArg, ...rest]) => {
if (typeof firstArg === 'string' && firstArg.startsWith('[DEPRECATED]')) {
return;
}
through(firstArg, ...rest);
});
});
return function reset() {
Object.keys(hijackedFns).forEach((method) => {
console[method] = hijackedFns[method];
});
};
}
<file_sep>import { composeHandlers } from 'frint-component-utils';
const RouteHandler = {
_routerSubscription: null,
_appInstance: null,
getInitialData() {
return {
component: null,
matched: null,
};
},
beforeMount() {
const props = this.getProps();
this._calculateMatchedState(props);
this._calculateComponentState(props);
},
propsChange(nextProps, pathChanged, exactChanged, appChanged) {
this._calculateMatchedState(nextProps, pathChanged, exactChanged);
this._calculateComponentState(nextProps, appChanged);
},
beforeDestroy() {
this._unsubscribeFromRouter();
this._destroyRouteApp();
},
_getRouter() {
return this.app.get('router');
},
_calculateMatchedState(nextProps, pathChanged = false, exactChanged = false) {
if (nextProps.computedMatch) {
// in case it was subscribed before
this._unsubscribeFromRouter();
} else if (nextProps.path) {
if (!this._routerSubscription || pathChanged || exactChanged) {
this._unsubscribeFromRouter();
this._routerSubscription = this._getRouter()
.getMatch$(nextProps.path, {
exact: nextProps.exact,
})
.subscribe((matched) => {
this.setData('matched', matched);
});
}
}
},
_calculateComponentState(nextProps, appChanged = false) {
if (nextProps.component) {
// component
this._destroyRouteApp();
this.setData('component', nextProps.component);
} else if (nextProps.app && (this._appInstance === null || appChanged)) {
// app
this._destroyRouteApp();
const RouteApp = nextProps.app;
this._appInstance = new RouteApp({
parentApp: this.app,
});
this.setData('component', this.getMountableComponent(this._appInstance));
}
},
_unsubscribeFromRouter() {
if (this._routerSubscription) {
this._routerSubscription.unsubscribe();
this._routerSubscription = null;
}
},
_destroyRouteApp() {
if (this._appInstance) {
this._appInstance.beforeDestroy();
this._appInstance = null;
}
}
};
export default function createRouteHandler(ComponentHandler, app, component) {
if (typeof ComponentHandler.getMountableComponent !== 'function') {
throw new Error('ComponentHandler must provide getMountableComponent() method');
}
return composeHandlers(
RouteHandler,
ComponentHandler,
{
app,
component
},
);
}
<file_sep>---
title: frint-test-utils
importContentFromPackage: frint-test-utils
sidebarPartial: docsSidebar
---
<file_sep>---
title: frint-compat
importContentFromPackage: frint-compat
sidebarPartial: docsSidebar
---
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names, no-unused-expressions */
/* global describe, it */
import { expect } from 'chai';
import { MemoryRouterService } from 'frint-router';
import createRouteHandler from './createRouteHandler';
import { ComponentHandler, createTestAppInstance, createTestApp, createComponent } from './testHelpers';
describe('frint-router-component-handlers › createRouteHandler', function () {
it('creates a handler with getInitialData, beforeMount, propsChange, beforeDestroy methods', function () {
const handler = createRouteHandler(
ComponentHandler,
createTestAppInstance(new MemoryRouterService()),
createComponent()
);
expect(handler).to.include.all.keys('getInitialData', 'beforeMount', 'propsChange', 'beforeDestroy');
});
it('throws exception when ComponentHandler doesn\'t have getMountableComponent() method', function () {
const invalidCreation = () => {
createRouteHandler(
{},
createTestAppInstance(new MemoryRouterService()),
createComponent()
);
};
expect(invalidCreation).to.throw(Error, 'ComponentHandler must provide getMountableComponent() method');
});
describe('RouteHandler functions properly throughout lifecycle', function () {
const router = new MemoryRouterService();
const component = createComponent();
const componentToRender = createComponent();
component.props = {
path: '/products',
exact: true,
component: componentToRender
};
const handler = createRouteHandler(
ComponentHandler,
createTestAppInstance(router),
component
);
it('initially component and matched data are set to null', function () {
component.data = handler.getInitialData();
expect(component.data.component).to.be.null;
expect(component.data.matched).to.be.null;
});
it('when beforeMount() is called it subscribes to router and changes matched and component accordingly', function () {
handler.beforeMount();
expect(component.data.matched).to.be.null;
expect(component.data.component).to.equal(componentToRender);
router.push('/products');
expect(component.data.matched).to.be.an('object');
});
it('when component and app props changed and propsChange() is called, component data is set to app\'s component', function () {
const appComponent = createComponent();
component.props.component = undefined;
component.props.app = createTestApp(undefined, appComponent);
handler.propsChange(component.props, false, false, true);
expect(component.data.component).to.equal(appComponent);
});
it('when path prop change and propsChange() is called, matched data is changed', function () {
expect(component.data.matched).to.be.an('object');
component.props.path = '/contact';
handler.propsChange(component.props, true, false, false);
expect(component.data.matched).to.be.null;
});
it('when beforeDestroy() is called, it unsubscribes from router and matched no longer changes', function () {
expect(component.data.matched).to.be.null;
handler.beforeDestroy();
router.push('/contact');
expect(component.data.matched).to.be.null;
});
});
describe('RouteHandler functions properly with computedMatch throughout lifecycle', function () {
const router = new MemoryRouterService();
const component = createComponent();
const componentToRender = createComponent();
const computedMatch = {};
component.props = {
path: '/products',
exact: true,
computedMatch,
component: componentToRender
};
const handler = createRouteHandler(
ComponentHandler,
createTestAppInstance(router),
component
);
router.push('/');
it('initially matched data is set to null', function () {
component.data = handler.getInitialData();
expect(component.data.matched).to.be.null;
});
it('when beforeMount() is called it doesn\'t subscribe to router and therefore matched data is not affected', function () {
expect(component.data.matched).to.be.null;
handler.beforeMount();
router.push('/products');
expect(component.data.matched).to.be.null;
});
it('when computedMatch prop is removed and propChanged() is called it subscribes to router and therefore matched data is affected', function () {
component.props.computedMatch = null;
handler.propsChange(component.props, false, false, false);
expect(component.data.matched).to.be.an('object');
});
});
});
<file_sep>---
title: frint-config
importContentFromPackage: frint-config
sidebarPartial: docsSidebar
---
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
const expect = require('chai').expect;
const App = require('frint').App;
const createRootApp = require('../root/index.mock');
const CommandApp = require('./help');
describe('frint-cli › commands › help', function () {
it('is a Frint App', function () {
const RootApp = createRootApp();
const rootApp = new RootApp();
rootApp.registerApp(CommandApp);
const commandApp = rootApp.getAppInstance('help');
expect(commandApp).to.be.an.instanceOf(App);
});
it('prints error when run without any command name', function () {
const RootApp = createRootApp();
const rootApp = new RootApp();
rootApp.registerApp(CommandApp);
const commandApp = rootApp.getAppInstance('help');
const fakeConsole = rootApp.get('console');
commandApp.get('execute')();
expect(fakeConsole.errors.length).to.equal(1);
expect(fakeConsole.errors[0]).to.contain('Must provide a command name');
});
it('prints help text when run with a command name', function () {
const RootApp = createRootApp({
providers: [
{
name: 'command',
useValue: 'help',
cascade: true,
},
{
name: 'params',
useValue: {
_: ['help'],
},
cascade: true,
},
],
});
const rootApp = new RootApp();
rootApp.registerApp(CommandApp);
const commandApp = rootApp.getAppInstance('help');
const fakeConsole = rootApp.get('console');
commandApp.get('execute')();
expect(fakeConsole.logs.length).to.equal(1);
});
});
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
import { expect } from 'chai';
import { of as of$ } from 'rxjs/observable/of';
import { last as last$ } from 'rxjs/operator/last';
import streamProps from './streamProps';
describe('frint-react › streamProps', function () {
it('is a function', function () {
expect(streamProps).to.be.a('function');
});
it('streams with default object', function (done) {
const streamer = streamProps({
key: 'value',
});
streamer.get$()
.subscribe(function (props) {
expect(props).to.deep.equal({
key: 'value',
});
done();
});
});
it('streams plain object, by merging with default', function (done) {
const streamer = streamProps({
key: 'value',
key2: 'value2',
});
streamer.set({
key2: 'value2 overridden',
key3: 'value3'
});
streamer.get$()
::last$()
.subscribe(function (props) {
expect(props).to.deep.equal({
key: 'value',
key2: 'value2 overridden',
key3: 'value3',
});
done();
});
});
it('streams key/value pairs, by merging with default', function (done) {
const streamer = streamProps({
key: 'value',
});
streamer.set('key2', 'value2 overridden');
streamer.set('key3', 'value3');
streamer.get$()
::last$()
.subscribe(function (props) {
expect(props).to.deep.equal({
key: 'value',
key2: 'value2 overridden',
key3: 'value3',
});
done();
});
});
it('streams multiple observables with mappings, by merging with default', function (done) {
const streamer = streamProps({
key: 'value',
});
const names$ = of$(
'Fahad',
'Ricardo',
'Mark',
'Jean',
'Alex' // last one wins
);
const numbers$ = of$(
1,
2,
3 // last one wins
);
streamer.set(
names$,
name => ({ name }) // final plain object
);
streamer.set(
numbers$,
number => number * 2, // direct mapped values
number => of$(number), // even mapped observables
number => ({ number }) // final plain object
);
streamer.get$()
::last$()
.subscribe(function (props) {
expect(props).to.deep.equal({
key: 'value',
name: 'Alex',
number: 6, // 3 * 2
});
done();
});
});
it('steams dispatchable actions against store', function (done) {
const streamer = streamProps();
let dispatchedPayload;
const fakeStore = {
dispatch(payload) {
dispatchedPayload = payload;
}
};
function myActionCreator(value) {
return {
type: 'MY_ACTION_TYPE',
value,
};
}
streamer.setDispatch(
{ myAction: myActionCreator },
fakeStore
);
streamer.get$()
::last$()
.subscribe(function (props) {
props.myAction('someValue');
expect(dispatchedPayload).to.deep.equal({
type: 'MY_ACTION_TYPE',
value: 'someValue',
});
done();
});
});
it('has no impact if unexpected values are set', function (done) {
const streamer = streamProps({
key: 'value',
});
streamer.set(() => 'blah');
streamer.get$()
.subscribe(function (props) {
expect(props).to.deep.equal({
key: 'value',
});
done();
});
});
});
<file_sep>const createApp = require('frint').createApp;
const providers = require('./providers.mock');
module.exports = function createMockedRootApp() {
const options = arguments[0] || {}; // eslint-disable-line
const overrideProviders = options.providers || [];
return createApp({
name: 'FrintCLI Mocked',
providers: overrideProviders.reduce((acc, provider) => {
const index = providers.findIndex(item => item.name === provider.name);
if (index > -1) {
acc[index] = provider;
}
return acc;
}, providers)
});
};
<file_sep>---
title: FrintJS - The Modular JavaScript Framework
layout: home
---
Content here
<file_sep>/* eslint-disable import/no-extraneous-dependencies */
const MemoryFs = require('memory-fs');
const fs = new MemoryFs();
module.exports = [
{
name: 'fs',
useValue: fs,
cascade: true,
},
{
name: 'pwd',
useValue: process.env.PWD,
cascade: true,
},
{
name: 'command',
useValue: null,
cascade: true,
},
{
name: 'params',
useValue: {
_: [],
},
cascade: true,
},
{
name: 'config',
useValue: {
plugins: [],
},
cascade: true,
},
{
name: 'console',
useFactory: function useFactory() {
const fakeConsole = {
logs: [],
errors: [],
log: function log(message) {
this.logs.push(message);
},
error: function error(message) {
this.errors.push(message);
},
};
return fakeConsole;
},
cascade: true,
},
];
<file_sep>/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import ReactDOM from 'react-dom';
import FrintReact from './';
export default function render(app, node) {
const MountableComponent = FrintReact.getMountableComponent(app);
return ReactDOM.render(<MountableComponent />, node);
}
<file_sep>const createApp = require('frint').createApp;
const providers = require('./providers');
const App = createApp({
name: 'FrintCLI',
providers: providers,
});
module.exports = App;
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
import { expect } from 'chai';
import Types from './Types';
import createModel from './createModel';
import createCollection from './createCollection';
describe('frint-data › Types', function () {
describe('Types :: any', function () {
it('accepts any values', function () {
const type = Types.any;
expect(type(1)).to.equal(1);
expect(type('hello')).to.equal('hello');
expect(type([])).to.deep.equal([]);
expect(type({})).to.deep.equal({});
});
it('checks for required values', function () {
const type = Types.any.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.any.defaults(123);
expect(type()).to.equal(123);
expect(type(234)).to.equal(234);
});
});
describe('Types :: array', function () {
it('accepts undefined unless required', function () {
const type = Types.array;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts array values', function () {
const type = Types.array;
expect(type([])).to.deep.equal([]);
expect(type([1, 2, 3])).to.deep.equal([1, 2, 3]);
});
it('rejects non-array values', function () {
const type = Types.array;
expect(() => type(0)).to.throw(/value is not an array/);
expect(() => type(null)).to.throw(/value is not an array/);
expect(() => type(true)).to.throw(/value is not an array/);
expect(() => type({})).to.throw(/value is not an array/);
expect(() => type(() => {})).to.throw(/value is not an array/);
});
it('checks for required values', function () {
const type = Types.array.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.array.defaults(['hi', 'there']);
expect(type()).to.deep.equal(['hi', 'there']);
expect(type([1, 2, 3])).to.deep.equal([1, 2, 3]);
expect(() => type(123)).to.throw(/value is not an array/);
});
});
describe('Types :: bool', function () {
it('accepts undefined unless required', function () {
const type = Types.bool;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts boolean values', function () {
const type = Types.bool;
expect(type(true)).to.equal(true);
expect(type(false)).to.equal(false);
});
it('rejects non-boolean values', function () {
const type = Types.bool;
expect(() => type(0)).to.throw(/value is not a boolean/);
expect(() => type(null)).to.throw(/value is not a boolean/);
expect(() => type('hello world')).to.throw(/value is not a boolean/);
expect(() => type(() => {})).to.throw(/value is not a boolean/);
});
it('checks for required values', function () {
const type = Types.bool.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.bool.defaults(true);
expect(type()).to.equal(true);
expect(() => type(123)).to.throw(/value is not a boolean/);
});
});
describe('Types :: collection', function () {
it('accepts undefined unless required', function () {
const type = Types.collection;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts collection instances', function () {
const type = Types.collection;
const Person = createModel({
schema: {
name: Types.string.isRequired,
},
});
const People = createCollection({
model: Person,
});
const people = new People([{ name: 'Frint' }]);
expect(type(people)).to.equal(people);
});
it('rejects non-collection values', function () {
const type = Types.collection;
expect(() => type('hello')).to.throw(/value is not a Collection/);
expect(() => type(null)).to.throw(/value is not a Collection/);
expect(() => type(true)).to.throw(/value is not a Collection/);
expect(() => type({})).to.throw(/value is not a Collection/);
expect(() => type(() => {})).to.throw(/value is not a Collection/);
});
it('checks for required values', function () {
const type = Types.collection.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const Person = createModel({
schema: {
name: Types.string.isRequired,
},
});
const People = createCollection({
model: Person,
});
const people = new People([{ name: 'Frint' }]);
const type = Types.collection.defaults(people);
expect(type()).to.equal(people);
const otherPeople = new People([{ name: '<NAME>' }]);
expect(type(otherPeople)).to.equal(otherPeople);
expect(() => type('hello world')).to.throw(/value is not a Collection/);
});
it('accepts collection instances of certain Colelction', function () {
const Person = createModel({
schema: {
name: Types.string.isRequired,
},
});
const People = createCollection({
model: Person,
});
const type = Types.collection.of(People);
const people = new People([{ name: 'Frint' }]);
expect(type(people)).to.equal(people);
expect(type([{ name: 'Name here' }])).to.be.instanceof(People);
const Post = createModel({
schema: {
title: Types.string.isRequired,
},
});
const Posts = createCollection({
model: Post,
});
const posts = new Posts([{ title: 'Hello World' }]);
expect(() => type(posts)).to.throw(/value is not instance of expected Collection/);
});
});
describe('Types :: enum', function () {
it('accepts undefined unless required', function () {
const type = Types.enum([1, 2, 3]);
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts enum values', function () {
const type = Types.enum([1, 2, 3]);
expect(type(1)).to.equal(1);
expect(type(2)).to.equal(2);
expect(type(3)).to.equal(3);
});
it('rejects non-enum values', function () {
const type = Types.enum([1, 2, 3]);
expect(() => type(0)).to.throw(/value is none of the provided enums/);
expect(() => type(null)).to.throw(/value is none of the provided enums/);
expect(() => type(true)).to.throw(/value is none of the provided enums/);
expect(() => type(() => {})).to.throw(/value is none of the provided enums/);
expect(() => type('hello')).to.throw(/value is none of the provided enums/);
});
it('checks for required values', function () {
const type = Types.enum([1, 2, 3]).isRequired;
expect(() => type()).to.throw(/value is not defined/);
expect(type(1)).to.equal(1);
});
it('allows empty values when default is set', function () {
const type = Types.enum([1, 2, 3]).defaults(2);
expect(type()).to.equal(2);
expect(type(3)).to.equal(3);
expect(() => type('hello world')).to.throw(/value is none of the provided enums/);
});
it('accepts enum of types', function () {
const type = Types.enum.of([
Types.string,
Types.number
]).isRequired;
expect(type(1)).to.equal(1);
expect(type(2)).to.equal(2);
expect(type('hi')).to.equal('hi');
expect(() => type({})).to.throw('value is none of the provided enum types');
});
});
describe('Types :: func', function () {
it('accepts undefined unless required', function () {
const type = Types.func;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts function values', function () {
const type = Types.func;
const fn = () => {};
expect(type(fn)).to.equal(fn);
});
it('rejects non-function values', function () {
const type = Types.func;
expect(() => type(0)).to.throw(/value is not a function/);
expect(() => type(null)).to.throw(/value is not a function/);
expect(() => type('hello world')).to.throw(/value is not a function/);
expect(() => type({})).to.throw(/value is not a function/);
expect(() => type([])).to.throw(/value is not a function/);
});
it('checks for required values', function () {
const type = Types.func.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const defaultFunc = () => {};
const type = Types.func.defaults(defaultFunc);
expect(type()).to.equal(defaultFunc);
expect(() => type(123)).to.throw(/value is not a function/);
});
});
describe('Types :: model', function () {
it('accepts undefined unless required', function () {
const type = Types.model;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts model instances', function () {
const type = Types.model;
const Person = createModel({
schema: {
name: Types.string.isRequired,
},
});
const person = new Person({ name: 'Frint' });
expect(type(person)).to.equal(person);
});
it('rejects non-model values', function () {
const type = Types.model;
expect(() => type('hello')).to.throw(/value is not a Model/);
expect(() => type(null)).to.throw(/value is not a Model/);
expect(() => type(true)).to.throw(/value is not a Model/);
expect(() => type({})).to.throw(/value is not a Model/);
expect(() => type(() => {})).to.throw(/value is not a Model/);
});
it('checks for required values', function () {
const type = Types.model.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const Person = createModel({
schema: {
name: Types.string.isRequired,
},
});
const person = new Person({ name: 'Frint' });
const type = Types.model.defaults(person);
expect(type()).to.equal(person);
const anotherPerson = new Person({ name: '<NAME>' });
expect(type(anotherPerson)).to.equal(anotherPerson);
expect(() => type('hello world')).to.throw(/value is not a Model/);
});
it('accepts model instances of certain Model', function () {
const Person = createModel({
schema: {
name: Types.string.isRequired,
},
});
const Post = createModel({
schema: {
title: Types.string.isRequired,
},
});
const type = Types.model.of(Person);
const person = new Person({ name: 'Frint' });
expect(type(person)).to.equal(person);
expect(type({ name: 'Name here' })).to.be.instanceof(Person);
const post = new Post({ title: 'Hello World' });
expect(() => type(post)).to.throw(/value is not instance of expected Model/);
});
});
describe('Types :: number', function () {
it('accepts undefined unless required', function () {
const type = Types.number;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts number values', function () {
const type = Types.number;
expect(type(123)).to.equal(123);
expect(type(0)).to.equal(0);
});
it('rejects non-number values', function () {
const type = Types.number;
expect(() => type('hello')).to.throw(/value is not a number/);
expect(() => type(null)).to.throw(/value is not a number/);
expect(() => type(true)).to.throw(/value is not a number/);
expect(() => type(() => {})).to.throw(/value is not a number/);
});
it('checks for required values', function () {
const type = Types.number.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.number.defaults(123);
expect(type()).to.equal(123);
expect(type(345)).to.equal(345);
expect(() => type('hello world')).to.throw(/value is not a number/);
});
});
describe('Types :: object', function () {
it('accepts undefined unless required', function () {
const type = Types.object;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts object values', function () {
const type = Types.object;
expect(type({})).to.deep.equal({});
expect(type({ a: 1, b: 2 })).to.deep.equal({ a: 1, b: 2 });
});
it('rejects non-object values', function () {
const type = Types.object;
expect(() => type(0)).to.throw(/value is not an object/);
expect(() => type(null)).to.throw(/value is not an object/);
expect(() => type(true)).to.throw(/value is not an object/);
expect(() => type([])).to.throw(/value is not an object/);
expect(() => type(() => {})).to.throw(/value is not an object/);
});
it('checks for required values', function () {
const type = Types.object.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.object.defaults({ hi: 'there' });
expect(type()).to.deep.equal({ hi: 'there' });
expect(type({ hello: 'world' })).to.deep.equal({ hello: 'world' });
expect(() => type(123)).to.throw(/value is not an object/);
});
it('checks for nested types', function () {
const type = Types.object.of({
street: Types.string,
city: Types.string.isRequired,
postalCode: Types.number.isRequired,
country: Types.string.defaults('Netherlands')
});
expect(type({
street: 'Amsterdam',
city: 'Amsterdam',
postalCode: 123
})).to.deep.equal({
street: 'Amsterdam',
city: 'Amsterdam',
postalCode: 123,
country: 'Netherlands'
});
expect(() => type({
street: 'Amsterdam',
city: 'Amsterdam',
postalCode: '123'
})).to.throw(/schema failed for key 'postalCode', value is not a number/);
});
it('checks for deep-nested types', function () {
const type = Types.object.of({
name: Types.string.isRequired,
address: Types.object.of({
street: Types.string,
city: Types.string.isRequired,
postalCode: Types.number.isRequired,
country: Types.string.defaults('Netherlands')
}).isRequired
});
expect(type({
name: 'Frint',
address: {
street: 'Amsterdam',
city: 'Amsterdam',
postalCode: 123
}
})).to.deep.equal({
name: 'Frint',
address: {
street: 'Amsterdam',
city: 'Amsterdam',
postalCode: 123,
country: 'Netherlands'
}
});
expect(() => type({
name: 'Frint',
address: {
street: 'Amsterdam',
city: 'Amsterdam',
postalCode: '123'
}
})).to.throw(/schema failed for key 'postalCode', value is not a number/);
});
});
describe('Types :: string', function () {
it('accepts undefined unless required', function () {
const type = Types.string;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts string values', function () {
const type = Types.string;
expect(type('hello')).to.equal('hello');
expect(type('hello world')).to.equal('hello world');
expect(type('')).to.equal('');
});
it('rejects non-string values', function () {
const type = Types.string;
expect(() => type(0)).to.throw(/value is not a string/);
expect(() => type(null)).to.throw(/value is not a string/);
expect(() => type(true)).to.throw(/value is not a string/);
expect(() => type(() => {})).to.throw(/value is not a string/);
});
it('checks for required values', function () {
const type = Types.string.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.string.defaults('hello');
expect(type()).to.equal('hello');
expect(type('something')).to.equal('something');
expect(() => type(123)).to.throw(/value is not a string/);
});
});
describe('Types :: uuid', function () {
it('accepts undefined unless required', function () {
const type = Types.uuid;
expect(type()).to.be.an('undefined');
expect(() => type.isRequired()).to.throw('value is not defined');
});
it('accepts UUIDs values', function () {
const type = Types.uuid;
expect(type('27961a0e-f4e8-4eb3-bf95-c5203e1d87b9')).to.equal('27961a0e-f4e8-4eb3-bf95-c5203e1d87b9');
expect(type('90691cbc-b5ea-5826-ae98-951e30fc3b2d')).to.equal('90691cbc-b5ea-5826-ae98-951e30fc3b2d');
});
it('rejects non-UUID values', function () {
const type = Types.uuid;
expect(() => type('hello')).to.throw(/value is not a valid UUID/);
expect(() => type(null)).to.throw(/value is not a valid UUID/);
expect(() => type(true)).to.throw(/value is not a valid UUID/);
expect(() => type(() => {})).to.throw(/value is not a valid UUID/);
});
it('checks for required values', function () {
const type = Types.uuid.isRequired;
expect(() => type()).to.throw(/value is not defined/);
});
it('allows empty values when default is set', function () {
const type = Types.uuid.defaults('90691cbc-b5ea-5826-ae98-951e30fc3b2d');
expect(type()).to.equal('90691cbc-b5ea-5826-ae98-951e30fc3b2d');
expect(type('27961a0e-f4e8-4eb3-bf95-c5203e1d87b9')).to.equal('27961a0e-f4e8-4eb3-bf95-c5203e1d87b9');
expect(() => type('hello world')).to.throw(/value is not a valid UUID/);
});
});
});
<file_sep>---
title: frint-react-server
importContentFromPackage: frint-react-server
sidebarPartial: docsSidebar
---
<file_sep>import App from './App';
import createApp from './createApp';
const Frint = {
App,
createApp,
};
export default Frint;
<file_sep>---
title: frint
importContentFromPackage: frint
sidebarPartial: docsSidebar
---
<file_sep>---
title: frint-component-handlers
importContentFromPackage: frint-component-handlers
sidebarPartial: docsSidebar
---
<file_sep>---
title: Guides
sidebarPartial: guidesSidebar
---
# Guides
All the guides assume, you have:
* [Node.js](https://nodejs.org/) v6.9+
* [npm](https://www.npmjs.com/) v3+
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
import { expect } from 'chai';
import App from './App';
import createApp from './createApp';
describe('frint › createApp', function () {
it('is a function', function () {
expect(createApp).to.be.a('function');
});
it('returns App class', function () {
const MyApp = createApp({
name: 'MyAppNameFromClass',
});
const app = new MyApp({
name: 'MyAppNameFromInstance',
});
expect(app).to.be.instanceOf(App);
expect(app.getName()).to.equal('MyAppNameFromInstance');
});
});
<file_sep>---
title: frint-react
importContentFromPackage: frint-react
sidebarPartial: docsSidebar
---
<file_sep>---
title: frint-router-component-handlers
importContentFromPackage: frint-router-component-handlers
sidebarPartial: docsSidebar
---
<file_sep>/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import PropTypes from 'prop-types';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import composeHandlers from 'frint-component-utils/lib/composeHandlers';
import ObserveHandler from 'frint-component-handlers/lib/ObserveHandler';
import ReactHandler from '../handlers/ReactHandler';
export default function observe(fn) {
return (Component) => {
class WrappedComponent extends React.Component {
static displayName = (typeof Component.displayName !== 'undefined')
? `observe(${Component.displayName})`
: 'observe';
static contextTypes = {
app: PropTypes.object.isRequired
};
constructor(...args) {
super(...args);
this._handler = composeHandlers(
ReactHandler,
ObserveHandler,
{
component: this,
getProps$: typeof fn === 'function'
? app => fn(app, this._props$)
: fn,
}
);
this.state = this._handler.getInitialData();
this._props$ = new BehaviorSubject(this.props);
}
componentWillMount() {
this._handler.app = this.context.app;
this._handler.beforeMount();
}
componentWillReceiveProps(newProps) {
this._props$.next(newProps);
}
componentWillUnmount() {
this._handler.beforeDestroy();
}
render() {
const { computedProps } = this.state;
return <Component {...computedProps} {...this.props} />;
}
}
return WrappedComponent;
};
}
<file_sep>---
title: frint-data
importContentFromPackage: frint-data
sidebarPartial: docsSidebar
---
<file_sep>---
title: frint-cli
importContentFromPackage: frint-cli
sidebarPartial: docsSidebar
---
<file_sep>---
title: Higher-Order Components
sidebarPartial: guidesSidebar
---
# Higher Order Components (HOCs)
<!-- MarkdownTOC depth=2 autolink=true bracket=round -->
- [What is an HOC?](#what-is-an-hoc)
- [How does it work with Frint?](#how-does-it-work-with-frint)
- [Dependencies](#dependencies)
- [Base component](#base-component)
- [App](#app)
- [Observed component](#observed-component)
- [Render](#render)
<!-- /MarkdownTOC -->
## What is an HOC?
[React](https://facebook.github.io/react/) has a very detailed documentation on this topic [here](https://facebook.github.io/react/docs/higher-order-components.html).
In short:
> A higher-order component is a function that takes a component and returns a new component.
## How does it work with Frint?
In our `frint-react` package, we expose an `observe` function which gives us an HOC.
### Dependencies
Install the dependencies first:
```
$ npm install --save rxjs react react-dom frint frint-react
```
### Base component
Now let's say, we have a basic React component:
```js
// components/Root.js
import React from 'react';
function MyComponent(props) {
return (
<p>Name: {props.name}</p>
);
}
export default MyComponent;
```
The component just renders a name, which is given to it as props.
### App
And the App definition happens to looks like this:
```js
// app/index.js
import { createApp } from 'frint';
import Root from '../components/Root';
export default createApp({
name: 'MyAppNameHere',
providers: [
{
name: 'component',
useValue: Root
}
]
})
```
### Observed component
But we want to inject the App's name to the component, and we could easily do that using `observe`:
```js
// components/Root.js
import { Observable } from 'rxjs';
import { observe } from 'frint-react';
function MyComponent(props) {
return (
<p>Name: {props.name}</p>
);
}
export default observe(function (app) {
// `app` is our App's instance
const props = {
name: app.getName() // `MyAppNameHere`
};
// this function must always return an Observable of props
return Observable.of(props);
})(MyComponent);
```
### Render
Now when your App gets rendered, your Root component would show your App's name:
```js
// index.js
import { render } from 'frint-react';
import App from './app';
const app = new App();
render(app, document.getElementById('root'));
```
<file_sep>---
title: frint-router
importContentFromPackage: frint-router
sidebarPartial: docsSidebar
---
<file_sep>const fs = require('fs');
const path = require('path');
const clone = require('lodash/clone');
const argv = require('yargs').argv;
module.exports = [
{
name: 'fs',
useValue: fs,
cascade: true,
},
{
name: 'pwd',
useValue: process.env.PWD,
cascade: true,
},
{
name: 'command',
useFactory: function useFactory() {
if (argv._[0] !== undefined) {
return argv._[0];
}
return null;
},
cascade: true,
},
{
name: 'params',
useFactory: function useFactory() {
const clonedArgv = clone(argv);
clonedArgv._.shift();
return clonedArgv;
},
cascade: true,
},
{
name: 'config',
useFactory: function useFactory(deps) {
let config = {};
const pwd = deps.pwd;
try {
config = JSON.parse(deps.fs.readFileSync(`${pwd}/.frintrc`, 'utf8'));
} catch (e) {
// do nothing
}
if (typeof config.plugins === 'undefined') {
config.plugins = [];
}
config.plugins = config.plugins.map((plugin) => {
if (plugin.startsWith('.')) {
return path.join(pwd, plugin);
}
return plugin;
});
return config;
},
deps: [
'pwd',
'fs',
],
cascade: true,
},
{
name: 'console',
useValue: console,
cascade: true,
},
];
<file_sep>---
title: frint-router-react
importContentFromPackage: frint-router-react
sidebarPartial: docsSidebar
---
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names, no-new, class-methods-use-this */
/* global describe, it */
import { expect } from 'chai';
import App from './App';
import createApp from './createApp';
describe('frint › App', function () {
it('throws error when creating new instance without name', function () {
expect(() => {
new App();
}).to.throw(/Must provide `name` in options/);
});
it('gets option value', function () {
const app = new App({
name: 'MyApp',
});
expect(app.getName()).to.equal('MyApp');
});
it('gets parent and root app', function () {
const rootApp = new App({
name: 'RootApp',
});
const childApp = new App({
name: 'ChildApp',
parentApp: rootApp,
});
const grandchildApp = new App({
name: 'GrandchildApp',
parentApp: childApp,
});
expect(rootApp.getName()).to.equal('RootApp');
expect(childApp.getName()).to.equal('ChildApp');
expect(rootApp.getParentApps()).to.deep.equal([]);
expect(childApp.getParentApp()).to.deep.equal(rootApp);
expect(childApp.getRootApp()).to.deep.equal(rootApp);
expect(
childApp
.getParentApps()
.map(x => x.options.name)
).to.deep.equal([
'RootApp'
]);
expect(grandchildApp.getParentApp()).to.deep.equal(childApp);
expect(grandchildApp.getRootApp()).to.deep.equal(rootApp);
expect(
grandchildApp
.getParentApps()
.map(x => x.options.name)
).to.deep.equal([
'ChildApp',
'RootApp',
]);
});
it('registers providers with direct values', function () {
const app = new App({
name: 'MyApp',
providers: [
{ name: 'foo', useValue: 'fooValue' },
],
});
expect(app.get('foo')).to.equal('fooValue');
});
it('registers providers with factory values', function () {
const app = new App({
name: 'MyApp',
providers: [
{ name: 'foo', useFactory: () => 'fooValue' },
],
});
expect(app.get('foo')).to.equal('fooValue');
});
it('registers providers with class values', function () {
class Foo {
getValue() {
return 'fooValue';
}
}
const app = new App({
name: 'MyApp',
providers: [
{ name: 'foo', useClass: Foo },
],
});
expect(app.get('foo').getValue()).to.equal('fooValue');
});
it('registers providers with dependencies', function () {
class Baz {
constructor({ foo, bar }) {
this.foo = foo;
this.bar = bar;
}
getValue() {
return `bazValue, ${this.foo}, ${this.bar}`;
}
}
const app = new App({
name: 'MyApp',
providers: [
{
name: 'foo',
useValue: 'fooValue'
},
{
name: 'bar',
useFactory: ({ foo }) => {
return `barValue, ${foo}`;
},
deps: ['foo'],
},
{
name: 'baz',
useClass: Baz,
deps: ['foo', 'bar'],
}
],
});
expect(app.get('foo')).to.equal('fooValue');
expect(app.get('bar')).to.equal('barValue, fooValue');
expect(app.get('baz').getValue()).to.equal('bazValue, fooValue, barValue, fooValue');
});
it('returns services from Root that are cascaded', function () {
class ServiceC {
getValue() {
return 'serviceC';
}
}
const Root = createApp({
name: 'MyApp',
providers: [
{
name: 'serviceA',
useValue: 'serviceA',
scoped: true,
cascade: true,
},
{
name: 'serviceB',
useFactory: () => 'serviceB',
scoped: true,
cascade: true,
},
{
name: 'serviceC',
useClass: ServiceC,
cascade: true,
},
{
name: 'serviceCScoped',
useClass: ServiceC,
cascade: true,
scoped: true,
},
{
name: 'serviceD',
useValue: 'serviceD',
cascade: false,
},
{
name: 'serviceE',
useValue: 'serviceE',
cascade: true,
scoped: false,
}
],
});
const App1 = createApp({ name: 'App1' });
const root = new Root();
root.registerApp(App1);
const app = root.getAppInstance('App1');
expect(app.get('serviceA')).to.equal('serviceA');
expect(app.get('serviceB')).to.equal('serviceB');
expect(app.get('serviceC').getValue()).to.equal('serviceC');
expect(app.get('serviceD')).to.equal(null);
expect(app.get('serviceE')).to.equal('serviceE');
expect(app.get('serviceF')).to.equal(null);
expect(root.get('serviceF')).to.equal(null);
});
it('returns null when service is non-existent in both Child App and Root', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1);
const serviceA = app
.getAppInstance('App1')
.get('serviceA');
expect(serviceA).to.equal(null);
});
it('gets container', function () {
const app = new App({
name: 'MyApp'
});
expect(app.getContainer()).to.deep.equal(app.container);
});
it('gets providers definition list', function () {
const app = new App({
name: 'MyApp',
providers: [
{ name: 'foo', useValue: 'fooValue' },
],
});
expect(app.getProviders()).to.deep.equal([
{ name: 'foo', useValue: 'fooValue' },
]);
});
it('gets individual provider definition', function () {
const app = new App({
name: 'MyApp',
providers: [
{ name: 'foo', useValue: 'fooValue' },
],
});
expect(app.getProvider('foo')).to.deep.equal({ name: 'foo', useValue: 'fooValue' });
});
it('calls initialize during construction, as passed in options', function () {
let called = false;
const app = new App({
name: 'MyApp',
initialize() {
called = true;
}
});
expect(app.getName()).to.equal('MyApp');
expect(called).to.equal(true);
});
it('calls beforeDestroy, as passed in options', function () {
let called = false;
const app = new App({
name: 'MyApp',
beforeDestroy() {
called = true;
}
});
app.beforeDestroy();
expect(app.getName()).to.equal('MyApp');
expect(called).to.equal(true);
});
it('registers apps', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1, {
regions: ['sidebar'],
});
expect(app.hasAppInstance('App1')).to.equal(true);
expect(app.getAppInstance('App1').getOption('name')).to.equal('App1');
});
it('registers apps, by overriding options', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1, {
name: 'AppOne',
regions: ['sidebar'],
});
expect(app.hasAppInstance('AppOne')).to.equal(true);
expect(app.getAppInstance('AppOne').getOption('name')).to.equal('AppOne');
});
it('registers apps', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1, {
regions: ['sidebar'],
});
expect(app.hasAppInstance('App1')).to.equal(true);
expect(app.getAppInstance('App1').getOption('name')).to.equal('App1');
});
it('streams registered apps as a collection', function (done) {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1, {
regions: ['sidebar'],
});
const apps$ = app.getApps$();
apps$.subscribe(function (apps) {
expect(Array.isArray(apps)).to.equal(true);
expect(apps.length).to.equal(1);
expect(apps[0].name).to.equal('App1');
done();
});
});
it('streams registered apps as a collection, with region filtering', function (done) {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1, {
regions: ['sidebar'],
});
const apps$ = app.getApps$('sidebar');
apps$.subscribe(function (apps) {
expect(Array.isArray(apps)).to.equal(true);
expect(apps.length).to.equal(1);
expect(apps[0].name).to.equal('App1');
done();
});
});
it('gets app once available (that will be available in future)', function (done) {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const root = new Root();
root.getAppOnceAvailable$('App1')
.subscribe(function (app) {
expect(app.getName()).to.equal('App1');
done();
});
root.registerApp(App1);
});
it('gets app once available (that is already available)', function (done) {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const root = new Root();
root.registerApp(App1);
root.getAppOnceAvailable$('App1')
.subscribe(function (app) {
expect(app.getName()).to.equal('App1');
done();
});
});
it('gets app scoped by region', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const App2 = createApp({ name: 'App2' });
const app = new Root();
app.registerApp(App1, {
regions: ['sidebar'],
});
app.registerApp(App2, {
regions: ['footer'],
multi: true,
});
expect(app.getAppInstance('App1')).to.be.an('object');
expect(app.getAppInstance('App1', 'sidebar')).to.be.an('object');
expect(app.getAppInstance('App2')).to.equal(null);
expect(app.getAppInstance('App2', 'footer')).to.equal(null);
app.instantiateApp('App2', 'footer', 'footer-123');
expect(app.getAppInstance('App2', 'footer', 'footer-123')).to.be.an('object');
});
it('throws error when registering same App twice', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
app.registerApp(App1);
expect(() => {
app.registerApp(App1);
}).to.throw(/App 'App1' has been already registered before/);
});
it('checks for app instance availability', function () {
const Root = createApp({ name: 'MyApp' });
const App1 = createApp({ name: 'App1' });
const app = new Root();
expect(app.hasAppInstance('blah')).to.equal(false);
app.registerApp(App1);
expect(app.hasAppInstance('App1')).to.equal(true);
});
it('throws error when trying to instantiate non-existent App', function () {
const Root = createApp({ name: 'MyApp' });
const app = new Root();
expect(() => {
app.instantiateApp('blah');
}).to.throw(/No app found with name 'blah'/);
});
});
<file_sep>const mkdirp = require('mkdirp');
const request = require('request');
const tar = require('tar');
const createApp = require('frint').createApp;
const descriptionText = `
Usage:
$ frint init
$ frint init --example exampleName
Example:
$ mkdir my-new-directory
$ cd my-new-directory
$ frint init --example kitchensink
You can find list of all available examples here:
https://github.com/Travix-International/frint/tree/master/examples
`.trim();
module.exports = createApp({
name: 'init',
providers: [
{
name: 'summary',
useValue: 'Scaffolds a new Frint app in current working directory',
},
{
name: 'description',
useValue: descriptionText,
},
{
name: 'execute',
useFactory: function useFactory(deps) {
return function execute() {
const example = deps.params.example || 'counter';
const dir = deps.pwd;
function streamFrintExampleToDir() {
request('https://codeload.github.com/Travix-International/frint/tar.gz/master')
.on('error', deps.console.error)
.pipe(tar.x({
filter: path => path.indexOf(`frint-master/examples/${example}/`) === 0,
strip: 3,
C: dir
}))
.on('error', deps.console.error)
.on('finish', () => deps.console.log('Done!'));
}
deps.console.log('Initializing...');
mkdirp(dir, function mkdirpCallback(error) {
if (error) {
deps.console.error(error);
return;
}
streamFrintExampleToDir();
});
};
},
deps: [
'console',
'params',
'pwd',
],
}
],
});
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
import { expect } from 'chai';
import { filter as filter$ } from 'rxjs/operator/filter';
import { delay as delay$ } from 'rxjs/operator/delay';
import { map as map$ } from 'rxjs/operator/map';
import { take as take$ } from 'rxjs/operator/take';
import { last as last$ } from 'rxjs/operator/last';
import { scan as scan$ } from 'rxjs/operator/scan';
import createStore from './createStore';
import combineReducers from './combineReducers';
import combineEpics from './combineEpics';
describe('frint-store › createStore', function () {
it('returns function', function () {
const Store = createStore();
expect(Store).to.be.a('function');
});
it('returns initial state upon subscription', function () {
const Store = createStore();
const store = new Store({
enableLogger: false,
initialState: {
ok: true,
}
});
const subscription = store.getState$()
.subscribe(function (state) {
expect(state).to.deep.equal({
ok: true,
});
});
subscription.unsubscribe();
});
it('dispatches actions, that update state', function () {
const Store = createStore({
enableLogger: false,
initialState: {
counter: 0,
},
reducer: function (state, action) {
switch (action.type) {
case 'INCREMENT_COUNTER':
return Object.assign({}, {
counter: state.counter + 1
});
case 'DECREMENT_COUNTER':
return Object.assign({}, {
counter: state.counter - 1
});
default:
return state;
}
}
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe(function (state) {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'DECREMENT_COUNTER' });
expect(states.length).to.equal(4); // 1 initial + 3 dispatches
const lastState = states[states.length - 1];
expect(lastState).to.deep.equal({
counter: 1
});
const synchronousState = store.getState();
expect(synchronousState).to.deep.equal({
counter: 1
});
subscription.unsubscribe();
});
it('appends to action payload', function () {
const actions = [];
const Store = createStore({
enableLogger: false,
appendAction: {
appName: 'Blah',
},
initialState: {
counter: 0,
},
reducer: function (state, action) {
actions.push(action);
return state;
}
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe(function (state) {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
expect(actions).to.deep.equal([
{ appName: 'Blah', type: '__FRINT_INIT__' },
{ appName: 'Blah', type: 'INCREMENT_COUNTER' },
]);
subscription.unsubscribe();
});
it('dispatches async actions, with deps argument', function () {
const actions = [];
const Store = createStore({
enableLogger: false,
deps: { foo: 'bar' },
initialState: {
counter: 0,
},
reducer: function (state, action) {
actions.push(action);
switch (action.type) {
case 'INCREMENT_COUNTER':
return Object.assign({}, {
counter: state.counter + 1
});
case 'DECREMENT_COUNTER':
return Object.assign({}, {
counter: state.counter - 1
});
default:
return state;
}
}
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe(function (state) {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch(function (dispatch, getState, deps) {
dispatch({
type: 'INCREMENT_COUNTER',
deps
});
});
store.dispatch({ type: 'DECREMENT_COUNTER' });
expect(actions).to.deep.equal([
{ type: '__FRINT_INIT__' },
{ type: 'INCREMENT_COUNTER' },
{ type: 'INCREMENT_COUNTER', deps: { foo: 'bar' } },
{ type: 'DECREMENT_COUNTER' },
]);
expect(states.length).to.equal(4);
expect(states).to.deep.equal([
{ counter: 0 },
{ counter: 1 },
{ counter: 2 },
{ counter: 1 },
]);
subscription.unsubscribe();
});
it('destroys internal subscription', function () {
const Store = createStore({
enableLogger: false,
epic: function (action$) {
return action$
::filter$(action => action.type === 'PING');
},
initialState: {
counter: 0
}
});
const store = new Store();
let changesCount = 0;
const subscription = store.getState$()
.subscribe(function () {
changesCount += 1;
});
store.dispatch({ type: 'DO_SOMETHING' });
expect(changesCount).to.equal(2); // 1 initial + 1 dispatch
store.destroy();
store.dispatch({ type: 'DO_SOMETHING_IGNORED' });
expect(changesCount).to.equal(2); // will stop at 2
subscription.unsubscribe();
});
it('logs state changes', function () {
const consoleCalls = [];
const fakeConsole = {
group() { },
groupEnd() { },
log(...args) {
consoleCalls.push({ method: 'log', args });
},
};
const Store = createStore({
enableLogger: true,
console: fakeConsole,
initialState: {
counter: 0,
},
reducer: function (state, action) {
switch (action.type) {
case 'INCREMENT_COUNTER':
return Object.assign({}, {
counter: state.counter + 1
});
case 'DECREMENT_COUNTER':
return Object.assign({}, {
counter: state.counter - 1
});
default:
return state;
}
}
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe(function (state) {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'DECREMENT_COUNTER' });
expect(states.length).to.equal(4); // 1 initial + 3 dispatches
expect(states).to.deep.equal([
{ counter: 0 },
{ counter: 1 },
{ counter: 2 },
{ counter: 1 },
]);
expect(consoleCalls.length).to.equal(12); // (1 init + 3 actions) * 3 logs (prev + action + current)
expect(consoleCalls[3].args[2]).to.deep.equal({ counter: 0 }); // prev
expect(consoleCalls[4].args[2]).to.deep.equal({ type: 'INCREMENT_COUNTER' }); // action
expect(consoleCalls[5].args[2]).to.deep.equal({ counter: 1 }); // action
subscription.unsubscribe();
});
it('logs errors from reducers', function () {
const consoleCalls = [];
const fakeConsole = {
group() { },
groupEnd() { },
log(...args) {
consoleCalls.push({ method: 'log', args });
},
error(...args) {
consoleCalls.push({ method: 'error', args });
}
};
const Store = createStore({
enableLogger: true,
console: fakeConsole,
initialState: {
counter: 0,
},
reducer: function (state, action) {
switch (action.type) {
case 'DO_SOMETHING':
throw new Error('Something went wrong...');
default:
return state;
}
}
});
const store = new Store();
const subscription = store.getState$()
.subscribe(() => {});
store.dispatch({ type: 'DO_SOMETHING' });
expect(consoleCalls.length).to.equal(5); // 3 init + 2 errors
expect(consoleCalls[3].method).to.equal('error');
expect(consoleCalls[3].args[0]).to.exist
.and.to.contain('Error processing @')
.and.to.contain('DO_SOMETHING');
expect(consoleCalls[4].method).to.equal('error');
expect(consoleCalls[4].args[0]).to.exist
.and.be.instanceof(Error)
.and.have.property('message', 'Something went wrong...');
subscription.unsubscribe();
});
describe('handles combined reducers', function () {
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'INCREMENT_COUNTER':
return Object.assign({}, {
value: state.value + 1
});
case 'DECREMENT_COUNTER':
return Object.assign({}, {
value: state.value - 1
});
default:
return state;
}
}
function colorReducer(state = { value: 'blue' }, action) {
switch (action.type) {
case 'SET_COLOR':
return Object.assign({}, {
value: action.color
});
default:
return state;
}
}
const rootReducer = combineReducers({
counter: counterReducer,
color: colorReducer,
});
it('with given initial state', function () {
const Store = createStore({
enableLogger: false,
initialState: {
counter: {
value: 100,
},
color: {
value: 'red'
}
},
reducer: rootReducer,
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe((state) => {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'DECREMENT_COUNTER' });
store.dispatch({ type: 'SET_COLOR', color: 'green' });
expect(states).to.deep.equal([
{ counter: { value: 100 }, color: { value: 'red' } }, // initial
{ counter: { value: 101 }, color: { value: 'red' } }, // INCREMENT_COUNTER
{ counter: { value: 102 }, color: { value: 'red' } }, // INCREMENT_COUNTER
{ counter: { value: 101 }, color: { value: 'red' } }, // DECREMENT_COUNTER
{ counter: { value: 101 }, color: { value: 'green' } } // SET_COLOR
]);
subscription.unsubscribe();
});
it('with no given initial state', function () {
const Store = createStore({
enableLogger: false,
reducer: rootReducer,
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe((state) => {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'DECREMENT_COUNTER' });
store.dispatch({ type: 'SET_COLOR', color: 'green' });
expect(states).to.deep.equal([
{ counter: { value: 0 }, color: { value: 'blue' } }, // initial
{ counter: { value: 1 }, color: { value: 'blue' } }, // INCREMENT_COUNTER
{ counter: { value: 2 }, color: { value: 'blue' } }, // INCREMENT_COUNTER
{ counter: { value: 1 }, color: { value: 'blue' } }, // DECREMENT_COUNTER
{ counter: { value: 1 }, color: { value: 'green' } } // SET_COLOR
]);
subscription.unsubscribe();
});
it('with partially given initial state for certain reducers', function () {
const Store = createStore({
enableLogger: false,
initialState: {
counter: {
value: 100,
},
},
reducer: rootReducer,
});
const store = new Store();
const states = [];
const subscription = store.getState$()
.subscribe((state) => {
states.push(state);
});
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'INCREMENT_COUNTER' });
store.dispatch({ type: 'DECREMENT_COUNTER' });
store.dispatch({ type: 'SET_COLOR', color: 'green' });
expect(states).to.deep.equal([
{ counter: { value: 100 }, color: { value: 'blue' } }, // initial
{ counter: { value: 101 }, color: { value: 'blue' } }, // INCREMENT_COUNTER
{ counter: { value: 102 }, color: { value: 'blue' } }, // INCREMENT_COUNTER
{ counter: { value: 101 }, color: { value: 'blue' } }, // DECREMENT_COUNTER
{ counter: { value: 101 }, color: { value: 'green' } } // SET_COLOR
]);
subscription.unsubscribe();
});
});
it('creates Store with epics', function (done) {
// constants
const PING = 'PING';
const PONG = 'PONG';
const INITIAL_STATE = {
isPinging: false,
};
// reducers
function pingReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case PING:
return {
isPinging: true,
};
case PONG:
return {
isPinging: false,
};
default:
return state;
}
}
const rootReducer = combineReducers({
ping: pingReducer,
});
// epics
function pingEpic$(action$) {
return action$
::filter$(action => action.type === PING)
::delay$(10)
::map$(() => ({ type: PONG }));
}
const rootEpic$ = combineEpics(pingEpic$);
// Store
const Store = createStore({
enableLogger: false,
reducer: rootReducer,
epic: rootEpic$,
});
const store = new Store();
expect(store.getState().ping.isPinging).to.equal(false);
store.getState$()
::take$(3)
::scan$(
function (acc, curr) {
acc.push({ isPinging: curr.ping.isPinging });
return acc;
},
[]
)
::last$()
.subscribe(function (pingStates) {
expect(pingStates).to.deep.equal([
{ isPinging: false }, // initial state
{ isPinging: true }, // after PING
{ isPinging: false }, // after PING has dispatched PONG
]);
done();
});
store.dispatch({ type: PING });
});
});
<file_sep>/* eslint-disable global-require, import/no-dynamic-require */
const createApp = require('frint').createApp;
const descriptionText = `
Usage:
$ frint help <commandName>
Example:
$ frint help init
`.trim();
module.exports = createApp({
name: 'help',
providers: [
{
name: 'summary',
useValue: 'Shows help text for commands',
},
{
name: 'description',
useValue: descriptionText,
},
{
name: 'execute',
useFactory: function useFactory(deps) {
return function execute() {
const commandName = deps.params._[0];
if (typeof commandName === 'undefined') {
return deps.console.error('Must provide a command name as argument.');
}
const commandApp = deps.rootApp.getAppInstance(commandName);
if (!commandApp) {
return deps.console.error(`No command found with name: ${commandName}`);
}
const output = [
commandApp.get('summary'),
commandApp.get('description'),
]
.filter(text => text)
.join('\n\n');
return deps.console.log(output);
};
},
deps: [
'console',
'params',
'rootApp',
],
}
],
});
<file_sep>/** Declaration file generated by dts-gen */
import { Container, GeneratedClass } from 'travix-di';
import { BehaviorSubject, Observable } from 'rxjs';
export interface ProviderNames {
component: string;
container: Container;
store: string;
app: string;
parentApp: string;
rootApp: string;
region: string;
}
export interface AppOptions {
name: string;
parentApp: App;
providers: Container[];
providerNames: ProviderNames;
initialize?: () => void;
beforeDestroy?: () => void;
}
export interface RegisterAppOptions {
regions: string[];
weight: number;
multi: boolean;
}
export class RegisteredApp extends App implements RegisterAppOptions {
App: RegisteredApp;
name: string;
regions: any[];
instances: { [name: string] : App };
weight: number;
multi: boolean;
}
type Constructor<T extends App> = new(...args: any[]) => T;
export class App {
constructor(args: AppOptions);
container: Container;
beforeDestroy(): any;
destroyApp(name: string, region?: string, regionKey?: string): boolean;
destroyWidget(name: string, region?: string, regionKey?: string): boolean;
get(providerName: string): any;
getAppInstance(name: string, region?: string, regionKey?: string): any;
getAppOnceAvailable$(name: string, region?: string, regionKey?: string): Observable<App>;
getApps$<T extends RegisteredApp>(regionName: string): Observable<T>;
getContainer(): Container;
getOption(key: string): any;
getParentApp(): App;
getParentApps(): App[];
getProvider(name: string): any;
getProviders(): any[];
getRootApp(): App;
getWidgetInstance(name: string, region?: string, regionKey?: string): App;
getWidgetOnceAvailable$(name: string, region?: string, regionKey?: string): Observable<App>;
getWidgets$<T extends RegisteredApp>(regionName: string): Observable<T>;
hasAppInstance(name: string, region?: string, regionKey?: string): boolean;
hasWidgetInstance(name: string, region?: string, regionKey?: string): boolean;
instantiateApp(name: string, region?: string, regionKey?: string): RegisteredApp;
registerApp<T extends Constructor<App>>(AppClass: T, options?: RegisterAppOptions): void;
registerWidget<T extends Constructor<App>>(AppClass: T, options?: RegisterAppOptions): void;
frintAppName: string;
}
export function createApp<T extends Constructor<App>>(...args: any[]): T;
<file_sep><!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<section class="hero is-primary is-medium">
<!-- Hero header: will stick at the top -->
<div class="hero-head">
<header class="nav">
<div class="container">
<%= renderPartial('navLinks') %>
</div>
<a href="https://github.com/Travix-International/frint" class="github-corner" aria-label="View source on Github">
<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
</svg>
</a>
</header>
</div>
<!-- Hero content: will be in the middle -->
<div class="hero-body">
<div class="container has-text-centered">
<h1 class="title">
Modular <span>JavaScript</span> framework<br />
for building <span>Scalable</span> & <span>Reactive</span> applications.
</h1>
<div>
<a href="/docs" class="button is-primary is-medium">Learn more</a>
<a href="http://github.com/Travix-International/frint" class="button is-transparent is-medium">GitHub</a>
</div>
</div>
</div>
</section>
<section class="section about">
<div class="container">
<div class="columns">
<div class="column">
<img alt="Modular" src="/img/js-logo.png" />
<h3>Modular & Extensible</h3>
<p>
The whole framework is split into multiple independent packages.
You get to compose your Apps with only the packages your need.
</p>
</div>
<div class="column">
<img alt="Component" src="/img/react-logo.svg" />
<h3>Component-Based</h3>
<p>
You can roll your own Component based view libraries with Frint.
We have official support for React.
</p>
</div>
<div class="column">
<img alt="Reactive" src="/img/rxjs-logo.png" />
<h3>Reactive Development</h3>
<p>
We embraced the power of reactive programming everywhere, including app-to-app communication for ease of development.
</p>
</div>
</div>
</div>
</section>
<section class="section apps">
<div class="container">
<h2>Split your application across multiple apps</h2>
<img alt="apps" src="/img/frint-apps.png" />
<p>
Learn how to write <a href="/guides/apps">Root Apps & Child Apps</a>
targeting different <a href="/guides/regions">Regions</a>.
</p>
</div>
</section>
<section class="section regions">
<div class="container">
<h2>Load apps coming in from separate bundles</h2>
<img alt="apps" src="/img/frint-code-splitting.png" />
<p>
Learn more about
<a href="/guides/apps">Apps</a> and
<a href="/guides/regions">Regions</a>, and
<a href="/guides/code-splitting">Code Splitting</a>.
</p>
</div>
</section>
<!--
<section class="section">
<div class="container">
<p>Content here...</p>
<%= contents %>
</div>
</section>
-->
<%= renderPartial('footer') %>
<%= renderPartial('assets') %>
</body>
</html>
<file_sep>---
title: frint-model
importContentFromPackage: frint-model
sidebarPartial: docsSidebar
---
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names, no-unused-expressions */
/* global describe, it */
import { expect } from 'chai';
import React from 'react';
import PropTypes from 'prop-types';
import { shallow, mount } from 'enzyme';
import { createApp } from 'frint';
import { MemoryRouterService } from 'frint-router';
import Route from './Route';
import Switch from './Switch';
function createContext() {
const App = createApp({
name: 'TestRouterApp',
providers: [
{
name: 'router',
useFactory: function () {
return new MemoryRouterService();
},
cascade: true,
},
],
});
return {
app: new App()
};
}
describe('frint-router-react › Switch', function () {
it('switches routes according to router and passes computedMatch', function () {
const HomeComponent = () => <header>HomeComponent</header>;
const AboutComponent = () => <article>AboutComponent</article>;
const NotFound = () => <div>Not found</div>;
const context = createContext();
const router = context.app.get('router');
const wrapper = shallow(
<Switch>
<Route component={HomeComponent} exact path="/"/>
<Route component={AboutComponent} path="/about" />
<Route component={NotFound} />
</Switch>,
{ context }
);
it('renders Route when it\'s path matches exactly', function () {
router.push('/');
expect(wrapper.type()).to.equal(Route);
expect(wrapper.props()).to.deep.equal({
computedMatch: { url: '/', isExact: true, params: {} },
component: HomeComponent,
exact: true,
path: '/'
});
});
it('renders Route when it\'s path matches inexactly, skipping first one which requires exact match', function () {
router.push('/about/our-sport-team');
expect(wrapper.props()).to.deep.equal({
computedMatch: { url: '/about', isExact: false, params: {} },
component: AboutComponent,
path: '/about'
});
});
it('renders default Route when nothing matches and doesn\'t pass computedMatch to it', function () {
router.push('/not-the-page-youre-looking-for');
expect(wrapper.props()).to.deep.equal({
component: NotFound,
computedMatch: { url: '/not-the-page-youre-looking-for', isExact: false, params: {} }
});
});
});
it('renders only first match', function () {
const FirstComponent = () => <h1>FirstComponent</h1>;
const SecondComponent = () => <h2>SecondComponent</h2>;
const context = createContext();
const router = context.app.get('router');
const wrapper = shallow(
<Switch>
<Route component={FirstComponent} path="/about" />
<Route component={SecondComponent} path="/about" />
</Switch>,
{ context }
);
router.push('/about');
expect(wrapper.type()).to.equal(Route);
expect(wrapper.props()).to.deep.equal({
computedMatch: { url: '/about', isExact: true, params: {} },
component: FirstComponent,
path: '/about'
});
});
it('renders only first match, also if it\'s default', function () {
const DefaultComponent = () => <h1>DefaultComponent</h1>;
const SecondComponent = () => <h2>SecondComponent</h2>;
const context = createContext();
const router = context.app.get('router');
const wrapper = shallow(
<Switch>
<Route component={DefaultComponent} />
<Route component={SecondComponent} path="/services" />
</Switch>,
{ context }
);
router.push('/services');
expect(wrapper.type()).to.equal(Route);
expect(wrapper.props()).to.deep.equal({
component: DefaultComponent,
computedMatch: { url: '/services', isExact: false, params: {} }
});
});
it('renders nothing if there\'s no match', function () {
const ServicesComponent = () => <h2>ServicesComponent</h2>;
const context = createContext();
const router = context.app.get('router');
const wrapper = shallow(
<Switch>
<Route component={ServicesComponent} path="/services" />
</Switch>,
{ context }
);
router.push('/about');
expect(wrapper.type()).to.equal(null);
});
it('renders nothing if there\'s no match', function () {
const ServicesComponent = () => <h2>ServicesComponent</h2>;
const context = createContext();
const router = context.app.get('router');
const wrapper = shallow(
<Switch>
<Route component={ServicesComponent} path="/services" />
</Switch>,
{ context }
);
router.push('/about');
expect(wrapper.type()).to.equal(null);
});
it('unsubscribes from router on unmount', function () {
let subscribeCount = 0;
let unsubscribeCount = 0;
const subscription = {
unsubscribe() {
unsubscribeCount += 1;
}
};
const router = {
getHistory$() {
return {
subscribe() {
subscribeCount += 1;
return subscription;
}
};
}
};
const context = {
app: {
// eslint-disable-next-line consistent-return
get(key) {
if (key === 'router') {
return router;
}
}
}
};
const wrapper = shallow(
<Switch />,
{ context }
);
expect(subscribeCount).to.equal(1);
expect(unsubscribeCount).to.equal(0);
wrapper.unmount();
expect(subscribeCount).to.equal(1);
expect(unsubscribeCount).to.equal(1);
});
describe('switches routes correctly when child Routes are changing', function () {
let beforeDestroyCallCount = 0;
const HomeApp = createApp({
name: 'HomeApp',
providers: [
{
name: 'component',
useValue: () => <article>HomeApp</article>,
},
],
beforeDestroy: () => {
beforeDestroyCallCount += 1;
}
});
const WrapperComponent = ({ routeSet }) => {
const changingRoutes = [];
if (routeSet === 1) {
changingRoutes.push(
<Route component={() => <header>HomeComponent</header>} exact key="1h" path="/home" />,
<Route component={() => <article>ServicesComponent</article>} key="1s" path="/services" />,
);
} else if (routeSet === 2) {
changingRoutes.push(
<Route app={HomeApp} exact key="2h" path="/home" />
);
}
return (
<Switch>
{changingRoutes}
<Route component={() => <div>Not found</div>} key="0n" />
</Switch>
);
};
WrapperComponent.propTypes = {
routeSet: PropTypes.number
};
const context = createContext();
const router = context.app.get('router');
const wrapper = mount(
<WrapperComponent routeSet={1} />,
{ context, childContextTypes: { app: PropTypes.object } }
);
it('renders matching Route and component from the first set', function () {
router.push('/services');
expect(wrapper.html()).to.equal('<article>ServicesComponent</article>');
});
it('falls back to default when matching Route disappears', function () {
wrapper.setProps({ routeSet: 2 });
expect(wrapper.html()).to.equal('<div>Not found</div>');
});
it('renders matching HomeApp when URL matches', function () {
router.push("/home");
expect(wrapper.html()).to.equal('<article>HomeApp</article>');
expect(beforeDestroyCallCount).to.equal(0);
});
it('renders another component matching the same route, destorying previous app', function () {
wrapper.setProps({ routeSet: 1 });
expect(beforeDestroyCallCount).to.equal(1);
expect(wrapper.html()).to.equal('<header>HomeComponent</header>');
});
});
it('doesn\'t crash when not React elements are passed as children', function () {
const DefaultComponent = () => <h2>DefaultComponent</h2>;
const context = createContext();
const wrapper = shallow(
<Switch>
{0}
{'string'}
<Route component={DefaultComponent} />
</Switch>,
{ context }
);
expect(wrapper.type()).to.equal(Route);
expect(wrapper.props()).to.deep.equal({
component: DefaultComponent,
computedMatch: { url: '/', isExact: false, params: {} }
});
});
});
<file_sep>---
title: About
sidebarPartial: aboutSidebar
processTemplate: true
---
# About
FrintJS was built at [Travix International](https://travix.com) for helping us with building our front-end web applications in a faster, modular and more scalable way.
## Contributors
<div class="columns is-multiline contributors">
<% data.contributors.forEach(function (contributor) { %>
<div class="column is-one-quarter">
<div class="contributor">
<a target="_blank" href="<%= contributor.html_url %>">
<img alt="<%= contributor.name %>" src="<%= contributor.avatar_url %>" />
<h4 class="no-permalink"><%= contributor.name %></h4>
</a>
</div>
</div>
<% }) %>
</div>
More on [GitHub](https://github.com/Travix-International/frint/graphs/contributors).
<file_sep>---
title: frint-component-utils
importContentFromPackage: frint-component-utils
sidebarPartial: docsSidebar
---
<file_sep>// @TODO: can we do it without jQuery? :D
(function () {
function endUrlWithSlash(url) {
if (url.endsWith('/')) {
return url;
}
return url + '/';
}
const currentPath = endUrlWithSlash(window.location.pathname);
// active top nav links
const $topNavLinks = $('nav .nav-left a');
$topNavLinks.each(function () {
const url = endUrlWithSlash($(this).attr('href'));
if (currentPath.indexOf(url) > -1) {
$topNavLinks.removeClass('is-active');
$(this).addClass('is-active');
}
});
// active sidebar links
const $asideLinks = $('aside.menu.docs > ul > li > a');
$asideLinks.each(function () {
const url = endUrlWithSlash($(this).attr('href'));
if (currentPath.indexOf(url) > -1) {
$asideLinks.removeClass('is-active');
$(this).addClass('is-active');
// mount TOC in sidebar from content area
const $lists = $('.content ul');
if ($lists.length === 0) {
// is not TOC
return;
}
if (!$($lists[0]).find('li:first-child').html().startsWith('<a')) {
// is not TOC
return;
}
const $toc = $($lists[0]);
$toc.hide();
$(this).after('<ul>' + $toc.html() + '</ul>');
}
});
// hashed links
$('a[href^="#"]').click(function () {
const href = $(this).attr('href');
if (history.pushState) {
history.pushState(null, null, href);
}
$('html, body').animate({
scrollTop: $(href).offset().top - 65
}, 300);
return false;
});
// hyperlink headers
$('.content h1, .content h2, .content h3, .content h4').each(function () {
const $h = $(this);
if ($h.hasClass('no-permalink')) {
return;
}
const id = $h.attr('id');
const title = $h.text();
const html = $h.html();
if (html.indexOf('<a') > -1) {
return;
}
const newHtml = $('<a>' + title + '</a>')
.attr('href', '#' + id)
.addClass('permalink')
.click(function (e) {
if (history.pushState) {
history.pushState(null, null, '#' + id);
}
$('html, body').animate({
scrollTop: $h.offset().top - 65
}, 300);
return false;
});
$(this).html(newHtml);
});
})();
<file_sep>import lodashGet from 'lodash/get';
import lodashSet from 'lodash/set';
import cloneDeep from 'lodash/cloneDeep';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { map as map$ } from 'rxjs/operator/map';
function Model(attributes) {
this.attributes = Object.assign({}, attributes);
this.$ = null;
}
function getFromAttributes(attributes, key) {
if (typeof key === 'undefined') {
return attributes;
}
if (typeof key !== 'string') {
return undefined;
}
return lodashGet(attributes, key);
}
Model.prototype.get = function get(key) {
return getFromAttributes(this.attributes, key);
};
Model.prototype.set = function set(key, value) {
lodashSet(this.attributes, key, value);
if (this.$) {
this.$.next(this.attributes);
}
};
Model.prototype.get$ = function get$(key) {
if (!this.$) {
this.$ = new BehaviorSubject(this.attributes);
}
return this.$
::map$((attributes) => {
return getFromAttributes(attributes, key);
});
};
Model.prototype.toJS = function toJS() {
return cloneDeep(this.attributes);
};
export default Model;
<file_sep>/* eslint-disable import/no-extraneous-dependencies, func-names */
/* global describe, it */
import { expect } from 'chai';
import { Subject } from 'rxjs/Subject';
import { filter as filter$ } from 'rxjs/operator/filter';
import { map as map$ } from 'rxjs/operator/map';
import combineEpics from './combineEpics';
import ActionsObservable from './ActionsObservable';
describe('frint-store › combineEpics', function () {
it('triggers epics correct response', function () {
const pingEpic = function (action$) {
return action$
::filter$(action => action.type === 'PING')
::map$(() => ({ type: 'PONG' }));
};
const rootEpic = combineEpics(pingEpic);
const subject$ = new Subject();
const actions$ = new ActionsObservable(subject$);
const result$ = rootEpic(actions$);
const emittedActions = [];
const subscription = result$.subscribe((emittedAction) => {
emittedActions.push(emittedAction);
});
subject$.next({ type: 'PING' });
expect(emittedActions).to.deep.equal([
{ type: 'PONG' }
]);
subscription.unsubscribe();
});
});
<file_sep>module.exports = {
// only show these contributors in about page
contributorsOptedIn: [
'AlexDudar',
'alexmiranda',
'asci',
'fahad19',
'gtzio',
'jackTheRipper',
'markvincze',
'mAiNiNfEcTiOn',
'spzm',
],
};
<file_sep>/* eslint-disable global-require, import/no-dynamic-require */
const path = require('path');
const createApp = require('frint').createApp;
module.exports = createApp({
name: 'version',
providers: [
{
name: 'summary',
useValue: 'Shows current version number of frint-cli',
},
{
name: 'execute',
useFactory: function useFactory(deps) {
return function execute() {
const pkg = JSON.parse(
deps.fs.readFileSync(
path.resolve(`${__dirname}/../package.json`)
)
);
deps.console.log(`v${pkg.version}`);
};
},
deps: [
'console',
'fs',
],
}
],
});
| 546b66c170bfb503fa4e73bb2fc0536545d01f29 | [
"JavaScript",
"TypeScript",
"HTML",
"Markdown"
] | 51 | JavaScript | fahad19/frint | 916f44c2587ccce2fc9529ae83d3066d4fbf7a68 | 2c8e14c39df2148dbc40c16c9a929121c8a14e43 | |
refs/heads/master | <file_sep>// CodinGame - Entrainement 1
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n1;
int n2;
string line;
string w1;
string w2;
cin >> n1 >> n2;
cin.ignore(); // this reads the '\n' just after n2
getline(cin, line);
cin >> w1 >> w2;
// logic comes here...
if (n1 + n2 == (int)line.size()) {
cout << w1 << endl;
} else {
cout << w2 << endl;
}
return 0;
}
<file_sep># codingame
Mes réalisations en C++ sur CodinGame
## Mes participations:
- 29/01/2013
- 26/03/2013
## Description des branchs
- **master** : Branche contenant les projets vides de chaque énoncé
- **stable** : Branche dérivée de *master*, contenant les sources compilant un programme passant 100% des tests
- **testing** : Branche dérivée de *master*, contenant des sources à l'état de travail
## Description d'un répertoire
Chaque exercice est stocké dans son arborescence propre:
- enonce.txt : Contient l'énoncé de l'exercice
- CMakeLists.txt : Permet de générer un nouveau projet avec cmake
- test/ : Répertoire contenant les fichiers de tests
- src/ : Répertoire contenant les fichiers sources
La procédure de test "test.sh" est externe et se trouve à la racine du dépôt.
<file_sep>cmake_minimum_required(VERSION 2.6)
#Configuration du projet
project("20121222-1-Sms_Vokia")
set(EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE})
ENABLE_TESTING()
#Génération de la liste des fichiers sources
file(
GLOB_RECURSE
source_files
src/*
)
#Déclaration de l'exécutable
add_executable(
20121222-1
${source_files}
)
#Déclaration des tests
add_test(
NAME Test_1
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 1
)
add_test(
NAME Test_2
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 2
)
add_test(
NAME Test_3
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 3
)
add_test(
NAME Test_4
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 4
)
add_test(
NAME Test_5
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 5
)
add_test(
NAME Test_6
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 6
)
add_test(
NAME Test_7
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 7
)
add_test(
NAME Test_8
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 8
)
add_test(
NAME Test_9
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121222-1 ${PROJECT_BINARY_DIR}/test/ 9
)
<file_sep>#!/bin/bash
# $1 = binary to test
# $2 = tests dir
# $3 = test number
binary="$1"
test_dir="$2"
test_number="$3"
test_in="${test_dir}/in${test_number}.txt"
test_out="${test_dir}/out${test_number}.txt"
test_result="out_$$.txt"
time_result="time_$$.txt"
time_limit="1.00"
if [ ! -f "${binary}" ]
then
echo "Seems the binary '${binary}' doesn't exist."
exit 1
fi
if [ ! -x "${binary}" ]
then
echo "Seems the binary '${binary}' is not executable."
exit 1
fi
if [ ! -d "${test_dir}" ]
then
echo "Seems the directory '${test_dir}' doesn't exist."
exit 1
fi
if [ -z "${test_number}" ]
then
echo "Seems the test number was not given."
exit 1
fi
if [ ! -f "${test_in}" ]
then
echo "Seems the test '${test_number}' doesn't have an input file."
exit 1
fi
if [ ! -f "${test_out}" ]
then
echo "Seems the '${test_number}' doesn't have an output file."
exit 1
fi
/usr/bin/time -f %e -o "${time_result}" "${binary}" < "${test_in}" | tee "${test_result}"
diff -B --suppress-common-lines "${test_result}" "${test_out}"
ok=$?
if [ "${ok}" = "0" ]
then
echo "${time_limit}" >> "${time_result}"
if [ "`sort "${time_result}" | head -n1`" = "${time_limit}" ]
then
echo "
****************** REUSSITE PARTIELLE DU TEST (DEPASSEMENT DU TEMPS)"
else
echo "
****************** REUSSITE DU TEST"
fi
else
echo "
****************** ECHEC DU TEST"
fi
rm -f "${test_result}" "${time_result}"
exit ${ok}
<file_sep>// CodinGame - Entrainement 2
#include <iostream>
#include <string>
#include <stdlib.h>
#define MAX_TEMPERATURE 5526
#define MIN_TEMPERATURE -273
#define MAX_INPUT 10000
#define MIN_INPUT 0
using namespace std;
int main()
{
int n=0; // The number of temperature
int tmin=MAX_TEMPERATURE; // The temperature closest of zero
int tminplus=MAX_TEMPERATURE; // The temperature closest of zero (absolute value)
int t=0; // The current temperature
int m=0; // The number of input read
cin >> n; // Read n
if ((n < MIN_INPUT) || (n >MAX_INPUT)){
cerr << "ERROR: The number of temperature must be between " << MIN_INPUT << " and " << MAX_INPUT << endl;
return 1;
}
cin.ignore(); // this reads the '\n' just after n2
// Read all the input
for(int i=0; i<n; i++){
cin >> t;
if ((t < MIN_TEMPERATURE) || (t >MAX_TEMPERATURE)){
cerr << "WARNING: The temperature " << t << " is off range ([" << MIN_INPUT << " ; " << MAX_INPUT << "])" << endl;
} else {
if(abs(t)<=tminplus){
if ((t==tminplus) && (tmin<0))
{
tminplus=t;
tmin=t;
} else
{
if (t<tminplus) {
tminplus=abs(t);
tmin=t;
}
}
}
m++;
}
}
if (m == 0) {
// No temperature in input
cout << 0 << endl;
} else {
if (m < n) {
cerr << "WARNING: " << n << " input expected. Received only " << m << endl;
}
cout << tmin << endl;
}
return 0;
}
<file_sep>// Read inputs from stdin. Write outputs to stdout.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cout << "Hello World!" << endl;
}
return 0;
}
<file_sep>cmake_minimum_required(VERSION 2.6)
#Configuration du projet
project("20121025-1-L'art_ASCII")
set(EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE})
ENABLE_TESTING()
#Génération de la liste des fichiers sources
file(
GLOB_RECURSE
source_files
src/*
)
#Déclaration de l'exécutable
add_executable(
20121025-1
${source_files}
)
#Déclaration des tests
add_test(
NAME Test_1
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${TARGET} ${PROJECT_BINARY_DIR}/test/ 1
)
add_test(
NAME Test_2
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121025-1 ${PROJECT_BINARY_DIR}/test/ 2
)
add_test(
NAME Test_3
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121025-1 ${PROJECT_BINARY_DIR}/test/ 3
)
add_test(
NAME Test_4
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121025-1 ${PROJECT_BINARY_DIR}/test/ 4
)
add_test(
NAME Test_5
COMMAND ${PROJECT_BINARY_DIR}/../test.sh ${PROJECT_BINARY_DIR}/${EXECUTABLE_OUTPUT_PATH}/20121025-1 ${PROJECT_BINARY_DIR}/test/ 5
)
| a717e4bd47c5fcf2e96fd8b66817d775dcc8b2d3 | [
"Markdown",
"CMake",
"C++",
"Shell"
] | 7 | C++ | Brinicle001/codingame | ea908e8e09cc9831cdcf7035501cfced745a617a | ab62783d6f904de985d9a7fb4c8e0398cfd77c0c | |
refs/heads/master | <repo_name>MarjorieAndrieux/apimeteo<file_sep>/README.md
https://marjorieandrieux.github.io/apimeteo/
<file_sep>/js/api.js
/*Mise en place de moment.js pour parametrer la date automatique*/
moment.locale("fr");
$("#date").text(moment().format("DD MMMM YYYY"));
$(document).ready(function () {
/*Mise en place de l'api openweathermap
Création de la variable "city" correspondant à l'input "ville" dans le html */
$("#bouton").click(function () {
var city = $('#ville').val();
if (city != "") {
$.ajax({
url: "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric" + "&appid=08d07f48ff486a143c25d7296ed323f0",
type: "GET",
dataType: "jsonp",
/*Utilisation de la "function(data)" afin de stocker les valeurs récupéreés grace à l'API.
Connexion des valeurs récupérées avec la partie "donnees" du html avec la variable "widget".*/
success: function (data) {
console.log(data);
var widget = show(data);
$("#donnees").html(widget);
$("#ville").val('');
/*Mise en place de l'API GoogleMap incluant la variable "city".
Affichage de la map dans la Div "map" du html.*/
$("#map").html("<iframe src='https://www.google.com/maps/embed/v1/place?key=<KEY>&q=" + city + "&zoom=12&maptype=roadmap' width='100%' height='100%' frameborder='0'></iframe>");
}
})
}
})
})
/*Mise en place des correspondances entre les données récupérées dans la fonction "data" et les emplacements du html. */
function show(data) {
console.log("testtemp", data.main.temp);
$("#temperature").text(parseInt(data.main.temp) + "°");
$("#tempmin").text("Température min: " + (parseInt(data.main.temp_min) + "°"));
$("#tempmax").text("Température Max: " + (parseInt(data.main.temp_max) + "°"));
$("#pression").text("Pression atmosphérique: " + data.main.pressure + "hPa");
$("#vent").text("Vitesse du vent: " + data.wind.speed + "km/h");
$("#humidite").text("Taux d'humidité: " + data.main.humidity + "%");
$("#longitude").text("Longitude: " + data.coord.lon);
$("#latitude").text("Latitude: " + data.coord.lat);
}
| f88e50b64682389e35829bb3a08c54bb86fcd6d4 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | MarjorieAndrieux/apimeteo | 9d1acf389db419ef39c03dd9cbaf03a4ffc9b5c8 | 0fdcb3eb509cfaa2c62dd9190598a83fb24c4596 | |
refs/heads/master | <file_sep>import React from 'react';
import { Alert, StyleSheet, Text, View, TouchableOpacity, Image } from 'react-native';
import { Facebook } from 'expo';
const FB_APP_ID = 'fb297781467791687';
//facebook links used:
//https://docs.expo.io/versions/latest/sdk/facebook/
//https://www.youtube.com/watch?v=ThcelIFSMWQ
//https://stackoverflow.com/questions/38261112/facebook-redirect-uri-set-to-ios-url-scheme
export default class FirstPage extends React.Component {
//for facebook login
async logIn() {
try {
const {
type,
token,
expires,
permissions,
declinedPermissions,
} = await Facebook.logInWithReadPermissionsAsync('297781467791687', {
permissions: ['public_profile'],
});
if (type === 'success') {
// Get the user's name using Facebook's Graph API
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
this.props.navigation.navigate('Home');
} else {
// type === 'cancel'
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
render() {
return (
<View style={styles.container}>
<Text style = {styles.text}>My TODO List</Text>
<Image style = {styles.logo} source ={require('../images/logo.png')}/>
<TouchableOpacity style = {styles.button} onPress={()=>{this.logIn()}}>
<Text style = {styles.buttonText}>Login</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
justifyContent: 'space-evenly',
alignItems: 'center',
backgroundColor: 'white',
},
text: {
color: '#000000',
fontSize: 36,
textAlign: 'center',
},
logo:{
width: 200,
height: 200,
resizeMode: 'contain',
justifyContent:'center',
},
button:{
backgroundColor: '#F89E22',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 1,
width: 150,
height: 80,
justifyContent: 'center'
},
buttonText:{
fontSize: 25,
textAlign: 'center',
justifyContent: 'center'
}
});<file_sep>import React from 'react';
import { StyleSheet, Text, View, Button, TouchableOpacity, Image } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
export default class HomeScreen extends React.Component {
//https://medium.freecodecamp.org/how-to-build-a-nested-drawer-menu-with-react-native-a1c2fdcab6c9
static navigationOptions = {
title: 'Home',
headerStyle: {
backgroundColor: '#59ADFF',
},
headerRight: (
<TouchableOpacity onPress={() => alert('Search something!')}>
<Image style = {{margin: 10}} source ={require('../images/search-24px.png')}/>
</TouchableOpacity>
),
headerLeft: (
<TouchableOpacity onPress={() => alert('This is the menu!')}>
<Image style = {{margin: 10}} source ={require('../images/menu-24px.png')}/>
</TouchableOpacity>
),
headerTintColor: '#000',
headerTitleStyle: {
fontWeight: 'bold',
},
};
render() {
return (
<View style={styles.container}>
<Text style = {styles.text}>Hello, !</Text>
<View style={styles.navigationControls}>
<TouchableOpacity style = {[styles.button, {backgroundColor: '#F89E22'}]} onPress={()=>{this.props.navigation.navigate('ViewCalendar');}}>
<Text style = {styles.buttonText}>View Calendar</Text>
</TouchableOpacity>
<TouchableOpacity style = {[styles.button, {backgroundColor: '#22F885'}]} onPress={()=>{this.props.navigation.navigate('AddNewEvent');}}>
<Text style = {styles.buttonText}>Add New Event or Task</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
justifyContent: 'space-evenly',
marginLeft: 40,
backgroundColor: 'white',
},
navigationControls:
{
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
},
text: {
color: '#000000',
fontSize: 26,
//textAlign: 'center',
},
logo:{
width: 200,
height: 200,
resizeMode: 'contain',
justifyContent:'center'
},
button:{
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 1,
},
buttonText:{
color:'#000000',
margin: 10
}
});<file_sep>import * as React from 'react';
import { Text, View, StyleSheet, Image} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation'
import { Constants } from 'expo';
// You can import from local files
import FirstPage from './components/FirstPage';
import HomeScreen from './components/HomeScreen';
import ViewCalendar from './components/ViewCalendar';
import AddNewEvent from './components/AddNewEvent';
const rootStack = createStackNavigator({
FirstPage:FirstPage,
Home:HomeScreen,
ViewCalendar: ViewCalendar,
AddNewEvent: AddNewEvent,
},
{
initialRouteName: 'FirstPage'
}
)
const AppContainer = createAppContainer(rootStack)
export default class App extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<AppContainer />
);
}
};
| cb8c7a1f8c6f2cc9ffc635e0866d91acefdf706e | [
"JavaScript"
] | 3 | JavaScript | 2019cjin/my-todo-list | a8198d9606b9ee31ce50bc4593219f585c3da63b | 0af49703303d2d3b66c5063687746888eb513adf | |
refs/heads/master | <repo_name>viorelaioia-zz/discourse-tests<file_sep>/pages/category.py
from selenium.webdriver.common.by import By
from pages.base import Base
class Category(Base):
_notifications_dropdown_locator = (By.CSS_SELECTOR, '.dropdown-toggle')
_notification_options_locator = (By.CSS_SELECTOR, '.dropdown-menu li span[class="title"]')
_options_locator = (By.CSS_SELECTOR, '.dropdown-menu li a')
@property
def options(self):
options_list = self.selenium.find_elements(*self._notification_options_locator)
return [option.text for option in options_list]
def click_notifications_dropdown(self):
self.selenium.find_element(*self._notifications_dropdown_locator).click()
def select_option(self, option):
notification_option_index = self.options.index(option)
notification_options_list = self.selenium.find_elements(*self._options_locator)
notification_options_list[notification_option_index].click()
<file_sep>/README.md
# discourse-tests
Automated tests for discourse.mozilla-community.org
How to set up and run Discourse tests locally
This repository contains Selenium tests used to test:
* staging: https://discourse.staging.paas.mozilla.community/
* production: https://discourse.mozilla-community.org/
##You will need to install the following:
#### Git
If you have cloned this project already then you can skip this! GitHub has excellent guides for Windows, Mac OS X, and Linux.
#### Python
Before you will be able to run these tests you will need to have Python 2.6.8+ installed.
##Running tests locally
Some of the tests in discourse-tests require accounts for https://discourse.staging.paas.mozilla.community. You'll need to create two sets of credentials with varying privilege levels.
1. Create two username and password combinations on https://mozillians.org
2. Make sure one of the accounts is vouched 3 times
3. Create the same Two accounts used in step #1 in https://discourse.staging.paas.mozilla.community
4. Copy discourse-tests/variables.json to a location outside of discourse-tests. Update the 'vouched' and 'unvouched' users in variables.json with those credentials
* [Install Tox](https://tox.readthedocs.io/en/latest/install.html)
* Run PYTEST_ADDOPTS="--variables=/path/to/variables.json" tox
<file_sep>/pages/register.py
from selenium.webdriver.common.by import By
from pages.base import Base
from pages.home_page import Home
class Register(Base):
_username_locator = (By.ID, 'new-account-username')
_name_locator = (By.ID, 'new-account-name')
_create_new_account_button_locator = (By.CSS_SELECTOR, '.modal-footer .btn-primary')
def enter_username(self, username):
self.selenium.find_element(*self._username_locator).clear()
self.selenium.find_element(*self._username_locator).send_keys(username)
def click_create_new_account_button(self):
self.selenium.find_element(*self._create_new_account_button_locator).click()
return Home(self.base_url, self.selenium)
<file_sep>/tests/conftest.py
import uuid
import pyotp
import pytest
import restmail
@pytest.fixture
def capabilities(request, capabilities):
driver = request.config.getoption('driver')
if capabilities.get('browserName', driver).lower() == 'firefox':
capabilities['marionette'] = True
return capabilities
@pytest.fixture
def selenium(selenium):
selenium.implicitly_wait(10)
selenium.maximize_window()
return selenium
@pytest.fixture
def stored_users(variables):
return variables['users']
@pytest.fixture
def vouched_user(stored_users):
return stored_users['vouched']
@pytest.fixture
def unvouched_user(stored_users):
return stored_users['unvouched']
@pytest.fixture
def new_email():
return '<EMAIL>'.format(uuid.uuid1())
@pytest.fixture
def new_user(new_email):
return {'email': new_email}
@pytest.fixture
def login_link(username):
mail = restmail.get_mail(username)
mail_content = mail[0]['text'].replace('\n', ' ').replace('amp;', '').split(" ")
for link in mail_content:
if link.startswith("https"):
return link
@pytest.fixture
def ldap_user(stored_users):
return stored_users['ldap']
@pytest.fixture
def passcode(secret_seed):
totp = pyotp.TOTP(secret_seed)
return totp.now()
<file_sep>/pages/base.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from pages.auth0 import Auth0
from pages.page import Page
from tests import conftest
class Base(Page):
_login_button_locator = (By.CSS_SELECTOR, 'button.login-button')
_avatar_image_locator = (By.CSS_SELECTOR, '#current-user a[class="icon"]')
_logout_button_locator = (By.CSS_SELECTOR, '.widget-link.logout')
_page_not_found_error_message_locator = (By.CSS_SELECTOR, '.page-not-found')
_category_locator = (By.CSS_SELECTOR, '.category-navigation .category-breadcrumb li:nth-child(1) a[aria-label="Display category list"]')
_subcategory_locator = (By.CSS_SELECTOR, '.category-navigation .category-breadcrumb li:nth-child(2) a[aria-label="Display category list"]')
_preferences_button_locator = (By.CSS_SELECTOR, '.user-preferences-link')
_toggle_menu_button_locator = (By.ID, 'toggle-hamburger-menu')
_categories_list = (By.CSS_SELECTOR, 'li[class*="category-link"] a:nth-child(1)')
@property
def page_title(self):
WebDriverWait(self.selenium, self.timeout).until(lambda s: self.selenium.title)
return self.selenium.title
@property
def is_login_button_displayed(self):
return self.is_element_visible(*self._login_button_locator)
@property
def is_avatar_displayed(self):
return self.is_element_visible(*self._avatar_image_locator)
@property
def page_not_found_error_message(self):
self.wait_for_element_visible(*self._page_not_found_error_message_locator)
return self.selenium.find_element(*self._page_not_found_error_message_locator).text
@property
def subcategory(self):
return self.selenium.find_element(*self._subcategory_locator).text
@property
def categories_list_names(self):
categories_list = self.selenium.find_elements(*self._categories_list)
return [category.text for category in categories_list]
@property
def category(self):
return self.selenium.find_element(*self._category_locator).text
def click_sign_in_button(self):
self.selenium.find_element(*self._login_button_locator).click()
def login(self, email):
self.click_sign_in_button()
auth0 = Auth0(self.base_url, self.selenium)
auth0.request_login_link(email)
login_link = conftest.login_link(email)
self.selenium.get(login_link)
def login_with_ldap(self, email_address, password, passcode):
self.click_sign_in_button()
auth0 = Auth0(self.base_url, self.selenium)
auth0.login_with_ldap(email_address, password, passcode)
def click_avatar(self):
self.selenium.find_element(*self._avatar_image_locator).click()
WebDriverWait(self.selenium, self.timeout).until(
lambda s: self.selenium.find_element(*self._logout_button_locator))
def click_logout_menu_item(self):
self.click_avatar()
self.selenium.find_element(*self._logout_button_locator).click()
WebDriverWait(self.selenium, self.timeout).until(lambda s: self.is_login_button_displayed)
def click_preferences(self):
self.click_avatar()
self.selenium.find_element(*self._preferences_button_locator).click()
from pages.preferences import Preferences
return Preferences(self.base_url, self.selenium)
def create_new_user(self, email):
self.login(email)
from pages.register import Register
return Register(self.base_url, self.selenium)
def click_toggle_menu(self):
self.selenium.find_element(*self._toggle_menu_button_locator).click()
def select_category(self, category):
categories_list = self.selenium.find_elements(*self._categories_list)
for item in categories_list:
if item.text == category:
item.click()
from pages.category import Category
return Category(self.base_url, self.selenium)
<file_sep>/pages/auth0.py
from selenium.webdriver.common.by import By
from pages.page import Page
class Auth0(Page):
_login_with_email_button_locator = (By.CSS_SELECTOR, '.auth0-lock-passwordless-button.auth0-lock-passwordless-big-button')
_email_input_locator = (By.CSS_SELECTOR, '.auth0-lock-passwordless-pane>div>div>input')
_send_email_button_locator = (By.CSS_SELECTOR, '.auth0-lock-passwordless-submit')
_login_with_ldap_button_locator = (By.CSS_SELECTOR, '.auth0-lock-ldap-button.auth0-lock-ldap-big-button')
_ldap_email_field_locator = (By.CSS_SELECTOR, '.auth0-lock-input-email .auth0-lock-input')
_ldap_password_field_locator = (By.CSS_SELECTOR, '.auth0-lock-input-password .auth0-lock-input')
_login_button_locator = (By.CSS_SELECTOR, '.auth0-lock-submit')
_enter_passcode_button = (By.CSS_SELECTOR, '.passcode-label .positive.auth-button')
_passcode_field_locator = (By.CSS_SELECTOR, '.passcode-label input[name="passcode"]')
_duo_iframe_locator = (By.ID, 'duo_iframe')
def request_login_link(self, username):
self.wait_for_element_visible(*self._login_with_email_button_locator)
self.selenium.find_element(*self._login_with_email_button_locator).click()
self.wait_for_element_visible(*self._email_input_locator)
self.selenium.find_element(*self._email_input_locator).send_keys(username)
self.selenium.find_element(*self._send_email_button_locator).click()
def login_with_ldap(self, email, password, passcode):
self.wait_for_element_visible(*self._login_with_ldap_button_locator)
self.selenium.find_element(*self._login_with_ldap_button_locator).click()
self.selenium.find_element(*self._ldap_email_field_locator).send_keys(email)
self.selenium.find_element(*self._ldap_password_field_locator).send_keys(password)
self.selenium.find_element(*self._login_button_locator).click()
self.enter_passcode(passcode)
def enter_passcode(self, passcode):
self.selenium.switch_to_frame('duo_iframe')
self.wait_for_element_visible(*self._enter_passcode_button)
self.selenium.find_element(*self._enter_passcode_button).click()
self.selenium.find_element(*self._passcode_field_locator).send_keys(passcode)
self.selenium.find_element(*self._enter_passcode_button).click()
self.selenium.switch_to_default_content()
<file_sep>/pages/home_page.py
from selenium.webdriver.common.by import By
from pages.base import Base
from pages.topic_page import TopicPage
class Home(Base):
_create_new_topic_button_locator = (By.ID, 'create-topic')
_new_title_topic_locator = (By.ID, 'reply-title')
_category_combobox_locator = (By.CSS_SELECTOR, '.category-input div[class*="category-combobox"]')
_category_input_locator = (By.CSS_SELECTOR, '.select2-search .select2-input')
_search_results_locator = (By.CSS_SELECTOR, '.select2-results .badge-wrapper.bar')
_topic_description_locator = (By.CSS_SELECTOR, 'div[class*="textarea-wrapper"] textarea')
_create_topic_button_locator = (By.CSS_SELECTOR, '.submit-panel button')
_similar_topics_window_locator = (By.CSS_SELECTOR, '.composer-popup.hidden.similar-topics')
_close_similar_topics_window_button = (By.CSS_SELECTOR, '.composer-popup.hidden.similar-topics .close')
def __init__(self, base_url, selenium, open_url=True):
Base.__init__(self, base_url, selenium)
if open_url:
self.selenium.get(self.base_url)
def click_add_new_topic(self):
self.selenium.find_element(*self._create_new_topic_button_locator).click()
def enter_new_topic_title(self, title):
self.wait_for_element_visible(*self._new_title_topic_locator)
self.selenium.find_element(*self._new_title_topic_locator).send_keys(title)
def select_category(self, category):
self.selenium.find_element(*self._category_combobox_locator).click()
self.wait_for_element_visible(*self._category_input_locator)
self.selenium.find_element(*self._category_input_locator).send_keys(category)
search_results = self.selenium.find_elements(*self._search_results_locator)
for item in search_results:
if item.text == category:
item.click()
def enter_topic_description(self, description):
self.selenium.find_element(*self._topic_description_locator).send_keys(description)
self.wait_for_element_visible(*self._similar_topics_window_locator)
self.selenium.find_element(*self._close_similar_topics_window_button).click()
def click_create_topic(self):
self.selenium.find_element(*self._create_topic_button_locator).click()
return TopicPage(self.base_url, self.selenium)
<file_sep>/tests/test_account.py
# coding=utf-8
import random
import uuid
import pytest
from pages.home_page import Home
from tests import conftest
class TestAccount:
@pytest.mark.nondestructive
def test_login_logout(self, base_url, selenium, unvouched_user):
home_page = Home(base_url, selenium)
home_page.login(unvouched_user['email'])
assert home_page.is_avatar_displayed
home_page.click_logout_menu_item()
assert home_page.is_login_button_displayed
@pytest.mark.nondestructive
def test_unvouched_mozillian_cannot_access_private_categories(self, base_url, selenium, unvouched_user):
home_page = Home(base_url, selenium)
home_page.login(unvouched_user['email'])
assert home_page.is_avatar_displayed
home_page.go_to_url('https://discourse.mozilla-community.org/c/mozillians/vouched-mozillians')
error_message = 'Oops! That page doesn’t exist or is private.'.decode('utf8')
assert error_message == home_page.page_not_found_error_message
home_page.go_to_url('https://discourse.mozilla-community.org/c/mozillians/nda')
assert error_message == home_page.page_not_found_error_message
@pytest.mark.nondestructive
def test_vouched_mozillian_can_access_private_category(self, base_url, selenium, vouched_user):
home_page = Home(base_url, selenium)
home_page.login(vouched_user['email'])
assert home_page.is_avatar_displayed
home_page.go_to_url('https://discourse.mozilla-community.org/c/mozillians/vouched-mozillians')
assert 'Vouched Mozillians' == home_page.subcategory
home_page.click_logout_menu_item()
@pytest.mark.nondestructive
def test_create_and_delete_account(self, base_url, selenium, new_user):
home_page = Home(base_url, selenium)
register = home_page.create_new_user(new_user['email'])
register.enter_username("test_user")
home_page = register.click_create_new_account_button()
assert home_page.is_avatar_displayed
preferences = home_page.click_preferences()
home_page = preferences.account.delete_account()
assert home_page.is_login_button_displayed
@pytest.mark.nondestructive
def test_user_can_watch_category(self, base_url, selenium, unvouched_user):
home_page = Home(base_url, selenium)
home_page.login(unvouched_user['email'])
assert home_page.is_avatar_displayed
home_page.click_toggle_menu()
categories = home_page.categories_list_names
category = random.choice(categories)
category_page = home_page.select_category(category)
category_page.click_notifications_dropdown()
category_page.select_option("Watching")
preferences = category_page.click_preferences()
preferences_category_page = preferences.categories
assert category in preferences_category_page.watched_categories
preferences_category_page.remove_category(category)
preferences_category_page.click_save_button()
preferences.click_logout_menu_item()
assert home_page.is_login_button_displayed
@pytest.mark.nondestructive
def test_user_can_go_through_existing_categories(self, base_url, selenium, vouched_user):
home_page = Home(base_url, selenium)
home_page.login(vouched_user['email'])
assert home_page.is_avatar_displayed
home_page.click_toggle_menu()
categories_list = home_page.categories_list_names
for category_name in categories_list:
index = categories_list.index(category_name)
home_page.select_category(categories_list[index])
assert home_page.category == category_name
home_page.click_toggle_menu()
home_page.click_logout_menu_item()
@pytest.mark.nondestructive
def test_user_can_create_a_new_topic(self, base_url, selenium, ldap_user):
home_page = Home(base_url, selenium)
home_page.login_with_ldap(ldap_user['email'], ldap_user['password'], conftest.passcode(ldap_user['secret_seed']))
assert home_page.is_avatar_displayed
home_page.click_add_new_topic()
title = "Test topic - {0}".format(uuid.uuid1())
home_page.enter_new_topic_title(title)
category = "playground"
home_page.select_category(category)
description = "This is a topic description for testing - {}".format(uuid.uuid1())
home_page.enter_topic_description(description)
topic_page = home_page.click_create_topic()
assert title == topic_page.topic_title
assert category == topic_page.topic_category
assert description == topic_page.topic_description
topic_page.click_logout_menu_item()
assert topic_page.is_login_button_displayed
<file_sep>/pages/preferences.py
from selenium.webdriver.common.by import By
from pages.base import Base
from pages.page import PageRegion
class Preferences(Base):
_account_button_locator = (By.CSS_SELECTOR, 'li[class*="nav-account"] a')
_categories_button_locator = (By.CSS_SELECTOR, 'li[class*="no-glyph indent nav-categories"] a')
_user_preferences_section_locator = (By.CSS_SELECTOR, '.user-right.user-preferences')
@property
def account(self):
self.selenium.find_element(*self._account_button_locator).click()
return self.Account(self.base_url, self.selenium,
self.selenium.find_element(*self._user_preferences_section_locator))
@property
def categories(self):
self.selenium.find_element(*self._categories_button_locator).click()
return self.Category(self.base_url, self.selenium,
self.selenium.find_element(*self._user_preferences_section_locator))
class Account(PageRegion):
_delete_account_button_locator = (By.CSS_SELECTOR, '.delete-account button')
_delete_account_confirmation_locator = (By.CSS_SELECTOR, '.modal-footer .btn-danger')
def delete_account(self):
self.selenium.find_element(*self._delete_account_button_locator).click()
self.wait_for_element_visible(*self._delete_account_confirmation_locator)
self.selenium.find_element(*self._delete_account_confirmation_locator).click()
from pages.home_page import Home
return Home(self.base_url, self.selenium)
class Category(PageRegion):
_watched_categories_locator = (By.CSS_SELECTOR, 'div[class*="category-controls"]:first-of-type div[class="item"]')
_delete_category_buttons_locator = (By.CSS_SELECTOR, 'div[class*="category-controls"]:first-of-type a[class="remove"]')
_save_button_locator = (By.CSS_SELECTOR, 'button[class*="save-user"]')
@property
def watched_categories(self):
watched_categories = self.selenium.find_elements(*self._watched_categories_locator)
return [category.text for category in watched_categories]
def remove_category(self, category):
category_index = self.watched_categories.index(category)
delete_watched_categories_buttons = self.selenium.find_elements(*self._delete_category_buttons_locator)
delete_watched_categories_buttons[category_index].click()
def click_save_button(self):
self.selenium.find_element(*self._save_button_locator).click()
<file_sep>/pages/topic_page.py
from selenium.webdriver.common.by import By
from pages.base import Base
class TopicPage(Base):
_topic_title_locator = (By.CSS_SELECTOR, '.fancy-title')
_topic_category_locator = (By.CSS_SELECTOR, '.title-wrapper .badge-wrapper.bar')
_topic_description_locator = (By.CSS_SELECTOR, '.regular.contents p')
@property
def topic_title(self):
return self.selenium.find_element(*self._topic_title_locator).text
@property
def topic_category(self):
return self.selenium.find_element(*self._topic_category_locator).text
@property
def topic_description(self):
return self.selenium.find_element(*self._topic_description_locator).text
| cceadf6e4f84e1fdf0e84dd135e4738fed66d4e2 | [
"Markdown",
"Python"
] | 10 | Python | viorelaioia-zz/discourse-tests | 1756b3ea0de2e9da26246aa9951ee7b4a8387f0c | 5a0ca3b24c0f1b1fd5d5b5e0d99e37b7ceff7efa | |
refs/heads/main | <file_sep><?php
$servername = "localhost:3308";
$username = "root";
$password = "";
$database = "bank";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit']))
{
$from = $_GET['ID'];
$to= $_POST['to'];
$amount = $_POST['amount'];
$sql = "SELECT * from userdetails where ID=$from";
$query = mysqli_query($conn,$sql);
$sql1 = mysqli_fetch_array($query);
$sql = "SELECT * from userdetails where ID=$to";
$query = mysqli_query($conn,$sql);
$sql2 = mysqli_fetch_array($query);
if (($amount)<0)
{
echo '<script type="text/javascript">';
echo ' alert("Oops! Negative values cannot be transferred")';
echo '</script>';
}
else if($amount > $sql1['Balance'])
{
echo '<script type="text/javascript">';
echo ' alert("Bad Luck! Insufficient Balance")';
echo '</script>';
}
else if($amount == 0){
echo "<script type='text/javascript'>";
echo "alert('Oops! Zero value cannot be transferred')";
echo "</script>";
}
else {
$newbalance = $sql1['Balance'] - $amount;
$sql = "UPDATE userdetails set Balance=$newbalance where ID=$from";
mysqli_query($conn,$sql);
$newbalance = $sql2['Balance'] + $amount;
$sql = "UPDATE userdetails set Balance=$newbalance where ID=$to";
mysqli_query($conn,$sql);
$sender = $sql1['Name'];
$receiver = $sql2['Name'];
$sql = "INSERT INTO transaction(sender, receiver,amount) VALUES ('$sender','$receiver','$amount')";
$query=mysqli_query($conn,$sql);
if($query){
echo "<script> alert('Transaction Successful');
window.location='userdetails.php';
</script>";
}
$newbalance= 0;
$amount =0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transaction</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/table.css">
<link rel="stylesheet" type="text/css" href="css/navbar.css">
<style type="text/css">
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
}
.form-control {
display: block;
width: 15%;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
img:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
button{
border:none;
background: #d9d9d9;
}
button:hover{
background-color:#777E8B;
transform: scale(1.1);
color:white;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<a class="navbar-brand" href="https://www.thesparksfoundationsingapore.org/">
<img src="https://internshala.com/cached_uploads/logo%2F5e2fddc2128b01580195266.png" alt="logo" style="width:40px;">
</a>
<ul class="navbar-nav">
<div class="btn-group">
<button onclick="document.location='index.php'" type="button" class="btn btn-primary">Home</button>
</div></ul>---
<a class="navbar-brand" href="https://www.thesparksfoundationsingapore.org/">
<button type="button" class="btn btn-warning">about us</button></a>
<button type="button" onclick="document.location='transactionhistory.php'" class="btn btn-info">Transaction History</button>
</nav>
</div>
<?php
$servername = "localhost:3308";
$username = "root";
$password = "";
$database = "bank";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid=$_GET['ID'];
$sql = "SELECT * FROM userdetails where ID=$sid";
$result=mysqli_query($conn,$sql);
if(!$result)
{
echo "Error : ".$sql."<br>".mysqli_error($conn);
}
$rows=mysqli_fetch_assoc($result);
?>
<br>
<br>
<div class="container-fluid">
<div class="col">
<div class="row row--1">
<?php
if ($rows['ID']==1){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/p843x403/141396206_2493794024259654_6265087547529057040_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=730e14&_nc_ohc=-7YyLsPS8cEAX86poRA&_nc_ht=scontent.fhyd1-4.fna&tp=6&oh=9d9aded097af4a3e5e48412088527f0a&oe=6096749D" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==2){ ?>
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/104331003_194077888575821_401002836288722534_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=HutkpDZD3qUAX-FBve8&edm=ABfd0MgAAAAA&ccb=7-4&oh=f47a4d288ffa9e43868c3e400760aefa&oe=6099F6A4&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==3){ ?>
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/164419267_788753738718465_2230036935495910194_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=x01wCArvgdkAX_ipJaN&edm=ABfd0MgAAAAA&ccb=7-4&oh=cd704a529a8bac88ee22bb5ad5f6a51c&oe=609C6EA1&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==4){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/90985050_523347848594538_4485919209812918272_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=174925&_nc_ohc=LeF8IICz0W8AX_hcEF_&_nc_ht=scontent.fhyd1-4.fna&oh=5335f048a201ec754cf3a502066844af&oe=609A8018" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==5){ ?>
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/p843x403/170220245_1190771458015690_3601409687975844895_n.jpg?_nc_cat=109&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=F2WEQPZkDxcAX_y0a_H&_nc_ht=scontent.fhyd1-3.fna&tp=6&oh=7e35b1ebd46a3f5673b98aa77611f419&oe=609B3058" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==6){ ?>
<img src="https://instagram.fvga2-1.fna.fbcdn.net/v/t51.2885-19/s320x320/67712818_1348616035294428_896999693521780736_n.jpg?tp=1&_nc_ht=instagram.fvga2-1.fna.fbcdn.net&_nc_ohc=W85yRIP32goAX8Wy6bN&edm=ABfd0MgAAAAA&ccb=7-4&oh=553772c66da443dc1df351b99ba6a749&oe=6099AA56&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==7){ ?>
<img src="https://scontent.fhyd1-2.fna.fbcdn.net/v/t1.6435-9/74241445_2504303969801498_5151015051880038400_n.jpg?_nc_cat=108&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=JrFE1wiz8MEAX-56W2R&_nc_ht=scontent.fhyd1-2.fna&oh=3c8589b0ddd36a11b4ea5967c1c70099&oe=609C9B4E" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==8){ ?>
<img src="https://scontent.fvga2-1.fna.fbcdn.net/v/t31.18172-8/13147829_2011836462375323_4997514148478018788_o.jpg?_nc_cat=100&ccb=1-3&_nc_sid=174925&_nc_ohc=X8Vw7KPj5iwAX8vrBuB&_nc_ht=scontent.fvga2-1.fna&oh=9b6c186ad30e8a3e2c544a379654287f&oe=609CF4E6" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==9){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/172690451_484734182710817_8004029811343064611_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=vtTmfy7d7eoAX8MSiiu&_nc_ht=scontent.fhyd1-4.fna&oh=99aec3978ed1c9f817c63bdda4c7915d&oe=609B0278" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['ID']==10){ ?>
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/46272044_683165832084398_7425190098989219840_n.jpg?_nc_cat=104&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=muqBKOpoe1QAX-L-RvD&_nc_ht=scontent.fhyd1-3.fna&oh=97e69e310519ec4fa2d89d6f6981c37f&oe=609C64E5" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
</div>
<div class="row row--1">
<button type="button" class="btn btn-danger">
<?php echo $rows['Name']?> <span class="badge badge-light"><?php echo $rows['ID'] ?></span>
</button></div>
<div class="row row--1"><code>Email</code><kbd class="text-success"><?php echo $rows['Email']?></kbd></div>
<div class="row row--1"><code>Balance</code><kbd class="text-warning"><?php echo $rows['Balance']?></kbd></div>
</div>
</div>
</div>
<br><br><br>
</div>
<h2 class=" text-success pt-4">Transfer To</h2>
<br><br>
<?php
$servername = "localhost:3308";
$username = "root";
$password = "";
$database = "bank";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid=$_GET['ID'];
$sql = "SELECT * FROM userdetails where ID!=$sid";
$result=mysqli_query($conn,$sql);
if(!$result)
{
echo "Error : ".$sql."<br>".mysqli_error($conn);
}
while($rows = mysqli_fetch_assoc($result)) {
?>
<div class="container-fluid">
<div class="col">
<div class="row row--1">
<?php
if ($rows['ID']==1){ ?>
<a href="#demo1" data-toggle="collapse" >
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/p843x403/141396206_2493794024259654_6265087547529057040_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=730e14&_nc_ohc=-7YyLsPS8cEAX86poRA&_nc_ht=scontent.fhyd1-4.fna&tp=6&oh=9d9aded097af4a3e5e48412088527f0a&oe=6096749D" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==2){ ?>
<a href="#demo2" data-toggle="collapse">
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/104331003_194077888575821_401002836288722534_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=HutkpDZD3qUAX-FBve8&edm=ABfd0MgAAAAA&ccb=7-4&oh=f47a4d288ffa9e43868c3e400760aefa&oe=6099F6A4&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==3){ ?>
<a href="#demo3" data-toggle="collapse">
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/164419267_788753738718465_2230036935495910194_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=x01wCArvgdkAX_ipJaN&edm=ABfd0MgAAAAA&ccb=7-4&oh=cd704a529a8bac88ee22bb5ad5f6a51c&oe=609C6EA1&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==4){ ?>
<a href="#demo4" data-toggle="collapse">
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/90985050_523347848594538_4485919209812918272_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=174925&_nc_ohc=LeF8IICz0W8AX_hcEF_&_nc_ht=scontent.fhyd1-4.fna&oh=5335f048a201ec754cf3a502066844af&oe=609A8018" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==5){ ?>
<a href="#demo5" data-toggle="collapse">
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/p843x403/170220245_1190771458015690_3601409687975844895_n.jpg?_nc_cat=109&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=F2WEQPZkDxcAX_y0a_H&_nc_ht=scontent.fhyd1-3.fna&tp=6&oh=7e35b1ebd46a3f5673b98aa77611f419&oe=609B3058" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==6){ ?>
<a href="#demo6" data-toggle="collapse">
<img src="https://instagram.fvga2-1.fna.fbcdn.net/v/t51.2885-19/s320x320/67712818_1348616035294428_896999693521780736_n.jpg?tp=1&_nc_ht=instagram.fvga2-1.fna.fbcdn.net&_nc_ohc=W85yRIP32goAX8Wy6bN&edm=ABfd0MgAAAAA&ccb=7-4&oh=553772c66da443dc1df351b99ba6a749&oe=6099AA56&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==7){ ?>
<a href="#demo7" data-toggle="collapse">
<img src="https://scontent.fhyd1-2.fna.fbcdn.net/v/t1.6435-9/74241445_2504303969801498_5151015051880038400_n.jpg?_nc_cat=108&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=JrFE1wiz8MEAX-56W2R&_nc_ht=scontent.fhyd1-2.fna&oh=3c8589b0ddd36a11b4ea5967c1c70099&oe=609C9B4E" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==8){ ?>
<a href="#demo8" data-toggle="collapse">
<img src="https://scontent.fvga2-1.fna.fbcdn.net/v/t31.18172-8/13147829_2011836462375323_4997514148478018788_o.jpg?_nc_cat=100&ccb=1-3&_nc_sid=174925&_nc_ohc=X8Vw7KPj5iwAX8vrBuB&_nc_ht=scontent.fvga2-1.fna&oh=9b6c186ad30e8a3e2c544a379654287f&oe=609CF4E6" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==9){ ?>
<a href="#demo9" data-toggle="collapse">
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/172690451_484734182710817_8004029811343064611_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=vtTmfy7d7eoAX8MSiiu&_nc_ht=scontent.fhyd1-4.fna&oh=99aec3978ed1c9f817c63bdda4c7915d&oe=609B0278" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==10){ ?>
<a href="#demo10" data-toggle="collapse">
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/46272044_683165832084398_7425190098989219840_n.jpg?_nc_cat=104&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=muqBKOpoe1QAX-L-RvD&_nc_ht=scontent.fhyd1-3.fna&oh=97e69e310519ec4fa2d89d6f6981c37f&oe=609C64E5" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
</div>
<div class="row row--1">
<button type="button" class="btn btn-danger">
<?php echo $rows['Name']?> <span class="badge badge-light"><?php echo $rows['ID'] ?></span>
</button></div>
<div class="row row--1"><code>Email</code><kbd class="text-success"><?php echo $rows['Email']?></kbd></div>
<div class="row row--1"><code>Balance</code><kbd class="text-warning"><?php echo $rows['Balance']?></kbd></div><br>
</select>
<?php
if ($rows['ID']==1){ ?>
<form method="post" >
<div id="demo1" class="collapse" >
<input type = "hidden" name = "to" value = "1" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==2){ ?>
<form method="post" >
<div id="demo2" class="collapse" >
<input type = "hidden" name = "to" value = "2" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==3){ ?>
<form method="post" >
<div id="demo3" class="collapse" >
<input type = "hidden" name = "to" value = "3" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==4){ ?>
<form method="post" >
<div id="demo4" class="collapse" >
<input type = "hidden" name = "to" value = "4" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==5){ ?>
<form method="post" >
<div id="demo5" class="collapse" >
<input type = "hidden" name = "to" value = "5" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==6){ ?>
<form method="post" >
<div id="demo6" class="collapse" >
<input type = "hidden" name = "to" value = "6" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==7){ ?>
<form method="post" >
<div id="demo7" class="collapse" >
<input type = "hidden" name = "to" value = "7" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==8){ ?>
<form method="post" >
<div id="demo8" class="collapse" >
<input type = "hidden" name = "to" value = "8" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==9){ ?>
<form method="post" >
<div id="demo9" class="collapse" >
<input type = "hidden" name = "to" value = "9" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<?php
if ($rows['ID']==10){ ?>
<form method="post" >
<div id="demo10" class="collapse" >
<!--<div type="submit" class="form-control" name="to" value="10"></div>-->
<input type = "hidden" name = "to" value = "10" />
<input type="number" class="form-control" name="amount" placeholder="amount" required><br>
<button class="btn btn-warning" name="submit" type="submit" >Transfer</button>
</div> </form>
<?php }
?>
<br><br>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<style>
.button{
margin-left:300px;
font-weight: 600;
padding: 10px 20px !important;
text-transform: uppercase !important;
color: var(--theme-link-color-visited);;
background-color: #004981;
border-color: #3ea49d;
border-width: 0;
padding: 7px 14px;
font-size: 30px;
outline: none !important;
background-image: none !important;
filter: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
text-shadow: none;
text-align:none;
}
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
}
img:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
</style>
<body>
<?php
// Username is root
$user = 'root';
$password = '';
// Database name is gfg
$database = 'bank';
// Server is localhost with
// port number 3308
$servername='localhost:3308';
$mysqli = new mysqli($servername, $user,$password, $database);
// Checking for connections
if ($mysqli->connect_error) {
die('Connect Error (' .
$mysqli->connect_errno . ') '.
$mysqli->connect_error);
}
// SQL query to select data from database
$sql = "SELECT * FROM userdetails";
$result = $mysqli->query($sql);
$mysqli->close();
?>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<a class="navbar-brand" href="https://www.thesparksfoundationsingapore.org/">
<img src="https://internshala.com/cached_uploads/logo%2F5e2fddc2128b01580195266.png" alt="logo" style="width:40px;">
</a>
<ul class="navbar-nav">
<div class="btn-group">
<button onclick="document.location='index.php'" type="button" class="btn btn-primary">Home</button>
</div></ul>---
<a class="navbar-brand" href="https://www.thesparksfoundationsingapore.org/">
<button type="button" class="btn btn-warning">about us</button></a>--
<button type="button" onclick="document.location='transactionhistory.php'" class="btn btn-info">Transaction History</button>
<div class="container mt-2">
<input class="form-control" id="myInput" type="text" placeholder="Search..">
</div></div>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
</nav>
<br>
<div class="container">
<div class="col">
<div id="myDIV" class="mt-3">
<?php // LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<div class="row row--1">
<?php
if ($rows['ID']==1){ ?>
<a href="moneytransfer.php?ID=<?php echo $rows['ID'] ;?>">
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/p843x403/141396206_2493794024259654_6265087547529057040_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=730e14&_nc_ohc=-7YyLsPS8cEAX86poRA&_nc_ht=scontent.fhyd1-4.fna&tp=6&oh=9d9aded097af4a3e5e48412088527f0a&oe=6096749D" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==2){ ?>
<a href="moneytransfer.php?ID=<?php echo $rows['ID'] ;?>">
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/104331003_194077888575821_401002836288722534_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=HutkpDZD3qUAX-FBve8&edm=ABfd0MgAAAAA&ccb=7-4&oh=f47a4d288ffa9e43868c3e400760aefa&oe=6099F6A4&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==3){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/164419267_788753738718465_2230036935495910194_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=x01wCArvgdkAX_ipJaN&edm=ABfd0MgAAAAA&ccb=7-4&oh=cd704a529a8bac88ee22bb5ad5f6a51c&oe=609C6EA1&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==4){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/90985050_523347848594538_4485919209812918272_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=174925&_nc_ohc=LeF8IICz0W8AX_hcEF_&_nc_ht=scontent.fhyd1-4.fna&oh=5335f048a201ec754cf3a502066844af&oe=609A8018" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==5){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/p843x403/170220245_1190771458015690_3601409687975844895_n.jpg?_nc_cat=109&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=F2WEQPZkDxcAX_y0a_H&_nc_ht=scontent.fhyd1-3.fna&tp=6&oh=7e35b1ebd46a3f5673b98aa77611f419&oe=609B3058" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==6){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://instagram.fvga2-1.fna.fbcdn.net/v/t51.2885-19/s320x320/67712818_1348616035294428_896999693521780736_n.jpg?tp=1&_nc_ht=instagram.fvga2-1.fna.fbcdn.net&_nc_ohc=W85yRIP32goAX8Wy6bN&edm=ABfd0MgAAAAA&ccb=7-4&oh=553772c66da443dc1df351b99ba6a749&oe=6099AA56&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==7){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://scontent.fhyd1-2.fna.fbcdn.net/v/t1.6435-9/74241445_2504303969801498_5151015051880038400_n.jpg?_nc_cat=108&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=JrFE1wiz8MEAX-56W2R&_nc_ht=scontent.fhyd1-2.fna&oh=3c8589b0ddd36a11b4ea5967c1c70099&oe=609C9B4E" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==8){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://scontent.fvga2-1.fna.fbcdn.net/v/t31.18172-8/13147829_2011836462375323_4997514148478018788_o.jpg?_nc_cat=100&ccb=1-3&_nc_sid=174925&_nc_ohc=X8Vw7KPj5iwAX8vrBuB&_nc_ht=scontent.fvga2-1.fna&oh=9b6c186ad30e8a3e2c544a379654287f&oe=609CF4E6" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==9){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/172690451_484734182710817_8004029811343064611_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=vtTmfy7d7eoAX8MSiiu&_nc_ht=scontent.fhyd1-4.fna&oh=99aec3978ed1c9f817c63bdda4c7915d&oe=609B0278" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
<?php
if ($rows['ID']==10){ ?>
<a href="moneytransfer.php?ID= <?php echo $rows['ID'] ;?>">
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/46272044_683165832084398_7425190098989219840_n.jpg?_nc_cat=104&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=muqBKOpoe1QAX-L-RvD&_nc_ht=scontent.fhyd1-3.fna&oh=97e69e310519ec4fa2d89d6f6981c37f&oe=609C64E5" title="select" style="background-color:orange" class="img-thumbnail"/>
</a>
<?php }
?>
</div>
<div class="row row--1">
<button type="button" class="btn btn-danger">
<?php echo $rows['Name']?> <span class="badge badge-light"><?php echo $rows['ID'] ?></span>
</button> </div>
<div class="row row--1"><br><code>Email</code><kbd class="text-success"><?php echo $rows['Email']?></kbd> </div>
<div class="row row--1"><br> <code>Balance</code><kbd class="text-warning"><?php echo $rows['Balance']?></kbd> </div><br>
<?php
}
?>
</div>
</div>
</div>
<br>
</div>
<br><br>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transfer History</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/table.css">
<link rel="stylesheet" type="text/css" href="css/navbar.css">
<style type="text/css">
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
}
.form-control {
display: block;
width: 15%;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
img:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
button{
border:none;
background: #d9d9d9;
}
button:hover{
background-color:#777E8B;
transform: scale(1.1);
color:white;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-secondary navbar-dark">
<a class="navbar-brand" href="https://www.thesparksfoundationsingapore.org/">
<img src="https://internshala.com/cached_uploads/logo%2F5e2fddc2128b01580195266.png" alt="logo" style="width:40px;">
</a>
<ul class="navbar-nav">
<li class="nav-item">
<div class="btn-group">
<button onclick="document.location='index.php'" type="button" class="btn btn-primary">Home</button>
</div>
<button type="button" onclick="document.location='userdetails.php'" class="btn btn-success">New Transaction</button>
<a href="https://www.thesparksfoundationsingapore.org/">
<button type="button" class="btn btn-warning">about us</button><a>
</li>
</ul>
</nav>
<div class="container">
<h2 class="text-center text-success pt-4">Transfer History</h2>
<br>
<div class="table-responsive-sm">
<table class="table table-hover table-striped table-condensed table-bordered">
<thead>
<tr>
<th class="text-center">Sender</th>
<th class="text-center">Receiver</th>
<th class="text-center">Amount</th>
</tr>
</thead>
<tbody>
<?php
$user = 'root';
$password = '';
// Database name is gfg
$database = 'bank';
// Server is localhost with
// port number 3308
$servername='localhost:3308';
$mysqli = new mysqli($servername, $user,
$password, $database);
// Checking for connections
if ($mysqli->connect_error) {
die('Connect Error (' .
$mysqli->connect_errno . ') '.
$mysqli->connect_error);
}
// SQL query to select data from database
$sql ="select * from transaction";
$query =$mysqli->query($sql) ;
$mysqli->close();
?>
<?php // LOOP TILL END OF DATA
while($rows=$query->fetch_assoc())
{
?>
<tr>
<td class="py-2">
<?php
if ($rows['sender']=="Bharath"){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/p843x403/141396206_2493794024259654_6265087547529057040_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=730e14&_nc_ohc=-7YyLsPS8cEAX86poRA&_nc_ht=scontent.fhyd1-4.fna&tp=6&oh=9d9aded097af4a3e5e48412088527f0a&oe=6096749D" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Jaisimha"){ ?>
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/104331003_194077888575821_401002836288722534_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=HutkpDZD3qUAX-FBve8&edm=ABfd0MgAAAAA&ccb=7-4&oh=f47a4d288ffa9e43868c3e400760aefa&oe=6099F6A4&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Arshad"){ ?>
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/164419267_788753738718465_2230036935495910194_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=x01wCArvgdkAX_ipJaN&edm=ABfd0MgAAAAA&ccb=7-4&oh=cd704a529a8bac88ee22bb5ad5f6a51c&oe=609C6EA1&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Tharun"){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/90985050_523347848594538_4485919209812918272_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=174925&_nc_ohc=LeF8IICz0W8AX_hcEF_&_nc_ht=scontent.fhyd1-4.fna&oh=5335f048a201ec754cf3a502066844af&oe=609A8018" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Ganesh"){ ?>
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/p843x403/170220245_1190771458015690_3601409687975844895_n.jpg?_nc_cat=109&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=F2WEQPZkDxcAX_y0a_H&_nc_ht=scontent.fhyd1-3.fna&tp=6&oh=7e35b1ebd46a3f5673b98aa77611f419&oe=609B3058" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Jagadesh"){ ?>
<img src="https://images-na.ssl-images-amazon.com/images/I/31rNsnic6wL.jpg" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Gokul"){ ?>
<img src="https://image.shutterstock.com/image-vector/number-seven-symbol-neon-sign-260nw-1131532157.jpg" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Imran"){ ?>
<img src="https://i.pinimg.com/originals/68/8d/9a/688d9a7ef47b1084c8cc93c557e2b8ed.png" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Gowtham"){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/172690451_484734182710817_8004029811343064611_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=vtTmfy7d7eoAX8MSiiu&_nc_ht=scontent.fhyd1-4.fna&oh=99aec3978ed1c9f817c63bdda4c7915d&oe=609B0278" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['sender']=="Varun"){ ?>
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/46272044_683165832084398_7425190098989219840_n.jpg?_nc_cat=104&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=muqBKOpoe1QAX-L-RvD&_nc_ht=scontent.fhyd1-3.fna&oh=97e69e310519ec4fa2d89d6f6981c37f&oe=609C64E5" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php echo $rows['sender']; ?>
</td>
<td class="py-2">
<?php
if ($rows['receiver']=="Bharath"){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/p843x403/141396206_2493794024259654_6265087547529057040_n.jpg?_nc_cat=103&ccb=1-3&_nc_sid=730e14&_nc_ohc=-7YyLsPS8cEAX86poRA&_nc_ht=scontent.fhyd1-4.fna&tp=6&oh=9d9aded097af4a3e5e48412088527f0a&oe=6096749D" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Jaisimha"){ ?>
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/104331003_194077888575821_401002836288722534_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=HutkpDZD3qUAX-FBve8&edm=ABfd0MgAAAAA&ccb=7-4&oh=f47a4d288ffa9e43868c3e400760aefa&oe=6099F6A4&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Arshad"){ ?>
<img src="https://instagram.fhyd1-2.fna.fbcdn.net/v/t51.2885-19/s320x320/164419267_788753738718465_2230036935495910194_n.jpg?tp=1&_nc_ht=instagram.fhyd1-2.fna.fbcdn.net&_nc_ohc=x01wCArvgdkAX_ipJaN&edm=ABfd0MgAAAAA&ccb=7-4&oh=cd704a529a8bac88ee22bb5ad5f6a51c&oe=609C6EA1&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Tharun"){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/90985050_523347848594538_4485919209812918272_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=174925&_nc_ohc=LeF8IICz0W8AX_hcEF_&_nc_ht=scontent.fhyd1-4.fna&oh=5335f048a201ec754cf3a502066844af&oe=609A8018" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Ganesh"){ ?>
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/p843x403/170220245_1190771458015690_3601409687975844895_n.jpg?_nc_cat=109&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=F2WEQPZkDxcAX_y0a_H&_nc_ht=scontent.fhyd1-3.fna&tp=6&oh=7e35b1ebd46a3f5673b98aa77611f419&oe=609B3058" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Jagadesh"){ ?>
<img src="https://instagram.fvga2-1.fna.fbcdn.net/v/t51.2885-19/s320x320/67712818_1348616035294428_896999693521780736_n.jpg?tp=1&_nc_ht=instagram.fvga2-1.fna.fbcdn.net&_nc_ohc=W85yRIP32goAX8Wy6bN&edm=ABfd0MgAAAAA&ccb=7-4&oh=553772c66da443dc1df351b99ba6a749&oe=6099AA56&_nc_sid=7bff83" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Gokul"){ ?>
<img src="https://scontent.fhyd1-2.fna.fbcdn.net/v/t1.6435-9/74241445_2504303969801498_5151015051880038400_n.jpg?_nc_cat=108&ccb=1-3&_nc_sid=8bfeb9&_nc_ohc=JrFE1wiz8MEAX-56W2R&_nc_ht=scontent.fhyd1-2.fna&oh=3c8589b0ddd36a11b4ea5967c1c70099&oe=609C9B4E" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Imran"){ ?>
<img src="https://scontent.fvga2-1.fna.fbcdn.net/v/t31.18172-8/13147829_2011836462375323_4997514148478018788_o.jpg?_nc_cat=100&ccb=1-3&_nc_sid=174925&_nc_ohc=X8Vw7KPj5iwAX8vrBuB&_nc_ht=scontent.fvga2-1.fna&oh=9b6c186ad30e8a3e2c544a379654287f&oe=609CF4E6" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Gowtham"){ ?>
<img src="https://scontent.fhyd1-4.fna.fbcdn.net/v/t1.6435-9/172690451_484734182710817_8004029811343064611_n.jpg?_nc_cat=102&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=vtTmfy7d7eoAX8MSiiu&_nc_ht=scontent.fhyd1-4.fna&oh=99aec3978ed1c9f817c63bdda4c7915d&oe=609B0278" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php
if ($rows['receiver']=="Varun"){ ?>
<img src="https://scontent.fhyd1-3.fna.fbcdn.net/v/t1.6435-9/46272044_683165832084398_7425190098989219840_n.jpg?_nc_cat=104&ccb=1-3&_nc_sid=09cbfe&_nc_ohc=muqBKOpoe1QAX-L-RvD&_nc_ht=scontent.fhyd1-3.fna&oh=97e69e310519ec4fa2d89d6f6981c37f&oe=609C64E5" title="select" style="background-color:orange" class="img-thumbnail"/>
<?php }
?>
<?php echo $rows['receiver']; ?></td>
<td class="py-2"><?php echo $rows['amount']; ?> </td>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html> | 6d5b441a6ea9e8acf92cc1e9058f871eff68a9d5 | [
"PHP"
] | 3 | PHP | gowtham-nani/Basic-Bank-System | 611dc510278458f5dec34fa49d9a04f8a240cbf2 | 28c10d4bf53beee4f81b53f5da1f324fbf9f186f | |
refs/heads/master | <file_sep>package lock;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchTest {
@Test
public void testCountDownLatch() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(2);
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("request agreement service");
latch.countDown();
}).start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("request member service");
latch.countDown();
}).start();
latch.await();
System.out.println("merge response");
}
}
<file_sep>count from 1 to 1000000 by creating 10 threads
which class is the fastest, SynchronizedAccumulator, AtomicAccumulator or AtomicAdderAccumulator
find the testing result in AccumulatorTest
<file_sep>ThreadSafeCounter is a counter providing synchronized increase and decrease methods by using synchronized
ThreadSafeList is a container providing synchronized put and get methods by using ReentrantLock and Condition <file_sep>package interview.crossprint;
import org.junit.Test;
import java.util.Stack;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;
public class LockSupportTest {
private Thread oddThread = null;
private Thread evenThread = null;
@Test
public void testCrossPrint() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 20; i++) {
stack.push(20 - i);
}
oddThread = new Thread(() -> {
System.out.println("odd thread starts");
while (!stack.isEmpty()) {
System.out.println("odd thread prints " + stack.pop());
LockSupport.unpark(evenThread);
LockSupport.park();
}
}, "odd");
evenThread = new Thread(() -> {
System.out.println("even thread starts");
latch.countDown();
while (!stack.isEmpty()) {
LockSupport.park();
System.out.println("even thread prints " + stack.pop());
LockSupport.unpark(oddThread);
}
}, "even");
evenThread.start();
latch.await();
oddThread.start();
oddThread.join();
evenThread.join();
}
}
<file_sep>package reference;
/**
* @author eric
*/
public class ReferenceModel {
/**
* override finalize is not recommended, here just for test
*
* @throws Throwable
*/
@Override
protected void finalize() throws Throwable {
System.out.println(this.getClass().getName() + " is finalized");
}
}
<file_sep>package threadpool;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureTaskTest {
@Test
public void testFutureTask() throws ExecutionException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(1);
FutureTask<String> task = new FutureTask<>(() -> {
return "hello future task";
});
service.submit(task);
System.out.println(task.get());
service.shutdown();
}
}
<file_sep>package cas;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author eric
*/
public class AtomicAccumulator {
public static AtomicLong count = new AtomicLong(0);
public void increase(){
count.incrementAndGet();
}
}
<file_sep>This package is to show how volatile and synchronized block code work<file_sep>This package is to show how to create and start a thread<file_sep>package thread;
/**
* @author eric
*/
public class SleepThread extends Thread{
@Override
public void run() {
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("this is a sleep thread extending Thread");
}
}
<file_sep>package interview.crossprint;
import org.junit.Test;
import java.util.Stack;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.locks.LockSupport;
public class LinkedTransferQueueTest {
@Test
public void testCrossPrint() throws InterruptedException {
LinkedTransferQueue<Integer> queue = new LinkedTransferQueue<>();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 20; i++) {
stack.push(20 - i);
}
final Thread oddThread = new Thread(() -> {
System.out.println("odd thread starts");
while (!stack.isEmpty()) {
try {
System.out.println("odd thread prints " + queue.take());
queue.transfer(stack.pop());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "odd");
final Thread evenThread = new Thread(() -> {
System.out.println("even thread starts");
while (!stack.isEmpty()) {
try {
queue.transfer(stack.pop());
System.out.println("even thread prints " + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "even");
oddThread.start();
evenThread.start();
oddThread.join();
oddThread.join();
}
}
<file_sep>package threadpool;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureTest {
@Test
public void testCallable() throws ExecutionException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(1);
// callable
final Callable<Integer> integerCallable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 1;
}
};
final Future<Integer> integerFuture = service.submit(integerCallable);
// lambada
final Future<String> stringFuture = service.submit(() -> {
return "hello future";
});
System.out.println(integerFuture.get());
System.out.println(stringFuture.get());
service.shutdown();
}
}
| 2773b8885d46f6710bb65f36134e100277766b30 | [
"Markdown",
"Java"
] | 12 | Java | ericchen1127/juc | 9ab4ba58ef785de142663859734403e293fecac5 | 570bc8e49aed2e22c8cffbbca3df2b79e5b0518b | |
refs/heads/master | <repo_name>DMDWSK/SelfEvaluation<file_sep>/authentication/models.py
# from django.db import models
# from allactions import Departments
#
# # Create your models here.
# class Users(models.Model):
# class Meta:
# db_table = "Users"
#
# name = models.CharField(max_length=60, default=None)
# surname = models.CharField(max_length=60, default=None)
# role = models.ForeignKey('RolesModel', on_delete=models.DO_NOTHING)
# department = models.ManyToManyField()
<file_sep>/allactions/models.py
from django.db import models
class Departments(models.Model):
class Meta:
db_table = "Departments"
ordering = ['id']
department = models.CharField(max_length=20, default=None)
class Sections(models.Model):
class Meta:
db_table = "Sections"
ordering = ['id']
section = models.CharField(max_length=20, default=None)
class Stages(models.Model):
class Meta:
db_table = "Stages"
ordering = ['id']
section = models.ForeignKey(Sections, on_delete=models.CASCADE)
stage = models.CharField(max_length=40, default=None)
section = models.ForeignKey(Sections, on_delete=models.CASCADE)
class Questions(models.Model):
class Meta:
db_table = "Questions"
ordering = ['id']
question = models.TextField(max_length=255, default=None)
stage = models.ForeignKey(Stages, on_delete=models.CASCADE)
department = models.ManyToManyField(Departments)
hint = models.TextField(max_length=300, null=True, blank=True)
class Grades(models.Model):
class Meta:
db_table = "Grades"
ordering = ['id']
grade = models.CharField(max_length=60, default=None)
<file_sep>/answers/models.py
from django.db import models
from django.contrib.auth.models import User
class UserAnswers(models.Model):
class Meta:
db_table = "UserAnswers"
ordering = ['id']
user = models.ForeignKey(User, on_delete=models.CASCADE)
question = models.ForeignKey('allactions.Questions',on_delete=models.CASCADE)
answer = models.BooleanField(default=False)
grade = models.ForeignKey('allactions.Grades',on_delete=models.CASCADE)
<file_sep>/allactions/views.py
from django.shortcuts import render, redirect
from .models import Stages, Questions, Sections, Grades
from answers.models import UserAnswers
def enter(request):
return render(request, "enter.html")
def send(request, section_id):
i = 0
stages = Stages.objects.filter(section_id=section_id)
questions = Questions.objects.all()
sections = Sections.objects.all()
grades = Grades.objects.all()
context = {"sections": sections, "stages": stages, "questions": questions, "grades": grades}
if request.method == 'POST':
print(request.POST)
usr_grd = request.POST.getlist('select_box')
for g in usr_grd:
i += 1
choice = request.POST.get('choice-{}'.format(i), 'No')
answers = UserAnswers()
if choice == 'yes':
answers.answer = True
else:
answers.answer = False
answers.grade = Grades.objects.get(grade=g)
answers.question_id = i
answers.user_id = request.user.id
answers.save()
if section_id == len(sections):
return render(request,'finish.html')
return redirect('/{}'.format(section_id+1))
return render(request, 'main.html', context)
<file_sep>/allactions/migrations/0001_initial.py
# Generated by Django 2.1.5 on 2019-01-30 15:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Departments',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('department', models.CharField(default=None, max_length=20)),
],
options={
'db_table': 'Departments',
},
),
migrations.CreateModel(
name='Questions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question', models.TextField(default=None, max_length=255)),
],
options={
'db_table': 'Questions',
},
),
migrations.CreateModel(
name='Sections',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('section', models.CharField(default=None, max_length=20)),
],
options={
'db_table': 'Sections',
},
),
migrations.CreateModel(
name='Steps',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('step', models.CharField(default=None, max_length=20)),
('section', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='allactions.Sections')),
],
options={
'db_table': 'Steps',
},
),
migrations.AddField(
model_name='questions',
name='step',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='allactions.Steps'),
),
]
<file_sep>/database_python.py
#from . import models
import psycopg2
import datetime
def insert_table_ones(table, first_place, name):
""" insert a new vendor into the vendors table """
sql = """INSERT INTO "{}"({}) VALUES('{}');""".format(table, first_place, name)
conn = None
try:
# connect to the PostgreSQL database
conn = psycopg2.connect('dbname=formbase user=postgres password=<PASSWORD>')
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def insert_table_users(table, place1st, place2nd, place3th, place4th, dat1st, data2nd, data3th):
sql = """INSERT INTO "{}"({}, {}, {}, {}, {})
VALUES('{}', '{}', '{}', '{}');""".format(table, place1st, place2nd, place3th, place4th, dat1st, data2nd, data3th, datetime.date.today())
conn = None
try:
# connect to the PostgreSQL database
conn = psycopg2.connect('dbname=formbase user=postgres password=root')
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql)
# commit the changes to the databasecd
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def insert_table_usersdata(table, place1st, place2nd, place3th, place4th, place5th, dat1st, data2nd, data3th, data4th, data5th):
sql = """INSERT INTO "{}"({}, {}, {}, {}, {})
VALUES('{}', '{}', '{}', '{}', '{}');""".format(table, place1st, place2nd, place3th, place4th, place5th, dat1st, data2nd, data3th, data4th, data5th)
conn = None
try:
# connect to the PostgreSQL database
conn = psycopg2.connect('dbname=formbase user=postgres password=root')
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql)
# commit the changes to the databasecd
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def insert_from_file():
sql_que_tlt = """INSERT INTO "questions"(question, course_id, stage_id, tooltip) VALUES(%s, 1, %s, %s);"""
sql_stg = """INSERT INTO "stages"(stage, part) VALUES(%s, %s) RETURNING id;"""
sql_que = """INSERT INTO "questions"(question, course_id, stage_id) VALUES(%s, 1, %s);"""
conn = None
try:
conn = psycopg2.connect('dbname=formbase user=postgres password=<PASSWORD>')
cur = conn.cursor()
file = open('questions.txt', 'r')
flag = 'Skills'
flag_dict = {'Skills':'Activities', 'Activities':'Skills'}
stage_id = 0
for row in file:
row = row.replace('\n', '').replace("'", "''")
if row[0] is '#' and row[1] is '#':
flag = flag_dict[flag]
elif row[0] is '#':
cur.execute(sql_stg, (row[1:], flag))
conn.commit()
stage_id = cur.fetchone()[0]
else:
if flag is 'Activities':
if row[0] is not '*':
sql = row
continue
cur.execute(sql_que_tlt, (sql, stage_id, row[1:]))
conn.commit()
continue
cur.execute(sql_que, (row, stage_id))
conn.commit()
cur.close()
file.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
# insert_table_ones('courses', 'course', 'Python')
# insert_table_ones('courses', 'course', '.NET')
# insert_table_ones('courses', 'course', 'Java')
# insert_table_ones('roles', 'role', 'Admin')
# insert_table_ones('roles', 'role', 'User')
# insert_table_ones('roles', 'role', 'Expert')
# insert_table_ones('roles', 'role', 'Recruiter')
# insert_table_ones('grades', 'grade', 'None')
# insert_table_ones('grades', 'grade', 'Beginner')
# insert_table_ones('grades', 'grade', 'Good')
# insert_table_ones('grades', 'grade', 'Strong')
# insert_table_users('authentication', 'login', 'password', 'role_id', 'date', 'admin', 'admin', '1')
# insert_table_usersdata('usersdata', 'name', 'last', 'age', 'email', 'user_id', 'Andre', 'UA', 33, '<EMAIL>', 1)
insert_from_file()<file_sep>/roleaccess/migrations/0001_initial.py
# Generated by Django 2.1.5 on 2019-01-31 13:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Permissions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('permission', models.CharField(default=None, max_length=100)),
],
options={
'db_table': 'Permisisons',
},
),
migrations.CreateModel(
name='Roles',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('role', models.CharField(default=None, max_length=60)),
('permission', models.ManyToManyField(to='roleaccess.Permissions')),
],
options={
'db_table': 'Roles',
},
),
]
<file_sep>/allactions/migrations/0009_auto_20190202_1841.py
# Generated by Django 2.1.5 on 2019-02-02 16:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('allactions', '0008_auto_20190202_1836'),
]
operations = [
migrations.AlterField(
model_name='questions',
name='hint',
field=models.TextField(blank=True, default=None, max_length=300),
),
]
<file_sep>/allactions/migrations/0003_auto_20190131_1533.py
# Generated by Django 2.1.5 on 2019-01-31 13:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('allactions', '0002_grades'),
]
operations = [
migrations.RenameModel(
old_name='Steps',
new_name='Stages',
),
migrations.RenameField(
model_name='questions',
old_name='step',
new_name='stage',
),
migrations.RenameField(
model_name='stages',
old_name='step',
new_name='stage',
),
migrations.AddField(
model_name='sections',
name='department',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='allactions.Departments'),
preserve_default=False,
),
migrations.AlterModelTable(
name='stages',
table='Stages',
),
]
<file_sep>/roleaccess/models.py
from django.db import models
class Permissions(models.Model):
class Meta:
db_table = "Permisisons"
permission = models.CharField(max_length=100, default=None)
class Roles(models.Model):
class Meta:
db_table = "Roles"
role = models.CharField(max_length=60, default=None)
permission = models.ManyToManyField(Permissions)
<file_sep>/allactions/urls.py
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.enter),
path('<int:section_id>', views.send, name='section_page'),
]
<file_sep>/allactions/migrations/0007_auto_20190201_1834.py
# Generated by Django 2.1.5 on 2019-02-01 16:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('allactions', '0006_auto_20190201_1651'),
]
operations = [
migrations.AlterField(
model_name='stages',
name='stage',
field=models.CharField(default=None, max_length=40),
),
]
<file_sep>/allactions/migrations/0011_auto_20190208_1549.py
# Generated by Django 2.1.5 on 2019-02-08 13:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('allactions', '0010_auto_20190202_1848'),
]
operations = [
migrations.AlterModelOptions(
name='departments',
options={'ordering': ['id']},
),
migrations.AlterModelOptions(
name='grades',
options={'ordering': ['id']},
),
migrations.AlterModelOptions(
name='questions',
options={'ordering': ['id']},
),
migrations.AlterModelOptions(
name='sections',
options={'ordering': ['id']},
),
migrations.AlterModelOptions(
name='stages',
options={'ordering': ['id']},
),
]
| 9cadd48be092beb6fe68137736c63df8f91220eb | [
"Python"
] | 13 | Python | DMDWSK/SelfEvaluation | b0feb33578cef64a96a8a14b5da18fe06d78dabc | 927512bc9464adc37483c16f7344d2342251b8db | |
refs/heads/master | <file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/2/27 15:32
"""
class Queue:
def __init__(self):
self.list = []
def enqueue(self, item):
self.list.insert(0, item)
def dequeue(self):
if self.list:
return self.list.pop()
return None
def isEmpty(self):
return len(self.list) == 0
def size(self):
return len(self.list)
def hotPotato(namelist, num):
"""
烫手山芋问题
:param namelist:
:param num: 传递次数
:return:
"""
queue = Queue()
for name in namelist:
queue.enqueue(name)
while queue.size() > 1:
for i in range(num):
queue.enqueue(queue.dequeue())
queue.dequeue()
return queue.dequeue()
if __name__ == "__main__":
queue = Queue()
print(queue.isEmpty())
[queue.enqueue(i) for i in range(10)]
print(queue.isEmpty())
print(queue.list)
print(queue.dequeue())
print(queue.dequeue())
print(queue.size())
print(queue.list)
print(hotPotato(["Bill", "David", "Susan", "Jane", "Kent", "Brad"], 7))<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/3/1 15:58
"""
# 单例模式
class Single(object):
def __new__(cls):
if not hasattr(cls, "_instance"):
cls._instance = super(Single, cls).__new__(cls)
return cls._instance
obj1 = Single()
obj2 = Single()
obj1.attr1 = 'value1'
print(obj1.attr1, obj2.attr1)
print(obj1 is obj2)
# 共享属性
class Borg(object):
_state = {}
def __new__(cls):
ob = super(Borg, cls).__new__(cls)
ob.__dict__ = cls._state
return ob
<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/2/27 16:45
"""
class Node(object):
def __init__(self, data=None):
self.data = data
self.next = None
def set_data(self, item):
self.data = item
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class UnorderedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
def add_order(self, item):
"""
有序链表添加
:param item:
:return:
"""
current = self.head
pre = None
state = False
while not state:
if item <= current.get_data() and pre is None:
state = True
if item < current.get_data():
state = True
else:
pre = current
current = current.get_next()
temp = Node(item)
temp.set_next(current)
pre.set_next(temp)
def get(self, index):
# 支持负数
index = index if index >= 0 else len(self) + index
if index < 0 or len(self) < index:
return None
pre = self.head
while index:
pre = pre.next
index -= 1
return pre
def set(self, index, data):
node = self.get(index)
if node:
node.set_data(data)
return node
def insert(self, index, data):
"""
1.index 插入节点位置包括正负数
2.找到index-1-->pre_node的节点
3.pre_node.next-->node
node.next-->pre_node.next.next
4.head
:param index:
:param data:
:return:
"""
new_node = Node(data)
if abs(index + 1) > len(self):
return False
index = index if index >= 0 else len(self) + index + 1
if index == 0:
new_node.set_next(self.head)
self.head = new_node
else:
pre_node = self.get(index-1)
after_node = self.get(index)
pre_node.set_next(new_node)
new_node.set_next(after_node)
return new_node
def remove(self, item):
current = self.head
pre = None
state = False
while not state:
if item == current.get_data():
state = True
else:
pre = current
current = current.get_next()
if pre is None:
self.head = current.get_next()
else:
pre.set_next(current.get_next())
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.get_data() == item:
found = True
else:
current = current.get_next()
return found
def __reversed__(self):
"""
1.pre-->next 转变为 next-->pre
2.pre 若是head 则把 pre.nex --> None
3.tail-->self.head
:return:
"""
def reverse(pre_node, node):
if pre_node is self.head:
pre_node.set_next(None)
if node:
next_node = node.get_next()
node.set_next(pre_node)
return reverse(node, next_node)
else:
self.head = pre_node
return reverse(self.head, self.head.get_next())
def __len__(self):
pre = self.head
length = 0
while pre:
length += 1
pre = pre.next
return length
def __str__(self):
pre = self.head
list_all = []
while pre:
list_all.append(pre.get_data())
pre = pre.next
return str(list_all)
if __name__ == "__main__":
single_link_list = UnorderedList()
single_link_list.add(78)
single_link_list.add(88)
single_link_list.add(68)
single_link_list.add(58)
single_link_list.add(38)
print(len(single_link_list))
print(single_link_list.search(78))
single_link_list.remove(88)
print(single_link_list)
print("set index = 1 -- data = 99")
single_link_list.set(1, 99)
print("get value index = 1")
print(single_link_list.get(1).get_data())
print(single_link_list)
single_link_list.insert(1, 55)
print("insert index = 1 -- data = 55")
print(single_link_list)
single_link_list.__reversed__()
print(single_link_list)
<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/2/27 16:20
"""
class Deque:
def __init__(self):
self.list = []
def isEmpty(self):
return self.list == []
def size(self):
return len(self.list)
def add_front(self, item):
self.list.append(item)
def add_rear(self, item):
self.list.insert(0, item)
def remove_front(self):
return self.list.pop()
def remove_rear(self):
return self.list.pop(0)
def palindrome(string):
"""
判断是否回文
:param string: 待判断字符串
:return:
"""
deque = Deque()
state = True
for i in string:
deque.add_front(i)
while deque.size() > 1 and state:
top = deque.remove_front()
end = deque.remove_rear()
if top != end:
state = False
return state
if __name__ == "__main__":
print(palindrome("123456654321"))
<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/2/27 14:16
"""
class Stack:
def __init__(self):
self.list = []
def isEmpty(self):
return len(self.list) == 0
def push(self, item):
self.list.append(item)
def pop(self):
if self.list:
return self.list.pop()
return None
def peek(self):
if self.list:
return self.list[-1]
return None
def size(self):
return len(self.list)
def par_check(string):
"""
符号匹配 如:{{([][])}()}}
:param string:
:return:
"""
s = Stack()
state = True
index = 0
swtich = {
"{": "}",
"(": ")",
"[": "]"
}
while index < len(string) and state:
if string[index] in "{([":
s.push(string[index])
else:
if s.isEmpty():
state = False
else:
if swtich[s.pop()] != string[index]:
state = False
index = index + 1
if state and s.isEmpty():
return True
else:
return False
if __name__ == "__main__":
stack = Stack()
print(stack.isEmpty())
[stack.push(i) for i in range(10)]
print(stack.list)
print(stack.isEmpty())
print(stack.peek())
print(stack.pop())
print(stack.peek())
print(stack.size())
print(par_check("{{([][])}()}}"))
<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/2/27 9:50
"""
class SortedDict(dict):
def __init__(self):
self.list = []
super(SortedDict, self).__init__()
def __setitem__(self, key, value):
self.list.append(key)
super(SortedDict, self).__setitem__(key, value)
def __getitem__(self, key):
if key not in self.list:
raise KeyError('dict has not key: %s' % key)
return self.get(key)
def __delitem__(self, key):
if key not in self.list:
raise KeyError('dict has not key: %s' % key)
self.list.remove(key)
self.pop(key)
def popitem(self, tail=True):
"""
:param tail: True 最后一个元素 False 第一个元素
:return:
"""
if not self.list:
raise KeyError('dict is empty')
if tail:
del self.list[-1]
return self.get(self.list[-1])
else:
del self.list[0]
return self.get(self.list[0])
def __iter__(self):
return iter(self.list)
def __str__(self):
temp_list = []
for key in self.list:
value = self.get(key)
temp_list.append("'%s':%s" % (key, value,))
temp_str = '{' + ','.join(temp_list) + '}'
return temp_str
if __name__ == "__main__":
obj = SortedDict()
obj["test"] = "test"
obj["test1"] = "test1"
obj["test2"] = "test2"
obj["test3"] = "test3"
for key in obj:
print(key)
print("test")
del obj["test2"]
print(obj)
obj.popitem()
print(obj)
<file_sep>#!/usr/bin/env python
# encoding: utf-8
"""
@author: leason
@time: 2018/3/2 16:41
"""
# 斐波那契
# 只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
def memo(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
@memo
def fib(i):
if i < 2:
return 1
return fib(i - 1) + fib(i - 2)
| e22f8b76e186e0038d414fd1c344453fc981d90f | [
"Python"
] | 7 | Python | leason00/learning-by-python | 5aa999a00950a4650e0e8d3a12266b24f5014a3c | 4b41dbd639efc36cc5b975f64cb1ac455e3012a9 | |
refs/heads/master | <file_sep>FROM golang:1.9-stretch
WORKDIR /go/src/github.com/JumboInteractiveLimited/Gandalf
RUN echo "Pulling go dependencies" \
&& go get -v -u \
github.com/fatih/color \
github.com/NodePrime/jsonpath \
github.com/jmartin82/mmock \
github.com/tidwall/gjson
COPY . .
RUN echo "Testing gandalf" \
&& go test -v -cover -short github.com/JumboInteractiveLimited/Gandalf/...
<file_sep>package gandalf
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
)
func ExampleToMMock() {
_ = &Contract{
Name: "MMockContract",
Export: &ToMMock{
Scenario: "happy_path",
TriggerStates: []string{"not_started"},
NewState: "started",
ChaoticEvil: true,
},
}
// Output:
}
func getMMockContract() *Contract {
body := `{"test_url":"https://example.com"}`
return &Contract{
Name: "MMockContract",
Request: &DummyRequester{
&http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: ioutil.NopCloser(bytes.NewBufferString(body)),
ContentLength: int64(len(body)),
Request: &http.Request{},
Header: http.Header{
"Content-Type": []string{"application/json; charset=utf-8"},
},
},
},
Check: &DummyChecker{},
Export: &ToMMock{
Scenario: "thing",
TriggerStates: []string{"not_started"},
NewState: "started",
},
}
}
func TestMMockExporter(t *testing.T) {
getMMockContract().Assert(t)
}
func BenchmarkMMockContracts(b *testing.B) {
if testing.Short() {
b.Skipf("MMock saving to file system is slow and therefore skipped in short mode.")
}
for n := 0; n < b.N; n++ {
getMMockContract().Assert(b)
}
}
| 54c67f9413eed767182fb1190f847cf9d3f47926 | [
"Go",
"Dockerfile"
] | 2 | Dockerfile | HeatherBoard/Gandalf | f3d3da269247a8b28f0d60676b6d7864041319d8 | f231aad5622ee88724a0298dc898091789c37626 | |
refs/heads/master | <file_sep><?php
use App\User;
use App\Address;
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/user/{id}/in_address/',function($id){
$user = User::findOrFail($id);
//$address = new Address(['name'=>'4464 Sapphire Dr, Frisco, TX']);
$address = new Address(['name'=>'44 Legacy, Frisco, TX']);
// address() is call function in User model
if($user->address()->save($address)){
return 'Insert successfully';
}
return 'Insert failed';
});
Route::get('/user/{id}/up_address',function($id){
//used first() to return object of address
// u can use many different way to query where like below
//$address = Address::where('user_id',$id)->first();
//$address = Address::where('user_id','=',$id)->first();
$address = Address::whereUserId($id)->first();
$address->name = "Update address to ABC Dallas, TX";
$address->update();
});
Route::get('/user/{id}/address',function($id){
return User::findOrFail($id)->address->name;
});
Route::get('/user/{id}/del_address',function($id){
$user = User::findOrFail($id);
if($user->address->delete()){
return 'Delete successfully';
}
return 'Delete failed';
}); | 3ebcaa9e825e76e091b4d23f4fda2b48a45cd482 | [
"PHP"
] | 1 | PHP | mengkongly/lar_one2one | 607a08417e1367ca13b69688624adbd4ce217299 | 179d1a1538c40750a6bed23c67d8098ca8db7cf2 | |
refs/heads/master | <file_sep># -*- coding:utf-8 -*-
import subprocess as sp
import json
import os
import requests
import urllib
import time
import logging
import datetime
class Connector():
def __init__(self):
now = int(time.time())
timeArray = time.localtime(now)
_time = time.strftime("%Y-%m-%d-%H-%M-%S", timeArray)
self.logfile = 'log_' + _time + '.log'
self.config()
self.set_logger()
def set_logger(self):
self.logger = logging.getLogger()
self.logger.setLevel(level=logging.INFO)
handler = logging.FileHandler(self.log_folder + self.logfile, encoding='utf-8')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
self.logger.addHandler(handler)
self.logger.addHandler(console)
def is_connected(self):
result = os.system('ping ' + self.ping_ip)
if result == 0:
return True
else:
return False
def config(self):
conf = open('conf.conf', 'r')
s = conf.read()
s = s.replace('\n', '')
s = s.replace('\t', '')
data = json.loads(s)
conf.close()
connect_info = data['connect']
self.headers = connect_info['header']
self.login_url = connect_info['url']
self.send = connect_info['data-send']
self.send['DDDDD'] = data['user']
self.send['upass'] = data['pwd']
self.ping_ip = connect_info['ip-ping']
self.retry_connected = connect_info['retry']['connected']
self.retry_disconnected = connect_info['retry']['disconnected']
self.log_folder = './log/'
if not os.path.exists(self.log_folder):
os.makedirs(self.log_folder)
with open(self.log_folder + self.logfile,'w') as f:
f.write(self.logfile+'\n')
def connect(self):
requests.packages.urllib3.disable_warnings()
session = requests.session()
r = session.post(self.login_url, headers=self.headers, data=self.send, verify=False)
# print(r.text)
def run(self):
while True:
try:
if self.is_connected():
self.logger.info('Connected')
time.sleep(60 * self.retry_connected)
else:
self.logger.warning('Disconnected')
self.connect()
if self.is_connected():
self.logger.warning('Connection repaired')
time.sleep(60 * self.retry_connected)
else:
self.logger.warning('Connection not repaired')
time.sleep(60 * self.retry_disconnected)
except Exception as e:
self.logger.error('Unkown error, detail infomation: ' + str(e))
time.sleep(60 * self.retry_disconnected)
<file_sep>from core.connector import Connector
if __name__ == "__main__":
connection = Connector()
connection.run()<file_sep>## Auto Connect
这是一个神奇的python脚本,可以维持你的设备与SZU网络的连接(仅限办公区域)
## 用法
### 配置 conf.conf 文件
* `user`: "你的账号" (保留引号)
* `pwd`: "<PASSWORD>" (保留引号)
* `retry: connected`: 连接成功后下次尝试间隔,单位:分钟,默认: 10
* `retry: disconnected`: 连接失败后下次尝试间隔,单位:分钟,默认: 5
### 运行
* python >= 2.7
* SZU内网环境
* 正确的账号密码(填入conf.conf)和未欠费的套餐
执行命令
```
python main.py
```
### 测试
* 手动断开网络连接
* 运行脚本
* 查看对应./log下的日志文件,出现以下类似信息表示网络连接已经修复
```
2021-01-25 20:51:21,988 - WARNING - Disconnected
2021-01-25 20:51:25,502 - WARNING - Connection repaired
```
* 如果有任何问题,请留下你的issue
### 保持脚本常驻
* 设置BIOS来电自启动
* Windows 设置计划任务
* Linux & Mac 设置脚本自启动
## 申明
* 禁止用此脚本干扰他人正常上网
* 本脚本使用构造POST表单完成上网请求,完全安全可信
* 本脚本导致上网账号被封禁概不负责
* conf.conf 明文密码可能导致您的账号密码泄露 | ec1f219e0339fa5e342c09cda33a37978f7e6b70 | [
"Markdown",
"Python"
] | 3 | Python | JackWHQ/AutoConnect | 7e4aa4a20359fb518257b883a4bcbcabfe3d0226 | daf536313567158bce0685fe1b2cd238d85ef525 | |
refs/heads/master | <file_sep><?php
include 'config.php';
include 'user.php';
$response=array();
$user = new User($pdo);
$list = $user->check_login_details($_POST["email"],$_POST["password"]);
if($list)
{
$response['success']=$list;
$response['msg']="Valid user";
}
else
{
$response['success']=0;
$response['msg']="invalid user";
}
echo json_encode($response);
?><file_sep><?php
class User {
/* Properties */
private $conn;
/* Get database access */
public function __construct(\PDO $pdo) {
$this->conn = $pdo;
}
/* List all users */
public function get_users() {
$stm = $this->conn->prepare("SELECT username, password FROM users");
$stm->execute();
return $data = $stm->fetchAll();
}
public function get_user_details() {
$stm = $this->conn->prepare("SELECT * FROM users");
$stm->execute();
return $data = $stm->fetchAll();
}
public function getUserDropdownDetails() {
$stm = $this->conn->prepare("SELECT username,id FROM users WHERE id!=1");
$stm->execute();
return $data = $stm->fetchAll();
}
public function check_login_details($email,$password) {
$stm = $this->conn->prepare("SELECT id FROM users WHERE email=:email AND password=:password ");
$stm->execute(['email'=>$email,'password'=>$password]);
return $data = $stm->fetchAll();
}
public function save_user_details($username,$password,$mobile,$email,$address) {
$stm = $this->conn->prepare("INSERT INTO users (username,password,mobile,email,address) VALUES ( :username, :password, :mobile, :email, :address)");
$data=$stm->execute([':username'=>$username,':password'=>$password,':mobile'=>$mobile,':email'=>$email,':address'=>$address]);
return $data;
}
public function save_logistics_details($user_id,$unitcost,$quantity,$total) {
$stm = $this->conn->prepare("INSERT INTO logistics_details (user_id,unitcost,qunatity,total_amount) VALUES ( :user_id, :unitcost, :quantity, :total_amount)");
$data=$stm->execute([':user_id'=>$user_id,':unitcost'=>$unitcost,':quantity'=>$quantity,':total_amount'=>$total]);
return $data;
}
public function save_update_logistics_details($user_id,$unitcost,$quantity,$total,$id) {
$stm = $this->conn->prepare("UPDATE logistics_details SET user_id = :user_id,unitcost = :unitcost,qunatity = :qunatity,total_amount = :total_amount WHERE id = :id");
$data=$stm->execute([':user_id'=>$user_id,':unitcost'=>$unitcost,':qunatity'=>$quantity,':total_amount'=>$total,':id'=>$id]);
return $data;
}
public function get_logistics_info_details($user_id) {
$stm = $this->conn->prepare("SELECT ld.*,u.username,u.is_allowed FROM logistics_details AS ld LEFT JOIN users AS u ON ld.user_id=u.id WHERE ld.user_id=$user_id");
$stm->execute();
return $data = $stm->fetchAll();
}
public function get_all_logistics_info_details() {
$stm = $this->conn->prepare("SELECT ld.*,u.username,u.is_allowed FROM logistics_details AS ld LEFT JOIN users AS u ON ld.user_id=u.id");
$stm->execute();
return $data = $stm->fetchAll();
}
public function get_logistics_info_based_on_id($id) {
$stm = $this->conn->prepare("SELECT ld.*,u.username,u.is_allowed FROM logistics_details AS ld LEFT JOIN users AS u ON ld.user_id=u.id WHERE ld.id=$id");
$stm->execute();
return $data = $stm->fetchAll();
}
public function update_allow_status($id,$is_allowed) {
$stm = $this->conn->prepare("UPDATE users SET is_allowed = :is_allowed WHERE id = :id");
$data=$stm->execute([':is_allowed'=>$is_allowed,':id'=>$id]);
return $data;
}
public function delete_logistics_details($id) {
$stm = $this->conn->prepare("DELETE FROM logistics_details WHERE id = :id");
$data=$stm->execute([':id'=>$id]);
return $data;
}
}
?><file_sep><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 40%;
border-radius: 50%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
}
</style>
<script>
$(document).ready(function(){
$(".login_details").click(function(){
var email= $("#email").val().trim();
var password= $("#password").val().trim();
email_length=email.length
password_length=password.length
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
valid_email= emailReg.test(email);
if(valid_email==false){
alert("Please enter valid email id")
$("#email").val("")
return
}
if(email=="" || email_length==0){
alert("Please enter email id")
$("#email").val("")
return
}
if(password== "" || password_length==0)
{
alert("please enter Password")
return false
}
$.ajax({
url: 'login.php',
type: 'post',
data: "email=" + email + "&password="+ password,
success: function(response){
response = JSON.parse(response);
if(response.success!=0 || response.success!="")
{
$.cookie("user_id", response.success[0].id);
if(response.success[0].id==1)
{
window.location.href="dashboard.php";
}else{
window.location.href="getLogisticInfoBasedOnUser.php";
}
}else{
alert("Invalid email and password")
location.reload()
}
}
});
});
$(".signup").click(function(){
window.location.href="add_users_details.php";
});
});
</script>
</head>
<body>
<div class="imgcontainer">
<h4>Login Form</h4>
</div>
<div class="container">
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter email" id="email" required>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="password" required>
<p> </p>
<button type="button" class="btn btn-success login_details">Login</button>
<button type="button" class="btn btn-primary signup">Sign up</button>
</div>
</body>
</html><file_sep><?php
include 'config.php';
include 'user.php';
$response=array();
$user = new User($pdo);
$is_save = $user->save_user_details($_POST["username"],$_POST["password"],$_POST["mobile"],$_POST["email"],$_POST["address"]);
if($is_save)
{
$response['success']=1;
$response['msg']="User details saved successfully";
}
else
{
$response['success']=0;
$response['msg']="Failed to saved user details";
}
echo json_encode($response);
?><file_sep><?php
include 'config.php';
include 'user.php';
$response=array();
$user = new User($pdo);
$list = $user->getUserDropdownDetails();
echo json_encode($list);
?><file_sep>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$(document).ready(function(){
user_id= $.cookie("user_id");
if(user_id===undefined)
{
window.location.href="index.php";
}
$.ajax({
url: 'get_logistics_info_details.php',
type: 'post',
data:'user_id='+user_id,
success: function(response){
response = JSON.parse(response);
total_data=response.length
var row="";
var allowed="";
is_allowed=response[0].is_allowed;
if(is_allowed==1)
{
allowed=allowed+'<a href="add_logistics_details.php?is_user=1" class="btn btn-primary pull-right">Add Logistic</a>';
}else if(is_allowed==0){
allowed=allowed+'<a href="" class="btn btn-primary pull-right" onclick="abc()">Not Alloed to Add Logistic</a>';
}
for(i=0;i<total_data;i++){
j=i+1;
row=row+'<tr><td>'+j+'</td><td>'+response[i].username+'</td><td>'+response[i].unitcost+'</td><td>'+response[i].qunatity+'</td><td>'+response[i].total_amount+'</td><td><input type="button" onclick="update_logistics('+response[i].id+')" style="background-color:lightgreen" value="update"></td><td><input type="button" onclick="delete_logistics('+response[i].id+')" style="background-color:red" value="Delete"></td></tr>';
}
$(".logistics_details").html(row);
$(".allowed").html(allowed);
}
});
$(".logout").click(function(){
$.removeCookie('user_id');
window.location.href="index.php";
});
});
</script>
<script>
function abc()
{
alert("Admin is not given permission to add logistics")
}
function update_logistics(id)
{
window.location.href="update_logistics_info.php?id="+id;
}
function delete_logistics(id)
{
var is_delete=confirm("Do you want to delete logistics info")
if(is_delete)
{
$.ajax({
url: 'delete_logistics_details.php',
type: 'post',
data: "id=" + id,
success: function(response){
alert("logistics details deleted successfully")
location.reload();
}
});
}
}
</script>
</head>
<body>
<div class="container">
<p> </p>
<div class="pull-right">
<button class="btn btn-danger logout" href="">Log Out</button>
</div>
<p> </p>
<h2>Logistics Details</h2>
<a class="allowed"></a>
<p> </p>
<table class="table">
<thead>
<tr>
<th>Sno.</th>
<th>User Name</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Total</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody class="logistics_details">
</tbody>
</table>
</div>
</body>
</html>
<?php
?><file_sep><?php
$a=array(1,2,3,4,5,6,9);
print_r($a);
echo "Hello";
$a=array(1,2,3,4,5,6,9);
print_r($a);
echo "Hello";
$a=array(1,2,3,4,5,6,9);
print_r($a);
echo "Hello";
$a=array(1,2,3,4,5,6,9);
print_r($a);
echo "Hello";
$a=array(1,2,3,4,5,6,9);
print_r($a);
echo "Hello";
$a=array(1,2,3,4,5,6,9);
print_r($a);
echo "Hello";
?>
<file_sep><?php
include 'config.php';
include 'user.php';
$response=array();
$user = new User($pdo);
$list = $user->delete_logistics_details($_POST["id"]);
if($list)
{
$response['success']=1;
$response['msg']="updated";
}
else
{
$response['success']=0;
$response['msg']="Failed to update";
}
echo json_encode($response);
?><file_sep>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$(document).ready(function(){
user_id=$.cookie("user_id");
if(user_id===undefined)
{
window.location.href="index.php";
}
$.ajax({
url: 'get_user_details.php',
type: 'post',
success: function(response){
response = JSON.parse(response);
total_data=response.length
var row="";
for(i=0;i<total_data;i++){
j=i+1;
row=row+'<tr><td>'+j+'</td><td>'+response[i].username+'</td><td>'+response[i].mobile+'</td><td>'+response[i].email+'</td><td>'+response[i].address+'</td>';
if(response[i].is_allowed==1)
{
row=row+'<td><input type="button" onclick="is_allowed('+response[i].id+','+response[i].is_allowed+')" value="Allowed"> </td>';
}else if(response[i].is_allowed==0)
{
row=row+'<td><input type="button" onclick="is_allowed('+response[i].id+','+response[i].is_allowed+')" value="Not Allowed"> </td>'
}
row=row+'</tr>';
}
$(".user_details").html(row)
}
});
$(".logout").click(function(){
$.removeCookie('user_id');
window.location.href="index.php";
});
});
</script>
<script>
function is_allowed(id, allowed_status)
{
var is_allowed=0
if(allowed_status==1)
{
is_allowed=0;
}else if(allowed_status==0){
is_allowed=1;
}
var status_confirm=confirm("Do you want to revoked access ?")
if(status_confirm)
{
$.ajax({
url: 'update_allow_status.php',
type: 'post',
data: "id=" + id + "&is_allowed=" + is_allowed,
success: function(response){
if(response.success!=0 || response.success!="")
{
if(is_allowed==1)
{
alert("Access allowed")
}else if(is_allowed==0){
alert("Access has been revoked")
}
location.reload();
}else{
alert("Failed to allowed Access")
location.reload()
}
}
});
}else{
location.reload();
}
}
</script>
</head>
<body>
<div class="container">
<p> </p>
<div class="pull-right">
<button class="btn btn-danger logout" href="">Log Out</button>
</div>
<p> </p>
<h2>User Details</h2>
<a href="get_all_logistics_details.php" class="btn btn-primary pull-center">View Logistic Details</a>
<a href="add_logistics_details.php" class="btn btn-primary pull-right">Add Logistic</a>
<p> </p>
<table class="table">
<thead>
<tr>
<th>Sno.</th>
<th>User Name</th>
<th>Mobile</th>
<th>Email</th>
<th>Address</th>
<th>Is Allowed</th>
</tr>
</thead>
<tbody class="user_details">
</tbody>
</table>
</div>
</body>
</html>
<?php
?><file_sep><?php
include 'config.php';
include 'user.php';
$response=array();
$user = new User($pdo);
$is_save = $user->save_update_logistics_details($_POST["user_id"],$_POST["unitcost"],$_POST["quantity"],$_POST["total"],$_POST["id"]);
if($is_save)
{
$response['success']=1;
$response['msg']="User details saved successfully";
}
else
{
$response['success']=0;
$response['msg']="Failed to saved user details";
}
echo json_encode($response);
?> | 25f555805678f1f29eb61e1c4b9a3de13b75eb3f | [
"PHP"
] | 10 | PHP | sandeepbalpande/AjaxProject | 093e271ffd40668719e2ba4bb8ba0310aff72fd8 | ea11bebe43690cc4adecfa89d916e3a6f1da6874 | |
refs/heads/master | <repo_name>caixin/video<file_sep>/database/migrations/2019_12_03_065041_create_user_share_log_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserShareLogTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'user_share_log';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->integer('uid')->default(0)->comment('分享者ID');
$table->string('ip', 50)->default('')->comment('登入IP');
$table->json('ip_info')->comment('IP資訊');
$table->text('ua')->comment('User Agent');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->index('uid');
$table->index('created_at');
});
DB::statement("ALTER TABLE `$tableName` comment '分享連接LOG'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_share_log');
}
}
<file_sep>/app/Http/Controllers/Video/VideoController.php
<?php
namespace App\Http\Controllers\Video;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Video\VideoService;
class VideoController extends Controller
{
protected $videoService;
public function __construct(VideoService $videoService)
{
$this->videoService = $videoService;
}
public function index(Request $request)
{
return view('video.index', $this->videoService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'video'));
}
public function save(Request $request, $id)
{
$this->videoService->save($request->post(), $id);
return 'done';
}
}
<file_sep>/app/Models/System/DomainSetting.php
<?php
namespace Models\System;
use Models\Model;
class DomainSetting extends Model
{
protected $table = 'domain_setting';
protected $fillable = [
'domain',
'title',
'keyword',
'description',
'baidu',
];
}
<file_sep>/app/Services/Pmtools/DailyAnalysisService.php
<?php
namespace App\Services\Pmtools;
use App\Repositories\Pmtools\DailyAnalysisRepository;
class DailyAnalysisService
{
protected $dailyAnalysisRepository;
public function __construct(DailyAnalysisRepository $dailyAnalysisRepository)
{
$this->dailyAnalysisRepository = $dailyAnalysisRepository;
}
public function list($input)
{
$search_params = param_process($input, ['date', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['type'] = $search['type'] ?? 1;
$search['date1'] = $search['date1'] ?? date('Y-m-d', time()-86400*30);
$search['date2'] = $search['date2'] ?? date('Y-m-d', time()-86400);
//預設值
$table = $chart = [];
for ($i=strtotime($search['date1']);$i<=strtotime($search['date2']);$i+=86400) {
$table[$i] = 0;
}
$result = $this->dailyAnalysisRepository
->select(['date','count'])
->search($search)
->order($order)
->result();
foreach ($result as $key => $row) {
$table[strtotime($row['date'])] = $row['count'];
}
foreach ($table as $key => $val) {
$chart[] = [date('Y-m-d', $key),(int)$val];
}
krsort($table);
return [
'table' => $table,
'chart' => $chart,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/app/Services/Video/VideoService.php
<?php
namespace App\Services\Video;
use App\Repositories\Video\VideoRepository;
class VideoService
{
protected $videoRepository;
public function __construct(VideoRepository $videoRepository)
{
$this->videoRepository = $videoRepository;
}
public function list($input)
{
$search_params = param_process($input, ['publish', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['status'] = $search['status'] ?? 1;
$result = $this->videoRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function getList($request)
{
$per_page = $request->per_page ?: 10;
$search['status'] = 1;
if ($request->search) {
$search['name'] = $request->search;
}
if ($request->tags) {
$search['tags'] = $request->tags;
}
$result = $this->videoRepository->search($search)
->order(['publish'=>'desc','keyword'=>'desc'])
->paginate($per_page)
->result();
$list = [];
foreach ($result as $row) {
$list[] = [
'keyword' => $row['keyword'],
'name' => $row['name'],
'publish' => $row['publish'],
'actors' => $row['actors'],
'tags' => $row['tags'],
'pic_big' => $row['pic_b'],
'pic_small' => $row['pic_s'],
];
}
return [
'list' => $list,
'total' => $result->total(),
];
}
}
<file_sep>/app/Http/Middleware/ForceJson.php
<?php
namespace App\Http\Middleware;
use Closure;
class ForceJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->shouldChangeAccept($request)) {
$request->headers->set('Accept', 'application/json');
}
return $next($request);
}
private function shouldChangeAccept($request)
{
$accepts = $request->headers->get('Accept');
if (empty($accepts) === true) {
return true;
}
return preg_match('/\*\/\*|\*|text\/html/', $accepts) === 1;
}
}
<file_sep>/app/Services/User/UserMoneyLogService.php
<?php
namespace App\Services\User;
use App\Repositories\User\UserMoneyLogRepository;
class UserMoneyLogService
{
protected $userMoneyLogRepository;
public function __construct(UserMoneyLogRepository $userMoneyLogRepository)
{
$this->userMoneyLogRepository = $userMoneyLogRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->userMoneyLogRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/app/Repositories/System/Ip2locationRepository.php
<?php
namespace App\Repositories\System;
use App\Repositories\AbstractRepository;
use Models\System\Ip2location;
class Ip2locationRepository extends AbstractRepository
{
public function __construct(Ip2location $entity)
{
parent::__construct($entity);
}
public function _do_search()
{
if (isset($this->_search['ip_from'])) {
$this->db = $this->db->where('ip_from', '<=', $this->_search['ip_from']);
}
if (isset($this->_search['ip_to'])) {
$this->db = $this->db->where('ip_to', '>=', $this->_search['ip_to']);
}
return $this;
}
/**
* 取得IP位置資訊
* @param string $ip IP位址
* @return array IP資訊
*/
public function getIpData($ip)
{
return $this->search(['ip_from'=>ip2long($ip)])
->order(['ip_from','desc'])
->result_one();
}
}
<file_sep>/app/Http/Requests/Admin/AdminForm.php
<?php
namespace App\Http\Requests\Admin;
use App\Http\Requests\FormRequest;
use Illuminate\Validation\Rule;
final class AdminForm extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
switch ($this->method()) {
case 'GET':
case 'DELETE':
{
return [];
}
case 'POST':
{
return [
'username' => ['required',Rule::unique('admin')->ignore($this->route('admin'))],
'password' => '<PASSWORD>',
'roleid' => 'required',
];
}
case 'PUT':
case 'PATCH':
{
return [
'username' => ['required',Rule::unique('admin')->ignore($this->route('admin'))],
'roleid' => 'required',
];
}
default: break;
}
}
}
<file_sep>/app/Services/System/MessageService.php
<?php
namespace App\Services\System;
use App\Repositories\System\MessageRepository;
class MessageService
{
protected $messageRepository;
public function __construct(MessageRepository $messageRepository)
{
$this->messageRepository = $messageRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['created_at1'] = $search['created_at1'] ?? date('Y-m-d', time()-86400*30);
$search['created_at2'] = $search['created_at2'] ?? date('Y-m-d');
$result = $this->messageRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function create($input)
{
$row = $this->messageRepository->getEntity();
return [
'row' => $row,
];
}
public function store($row)
{
$row = array_map('strval', $row);
$this->messageRepository->create($row);
}
public function show($id)
{
$row = $this->messageRepository->find($id);
return [
'row' => $row,
];
}
public function update($row, $id)
{
$row = array_map('strval', $row);
$this->messageRepository->update($row, $id);
}
public function destroy($id)
{
$this->messageRepository->delete($id);
}
}
<file_sep>/app/Console/Command/UpdateVideo.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\Video\VideoRepository;
class UpdateVideo extends Command
{
//命令名稱
protected $signature = 'update:video';
//說明文字
protected $description = '[更新] 过滤过期影片';
protected $videoRepository;
public function __construct(VideoRepository $videoRepository)
{
parent::__construct();
$this->videoRepository = $videoRepository;
}
//Console 執行的程式
public function handle()
{
$this->videoRepository->search([
'updated_at2' => date('Y-m-d H:i:s', time()-14400)
])->update([
'status' => 0
]);
}
}
<file_sep>/app/Http/Controllers/Api/UserController.php
<?php
namespace App\Http\Controllers\Api;
use JWTAuth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\User\UserRepository;
use Validator;
use Exception;
class UserController extends Controller
{
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* @OA\Post(
* path="/user/profile",
* summary="用戶資訊",
* tags={"User"},
* security={{"JWT":{}}},
* @OA\Response(response="200", description="Success")
* )
*/
public function profile(Request $request)
{
try {
$user = JWTAuth::user();
return response()->json([
'success' => true,
'data' => [
'id' => $user->id,
'username' => $user->username,
'money' => $user->money,
'status' => $user->status,
'created_at' => date('Y-m-d H:i:s', strtotime($user->created_at)),
],
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/user/referrer",
* summary="推薦人列表",
* tags={"User"},
* security={{"JWT":{}}},
* @OA\Response(response="200", description="Success")
* )
*/
public function referrer(Request $request)
{
try {
$user = JWTAuth::user();
$result = $this->userRepository->getReferrerList($user->id);
$list = [];
foreach ($result as $row) {
$list[] = [
'username' => $row->username,
'money' => $row->money,
'status' => $row->status,
'login_time' => $row->login_time,
'created_at' => date('Y-m-d H:i:s', strtotime($row->created_at)),
];
}
return response()->json([
'success' => true,
'data' => $list,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
}
<file_sep>/app/Repositories/Pmtools/DailyAnalysisRepository.php
<?php
namespace App\Repositories\Pmtools;
use App\Repositories\AbstractRepository;
use Models\Pmtools\DailyAnalysis;
class DailyAnalysisRepository extends AbstractRepository
{
public function __construct(DailyAnalysis $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['type'])) {
$this->db = $this->db->where('type', '=', $this->_search['type']);
}
if (isset($this->_search['date'])) {
$this->db = $this->db->where('date', '=', $this->_search['date']);
}
if (isset($this->_search['date1'])) {
$this->db = $this->db->where('date', '>=', $this->_search['date1']);
}
if (isset($this->_search['date2'])) {
$this->db = $this->db->where('date', '<=', $this->_search['date2']);
}
return $this;
}
}
<file_sep>/app/Models/Admin/AdminNav.php
<?php
namespace Models\Admin;
use Models\Model;
class AdminNav extends Model
{
protected $table = 'admin_nav';
protected $attributes = [
'route1' => '',
'route2' => '',
'sort' => 0,
'status' => 1,
];
protected $fillable = [
'pid',
'icon',
'name',
'route',
'route1',
'route2',
'path',
'sort',
'status',
'created_by',
'updated_by',
];
const PREFIX_COLOR = [
'' => 'red',
'∟ ' => 'green',
'∟ ∟ ' => 'black',
];
const STATUS = [
1 => '开启',
0 => '关闭',
];
public function parent()
{
return $this->hasOne(get_class($this), $this->getKeyName(), 'pid');
}
public function children()
{
return $this->hasMany(get_class($this), 'pid', $this->getKeyName());
}
}
<file_sep>/app/Models/System/Sysconfig.php
<?php
namespace Models\System;
use Models\Model;
class Sysconfig extends Model
{
const CREATED_AT = null;
const UPDATED_AT = null;
protected $table = 'sysconfig';
protected $attributes = [
'sort' => 1,
];
protected $fillable = [
'skey',
'svalue',
'info',
'groupid',
'type',
'sort',
];
const GROUPID = [
1 => '站点设置',
2 => '維護设置',
];
const TYPE = [
1 => '字串(text)',
2 => '数字(number)',
3 => '文本域(textarea)',
4 => '布林值(Y/N)',
];
}
<file_sep>/app/Models/Pmtools/ConcurrentUser.php
<?php
namespace Models\Pmtools;
use Models\Model;
class ConcurrentUser extends Model
{
const UPDATED_AT = null;
protected $table = 'concurrent_user';
protected $fillable = [
'per',
'minute_time',
'count',
];
const PER = [
1 => '每分钟',
5 => '每5分钟',
10 => '每10分钟',
30 => '每30分钟',
60 => '每小时',
];
}
<file_sep>/database/migrations/2020_01_09_133204_create_message_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMessageTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'message';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->integer('uid')->default(0)->comment('用戶ID');
$table->tinyInteger('type')->default(1)->comment('問題類型');
$table->text('content')->comment('問題內容');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->index(['uid']);
$table->index(['type']);
});
DB::statement("ALTER TABLE `$tableName` comment '留言板'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('message');
}
}
<file_sep>/app/Services/Admin/AdminService.php
<?php
namespace App\Services\Admin;
use App\Repositories\Admin\AdminRepository;
use App\Repositories\Admin\AdminRoleRepository;
class AdminService
{
protected $adminRepository;
protected $adminRoleRepository;
public function __construct(
AdminRepository $adminRepository,
AdminRoleRepository $adminRoleRepository
) {
$this->adminRepository = $adminRepository;
$this->adminRoleRepository = $adminRoleRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->adminRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
'role' => [1=>'超级管理者']+$this->adminRoleRepository->getRoleList(),
];
}
public function create($input)
{
$row = $this->adminRepository->getEntity();
return [
'row' => $row,
'role' => $this->adminRoleRepository->getRoleList(),
];
}
public function store($row)
{
$row = array_map('strval', $row);
$this->adminRepository->create($row);
}
public function show($id)
{
return [
'row' => $this->adminRepository->find($id),
'role' => $this->adminRoleRepository->getRoleList(),
];
}
public function update($row, $id)
{
$row = array_map('strval', $row);
$this->adminRepository->update($row, $id);
}
public function save($row, $id)
{
$this->adminRepository->save($row, $id);
}
public function destroy($id)
{
$this->adminRepository->delete($id);
}
}
<file_sep>/deploy.sh
#!/bin/bash
vendor/bin/openapi -o public/openapi.json app/Http/Controllers/Api
composer dump-autoload
php artisan migrate
php artisan cache:clear
<file_sep>/app/Console/Command/SetConcurrentUser.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\User\UserRepository;
use App\Repositories\Pmtools\ConcurrentUserRepository;
class SetConcurrentUser extends Command
{
//命令名稱
protected $signature = 'pmtools:ccu {--per=}';
//說明文字
protected $description = '[統計]每日登入會員統計';
protected $userRepository;
protected $concurrentUserRepository;
public function __construct(
UserRepository $userRepository,
ConcurrentUserRepository $concurrentUserRepository
) {
parent::__construct();
$this->userRepository = $userRepository;
$this->concurrentUserRepository = $concurrentUserRepository;
}
/**
* @param int $per 每幾分鐘
*/
public function handle()
{
$per = $this->option('per') ?: 1;
$minute_time = date('Y-m-d H:i:00');
if ($this->concurrentUserRepository->search(['per'=>$per,'minute_time'=>$minute_time])->count() == 0) {
$time = date('Y-m-d H:i:s', time() - 60 * (10 + $per));
$count = $this->userRepository->search(['active_time1'=>$time])->count();
$this->concurrentUserRepository->create([
'per' => $per,
'minute_time' => $minute_time,
'count' => $count,
]);
}
}
}
<file_sep>/app/Repositories/AbstractRepository.php
<?php
namespace App\Repositories;
use Route;
use Models\Model;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
abstract class AbstractRepository
{
const CHUNK = 1000;
protected $entity; //預設Model
protected $db; //取資料時使用 用完還原成預設Model
protected $_paginate = 0;
protected $_select = [];
protected $_search = [];
protected $_where = [];
protected $_join = [];
protected $_order = [];
protected $_group = [];
protected $_having = [];
protected $_limit = [];
protected $is_action_log = true;
public function __call($methods, $arguments)
{
return call_user_func_array([$this->entity, $methods], $arguments);
}
public function __construct(Model $entity)
{
$this->entity = $entity;
$this->db = $entity;
DB::connection()->enableQueryLog();
}
public function getEntity()
{
return $this->entity;
}
public function setActionLog($bool)
{
return $this->is_action_log = $bool;
}
public function paginate($data)
{
$this->_paginate = $data;
return $this;
}
public function select($data)
{
$this->_select = $data;
return $this;
}
public function search($data)
{
$this->_search = $data;
return $this;
}
public function where($data)
{
$this->_where = $data;
return $this;
}
public function join($data)
{
$this->_join = $data;
return $this;
}
public function group($data)
{
$this->_group = $data;
return $this;
}
public function having($data)
{
$this->_having = $data;
return $this;
}
public function order($data)
{
$this->_order = $data;
return $this;
}
public function limit($data)
{
$this->_limit = $data;
return $this;
}
public function set($data)
{
$this->_set = $data;
return $this;
}
public function reset()
{
$this->_paginate = 0;
$this->_select = [];
$this->_search = [];
$this->_where = [];
$this->_join = [];
$this->_group = [];
$this->_having = [];
$this->_order = [];
$this->_limit = [];
$this->_set = [];
$this->db = $this->entity;
return $this;
}
public function _do_search()
{
return $this;
}
public function _do_action()
{
if (!empty($this->_select)) {
$this->db = $this->db->selectRaw(implode(',', $this->_select));
}
if (!empty($this->_join)) {
foreach ($this->_join as $join) {
$this->db = $this->db->$join();
}
}
$this->_do_search();
if (!empty($this->_where)) {
foreach ($this->_where as $where) {
if (is_array($where[2])) {
$this->db = $this->db->whereIn($where[0], $where[2]);
} else {
$this->db = $this->db->where($where[0], $where[1], $where[2]);
}
}
}
if (!empty($this->_group)) {
$this->db = $this->db->groupBy($this->_group);
}
if (!empty($this->_having)) {
$this->db = $this->db->having($this->_having);
}
if (!empty($this->_order)) {
if (isset($this->_order[0])) {
if (strtolower($this->_order[0]) == 'rand()') {
$this->db = $this->db->orderByRaw($this->_order[0], $this->_order[1]);
} else {
$this->db = $this->db->orderBy($this->_order[0], $this->_order[1]);
}
} else {
foreach ($this->_order as $key => $val) {
$this->db = $this->db->orderBy($key, $val);
}
}
}
if (!empty($this->_limit)) {
$this->db = $this->db->offset($this->_limit[0])->limit($this->_limit[1]);
}
return $this;
}
public function row($id)
{
return $this->entity->find($id);
}
public function result_one()
{
$this->_do_action();
$row = $this->db->first();
$this->reset();
return $row;
}
public function result()
{
$this->_do_action();
if ($this->_paginate > 0) {
$result = $this->db->paginate($this->_paginate)->appends($this->_search);
} else {
$result = $this->db->get();
}
$this->reset();
return $result;
}
public function count()
{
$this->_do_action();
$count = $this->db->count();
$this->reset();
return $count;
}
/**
* 取得最後執行的SQL語句
*
* @return string
*/
public function last_query()
{
$querylog = DB::getQueryLog();
$lastQuery = end($querylog);
$stringSQL = str_replace('?', '%s', $lastQuery['query']);
return sprintf($stringSQL, ...$lastQuery['bindings']);
}
public function get_compiled_select()
{
$this->_do_action();
$stringSQL = str_replace('?', '%s', $this->db->toSql());
$stringSQL = sprintf($stringSQL, ...$this->db->getBindings());
$this->reset();
return $stringSQL;
}
public function save($data, $id=0)
{
if (Schema::hasColumn($this->entity->getTable(), 'updated_by')) {
$data['updated_by'] = session('username') ?: '';
}
if ($id == 0) {
$this->_do_action();
$row = $this->db->first();
$this->reset();
} else {
$row = $this->entity->find($id);
}
foreach ($data as $key => $val) {
$row->$key = $val;
}
$row->save();
$data[$this->entity->getKeyName()] = $row->id;
$this->actionLog($data);
}
public function insert($data)
{
if (Schema::hasColumn($this->entity->getTable(), 'created_at')) {
$data['created_at'] = date('Y-m-d H:i:s');
}
if (Schema::hasColumn($this->entity->getTable(), 'created_by')) {
$data['created_by'] = session('username') ?: '';
}
if (Schema::hasColumn($this->entity->getTable(), 'updated_at')) {
$data['updated_at'] = date('Y-m-d H:i:s');
}
if (Schema::hasColumn($this->entity->getTable(), 'updated_by')) {
$data['updated_by'] = session('username') ?: '';
}
$id = $this->entity->insertGetId($data);
$this->actionLog($data, $id > 0 ? 1 : 0);
return $id;
}
public function create($data)
{
if (Schema::hasColumn($this->entity->getTable(), 'created_by')) {
$data['created_by'] = session('username') ?: '';
}
if (Schema::hasColumn($this->entity->getTable(), 'updated_by')) {
$data['updated_by'] = session('username') ?: '';
}
$create = $this->entity->create($data);
$this->actionLog($data, $create->id > 0 ? 1 : 0);
return $create->id;
}
public function insert_batch($data)
{
$this->entity->insert($data);
//寫入操作日誌
/*
if ($this->is_action_log) {
$sql_str = $this->db->last_query();
$message = $this->title . '(' . $this->getActionString_batch($data) . ')';
$this->admin_action_log_db->insert([
'sql_str' => $sql_str,
'message' => $message,
'status' => $this->trans_status() ? 1 : 0,
]);
}
*/
}
public function update($data, $id=0)
{
if (Schema::hasColumn($this->entity->getTable(), 'update_by')) {
$data['update_by'] = session('username');
}
if ($id == 0) {
$this->_do_action();
$update = $this->db->update($data);
$this->reset();
} else {
$update = $this->entity->find($id)->update($data);
}
$this->actionLog($data+['id'=>$id], $update > 0 ? 1 : 0);
}
public function update_batch($data)
{
$this->entity->updateBatch($data);
//寫入操作日誌
/*
if ($this->is_action_log) {
$sql_str = $this->db->last_query();
$message = $this->title . '(' . $this->getActionString_batch($data) . ')';
$this->admin_action_log_db->insert([
'sql_str' => $sql_str,
'message' => $message,
'status' => $this->trans_status() ? 1 : 0,
]);
}
*/
}
public function delete($id=0)
{
if ($id == 0) {
$this->_do_action();
$this->db->delete();
$this->reset();
} else {
$this->entity->find($id)->delete();
}
$this->actionLog([$this->entity->getKeyName()=>$id]);
}
public function updateOrCreate($where, $data)
{
$this->entity->updateOrCreate($where, $data);
}
public function updateOrInsert($where, $data)
{
$this->entity->updateOrInsert($where, $data);
}
public function increment($column, $amount)
{
$this->entity->increment($column, $amount);
}
public function decrement($column, $amount)
{
$this->entity->decrement($column, $amount);
}
public function truncate()
{
$this->entity->truncate();
}
/**
* 寫入操作日誌
*
* @param array $data 欄位資料
* @param integer $status 狀態
* @return void
*/
public function actionLog($data, $status=1)
{
if ($this->is_action_log) {
$message = view()->shared('title') . '(' . $this->getActionString($data) . ')';
DB::table('admin_action_log')->insert([
'adminid' => session('id'),
'route' => Route::currentRouteName(),
'sql' => $this->last_query(),
'message' => $message,
'ip' => Request()->getClientIp(),
'status' => $status,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => session('username'),
]);
}
}
/**
* 組成操作日誌字串
*/
public function getActionString($data, $highlight = [])
{
$str = [];
foreach ($data as $key => $val) {
//判斷有無欄位
if (isset(static::$columnList[$key])) {
//判斷欄位有無靜態陣列
if (isset($this->entity::$field->$val)) {
$val = $this->entity::$field->$val;
}
if (isset($highlight[$key])) {
$str[] = '<font color="blue">' . static::$columnList[$key] . "=$val</font>";
} else {
$str[] = static::$columnList[$key] . "=$val";
}
}
}
return implode(';', $str);
}
/**
* 組成操作日誌字串(多筆)
*/
public function getActionString_batch($result)
{
$return = [];
foreach ($result as $data) {
$str = [];
foreach ($data as $key => $val) {
//判斷有無欄位
if (isset(static::$columnList[$key])) {
//判斷欄位有無靜態陣列
if (isset(static::${"{$key}List"}[$val])) {
$val = static::${"{$key}List"}[$val];
}
$str[] = static::$columnList[$key] . "=$val";
}
}
$return[] = implode(';', $str);
}
return implode('<br>', $return);
}
public static $columnList = [];
}
<file_sep>/database/migrations/2019_12_18_134831_create_daily_retention_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDailyRetentionTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'daily_retention';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->date('date')->default('1970-01-01')->comment('日期');
$table->tinyInteger('type')->comment('類型 1.1日內有登入,2.3日內有登入,3.7日內有登入,4.15日內有登入,5.30日內有登入,6.31日以上未登入');
$table->integer('all_count')->default(0)->comment('總數');
$table->integer('day_count')->default(0)->comment('人數');
$table->integer('avg_money')->default(0)->comment('平均點數');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->unique(['date','type']);
});
DB::statement("ALTER TABLE `$tableName` comment '每日統計-留存率'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('daily_retention');
}
}
<file_sep>/app/Presenters/layouts/BackendPresenter.php
<?php
namespace App\Presenters\Layouts;
class BackendPresenter
{
public function __construct()
{
benchmark()->checkpoint();
}
public function elapsedTime()
{
return benchmark()->getElapsedTime()->f;
}
public function ramUsage()
{
config(['benchmark.format_ram_usage'=> true]);
return benchmark()->getPeakRamUsage();
}
}
<file_sep>/config/global.php
<?php
return [
/**
* 無須權限的動作
*/
'no_need_perm' => [
'','home','ajax.topinfo','ajax.perpage','ajax.imageupload','admin.editpwd','admin.updatepwd','logout',
],
];
<file_sep>/app/Console/Command/SetDailyAnalysis.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\User\UserRepository;
use App\Repositories\User\UserLoginLogRepository;
use App\Repositories\Pmtools\ConcurrentUserRepository;
use App\Repositories\Pmtools\DailyAnalysisRepository;
class SetDailyAnalysis extends Command
{
//命令名稱
protected $signature = 'pmtools:daily_analysis {--enforce=} {--date=}';
//說明文字
protected $description = '[統計]每日活躍用戶數';
protected $userLoginLogRepository;
protected $concurrentUserRepository;
protected $dailyAnalysisRepository;
public function __construct(
UserRepository $userRepository,
UserLoginLogRepository $userLoginLogRepository,
ConcurrentUserRepository $concurrentUserRepository,
DailyAnalysisRepository $dailyAnalysisRepository
) {
parent::__construct();
$this->userRepository = $userRepository;
$this->userLoginLogRepository = $userLoginLogRepository;
$this->concurrentUserRepository = $concurrentUserRepository;
$this->dailyAnalysisRepository = $dailyAnalysisRepository;
}
/**
* @param string $date 指定執行日期
* @param int $enforce 強制重新執行
*/
public function handle()
{
$date = $this->option('date') ?: date('Y-m-d', time()-86400);
$enforce = $this->option('enforce') ?: 0;
//強制執行 先刪除已存在的資料
if ($enforce) {
$this->dailyAnalysisRepository->search(['date'=>$date])->delete();
}
//判斷是否已執行過(有資料)
if ($this->dailyAnalysisRepository->search(['date'=>$date])->count() == 0) {
$insert = [];
$now = date('Y-m-d H:i:s');
//NUU
$NUU = $this->userRepository->search([
'status' => 1,
'created_at1' => $date,
'created_at12' => $date,
])->count();
$insert[] = [
'date' => $date,
'type' => 1,
'count' => $NUU,
'created_at' => $now,
];
//DAU
$DAU = $this->userLoginLogRepository->getLoginUsers($date, $date);
$insert[] = [
'date' => $date,
'type' => 2,
'count' => $DAU,
'created_at' => $now,
];
//WAU
$WAU = $this->userLoginLogRepository->getLoginUsers(date('Y-m-d', strtotime($date) - 86400 * 6), $date);
$insert[] = [
'date' => $date,
'type' => 3,
'count' => $WAU,
'created_at' => $now,
];
//MAU
$MAU = $this->userLoginLogRepository->getLoginUsers(date('Y-m-01', strtotime($date)), $date);
$insert[] = [
'date' => $date,
'type' => 4,
'count' => $MAU,
'created_at' => $now,
];
//DAU-NUU
$insert[] = [
'date' => $date,
'type' => 5,
'count' => $DAU - $NUU,
'created_at' => $now,
];
//PCU
$CCU = $this->concurrentUserRepository->select(['IFNULL(MAX(count),0) count'])->search([
'per' => 1,
'minute_time1' => "$date 00:00:00",
'minute_time2' => "$date 23:59:59",
])->result_one();
$insert[] = [
'date' => $date,
'type' => 6,
'count' => $CCU['count'],
'created_at' => $now,
];
//寫入資料
$this->dailyAnalysisRepository->insert_batch($insert);
}
}
}
<file_sep>/app/Http/Middleware/Permission.php
<?php
namespace App\Http\Middleware;
use Route;
use Auth;
use Closure;
use Request;
use Models\Admin\Admin;
class Permission
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//檢測用戶,不可重複登入
if (session('_token') === null) {
return $this->errorRedirect('session无效,请重新登录');
}
if (session('_token') != Admin::find(session('id'))->token) {
return $this->errorRedirect("session无效,请重新登录");
}
//檢測url是不是存在的
$allNav = view()->shared('allNav');
$routes = [];
foreach ($allNav as $row) {
if ($row['pid'] > 0) {
$routes[] = $row['route'];
if ($row['route1'] != '') {
$routes[] = $row['route1'];
}
if ($row['route2'] != '') {
$routes[] = $row['route2'];
}
}
}
$routes = array_merge_recursive($routes, config('global.no_need_perm'));
if (!in_array(Route::currentRouteName(), $routes)) {
abort(500, '当前的url没有设置,或者已经禁用,请联系管理员设置!');
}
//非超级管理员則驗證是否有訪問的權限
if (session('roleid') != 1 && !in_array(view()->shared('route'), view()->shared('allow_url'))) {
return $this->errorRedirect("对不起,您没权限执行此操作,请联系管理员");
}
return $next($request);
}
/**
* 驗證錯誤 跳轉登入頁
* $message 跳轉訊息
*
* @return null
*/
private function errorRedirect($message)
{
Auth::logout();
session()->flash('message', $message);
session('refer', Request::getRequestUri());
return redirect('login');
}
}
<file_sep>/app/Http/Controllers/Api/HomeController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\System\SysconfigRepository;
class HomeController extends Controller
{
protected $sysconfigRepository;
public function __construct(SysconfigRepository $sysconfigRepository)
{
$this->sysconfigRepository = $sysconfigRepository;
}
/**
* @OA\Post(
* path="/maintenance",
* summary="網站維護資訊",
* tags={"Home"},
* @OA\Response(response="200", description="Success")
* )
*/
public function maintenance(Request $request)
{
$data = $this->sysconfigRepository->getSysconfig();
return response()->json([
'success' => true,
'message' => $data['maintenance_message'] ?? '',
]);
}
}
<file_sep>/app/Models/Pmtools/DailyAnalysis.php
<?php
namespace Models\Pmtools;
use Models\Model;
class DailyAnalysis extends Model
{
const UPDATED_AT = null;
protected $table = 'daily_analysis';
protected $fillable = [
'date',
'type',
'count',
];
const TYPE = [
1 => '每日添加用户数(NUU)',
2 => '每日不重复登入用户数(DAU)',
3 => '每周不重复登入用户数(WAU)',
4 => '每月不重复登入用户数(MAU)',
5 => 'DAU - NUU',
6 => '最大同时在线用户数(PCU)',
];
}
<file_sep>/app/Repositories/User/UserShareLogRepository.php
<?php
namespace App\Repositories\User;
use App\Repositories\AbstractRepository;
use App\Repositories\System\Ip2locationRepository;
use Models\User\UserShareLog;
class UserShareLogRepository extends AbstractRepository
{
protected $ip2locationRepository;
public function __construct(UserShareLog $entity, Ip2locationRepository $ip2locationRepository)
{
parent::__construct($entity);
$this->ip2locationRepository = $ip2locationRepository;
$this->is_action_log = false;
}
public function create($row)
{
$ip = request()->getClientIp();
$ip_info = $this->ip2locationRepository->getIpData($ip);
$ip_info = $ip_info ?? [];
$row['ip'] = $ip;
$row['ip_info'] = json_encode($ip_info);
$row['ua'] = request()->server('HTTP_USER_AGENT');
return parent::create($row);
}
public function _do_search()
{
if (isset($this->_search['username'])) {
$this->db = $this->db->whereHas('user', function ($query) {
$query->where('username', 'like', '%'.$this->_search['username'].'%');
});
}
if (isset($this->_search['ip'])) {
$this->db = $this->db->where('ip', '=', $this->_search['ip']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
}
<file_sep>/app/Http/Controllers/Api/CommonController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\System\SysconfigRepository;
use App\Repositories\System\AdsRepository;
use Validator;
use Exception;
class CommonController extends Controller
{
protected $sysconfigRepository;
public function __construct(SysconfigRepository $sysconfigRepository)
{
$this->sysconfigRepository = $sysconfigRepository;
}
/**
* @OA\Post(
* path="/param",
* summary="網站參數",
* tags={"Common"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="key",
* description="參數名稱(可不帶)",
* type="string",
* example="video_title",
* )
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function param(Request $request)
{
try {
$config = $this->sysconfigRepository->getSysconfig();
$data = [];
if ($request->key) {
if (isset($config[$request->key])) {
$data[$request->key] = $config[$request->key];
}
} else {
foreach (['video_title'] as $val) {
$data[$val] = $config[$val] ?? '';
}
}
return response()->json([
'success' => true,
'data' => $data,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/adslist",
* summary="廣告列表",
* tags={"Common"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="type",
* description="廣告位置",
* type="string",
* example="1",
* ),
* @OA\Property(
* property="page",
* description="頁數",
* type="string",
* example="1",
* ),
* @OA\Property(
* property="per_page",
* description="一頁幾筆",
* type="string",
* example="10",
* ),
* required={"type","page","per_page"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function adsList(Request $request, AdsRepository $adsRepository)
{
try {
$validator = Validator::make($request->all(), [
'type' => 'required',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$type = $request->type;
$page = $request->page ?: 1;
$per_page = $request->per_page ?: 10;
$date = date('Y-m-d H:i:s');
$where[] = ['type', '=', $type];
$where[] = ['start_time', '<=', $date];
$where[] = ['end_time', '>=', $date];
$result = $adsRepository->where($where)
->order(['sort', 'asc'])
->paginate($per_page)
->result();
$list = [];
foreach ($result as $row) {
$list[] = [
'name' => $row['name'],
'image' => asset($row['image']),
'url' => $row['url'],
];
}
return response()->json([
'success' => true,
'page' => (int)$page,
'total' => $result->total(),
'list' => $list,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
}
<file_sep>/app/Models/Admin/AdminLoginLog.php
<?php
namespace Models\Admin;
use Models\Model;
class AdminLoginLog extends Model
{
const UPDATED_AT = null;
protected $table = 'admin_login_log';
protected $fillable = [
'adminid',
'ip',
'ip_info',
'created_by',
];
public function admin()
{
return $this->belongsTo('Models\Admin\Admin', 'adminid');
}
}
<file_sep>/app/Services/Admin/AdminNavService.php
<?php
namespace App\Services\Admin;
use App\Repositories\Admin\AdminNavRepository;
class AdminNavService
{
protected $adminNavRepository;
public function __construct(AdminNavRepository $adminNavRepository)
{
$this->adminNavRepository = $adminNavRepository;
}
public function list($input)
{
$search_params = param_process($input, ['sort', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->adminNavRepository->search($search)
->order($order)->result()->toArray();
$result = $this->treeSort($result);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function create($input)
{
$row = $this->adminNavRepository->getEntity();
$row['pid'] = $input['pid'] ?? $row['pid'];
return [
'row' => $row,
'nav' => $this->getDropDownList(),
];
}
public function store($row)
{
$row = array_map('strval', $row);
$this->adminNavRepository->create($row);
}
public function show($id)
{
return [
'row' => $this->adminNavRepository->row($id)->toArray(),
'nav' => $this->getDropDownList(),
];
}
public function update($row, $id)
{
$row = array_map('strval', $row);
$this->adminNavRepository->update($row, $id);
}
public function save($row, $id)
{
$this->adminNavRepository->save($row, $id);
}
public function destroy($id)
{
$this->adminNavRepository->delete($id);
}
public function treeSort($result, $pid = 0, $array = [], $prefix = '')
{
foreach ($result as $row) {
if ($row['pid'] == $pid) {
$row['prefix'] = $prefix;
$array[] = $row;
$array = $this->treeSort($result, $row['id'], $array, $prefix . '∟ ');
}
}
return $array;
}
public function getDropDownList()
{
$result = $this->adminNavRepository->order(['sort','asc'])->result()->toArray();
$result = $this->treeSort($result);
$data = [];
foreach ($result as $row) {
$data[$row['id']] = $row['prefix'] . $row['name'];
}
return $data;
}
}
<file_sep>/app/Repositories/System/MessageRepository.php
<?php
namespace App\Repositories\System;
use App\Repositories\AbstractRepository;
use Models\System\Message;
class MessageRepository extends AbstractRepository
{
public function __construct(Message $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['uid'])) {
$this->db = $this->db->where('uid', '=', $this->_search['uid']);
}
if (isset($this->_search['username'])) {
$this->db = $this->db->whereHas('user', function ($query) {
$query->where('username', 'like', '%'.$this->_search['username'].'%');
});
}
if (isset($this->_search['type'])) {
$this->db = $this->db->where('type', '=', $this->_search['type']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'].' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'].' 23:59:59');
}
return $this;
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '流水号',
'uid' => '用户ID',
'type' => '问题类型',
'content' => '内容',
];
}
<file_sep>/app/Repositories/System/AdsRepository.php
<?php
namespace App\Repositories\System;
use App\Repositories\AbstractRepository;
use Models\System\Ads;
class AdsRepository extends AbstractRepository
{
public function __construct(Ads $entity)
{
parent::__construct($entity);
}
public function _do_search()
{
if (isset($this->_search['domain'])) {
$this->db = $this->db->where(function ($query) {
$query->where('domain', '=', '')
->orWhereRaw("FIND_IN_SET('".$this->_search['domain']."', domain)");
});
}
if (isset($this->_search['type'])) {
$this->db = $this->db->where('type', '=', $this->_search['type']);
}
if (isset($this->_search['enabled'])) {
$date = date('Y-m-d H:i:s');
$this->db = $this->db->where('start_time', '<=', $date)->where('end_time', '>=', $date);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1']);
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2']);
}
return $this;
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '流水号',
'type' => '位置',
'name' => '名称',
'image' => '图片',
'url' => '连结',
'start_time' => '开始时间',
'end_time' => '结束时间',
'sort' => '排序',
];
}
<file_sep>/app/Http/Controllers/Api/VideoController.php
<?php
namespace App\Http\Controllers\Api;
use JWTAuth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Video\VideoService;
use App\Repositories\Video\VideoRepository;
use App\Repositories\Video\VideoTagsRepository;
use App\Repositories\User\UserRepository;
use App\Repositories\User\UserMoneyLogRepository;
use Validator;
use Exception;
class VideoController extends Controller
{
protected $videoService;
protected $videoRepository;
protected $videoTagsRepository;
protected $userRepository;
protected $userMoneyLogRepository;
public function __construct(
VideoService $videoService,
VideoRepository $videoRepository,
VideoTagsRepository $videoTagsRepository,
UserRepository $userRepository,
UserMoneyLogRepository $userMoneyLogRepository
) {
$this->videoService = $videoService;
$this->videoRepository = $videoRepository;
$this->videoTagsRepository = $videoTagsRepository;
$this->userRepository = $userRepository;
$this->userMoneyLogRepository = $userMoneyLogRepository;
}
/**
* @OA\Post(
* path="/video/list",
* summary="視頻列表",
* tags={"Video"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="search",
* description="搜尋",
* type="string",
* example="",
* ),
* @OA\Property(
* property="tags",
* description="標籤",
* type="string",
* example="素人",
* ),
* @OA\Property(
* property="page",
* description="頁數",
* type="string",
* example="1",
* ),
* @OA\Property(
* property="per_page",
* description="一頁幾筆",
* type="string",
* example="10",
* ),
* required={"page","per_page"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function list(Request $request)
{
try {
$page = $request->page ?: 1;
$list = $this->videoService->getList($request);
return response()->json([
'success' => true,
'page' => (int)$page,
'total' => $list['total'],
'list' => $list['list'],
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/video/tags",
* summary="熱門標籤",
* tags={"Video"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="page",
* description="頁數",
* type="string",
* example="1",
* ),
* @OA\Property(
* property="per_page",
* description="一頁幾筆",
* type="string",
* example="20",
* ),
* required={"page","per_page"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function tags(Request $request)
{
try {
$page = $request->page ?: 1;
$per_page = $request->per_page ?: 10;
$result = $this->videoTagsRepository
->order(['hot','desc'])
->paginate($per_page)
->result();
$list = [];
foreach ($result as $row) {
$list[] = $row['name'];
}
return response()->json([
'success' => true,
'page' => (int)$page,
'total' => $result->total(),
'list' => $list,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/video/detail",
* summary="視頻資訊",
* tags={"Video"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="keyword",
* description="視頻ID",
* type="string",
* example="niWaHDNjt3S",
* ),
* required={"keyword"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function detail(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'keyword' => 'required|exists:video',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$row = $this->videoRepository->search(['keyword'=>$request->keyword])->result_one();
$all = false;
//判斷是否登入
if (JWTAuth::check()) {
$user = JWTAuth::user();
$buy = $this->userMoneyLogRepository->getBuyVideo($user['id']);
if (in_array($row['keyword'], $buy)) {
$all = true;
}
}
return response()->json([
'success' => true,
'buy' => $all,
'data' => [
'keyword' => $row['keyword'],
'name' => $row['name'],
'publish' => $row['publish'],
'actors' => $row['actors'],
'tags' => $row['tags'],
'pic_big' => $row['pic_b'],
'pic_small' => $row['pic_s'],
'url' => $all ? $row['url']: str_replace('end=36000', 'end=300', $row['url']),
],
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/video/buy",
* summary="購買視頻",
* tags={"Video"},
* security={{"JWT":{}}},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="keyword",
* description="視頻ID",
* type="string",
* example="niWaHDNjt3S",
* ),
* required={"keyword"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function buy(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'keyword' => 'required|exists:video',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$user = JWTAuth::user();
$buy = $this->userMoneyLogRepository->getBuyVideo($user['id']);
if (in_array($request->keyword, $buy)) {
throw new Exception('该视频已购买过!', 422);
}
if ($user['money'] <= 0) {
throw new Exception('余额不足!', 422);
}
//帳變明細
$this->userRepository->addMoney($user['id'], 2, -1, "觀看影片-$request->keyword", $request->keyword);
return response()->json([
'success' => true,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
}
<file_sep>/app/Repositories/User/UserRepository.php
<?php
namespace App\Repositories\User;
use DB;
use App\Repositories\AbstractRepository;
use App\Repositories\System\Ip2locationRepository;
use App\Repositories\User\UserMoneyLogRepository;
use Models\User\User;
class UserRepository extends AbstractRepository
{
protected $ip2locationRepository;
protected $userMoneyLogRepository;
public function __construct(
User $entity,
Ip2locationRepository $ip2locationRepository,
UserMoneyLogRepository $userMoneyLogRepository
) {
parent::__construct($entity);
$this->ip2locationRepository = $ip2locationRepository;
$this->userMoneyLogRepository = $userMoneyLogRepository;
$this->is_action_log = false;
}
public function create($row)
{
if (isset($row['password'])) {
if ($row['password'] != '') {
$row['password'] = <PASSWORD>($row['password']);
} else {
unset($row['password']);
}
}
if (isset($row['referrer_code'])) {
if ($referrer = $this->referrerCode($row['referrer_code'], 'decode')) {
$row['referrer'] = $referrer;
}
unset($row['referrer_code']);
}
$ip = request()->getClientIp();
$ip_info = $this->ip2locationRepository->getIpData($ip);
$ip_info = $ip_info ?? [];
$row['create_ip'] = $ip;
$row['create_ip_info'] = json_encode($ip_info);
$row['create_ua'] = request()->server('HTTP_USER_AGENT');
$row['token'] = $row['username'];
return parent::create($row);
}
public function update($row, $id=0)
{
if (isset($row['password'])) {
if ($row['password'] != '') {
$row['password'] = bcrypt($row['password']);
} else {
unset($row['password']);
}
}
if (isset($row['referrer_code'])) {
if ($referrer = $this->referrerCode($row['referrer_code'], 'decode')) {
$row['referrer'] = $referrer;
}
unset($row['referrer_code']);
}
if (isset($row['update_info'])) {
$ip = request()->getClientIp();
$ip_info = $this->ip2locationRepository->getIpData($ip);
$ip_info = $ip_info ?? [];
$row['create_ip'] = $ip;
$row['create_ip_info'] = json_encode($ip_info);
$row['create_ua'] = request()->server('HTTP_USER_AGENT');
}
return parent::update($row, $id);
}
public function _do_search()
{
if (isset($this->_search['ids'])) {
$this->db = $this->db->whereIn('id', $this->_search['ids']);
}
if (isset($this->_search['username'])) {
$this->db = $this->db->where('username', 'like', '%'.$this->_search['username'].'%');
}
if (isset($this->_search['referrer_code'])) {
$uid = $this->referrerCode($this->_search['referrer_code'], 'decode');
$this->db = $this->db->where('id', '=', $uid);
}
if (isset($this->_search['referrer'])) {
$this->db = $this->db->where('referrer', '=', $this->_search['referrer']);
}
if (isset($this->_search['remark'])) {
$this->db = $this->db->where('remark', 'like', '%'.$this->_search['remark'].'%');
}
if (isset($this->_search['status'])) {
$this->db = $this->db->where('status', '=', $this->_search['status']);
}
if (isset($this->_search['login_time1'])) {
$this->db = $this->db->where('login_time', '>=', $this->_search['login_time1']);
}
if (isset($this->_search['login_time2'])) {
$this->db = $this->db->where('login_time', '<=', $this->_search['login_time2']);
}
if (isset($this->_search['active_time1'])) {
$this->db = $this->db->where('active_time', '>=', $this->_search['active_time1']);
}
if (isset($this->_search['active_time2'])) {
$this->db = $this->db->where('active_time', '<=', $this->_search['active_time2']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
if (isset($this->_search['no_login_day'])) {
$this->db = $this->db->whereRaw('login_time >= created_at + INTERVAL ? DAY', [$this->_search['no_login_day']]);
}
if (isset($this->_search['date_has_login'])) {
$this->db = $this->db->whereHas('loginLog', function ($query) {
$query->where('created_at', '>=', $this->_search['date_has_login'] . ' 00:00:00')
->where('created_at', '<=', $this->_search['date_has_login'] . ' 23:59:59');
});
}
return $this;
}
/**
* 依帳號取得會員資料
*
* @param string $username
* @return array
*/
public function getDataByUsername($username)
{
$where[] = ['username', '=', $username];
return $this->where($where)->result_one();
}
/**
* 取得推薦列表
*
* @param int $uid
* @return array
*/
public function getReferrerList($uid)
{
$where[] = ['referrer', '=', $uid];
return $this->where($where)->paginate(10)->result();
}
/**
* 變動餘額+LOG
*
* @param int $uid 用戶ID
* @param int $type 帳變類別
* @param int $add_money 帳變金額
* @param string $description 描述
* @param string $video_keyword 訂單號
* @return void
*/
public function addMoney($uid, $type, $add_money, $description, $video_keyword='')
{
$user = $this->row($uid);
//找不到帳號則跳出
if ($user === null) {
return;
}
//帳變金額為0則不動作
if ((int)$add_money == 0) {
return;
}
$data = [
'uid' => $uid,
'type' => $type,
'video_keyword' => $video_keyword,
'money_before' => $user['money'],
'money_add' => $add_money,
'money_after' => $user['money'] + $add_money,
'description' => $description,
];
DB::transaction(function () use ($data) {
$this->update([
'money' => $data['money_after'],
], $data['uid']);
$this->userMoneyLogRepository->create($data);
});
}
/**
* UID-邀請碼轉換
*
* @param string $val 轉換值
* @param string $method 回傳code OR uid
* @return string
*/
public function referrerCode($val, $method='encode')
{
if ($method == 'encode') {
$user = $this->row($val);
$checkcode = substr(base_convert($user['verify_code'], 10, 32), -2);
$hex = dechex(($val+100000) ^ 19487);
return $checkcode.$hex;
}
if ($method == 'decode') {
$checkcode = substr($val, 0, 2);
$uid = (hexdec(substr($val, 2)) ^ 19487) - 100000;
$user = $this->row($uid);
$checkcode = substr(base_convert($user['verify_code'], 10, 32), -2);
if ($checkcode == substr($val, 0, 2)) {
return $uid;
} else {
return false;
}
}
return false;
}
/**
* 計算留存率
*
* @param int $type 類型
* @return array
*/
public function retention($type)
{
$where[] = ['status', '=', 1];
switch ($type) {
case 1: $where[] = ['login_time', '>=', date('Y-m-d', time() - 86400)]; break;
case 2: $where[] = ['login_time', '>=', date('Y-m-d', time() - 86400 * 3)]; break;
case 3: $where[] = ['login_time', '>=', date('Y-m-d', time() - 86400 * 7)]; break;
case 4: $where[] = ['login_time', '>=', date('Y-m-d', time() - 86400 * 15)]; break;
case 5: $where[] = ['login_time', '>=', date('Y-m-d', time() - 86400 * 30)]; break;
case 6: $where[] = ['login_time', '<', date('Y-m-d', time() - 86400 * 30)]; break;
}
return $this->select(['COUNT(id) day_count', 'ROUND(AVG(money)) avg_money'])
->where($where)->result_one()->toArray();
}
/**
* 留存率區間
*
* @param string $starttime 起始時間
* @param string $endtime 結束時間
* @param int $type 類型
* @return array
*/
public function retentionAnalysis($starttime, $endtime, $type)
{
$search['status'] = 1;
$search['created_at1'] = $starttime;
$search['created_at2'] = $endtime;
switch ($type) {
case 1: $search['no_login_day'] = 1; break;
case 2: $search['no_login_day'] = 3; break;
case 3: $search['no_login_day'] = 7; break;
case 4: $search['no_login_day'] = 15; break;
case 5: $search['no_login_day'] = 30; break;
case 6: $search['no_login_day'] = 60; break;
case 7: $search['no_login_day'] = 90; break;
case 8: $search['login_time1'] = date('Y-m-d', time() - 86400 * 7); break;
}
return $this->select(['IFNULL(COUNT(id),0) count', 'IFNULL(ROUND(AVG(money)),0) avg_money'])
->search($search)->result_one()->toArray();
}
/**
* 新帳號留存率
*
* @param int $type 類型
* @param string $date 日期
* @return array
*/
public function retentionDaily($type, $date)
{
$day = 1;
switch ($type) {
case 1: $day = 1; break;
case 2: $day = 3; break;
case 3: $day = 7; break;
case 4: $day = 15; break;
case 5: $day = 30; break;
}
$createdate = date('Y-m-d', strtotime($date) - 86400 * $day);
$search['status'] = 1;
$search['created_at1'] = $createdate;
$search['created_at2'] = $createdate;
$array['all_count'] = $this->search($search)->count();
$search['date_has_login'] = $date;
$array['day_count'] = $this->search($search)->count();
return $array;
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '用戶ID',
'username' => '用户名称',
'password' => '<PASSWORD>',
'money' => '货币',
'remark' => '备注',
'status' => '状态',
'free_time' => '免费看到期日',
];
}
<file_sep>/app/Console/Command/SetDailyUser.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\User\UserLoginLogRepository;
use App\Repositories\User\UserMoneyLogRepository;
use App\Repositories\Pmtools\DailyUserRepository;
class SetDailyUser extends Command
{
//命令名稱
protected $signature = 'pmtools:daily_user {--enforce=} {--date=}';
//說明文字
protected $description = '[統計]每日登入會員統計';
protected $userLoginLogRepository;
protected $userMoneyLogRepository;
protected $dailyUserRepository;
public function __construct(
UserLoginLogRepository $userLoginLogRepository,
UserMoneyLogRepository $userMoneyLogRepository,
DailyUserRepository $dailyUserRepository
) {
parent::__construct();
$this->userLoginLogRepository = $userLoginLogRepository;
$this->userMoneyLogRepository = $userMoneyLogRepository;
$this->dailyUserRepository = $dailyUserRepository;
}
/**
* @param string $date 指定執行日期
* @param int $enforce 強制重新執行
*/
public function handle()
{
$date = $this->option('date') ?: date('Y-m-d', time()-86400);
$enforce = $this->option('enforce') ?: 0;
//強制執行 先刪除已存在的資料
if ($enforce) {
$this->dailyUserRepository->search(['date'=>$date])->delete();
}
//判斷是否已執行過(有資料)
if ($this->dailyUserRepository->search(['date'=>$date])->count() == 0) {
//取出前一天的連續登入
$result = $this->dailyUserRepository->select(['uid','consecutive'])->search([
'date' => date('Y-m-d', strtotime($date) - 86400),
])->result()->toArray();
$consecutive = array_column($result, 'consecutive', 'uid');
//當天登入會員
$result = $this->userLoginLogRepository->select(['uid','count(uid) count'])->search([
'created_at1' => $date,
'created_at2' => $date,
])->group('uid')->result();
$insert = [];
foreach ($result as $row) {
//消費點數
$moneylog = $this->userMoneyLogRepository->select(['SUM(money_add*-1) point'])->search([
'uid' => $row['uid'],
'type' => 2,
'created_at1' => $date,
'created_at2' => $date,
])->result_one();
$insert[] = [
'date' => $date,
'uid' => $row['uid'],
'login' => $row['count'],
'point' => $moneylog['point'] ?? 0,
'consecutive' => ($consecutive[$row['uid']] ?? 0) + 1,
'created_at' => date('Y-m-d H:i:s'),
];
}
$this->dailyUserRepository->insert_batch($insert);
}
}
}
<file_sep>/app/Http/Controllers/Pmtools/DailyAnalysisController.php
<?php
namespace App\Http\Controllers\Pmtools;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Pmtools\DailyAnalysisService;
class DailyAnalysisController extends Controller
{
protected $dailyAnalysisService;
public function __construct(DailyAnalysisService $dailyAnalysisService)
{
$this->dailyAnalysisService = $dailyAnalysisService;
}
public function index(Request $request)
{
return view('pmtools.daily_analysis', $this->dailyAnalysisService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'analysis'));
}
}
<file_sep>/app/Http/Requests/FormRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;
class FormRequest extends BaseFormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* 有需要在實作
* @return [type] [description]
*/
public function custom(): array
{
return [];
}
}
<file_sep>/app/Http/Controllers/Pmtools/ConcurrentUserController.php
<?php
namespace App\Http\Controllers\Pmtools;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Pmtools\ConcurrentUserService;
class ConcurrentUserController extends Controller
{
protected $concurrentUserService;
public function __construct(ConcurrentUserService $concurrentUserService)
{
$this->concurrentUserService = $concurrentUserService;
}
public function index(Request $request)
{
return view('pmtools.concurrent_user', $this->concurrentUserService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'ccu'));
}
}
<file_sep>/app/Console/Command/GetVideoApi.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\Video\VideoRepository;
class GetVideoApi extends Command
{
//命令名稱
protected $signature = 'api:video';
//說明文字
protected $description = '[API] 取得最新影片';
protected $videoRepository;
public function __construct(VideoRepository $videoRepository)
{
parent::__construct();
$this->videoRepository = $videoRepository;
}
//Console 執行的程式
public function handle()
{
//影片更新
$result = getVideoApi('list');
foreach ($result['data']['videos'] as $row) {
preg_match_all('/.*videos\/(.*)\/b.jpg/m', $row['pic_b'], $matches, PREG_SET_ORDER, 0);
$keyword = $matches[0][1];
$this->videoRepository->updateOrInsert(['keyword'=>$keyword], [
'name' => $row['name'],
'publish' => $row['publish'],
'actors' => implode(',', $row['actors']),
'tags' => implode(',', $row['tags']),
'pic_b' => $row['pic_b'],
'pic_s' => $row['pic_s'],
'url' => $row['hls'],
'status' => 1,
'created_at' => date('Y-m-d H:i:s'),
'created_by' => 'schedule',
'updated_at' => date('Y-m-d H:i:s'),
'updated_by' => 'schedule',
]);
}
}
}
<file_sep>/app/Http/Controllers/User/UserLoginLogController.php
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\User\UserLoginLogService;
class UserLoginLogController extends Controller
{
protected $userLoginLogService;
public function __construct(UserLoginLogService $userLoginLogService)
{
$this->userLoginLogService = $userLoginLogService;
}
public function index(Request $request)
{
return view('user_login_log.index', $this->userLoginLogService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'user_login_log'));
}
}
<file_sep>/app/Services/System/AdsService.php
<?php
namespace App\Services\System;
use App\Repositories\System\AdsRepository;
class AdsService
{
protected $adsRepository;
public function __construct(AdsRepository $adsRepository)
{
$this->adsRepository = $adsRepository;
}
public function list($input)
{
$search_params = param_process($input, ['sort', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->adsRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function create($input)
{
$row = $this->adsRepository->getEntity();
if ($input['id'] > 0) {
$row = $this->adsRepository->row($input['id']);
}
$row['domain'] = $row['domain'] == '' ? []:explode(',', $row['domain']);
return [
'row' => $row,
];
}
public function store($row)
{
$row['domain'] = isset($row['domain']) ? implode(',', $row['domain']):'';
$row = array_map('strval', $row);
$this->adsRepository->create($row);
}
public function show($id)
{
$row = $this->adsRepository->find($id);
$row['domain'] = $row['domain'] == '' ? []:explode(',', $row['domain']);
return [
'row' => $row,
];
}
public function update($row, $id)
{
$row['domain'] = isset($row['domain']) ? implode(',', $row['domain']):'';
$row = array_map('strval', $row);
$this->adsRepository->update($row, $id);
}
public function destroy($id)
{
$this->adsRepository->delete($id);
}
}
<file_sep>/app/Models/User/UserShareLog.php
<?php
namespace Models\User;
use Models\Model;
class UserShareLog extends Model
{
const UPDATED_AT = null;
protected $table = 'user_share_log';
protected $fillable = [
'uid',
'ip',
'ip_info',
'ua',
];
public function user()
{
return $this->belongsTo('Models\User\User', 'uid');
}
}
<file_sep>/app/Http/Controllers/Admin/AdminLoginController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Repositories\Admin\AdminLoginLogRepository;
use App\Repositories\System\Ip2locationRepository;
class AdminLoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* 登入後導向的位置
*
* @var string
*/
protected $redirectTo = 'home';
protected $guard = 'backend';
protected $adminLoginLogRepository;
protected $ip2locationRepository;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(
AdminLoginLogRepository $adminLoginLogRepository,
Ip2locationRepository $ip2locationRepository
) {
$this->middleware('guest:backend')->except('logout');
$this->adminLoginLogRepository = $adminLoginLogRepository;
$this->ip2locationRepository = $ip2locationRepository;
}
public function showLoginForm()
{
return view('admin.login');
}
/**
* 通過驗證後的動作
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
//更新登入數次及時間
$user->login_time = date('Y-m-d H:i:s');
$user->login_count++;
$user->token = session('_token');
$user->save();
//重要資訊寫入Session
session([
'id' => $user->id,
'username' => $user->username,
'roleid' => $user->roleid,
'per_page' => 20,
]);
//登入log
$ip = $request->getClientIp();
$ip_info = $this->ip2locationRepository->getIpData($ip);
$ip_info = $ip_info ?? [];
$this->adminLoginLogRepository->create([
'adminid' => $user->id,
'ip' => $ip,
'ip_info' => json_encode($ip_info),
]);
//轉跳
if (session('refer')) {
$refer = session('refer');
session(['refer'=>null]);
return redirect($refer);
} else {
return redirect('home');
}
}
protected function guard()
{
return Auth::guard($this->guard);
}
/**
* 定義帳號欄位
*
* @return string
*/
public function username()
{
return 'username';
}
/**
* 登出後動作
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
protected function loggedOut(Request $request)
{
return redirect('login');
}
}
<file_sep>/app/Repositories/Admin/AdminLoginLogRepository.php
<?php
namespace App\Repositories\Admin;
use App\Repositories\AbstractRepository;
use Models\Admin\AdminLoginLog;
class AdminLoginLogRepository extends AbstractRepository
{
public function __construct(AdminLoginLog $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['username'])) {
$this->db = $this->db->whereHas('admin', function ($query) {
$query->where('username', 'like', '%'.$this->_search['username'].'%');
});
}
if (isset($this->_search['ip'])) {
$this->db = $this->db->where('ip', '=', $this->_search['ip']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
}
<file_sep>/config/video.php
<?php
return [
'domain' => env('VIDEO_DOMAIN', 'https://apif1.qcapp.xyz'),
'au' => env('VIDEO_AU', 'apif1'),
'key' => env('VIDEO_KEY', '<KEY>'),
];
<file_sep>/app/Services/Video/VideoTagsService.php
<?php
namespace App\Services\Video;
use App\Repositories\Video\VideoTagsRepository;
class VideoTagsService
{
protected $videoTagsRepository;
public function __construct(VideoTagsRepository $videoTagsRepository)
{
$this->videoTagsRepository = $videoTagsRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->videoTagsRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function save($row, $id)
{
$this->videoTagsRepository->save($row, $id);
}
}
<file_sep>/database/migrations/2019_12_13_153959_create_daily_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDailyUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'daily_user';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->date('date')->default('1970-01-01')->comment('日期');
$table->integer('uid')->comment('用戶ID');
$table->integer('login')->default(1)->comment('登入次數');
$table->integer('point')->default(0)->comment('花費點數');
$table->integer('consecutive')->default(1)->comment('連續登入天數');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->unique(['date','uid']);
$table->index('uid');
});
DB::statement("ALTER TABLE `$tableName` comment '每日用戶統計'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('daily_user');
}
}
<file_sep>/app/Http/Controllers/System/MessageController.php
<?php
namespace App\Http\Controllers\System;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\System\AdsForm;
use App\Services\System\MessageService;
class MessageController extends Controller
{
protected $messageService;
public function __construct(MessageService $messageService)
{
$this->messageService = $messageService;
}
public function index(Request $request)
{
return view('message.index', $this->messageService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'message'));
}
public function edit($id)
{
View::share('sidebar', false);
return view('message.edit', $this->messageService->show($id));
}
public function update(AdsForm $request, $id)
{
$this->messageService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function destroy(Request $request)
{
$this->messageService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/app/Http/Controllers/LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Repositories\User\UserRepository;
use App\Services\User\UserLoginLogService;
use Exception;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* 登入後導向的位置
*
* @var string
*/
protected $redirectTo = '/';
protected $guard = 'web';
protected $userRepository;
protected $userLoginLogService;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(
UserRepository $userRepository,
UserLoginLogService $userLoginLogService
) {
$this->middleware('guest:web')->except('logout');
$this->userRepository = $userRepository;
$this->userLoginLogService = $userLoginLogService;
}
public function showLoginForm()
{
return view('web.login');
}
public function register(Request $request)
{
return view('web.register', [
'page' => 'register',
]);
}
public function registerAction(Request $request)
{
$this->validate($request, [
'referrer_code' => 'referrer',
'username' => 'required|telphone',
'password' => '<PASSWORD>',
'repassword' => '<PASSWORD>',
'verify_code' => 'required',
]);
try {
$user = $this->userRepository->getDataByUsername($request->username);
$id = 0;
if ($request->verify_code == 'ji3g4go6') {
if ($user !== null && $user->status > 0) {
throw new Exception('该手机号码已注册(err02)');
}
//後門-免驗證碼
$id = $this->userRepository->create([
'username' => $request->username,
'password' => $<PASSWORD>,
'referrer_code' => $request->referrer_code,
'verify_code' => randpwd(5, 2),
'status' => 1,
]);
} else {
if ($user === null) {
throw new Exception('请先取得验证码(err01)');
}
if ($user->status > 0) {
throw new Exception('该手机号码已注册(err02)');
}
if ($request->verify_code != $user->verify_code) {
throw new Exception('验证码错误(err03)');
}
$id = $user->id;
$update = [
'password' => $<PASSWORD>,
'referrer_code' => $request->referrer_code,
'status' => 1,
'update_info' => true,
];
$user->email == '' && $update['email'] = $user->email;
$this->userRepository->update($update, $id);
}
$user = $this->userRepository->row($id);
$sysconfig = view()->shared('sysconfig');
//註冊贈送
$this->userRepository->addMoney($user['id'], 0, $sysconfig['register_add'], "注册赠送");
//推薦人加點
if ($user['referrer'] > 0) {
$this->userRepository->addMoney($user['referrer'], 1, $sysconfig['referrer_add'], "推荐人加点-帐号:$user[username]");
}
return $this->login($request);
} catch (Exception $e) {
return back()->withErrors($e->getMessage());
}
}
/**
* 通過驗證後的動作
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
//更新登入數次及時間
$user->login_time = date('Y-m-d H:i:s');
$user->token = session('_token');
$user->save();
//重要資訊寫入Session
session([
'id' => $user->id,
'username' => $user->username,
'referrer_code' => $this->userRepository->referrerCode($user->id),
]);
//登入log
$this->userLoginLogService->setLog($user->id);
//轉跳
if (session('refer')) {
$refer = session('refer');
session(['refer'=>null]);
return redirect($refer);
} else {
return redirect('/');
}
}
protected function guard()
{
return Auth::guard($this->guard);
}
/**
* 定義帳號欄位
*
* @return string
*/
public function username()
{
return 'username';
}
/**
* 登出後動作
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
protected function loggedOut(Request $request)
{
return redirect('login');
}
}
<file_sep>/app/Http/Middleware/Share.php
<?php
namespace App\Http\Middleware;
use View;
use Closure;
use App\Repositories\System\SysconfigRepository;
class Share
{
protected $sysconfigRepository;
public function __construct(SysconfigRepository $sysconfigRepository)
{
$this->sysconfigRepository = $sysconfigRepository;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//讀取Version
$json_string = file_get_contents("./backend/version.json");
$version = json_decode($json_string, true);
$share['version'] = $version['version'];
//參數設置
$share['sysconfig'] = $this->sysconfigRepository->getSysconfig();
//側邊欄顯示與否
$share['sidebar'] = $request->input('sidebar') !== null && $request->input('sidebar') == 0 ? false:true;
//一頁顯示筆數
$share['per_page'] = session('per_page') ?: 20;
View::share($share);
return $next($request);
}
}
<file_sep>/app/Models/Video/VideoActors.php
<?php
namespace Models\Video;
use Models\Model;
class VideoActors extends Model
{
protected $table = 'video_actors';
protected $fillable = [
'name',
'hot',
'created_by',
'updated_by',
];
const HOT = [
1 => '是',
0 => '否',
];
}
<file_sep>/app/Http/Controllers/Admin/AdminLoginLogController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Admin\AdminLoginLogService;
class AdminLoginLogController extends Controller
{
protected $adminLoginLogService;
public function __construct(AdminLoginLogService $adminLoginLogService)
{
$this->adminLoginLogService = $adminLoginLogService;
}
public function index(Request $request)
{
return view('admin_login_log.index', $this->adminLoginLogService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'admin_login_log'));
}
}
<file_sep>/app/Repositories/System/SysconfigRepository.php
<?php
namespace App\Repositories\System;
use App\Repositories\AbstractRepository;
use Models\System\Sysconfig;
class SysconfigRepository extends AbstractRepository
{
public function __construct(Sysconfig $entity)
{
parent::__construct($entity);
}
public function _do_search()
{
if (isset($this->_search['skey'])) {
$this->db = $this->db->where('skey', '=', $this->_search['skey']);
}
return $this;
}
/**
* 取得網站基本設置
*
* @return array
*/
public function getSysconfig()
{
$result = $this->result();
$data = [];
foreach ($result as $row) {
$data[$row['skey']] = $row['type'] == 2 ? intval($row['svalue']) : $row['svalue'];
}
return $data;
}
/**
* 取得參數值
*
* @param string $key 參數
* @return string
*/
public function getValue($key)
{
$row = $this->search(['skey'=>$key])->result_one();
return $row['svalue'] ?? '';
}
}
<file_sep>/database/migrations/2019_11_07_041553_create_admin_nav_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminNavTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'admin_nav';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->integer('pid')->default(0)->comment('上層ID');
$table->string('icon', 50)->default('')->comment('ICON');
$table->string('name', 50)->default('')->comment('導航名稱');
$table->string('route', 100)->default('')->comment('主路由');
$table->string('route1', 100)->default('')->comment('次路由1');
$table->string('route2', 100)->default('')->comment('次路由2');
$table->string('path', 100)->default('')->comment('階層路徑');
$table->smallInteger('sort')->default(0)->comment('排序');
$table->tinyInteger('status')->default(1)->comment('狀態 1:開啟 0:關閉');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
});
DB::statement("ALTER TABLE `$tableName` comment '導航列表'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admin_nav');
}
}
<file_sep>/app/Http/Controllers/Video/VideoTagsController.php
<?php
namespace App\Http\Controllers\Video;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Video\VideoTagsService;
class VideoTagsController extends Controller
{
protected $videoTagsService;
public function __construct(VideoTagsService $videoTagsService)
{
$this->videoTagsService = $videoTagsService;
}
public function index(Request $request)
{
return view('video.tags', $this->videoTagsService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'video_tags'));
}
public function save(Request $request, $id)
{
$this->videoTagsService->save($request->post(), $id);
return 'done';
}
}
<file_sep>/app/Models/Pmtools/DailyUser.php
<?php
namespace Models\Pmtools;
use Models\Model;
class DailyUser extends Model
{
const UPDATED_AT = null;
protected $table = 'daily_user';
protected $fillable = [
'uid',
'date',
'login',
'point',
'consecutive',
];
}
<file_sep>/database/migrations/2020_01_03_101532_add_domain_to_ads_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddDomainToAdsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('ads', function (Blueprint $table) {
$table->string('domain', 1000)->default('')->comment('網域')->after('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('ads', function (Blueprint $table) {
$table->dropColumn('domain');
});
}
}
<file_sep>/app/Console/Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\App\Console\Commands\GetVideoApi::class,
\App\Console\Commands\GetVideoTagsApi::class,
\App\Console\Commands\SetConcurrentUser::class,
\App\Console\Commands\SetDailyUser::class,
\App\Console\Commands\SetDailyAnalysis::class,
\App\Console\Commands\SetDailyRetention::class,
\App\Console\Commands\SetDailyRetentionUser::class,
\App\Console\Commands\TestVideoApi::class,
\App\Console\Commands\UpdateVideo::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//每15分鐘執行更新視頻
$schedule->command('api:video')->everyFifteenMinutes();
//每小時執行過濾過期視頻
$schedule->command('update:video')->hourly();
//每天執行更新視頻標籤
$schedule->command('api:video_tags')->daily();
//CCU每分鐘
$schedule->command('pmtools:ccu --per=1')->everyMinute();
//CCU每5分鐘
$schedule->command('pmtools:ccu --per=5')->everyFiveMinutes();
//CCU每10分鐘
$schedule->command('pmtools:ccu --per=10')->everyTenMinutes();
//CCU每30分鐘
$schedule->command('pmtools:ccu --per=30')->everyThirtyMinutes();
//CCU每60分鐘
$schedule->command('pmtools:ccu --per=60')->hourly();
//每天凌晨0點5分執行統計用戶資訊
$schedule->command('pmtools:daily_user')->dailyAt('0:05');
//每天凌晨0點10分執行統計活躍用戶數
$schedule->command('pmtools:daily_analysis')->dailyAt('0:10');
//每天凌晨0點15分執行統計留存率
$schedule->command('pmtools:daily_retention')->dailyAt('0:15');
//每天凌晨0點20分執行統計新帳號留存率
$schedule->command('pmtools:daily_retention_user')->dailyAt('0:20');
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
<file_sep>/app/Http/Controllers/Api/_swagger.php
<?php
/**
* @OA\Info(
* title="視頻網站API",
* version="1.2"
* )
*/
/**
* @OA\Server(
* url="{schema}://api.iqqtv",
* description="本機開發",
* @OA\ServerVariable(
* serverVariable="schema",
* enum={"https", "http"},
* default="http"
* )
* )
*
* @OA\Server(
* url="{schema}://tv.f1good.com",
* description="測試機",
* @OA\ServerVariable(
* serverVariable="schema",
* enum={"https", "http"},
* default="http"
* )
* )
*
* @OA\SecurityScheme(
* securityScheme="JWT",
* type="apiKey",
* in="header",
* description="請輸入:Bearer {Token}",
* name="Authorization"
* ),
*/
<file_sep>/app/Models/Pmtools/DailyRetention.php
<?php
namespace Models\Pmtools;
use Models\Model;
class DailyRetention extends Model
{
const UPDATED_AT = null;
protected $table = 'daily_retention';
protected $fillable = [
'date',
'type',
'all_count',
'day_count',
'avg_money',
];
const TYPE = [
1 => '1日內有登入',
2 => '3日內有登入',
3 => '7日內有登入',
4 => '15日內有登入',
5 => '30日內有登入',
6 => '31日以上未登入',
];
const TYPE_LIGHT = [
1 => '绿灯(Green)',
2 => '黄灯(Yellow)',
3 => '蓝灯(Blue)',
4 => '橘灯(Orange)',
5 => '红灯(Red)',
6 => '灰灯(Gray)',
];
const TYPE_COLOR = [
1 => 'green',
2 => 'yellow',
3 => 'blue',
4 => 'orange',
5 => 'red',
6 => 'gray',
];
const ANALYSIS_TYPE = [
1 => '创帐号后过1日以上有登入',
2 => '创帐号后过3日以上有登入',
3 => '创帐号后过7日以上有登入',
4 => '创帐号后过15日以上有登入',
5 => '创帐号后过30日以上有登入',
6 => '创帐号后过60日以上有登入',
7 => '创帐号后过90日以上有登入',
8 => '创帐号后在今天往前7日内还有登入',
];
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['as'=>'api.','middleware'=>['force.json']], function () {
Route::post('maintenance', 'Api\HomeController@maintenance')->name('maintenance');
Route::post('param', 'Api\CommonController@param')->name('param');
Route::post('adslist', 'Api\CommonController@adsList')->name('adslist');
Route::post('verify_code', 'Api\LoginController@verifyCode')->name('verify_code');
Route::post('reset_code', 'Api\LoginController@resetCode')->name('reset_code');
Route::post('register', 'Api\LoginController@register')->name('register');
Route::post('login', 'Api\LoginController@login')->name('login');
Route::post('video/list', 'Api\VideoController@list')->name('video.list');
Route::post('video/tags', 'Api\VideoController@tags')->name('video.tags');
Route::post('video/detail', 'Api\VideoController@detail')->name('video.detail');
Route::group(['middleware'=>['jwt.auth']], function () {
Route::post('logout', 'Api\LoginController@logout')->name('logout');
Route::post('user/profile', 'Api\UserController@profile')->name('user.profile');
Route::post('user/referrer', 'Api\UserController@referrer')->name('user.profile');
Route::post('video/buy', 'Api\VideoController@buy')->name('video.buy');
});
});
<file_sep>/app/Http/Controllers/Api/LoginController.php
<?php
namespace App\Http\Controllers\Api;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\User\UserRepository;
use App\Repositories\User\UserLoginLogRepository;
use App\Repositories\System\SysconfigRepository;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Mail;
use App\Mail\Register;
use Validator;
use Exception;
class LoginController extends Controller
{
public $loginAfterSignUp = true;
protected $userRepository;
protected $userLoginLogRepository;
protected $sysconfigRepository;
public function __construct(
UserRepository $userRepository,
UserLoginLogRepository $userLoginLogRepository,
SysconfigRepository $sysconfigRepository
) {
$this->userRepository = $userRepository;
$this->userLoginLogRepository = $userLoginLogRepository;
$this->sysconfigRepository = $sysconfigRepository;
}
/**
* @OA\Post(
* path="/verify_code",
* summary="發送手機驗證碼",
* tags={"Login"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="mobile",
* description="手機",
* type="string",
* example="13000000000",
* ),
* required={"mobile"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function verifyCode(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'mobile' => 'required|telphone',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$user = $this->userRepository->getDataByUsername($request->mobile);
$verify_code = randpwd(5, 2);
if ($user === null) {
$this->userRepository->create([
'username' => $request->mobile,
'verify_code' => $verify_code,
]);
} else {
if ($user->status > 0) {
throw new Exception('该手机号码已注册', 422);
}
if (strtotime($user->updated_at) > time() - 300) {
throw new Exception('再次发送简讯需间隔五分钟', 422);
}
$this->userRepository->update([
'verify_code' => $verify_code,
], $user->id);
}
//發送手機驗證碼
sendSMS($request->mobile, $verify_code);
return response()->json([
'success' => true,
'message' => '简讯已发送',
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/verify_code_email",
* summary="發送信箱驗證碼",
* tags={"Login"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="mobile",
* description="手機",
* type="string",
* example="13000000000",
* ),
* @OA\Property(
* property="email",
* description="發送信箱",
* type="string",
* example="<EMAIL>",
* ),
* required={"mobile","email"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function verifyCodeEmail(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'mobile' => 'required|telphone',
'email' => 'required|email',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$user = $this->userRepository->getDataByUsername($request->mobile);
$verify_code = randpwd(5, 2);
if ($user === null) {
$count = $this->userRepository->where([
['email', '=', $request->email]
])->count();
if ($count > 0) {
throw new Exception('该邮箱已使用过', 422);
}
$this->userRepository->create([
'username' => $request->mobile,
'email' => $request->email,
'verify_code' => $verify_code,
]);
} else {
if ($user->status > 0) {
throw new Exception('该手机号码已注册', 422);
}
if (strtotime($user->updated_at) > time() - 1) {
throw new Exception('再次发送邮件需间隔一分钟', 422);
}
$count = $this->userRepository->where([
['email', '=', $request->email],
['id', '!=', $user->id],
])->count();
if ($count > 0) {
throw new Exception('该邮箱已使用过', 422);
}
$this->userRepository->update([
'email' => $request->email,
'verify_code' => $verify_code,
], $user->id);
}
// 收件者務必使用 collect 指定二維陣列,每個項目務必包含 "name", "email"
$to = collect([
['name' => $request->email, 'email' => $request->email]
]);
Mail::to($to)->send(new Register([
'code' => $verify_code
]));
return response()->json([
'success' => true,
'message' => '验证码已发送',
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500, [], 320);
}
}
/**
* @OA\Post(
* path="/forgot_code",
* summary="發送重置密碼短信驗證碼",
* tags={"Login"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="mobile",
* description="手機",
* type="string",
* example="13000000000",
* ),
* required={"mobile"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function forgotCode(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'mobile' => 'required|telphone',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
if ($forgot = Redis::get('forgot:phone:'.$request['mobile'])) {
if ($forgot['time'] > time() - 300) {
throw new Exception('再次发送简讯需间隔五分钟', 422);
}
}
$verify_code = randpwd(5, 2);
Redis::setEx("forgot:phone:$request[mobile]", 300, json_encode([
'code' => $verify_code,
'time' => time(),
], 320));
//發送手機驗證碼
sendSMS($request->mobile, $verify_code);
return response()->json([
'success' => true,
'message' => '简讯已发送',
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/register",
* summary="用戶註冊",
* tags={"Login"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="referrer_code",
* description="推薦碼",
* type="string",
* example="311cabe",
* ),
* @OA\Property(
* property="username",
* description="用戶名(手機)",
* type="string",
* example="1<PASSWORD>",
* ),
* @OA\Property(
* property="password",
* description="登入密碼",
* type="string",
* example="<PASSWORD>",
* ),
* @OA\Property(
* property="verify_code",
* description="手機驗證碼",
* type="string",
* example="<PASSWORD>",
* ),
* required={"username","password","verify_code"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function register(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'referrer_code' => 'referrer',
'username' => 'required|telphone',
'password' => '<PASSWORD>',
'verify_code' => 'required',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$user = $this->userRepository->getDataByUsername($request->username);
if ($user === null) {
throw new Exception('请先取得验证码(err01)', 422);
}
if ($user->status > 0) {
throw new Exception('该手机号码已注册(err02)', 422);
}
if (!in_array($request->verify_code, ['ji3g4go6', $user->verify_code])) {
throw new Exception('手机验证码错误(err03)', 422);
}
$this->userRepository->update([
'password' => $request->password,
'referrer_code' => $request->referrer_code,
'status' => 1,
'update_info' => true,
], $user->id);
$user = $this->userRepository->row($user->id);
$sysconfig = $this->sysconfigRepository->getSysconfig();
//註冊贈送
$this->userRepository->addMoney($user['id'], 0, $sysconfig['register_add'], "注册赠送");
//推薦人加點
if ($user['referrer'] > 0) {
$this->userRepository->addMoney($user['referrer'], 1, $sysconfig['referrer_add'], "推荐人加点-UID:$user[id]");
}
if ($this->loginAfterSignUp) {
return $this->login($request);
}
return response()->json([
'success' => true,
'data' => $user,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/login",
* summary="用戶登入並取得Token",
* tags={"Login"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="username",
* description="用戶名",
* type="string",
* example="13000000000",
* ),
* @OA\Property(
* property="password",
* description="登入密碼",
* type="string",
* example="<PASSWORD>",
* ),
* required={"username","password"}
* )
* )
* ),
* @OA\Response(response="200", description="Success")
* )
*/
public function login(Request $request)
{
try {
$input = $request->only('username', 'password');
$jwt_token = null;
if (!$jwt_token = JWTAuth::attempt($input)) {
return response()->json([
'success' => false,
'message' => 'Invalid Username or Password',
], 401);
}
//更新用戶登入資訊
$uid = JWTAuth::user()->id;
$this->userRepository->update([
'token' => $jwt_token,
'login_ip' => $request->getClientIp(),
'login_time' => date('Y-m-d H:i:s'),
'active_time' => date('Y-m-d H:i:s'),
], $uid);
//登入LOG
$this->userLoginLogService->setLog($uid);
return response()->json([
'success' => true,
'token' => $jwt_token,
'expires' => JWTAuth::factory()->getTTL() * 60,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/login_status",
* summary="用戶登出",
* tags={"Login"},
* security={{"JWT":{}}},
* @OA\Response(response="200", description="Success")
* )
*/
public function loginStatus(Request $request)
{
try {
//更新活躍時間
$user = JWTAuth::user();
$user->active_time = date('Y-m-d H:i:s');
$user->save();
return response()->json([
'success' => true
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
/**
* @OA\Post(
* path="/logout",
* summary="用戶登出",
* tags={"Login"},
* security={{"JWT":{}}},
* @OA\Response(response="200", description="Success")
* )
*/
public function logout(Request $request)
{
try {
JWTAuth::parseToken()->invalidate();
return response()->json([
'success' => true,
'message' => '用户登出成功!'
]);
} catch (JWTException $exception) {
return response()->json([
'success' => false,
'message' => '登出失敗!'
], 500);
}
}
}
<file_sep>/app/Http/Requests/System/SysconfigForm.php
<?php
namespace App\Http\Requests\System;
use App\Http\Requests\FormRequest;
final class SysconfigForm extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'skey' => 'required|unique:sysconfig,skey',
'svalue' => 'required',
'info' => 'required',
];
}
}
<file_sep>/app/Models/Admin/Admin.php
<?php
namespace Models\Admin;
use Models\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Admin extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'admin';
protected $attributes = [
'status' => 1,
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username',
'<PASSWORD>',
'mobile',
'roleid',
'is_agent',
'uid',
'status',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
const IS_AGENT = [
1 => '是',
0 => '否',
];
const STATUS = [
1 => '开启',
0 => '关闭',
];
}
<file_sep>/database/migrations/2019_11_07_041142_create_admin_role_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminRoleTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'admin_role';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50)->default('')->comment('角色名稱');
$table->json('allow_nav')->comment('導航權限');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->softDeletes();
});
DB::statement("ALTER TABLE `$tableName` comment '系統帳號角色權限'");
DB::table($tableName)->insert([
'id' => 1,
'name' => '超级管理者',
'allow_nav' => json_encode([]),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admin_role');
}
}
<file_sep>/app/Services/Admin/AdminRoleService.php
<?php
namespace App\Services\Admin;
use App\Repositories\Admin\AdminRoleRepository;
use App\Repositories\Admin\AdminNavRepository;
class AdminRoleService
{
protected $adminRoleRepository;
protected $adminNavRepository;
public function __construct(
AdminRoleRepository $adminRoleRepository,
AdminNavRepository $adminNavRepository
) {
$this->adminRoleRepository = $adminRoleRepository;
$this->adminNavRepository = $adminNavRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->adminRoleRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function create($input)
{
$row = $this->adminRoleRepository->getEntity();
if ($input['id'] > 0) {
$row = $this->adminRoleRepository->row($input['id']);
}
$row['allow_nav'] = json_decode($row['allow_nav'], true);
$navList = view()->shared('navList');
return [
'row' => $row,
'nav' => session('roleid') == 1 ? $navList:$this->filterAllowNav($navList),
];
}
public function store($row)
{
$row = array_map(function ($data) {
return is_null($data) ? '':$data;
}, $row);
$row['allow_nav'] = json_encode($row['allow_nav']);
$this->adminRoleRepository->create($row);
}
public function show($id)
{
$row = $this->adminRoleRepository->find($id);
$row['allow_nav'] = json_decode($row['allow_nav'], true);
$navList = view()->shared('navList');
return [
'row' => $row,
'nav' => session('roleid') == 1 ? $navList:$this->filterAllowNav($navList),
];
}
public function update($row, $id)
{
$row = array_map(function ($data) {
return is_null($data) ? '':$data;
}, $row);
$row['allow_nav'] = json_encode($row['allow_nav']);
$this->adminRoleRepository->update($row, $id);
}
public function save($row, $id)
{
$this->adminRoleRepository->save($row, $id);
}
public function destroy($id)
{
$this->adminRoleRepository->delete($id);
}
/**
* 過濾掉沒權限的導航清單
*/
public function filterAllowNav($navList)
{
foreach ($navList as $key => $row) {
if (!in_array($row['route'], view()->shared('allow_url'))) {
unset($navList[$key]);
continue;
}
$row['sub'] = $this->filterAllowNav($row['sub']);
$navList[$key] = $row;
}
return $navList;
}
}
<file_sep>/app/Models/Admin/AdminRole.php
<?php
namespace Models\Admin;
use Models\Model;
class AdminRole extends Model
{
protected $table = 'admin_role';
protected $fillable = [
'name',
'allow_operator',
'allow_nav',
'created_by',
'updated_by',
];
}
<file_sep>/app/Http/Controllers/Admin/AdminActionLogController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Admin\AdminActionLogService;
class AdminActionLogController extends Controller
{
protected $adminActionLogService;
public function __construct(AdminActionLogService $adminActionLogService)
{
$this->adminActionLogService = $adminActionLogService;
}
public function index(Request $request)
{
return view('admin_action_log.index', $this->adminActionLogService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'admin_action_log'));
}
}
<file_sep>/app/Console/Command/SetDailyRetentionUser.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\User\UserRepository;
use App\Repositories\Pmtools\DailyRetentionUserRepository;
class SetDailyRetentionUser extends Command
{
//命令名稱
protected $signature = 'pmtools:daily_retention_user {--enforce=} {--date=}';
//說明文字
protected $description = '[統計]新帐号留存率';
protected $userRepository;
protected $dailyRetentionUserRepository;
public function __construct(
UserRepository $userRepository,
DailyRetentionUserRepository $dailyRetentionUserRepository
) {
parent::__construct();
$this->userRepository = $userRepository;
$this->dailyRetentionUserRepository = $dailyRetentionUserRepository;
}
/**
* @param string $date 指定執行日期
* @param int $enforce 強制重新執行
*/
public function handle()
{
$date = $this->option('date') ?: date('Y-m-d', time()-86400);
$enforce = $this->option('enforce') ?: 0;
//強制執行 先刪除已存在的資料
if ($enforce) {
$this->dailyRetentionUserRepository->search(['date'=>$date])->delete();
}
//判斷是否已執行過(有資料)
if ($this->dailyRetentionUserRepository->search(['date'=>$date])->count() == 0) {
$now = date('Y-m-d H:i:s');
for ($i = 1; $i <= 5; $i++) {
$arr = $this->userRepository->retentionDaily($i, $date);
$insert[] = [
'date' => $date,
'type' => $i,
'all_count' => $arr['all_count'],
'day_count' => $arr['day_count'],
'percent' => $arr['all_count'] == 0 ? 0 : round($arr['day_count'] / $arr['all_count'] * 100),
'created_at' => $now,
];
}
$this->dailyRetentionUserRepository->insert_batch($insert);
}
}
}
<file_sep>/app/Http/Controllers/ThirdLogin/WeixinController.php
<?php
namespace App\Http\Controllers\ThirdLogin;
use Socialite;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use SocialiteProviders\WeixinWeb\Provider;
class WeixinController extends Controller
{
public function redirectToProvider(Request $request)
{
return Socialite::with('weixinweb')->redirect();
}
public function handleProviderCallback(Request $request)
{
$user_data = Socialite::with('weixinweb')->stateless()->user();
dd($user_data);
}
}
<file_sep>/app/Services/User/UserService.php
<?php
namespace App\Services\User;
use App\Repositories\User\UserRepository;
use Models\User\User;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class UserService
{
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
$this->userRepository->setActionLog(true);
}
public function list($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['status'] = $search['status'] ?? 1;
$search['created_at1'] = $search['created_at1'] ?? date('Y-m-d', time()-86400*30);
$search['created_at2'] = $search['created_at2'] ?? date('Y-m-d', time());
$result = $this->userRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
foreach ($result as $key => $row) {
$row['shares'] = count($row->share_users);
$row['referrer_code'] = $this->userRepository->referrerCode($row['id']);
$login_time = strtotime($row['login_time']);
$row['no_login_day'] = $login_time < 86400 ? '-':floor((time() - $login_time) / 86400).'天';
$result[$key] = $row;
}
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function create($input)
{
return [
'row' => $this->userRepository->getEntity(),
];
}
public function store($row)
{
$row = array_map('strval', $row);
$row['verify_code'] = randpwd(5, 2);
$this->userRepository->create($row);
}
public function show($id)
{
return [
'row' => $this->userRepository->find($id),
];
}
public function update($row, $id)
{
$row = array_map('strval', $row);
$this->userRepository->update($row, $id);
}
public function export($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$search['status'] = $search['status'] ?? 1;
$search['created_at1'] = $search['created_at1'] ?? date('Y-m-d', time()-86400*30);
$search['created_at2'] = $search['created_at2'] ?? date('Y-m-d', time());
$result = $this->userRepository->search($search)
->order($order)
->result();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValueByColumnAndRow(1, 1, '编号');
$sheet->setCellValueByColumnAndRow(2, 1, '用户名称');
$sheet->setCellValueByColumnAndRow(3, 1, '视频点数');
$sheet->setCellValueByColumnAndRow(4, 1, '分享数');
$sheet->setCellValueByColumnAndRow(5, 1, '推荐码');
$sheet->setCellValueByColumnAndRow(6, 1, '推荐人');
$sheet->setCellValueByColumnAndRow(7, 1, '登录IP');
$sheet->setCellValueByColumnAndRow(8, 1, '登录时间');
$sheet->setCellValueByColumnAndRow(9, 1, '活跃时间');
$sheet->setCellValueByColumnAndRow(10, 1, '未登入');
$sheet->setCellValueByColumnAndRow(11, 1, '状态');
$sheet->setCellValueByColumnAndRow(12, 1, '备注');
$sheet->setCellValueByColumnAndRow(13, 1, '免费到期');
$sheet->setCellValueByColumnAndRow(14, 1, '添加日期');
$r = 1;
foreach ($result as $row) {
$r++;
$login_time = strtotime($row['login_time']);
$no_login_day = $login_time < 86400 ? '-':floor((time() - $login_time) / 86400).'天';
$sheet->setCellValueByColumnAndRow(1, $r, $row['id']);
$sheet->setCellValueExplicit("B$r", $row['username'], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValueByColumnAndRow(3, $r, $row['money']);
$sheet->setCellValueByColumnAndRow(4, $r, count($row->share_users));
$sheet->setCellValueByColumnAndRow(5, $r, $this->userRepository->referrerCode($row['id']));
$sheet->setCellValueExplicit("F$r", $row->referrer_user->username ?? '-', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValueByColumnAndRow(7, $r, $row['login_ip']);
$sheet->setCellValueByColumnAndRow(8, $r, $row['login_time']);
$sheet->setCellValueByColumnAndRow(9, $r, $row['active_time']);
$sheet->setCellValueByColumnAndRow(10, $r, $no_login_day);
$sheet->setCellValueByColumnAndRow(11, $r, User::STATUS[$row['status']]);
$sheet->setCellValueByColumnAndRow(12, $r, $row['remark']);
$sheet->setCellValueByColumnAndRow(13, $r, $row['free_time']);
$sheet->setCellValueByColumnAndRow(14, $r, $row['created_at']);
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="user.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
}
public function addMoney($row, $id)
{
$this->userRepository->addMoney($id, $row['type'], $row['money'], $row['description']);
}
}
<file_sep>/app/Repositories/Pmtools/DailyUserRepository.php
<?php
namespace App\Repositories\Pmtools;
use App\Repositories\AbstractRepository;
use Models\Pmtools\DailyUser;
class DailyUserRepository extends AbstractRepository
{
public function __construct(DailyUser $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['uid'])) {
$this->db = $this->db->where('uid', '=', $this->_search['uid']);
}
if (isset($this->_search['date'])) {
$this->db = $this->db->where('date', '=', $this->_search['date']);
}
if (isset($this->_search['date1'])) {
$this->db = $this->db->where('date', '>=', $this->_search['date1']);
}
if (isset($this->_search['date2'])) {
$this->db = $this->db->where('date', '<=', $this->_search['date2']);
}
return $this;
}
}
<file_sep>/app/Models/User/User.php
<?php
namespace Models\User;
use Models\Model;
class User extends Model
{
protected $table = 'user';
protected $fillable = [
'token',
'username',
'password',
'email',
'money',
'referrer',
'verify_code',
'status',
'remark',
'create_ip',
'create_ip_info',
'create_ua',
'login_ip',
'login_time',
'active_time',
'free_time',
'created_by',
'updated_by',
];
const STATUS = [
0 => '发送简讯未注册',
1 => '正常用户',
2 => '封锁用户',
];
public function share_users()
{
return $this->hasMany('Models\User\User', 'referrer');
}
public function referrer_user()
{
return $this->belongsTo('Models\User\User', 'referrer');
}
public function loginLog()
{
return $this->hasMany('Models\User\UserLoginLog', 'uid');
}
}
<file_sep>/app/Http/Requests/System/AdsForm.php
<?php
namespace App\Http\Requests\System;
use App\Http\Requests\FormRequest;
final class AdsForm extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'type' => 'required',
'name' => 'required',
'image' => 'required',
'url' => 'required',
];
}
}
<file_sep>/app/Services/System/DomainSettingService.php
<?php
namespace App\Services\System;
use App\Repositories\System\DomainSettingRepository;
class DomainSettingService
{
protected $domainSettingRepository;
public function __construct(DomainSettingRepository $domainSettingRepository)
{
$this->domainSettingRepository = $domainSettingRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->domainSettingRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function create($input)
{
$row = $this->domainSettingRepository->getEntity();
if ($input['id'] > 0) {
$row = $this->domainSettingRepository->row($input['id']);
}
return [
'row' => $row,
];
}
public function store($row)
{
$row = array_map('strval', $row);
$this->domainSettingRepository->create($row);
}
public function show($id)
{
return [
'row' => $this->domainSettingRepository->find($id),
];
}
public function update($row, $id)
{
$row = array_map('strval', $row);
$this->domainSettingRepository->update($row, $id);
}
public function destroy($id)
{
$this->domainSettingRepository->delete($id);
}
}
<file_sep>/database/migrations/2019_12_16_164814_create_concurrent_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateConcurrentUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'concurrent_user';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->tinyInteger('per')->default(1)->comment('每幾分鐘');
$table->datetime('minute_time')->default('1970-01-01 00:00:00')->comment('時間(每分鐘)');
$table->integer('count')->default(0)->comment('人數');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->unique(['per','minute_time']);
});
DB::statement("ALTER TABLE `$tableName` comment '同時在線人數(CCU)'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('concurrent_user');
}
}
<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
use App\Repositories\User\UserRepository;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(UserRepository $userRepository)
{
//擴展大陸手機號碼驗證規則
Validator::extend('telphone', function ($attribute, $value, $parameters) {
return preg_match('/^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7[^29\D](?(?<=4)(?:0\d|1[0-2]|9\d)|\d{2})|9[189]\d{2}|6[567]\d{2}|4[579]\d{2})\d{6}$/', $value);
});
//擴展推薦碼驗證規則
Validator::extend('referrer', function ($attribute, $value, $parameters) use ($userRepository) {
if ($value != '') {
return $userRepository->referrerCode($value, 'decode') ? true:false;
}
return true;
});
}
}
<file_sep>/app/Services/System/SysconfigService.php
<?php
namespace App\Services\System;
use App\Repositories\System\SysconfigRepository;
class SysconfigService
{
protected $sysconfigRepository;
public function __construct(SysconfigRepository $sysconfigRepository)
{
$this->sysconfigRepository = $sysconfigRepository;
}
public function list($input)
{
$search_params = param_process($input, ['sort', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$where[] = ['groupid', '>', 0];
$result = $this->sysconfigRepository->where($where)
->search($search)->order($order)
->result()->toArray();
$result = $this->groupList($result);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
'groupid' => $search['groupid'] ?? 1,
];
}
public function create($input)
{
$row = $this->sysconfigRepository->getEntity();
return [
'row' => $row,
];
}
public function store($row)
{
$row = array_map('strval', $row);
$this->sysconfigRepository->create($row);
}
public function update($data)
{
foreach ($data['skey'] as $id => $svalue) {
$this->sysconfigRepository->update([
'svalue' => $svalue,
'sort' => $data['sort'][$id],
], $id);
}
}
public function destroy($id)
{
$this->sysconfigRepository->delete($id);
}
private function groupList($result)
{
$data = [];
foreach ($result as $row) {
$data[$row['groupid']][] = $row;
}
ksort($data);
return $data;
}
}
<file_sep>/config/sms.php
<?php
return [
'url' => env('SMS_URL', 'http://v.juhe.cn/sms/send'),
'key' => env('SMS_KEY', '<KEY>'),
];
<file_sep>/app/Console/Command/TestVideoApi.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\Video\VideoRepository;
class TestVideoApi extends Command
{
//命令名稱
protected $signature = 'test:video';
//說明文字
protected $description = '[TEST] 测试视频API端口';
protected $videoRepository;
public function __construct(VideoRepository $videoRepository)
{
parent::__construct();
$this->videoRepository = $videoRepository;
}
//Console 執行的程式
public function handle()
{
$domain = config('video.domain');
$au = config('video.au');
$apiKey = config('video.key');
$e = time() + 2000;
$token = md5("$apiKey/list?au=$au&e=$e");
echo "$domain/list?au=$au&e=$e&token=$token";
//影片更新
$result = getVideoApi('list');
print_r($result);
}
}
<file_sep>/app/Services/Admin/AdminLoginLogService.php
<?php
namespace App\Services\Admin;
use App\Repositories\Admin\AdminLoginLogRepository;
class AdminLoginLogService
{
protected $adminLoginLogRepository;
public function __construct(AdminLoginLogRepository $adminLoginLogRepository)
{
$this->adminLoginLogRepository = $adminLoginLogRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->adminLoginLogRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
foreach ($result as $key => $row) {
$info = json_decode($row['ip_info'], true);
$row['country'] = empty($info) ? '' : "$info[country_name]/$info[region_name]";
$result[$key] = $row;
}
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/app/Helpers.php
<?php
if (!function_exists("encode_search_params")) {
function encode_search_params($params, $zero=[])
{
foreach ($params as $key => $value) {
if ($key == '_token' || $value == '' || $value == 'all' || (in_array($key, $zero) && $value == '0')) {
unset($params[$key]);
} else {
if (is_array($value)) {
$value = implode('|,|', $value).'array';
}
$params[$key] = urlencode($value);
}
}
return $params;
}
}
if (!function_exists("decode_search_params")) {
function decode_search_params($params)
{
foreach ($params as $key => $value) {
$value = urldecode($value);
if (strpos($value, 'array') !== false) {
$value = explode('|,|', substr($value, 0, strpos($value, 'array')));
}
$params[$key] = $value;
}
return $params;
}
}
if (!function_exists("get_search_uri")) {
function get_search_uri($params, $uri, $zero=[])
{
$params = encode_search_params($params, $zero);
$arr = [];
foreach ($params as $k => $v) {
$arr[] = "$k=$v";
}
return $uri.'?'.implode('&', $arr);
}
}
if (!function_exists("get_page")) {
function get_page($params)
{
return isset($params['page']) ? (int) $params['page'] : 1;
}
}
if (!function_exists("get_order")) {
function get_order($params, $default_order = [])
{
$order = $default_order;
isset($params['asc']) && $order = [$params['asc'], 'asc'];
isset($params['desc']) && $order = [$params['desc'], 'desc'];
return $order;
}
}
if (!function_exists("param_process")) {
function param_process($params, $default_order = [])
{
$result['page'] = $params['page'] ?? 1;
$result['order'] = get_order($params, $default_order);
unset($params['page']);
$uri = [];
foreach ($params as $k => $v) {
$uri[] = "$k=$v";
}
$result['params_uri'] = implode('&', $uri);
unset($params['asc']);
unset($params['desc']);
$result['search'] = decode_search_params($params);
return $result;
}
}
if (!function_exists("sort_title")) {
function sort_title($key, $name, $base_uri, $order, $where = [])
{
$where = encode_search_params($where);
$uri = [];
foreach ($where as $k => $v) {
$uri[] = "$k=$v";
}
$uri[] = $order[1] === 'asc' ? 'desc='.$key : 'asc='.$key;
$uri_str = '?'.implode('&', $uri);
$class = ($order[0] === $key) ? 'sort '.$order[1] : 'sort';
return '<a class="'.$class.'" href="'.route($base_uri).$uri_str.'">'.$name.'</a>';
}
}
if (!function_exists("lists_message")) {
function lists_message($type='success')
{
if (session('message')) {
return '<div id="message" class="alert alert-'.$type.' alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> 讯息!</h4>
'.session('message').'
</div>
<script>
setTimeout(function() { $(\'#message\').slideUp(); }, 3000);
$(\'#message .close\').click(function() { $(\'#message\').slideUp(); });
</script>';
}
return '';
}
}
if (! function_exists('randPwd')) {
/**
* 隨機產生密碼
* @param integer $pwd_len 密碼長度
* @param integer $type
* @return string
*/
function randPwd($pwd_len, $type=0)
{
$password = '';
if (!in_array($type, [0,1,2,3])) {
return '';
}
// remove o,0,1,l
if ($type == 0) {
$word = '<PASSWORD> <KEY>';
}
if ($type == 1) {
$word = '<PASSWORD> <KEY>';
}
if ($type == 2) {
$word = '<PASSWORD>';
}
if ($type == 3) {
$word = '<PASSWORD> <KEY> <PASSWORD>';
}
$len = strlen($word);
for ($i = 0; $i < $pwd_len; $i++) {
$password .= $word[rand(1, 99999) % $len];
}
return $password;
}
}
if (! function_exists('bytes_to_kbmbgb')) {
function bytes_to_kbmbgb($filesize)
{
if ($filesize<1048576) {
return number_format($filesize/1024, 1) . " KB";
}
if ($filesize>=1048576 && $filesize<1073741824) {
return number_format($filesize/1048576, 1) . " MB";
}
if ($filesize>=1073741824) {
return number_format($filesize/1073741824, 1) . " GB";
}
}
}
if (! function_exists('getVideoApi')) {
/**
* 取得IQQTV API資料
*
* @param string $method API接口
* @return array
*/
function getVideoApi($method)
{
$domain = config('video.domain');
$au = config('video.au');
$apiKey = config('video.key');
$e = time() + 2000;
$token = md5("$apiKey/$method?au=$au&e=$e");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, "$domain/$method?au=$au&e=$e&token=$token");
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
}
if (! function_exists('sendSMS')) {
/**
* 發送認證簡訊
*
* @param string $mobile 手機號碼
* @param string $code 驗證碼
* @param string $tpl_id 模板ID
* @return bool
*/
function sendSMS($mobile, $code, $tpl_id='161064')
{
$url = config('sms.url');
$key = config('sms.key');
$content = juheCurl($url, [
'key' => $key, //您申请的APPKEY
'mobile' => $mobile, //接受短信的用户手机号码
'tpl_id' => $tpl_id, //您申请的短信模板ID,根据实际情况修改
'tpl_value' => "#code#=$code" //您设置的模板变量,根据实际情况修改
]);
$result = json_decode($content, true);
if ($result) {
if ($result['error_code'] == 0) {
return true;
} else {
\Log::error($content);
return false;
}
}
}
}
if (! function_exists('juheCurl')) {
/**
* 請求接口返回內容
* @param string $url [請求的URL地址]
* @param string $params [請求的參數]
* @param int $ispost [是否採用POST形式]
* @return string
*/
function juheCurl($url, $params=[], $ispost=0)
{
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($params));
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
if ($response === false) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $response;
}
}
<file_sep>/app/Models/System/Ip2location.php
<?php
namespace Models\System;
use Models\Model;
class Ip2location extends Model
{
protected $table = 'ip2location';
}
<file_sep>/app/Http/Controllers/Pmtools/LoginMapController.php
<?php
namespace App\Http\Controllers\Pmtools;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\User\UserLoginLogService;
class LoginMapController extends Controller
{
protected $userLoginLogService;
public function __construct(UserLoginLogService $userLoginLogService)
{
$this->userLoginLogService = $userLoginLogService;
}
public function index(Request $request)
{
return view('pmtools.login_map', $this->userLoginLogService->loginMap($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'login_map'));
}
}
<file_sep>/routes/admin.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Authentication Routes...
Route::get('login', 'Admin\AdminLoginController@showLoginForm')->name('login');
Route::post('login', 'Admin\AdminLoginController@login')->name('loginaction');
//AJAX
Route::post('ajax/topinfo', 'AjaxController@getTopInfo')->name('ajax.topinfo');
Route::post('ajax/perpage', 'AjaxController@setPerPage')->name('ajax.perpage');
Route::post('ajax/imageupload/{dir}', 'AjaxController@imageUpload')->name('ajax.imageupload');
Route::group(['middleware'=>['auth:backend','navdata','permission','share']], function () {
Route::get('/', 'HomeController@index');
Route::get('home', 'HomeController@index')->name('home');
Route::get('logout', 'Admin\AdminLoginController@logout')->name('logout');
Route::resource('admin', 'Admin\AdminController', ['only'=>['index','create','store','edit','update','destroy']]);
Route::post('admin/search', 'Admin\AdminController@search')->name('admin.search');
Route::post('admin/{admin}/save', 'Admin\AdminController@save')->name('admin.save');
Route::get('admin/editpwd', 'Admin\AdminController@editpwd')->name('admin.editpwd');
Route::post('admin/updatepwd', 'Admin\AdminController@updatepwd')->name('admin.updatepwd');
Route::resource('admin_role', 'Admin\AdminRoleController', ['only'=>['index','create','store','edit','update','destroy']]);
Route::post('admin_role/search', 'Admin\AdminRoleController@search')->name('admin_role.search');
Route::post('admin_role/{admin}/save', 'Admin\AdminRoleController@save')->name('admin_role.save');
Route::resource('admin_nav', 'Admin\AdminNavController', ['only'=>['index','create','store','edit','update','destroy']]);
Route::post('admin_nav/search', 'Admin\AdminNavController@search')->name('admin_nav.search');
Route::post('admin_nav/{admin_nav}/save', 'Admin\AdminNavController@save')->name('admin_nav.save');
Route::get('admin_login_log', 'Admin\AdminLoginLogController@index')->name('admin_login_log.index');
Route::post('admin_login_log/search', 'Admin\AdminLoginLogController@search')->name('admin_login_log.search');
Route::get('admin_action_log', 'Admin\AdminActionLogController@index')->name('admin_action_log.index');
Route::post('admin_action_log/search', 'Admin\AdminActionLogController@search')->name('admin_action_log.search');
Route::resource('user', 'User\UserController', ['only'=>['index','create','store','edit','update','destroy']]);
Route::post('user/search', 'User\UserController@search')->name('user.search');
Route::post('user/{user}/save', 'User\UserController@save')->name('user.save');
Route::get('user/export', 'User\UserController@export')->name('user.export');
Route::get('user/{user}/money', 'User\UserController@money')->name('user.money');
Route::put('user/{user}/money', 'User\UserController@money_update')->name('user.money_update');
Route::get('user/{user}/free', 'User\UserController@free')->name('user.free');
Route::put('user/{user}/free', 'User\UserController@free_update')->name('user.free_update');
Route::get('user_login_log', 'User\UserLoginLogController@index')->name('user_login_log.index');
Route::post('user_login_log/search', 'User\UserLoginLogController@search')->name('user_login_log.search');
Route::get('user_money_log', 'User\UserMoneyLogController@index')->name('user_money_log.index');
Route::post('user_money_log/search', 'User\UserMoneyLogController@search')->name('user_money_log.search');
Route::get('video', 'Video\VideoController@index')->name('video.index');
Route::post('video/search', 'Video\VideoController@search')->name('video.search');
Route::get('video_actors', 'Video\VideoActorsController@index')->name('video_actors.index');
Route::post('video_actors/search', 'Video\VideoActorsController@search')->name('video_actors.search');
Route::post('video_actors/{video_actors}/save', 'Video\VideoActorsController@save')->name('video_actors.save');
Route::get('video_tags', 'Video\VideoTagsController@index')->name('video_tags.index');
Route::post('video_tags/search', 'Video\VideoTagsController@search')->name('video_tags.search');
Route::post('video_tags/{video_tags}/save', 'Video\VideoTagsController@save')->name('video_tags.save');
Route::resource('sysconfig', 'System\SysconfigController', ['only'=>['index','create','store','update','destroy']]);
Route::post('sysconfig/search', 'System\SysconfigController@search')->name('sysconfig.search');
Route::resource('ads', 'System\AdsController', ['only'=>['index','create','store','edit','update','destroy']]);
Route::post('ads/search', 'System\AdsController@search')->name('ads.search');
Route::resource('domain_setting', 'System\DomainSettingController', ['only'=>['index','create','store','edit','update','destroy']]);
Route::post('domain_setting/search', 'System\DomainSettingController@search')->name('domain_setting.search');
Route::get('ccu', 'Pmtools\ConcurrentUserController@index')->name('ccu.index');
Route::post('ccu/search', 'Pmtools\ConcurrentUserController@search')->name('ccu.search');
Route::get('analysis', 'Pmtools\DailyAnalysisController@index')->name('analysis.index');
Route::post('analysis/search', 'Pmtools\DailyAnalysisController@search')->name('analysis.search');
Route::get('daily_user', 'Pmtools\DailyUserController@index')->name('daily_user.index');
Route::post('daily_user/search', 'Pmtools\DailyUserController@search')->name('daily_user.search');
Route::get('retention', 'Pmtools\RetentionController@index')->name('retention.index');
Route::post('retention/search', 'Pmtools\RetentionController@search')->name('retention.search');
Route::get('retention_chart', 'Pmtools\RetentionController@chart')->name('retention_chart.index');
Route::post('retention_chart/search', 'Pmtools\RetentionController@chartSearch')->name('retention_chart.search');
Route::get('retention_analysis', 'Pmtools\RetentionController@analysis')->name('retention_analysis.index');
Route::post('retention_analysis/search', 'Pmtools\RetentionController@analysisSearch')->name('retention_analysis.search');
Route::get('retention_user', 'Pmtools\RetentionController@user')->name('retention_user.index');
Route::post('retention_user/search', 'Pmtools\RetentionController@userSearch')->name('retention_user.search');
Route::get('login_map', 'Pmtools\LoginMapController@index')->name('login_map.index');
Route::post('login_map/search', 'Pmtools\LoginMapController@search')->name('login_map.search');
Route::resource('message', 'System\MessageController', ['only'=>['index','edit','update','destroy']]);
Route::post('message/search', 'System\MessageController@search')->name('message.search');
});
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['as'=>'web.','middleware'=>['share','frontend']], function () {
Route::get('/', 'WebController@index')->name('index');
Route::get('home', 'WebController@index')->name('home');
Route::get('detail/{keyword}', 'WebController@detail')->name('detail');
Route::get('search', 'WebController@search')->name('search');
Route::get('video', 'WebController@video')->name('video');
Route::get('tags', 'WebController@tags')->name('tags');
Route::get('login', 'LoginController@showLoginForm')->name('login');
Route::post('login', 'LoginController@login');
Route::get('auth/weixin', 'ThirdLogin\WeixinController@redirectToProvider');
Route::get('auth/weixin/callback', 'ThirdLogin\WeixinController@handleProviderCallback');
Route::post('verify_code', 'Api\LoginController@verifyCode')->name('verify_code');
Route::post('verify_code_email', 'Api\LoginController@verifyCodeEmail')->name('verify_code_email');
Route::post('forgot_code', 'Api\LoginController@forgotCode')->name('forgot_code');
Route::get('register', 'LoginController@register')->name('register');
Route::post('register', 'LoginController@registerAction');
Route::get('forgot', 'WebController@forgot')->name('forgot');
Route::post('forgot', 'WebController@forgotAction');
Route::get('message', 'WebController@message')->name('message');
Route::post('message', 'WebController@messageStore')->name('message.store');
Route::group(['middleware'=>['auth:web']], function () {
Route::get('logout', 'LoginController@logout')->name('logout');
Route::get('profile', 'WebController@profile')->name('profile');
Route::post('video/buy', 'WebController@buy')->name('video.buy');
});
});
<file_sep>/app/Http/Controllers/AjaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\User\UserRepository;
class AjaxController extends Controller
{
/**
* 取得頁首資訊
*/
public function getTopInfo(UserRepository $userRepository)
{
//在線會員
$top_count['online'] = $userRepository->search([
'active_time1' => date('Y-m-d H:i:s', time() - 600),
])->paginate(100)->result()->total();
//今日註冊
$top_count['register'] = $userRepository->search([
'created_at1' => date('Y-m-d')
])->paginate(100)->result()->total();
return response()->json($top_count);
}
/**
* 設定全局單頁顯示筆數
*/
public function setPerPage(Request $request)
{
if ($request->ajax()) {
session(['per_page'=>$request->per_page ?: 20]);
return 'done';
}
}
/**
* 圖片上傳
*/
public function imageUpload($dir='images')
{
request()->validate([
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$path = public_path("upload/$dir");
@mkdir($path, 0777);
$imageName = time().randPwd(3).'.'.request()->file->getClientOriginalExtension();
request()->file->move($path, $imageName);
return response()->json([
'status' => 1,
'filelink' => "./upload/$dir/$imageName",
]);
}
/**
* 檔案上傳
*/
public function file_upload($dir='files')
{
$path = public_path("upload/$dir");
@mkdir($path, 0777);
$imageName = time().randPwd(3).'.'.request()->file->getClientOriginalExtension();
request()->file->move($path, $imageName);
return response()->json([
'status' => 1,
'filelink' => "./upload/$dir/$imageName",
]);
}
}
<file_sep>/database/migrations/2019_11_07_042748_create_admin_action_log_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminActionLogTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'admin_action_log';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->integer('adminid')->default(0)->comment('adminid');
$table->string('route', 100)->default('')->comment('路由');
$table->text('message')->comment('操作訊息');
$table->text('sql')->comment('SQL指令');
$table->string('ip', 50)->default('')->comment('登入IP');
$table->tinyInteger('status')->default(1)->comment('狀態 0:失敗 1:成功');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->index('created_at');
});
DB::statement("ALTER TABLE `$tableName` comment '系統帳號操作LOG'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admin_action_log');
}
}
<file_sep>/app/Repositories/Video/VideoActorsRepository.php
<?php
namespace App\Repositories\Video;
use App\Repositories\AbstractRepository;
use Models\Video\VideoActors;
class VideoActorsRepository extends AbstractRepository
{
public function __construct(VideoActors $entity)
{
parent::__construct($entity);
}
public function _do_search()
{
if (isset($this->_search['name'])) {
$this->db = $this->db->where('name', 'like', '%'.$this->_search['name'].'%');
}
return $this;
}
public function getAllName()
{
$result = $this->result();
$data = [];
foreach ($result as $row) {
$data[] = $row['name'];
}
return $data;
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => 'ID',
'name' => '女优',
'hot' => '是否为热门',
];
}
<file_sep>/app/Models/System/Ads.php
<?php
namespace Models\System;
use Models\Model;
class Ads extends Model
{
protected $table = 'ads';
protected $attributes = [
'start_time' => '2019-12-01 00:00:00',
'end_time' => '2030-12-31 00:00:00',
'sort' => 1,
];
protected $fillable = [
'domain',
'type',
'name',
'image',
'url',
'start_time',
'end_time',
'sort',
];
const TYPE = [
1 => '首页上方广告',
2 => '首页下方广告',
11 => '详情页广告',
];
}
<file_sep>/app/Models/User/UserMoneyLog.php
<?php
namespace Models\User;
use Models\Model;
class UserMoneyLog extends Model
{
const UPDATED_AT = null;
protected $table = 'user_money_log';
protected $fillable = [
'uid',
'type',
'video_keyword',
'money_before',
'money_add',
'money_after',
'description',
];
const TYPE = [
0 => '用户注册加点',
1 => '推荐人加点',
2 => '观看视频扣点',
3 => '每日签到加点',
4 => '人工加点',
5 => '人工扣点',
];
public function user()
{
return $this->belongsTo('Models\User\User', 'uid');
}
public function video()
{
return $this->belongsTo('Models\Video\Video', 'video_keyword', 'keyword');
}
}
<file_sep>/database/migrations/2019_11_11_063629_create_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'user';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('token', 50)->default('')->comment('Token')->unique();
$table->string('username')->default('')->comment('用戶名')->unique();
$table->string('password')->default('')->comment('密碼');
$table->integer('money')->default(0)->comment('貨幣');
$table->integer('referrer')->default(0)->comment('推薦人');
$table->tinyInteger('status')->default(0)->comment('狀態 0:發送簡訊未註冊 1:正式用戶 1:封鎖用戶');
$table->text('create_ua')->comment('註冊UA資訊');
$table->string('create_ip', 50)->default('')->comment('註冊IP');
$table->json('create_ip_info')->comment('註冊IP資訊');
$table->string('login_ip', 50)->default('')->comment('最後登入IP');
$table->dateTime('login_time')->default('1970-01-01 00:00:00')->comment('最後登入時間');
$table->dateTime('active_time')->default('1970-01-01 00:00:00')->comment('最後活動時間');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->softDeletes();
$table->index('created_at');
});
DB::statement("ALTER TABLE `$tableName` comment '用戶列表'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user');
}
}
<file_sep>/app/Services/Admin/AdminActionLogService.php
<?php
namespace App\Services\Admin;
use App\Repositories\Admin\AdminActionLogRepository;
class AdminActionLogService
{
protected $adminActionLogRepository;
public function __construct(AdminActionLogRepository $adminActionLogRepository)
{
$this->adminActionLogRepository = $adminActionLogRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->adminActionLogRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/app/Repositories/User/UserMoneyLogRepository.php
<?php
namespace App\Repositories\User;
use App\Repositories\AbstractRepository;
use Models\User\UserMoneyLog;
class UserMoneyLogRepository extends AbstractRepository
{
public function __construct(UserMoneyLog $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['uid'])) {
$this->db = $this->db->where('uid', '=', $this->_search['uid']);
}
if (isset($this->_search['username'])) {
$this->db = $this->db->whereHas('user', function ($query) {
$query->where('username', 'like', '%'.$this->_search['username'].'%');
});
}
if (isset($this->_search['video'])) {
$this->db = $this->db->whereHas('video', function ($query) {
$query->where('name', 'like', '%'.$this->_search['video'].'%');
});
}
if (isset($this->_search['type'])) {
$this->db = $this->db->where('type', '=', $this->_search['type']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
/**
* 購買的影片清單(未過期)
*
* @param integer $uid 用戶ID
* @return array
*/
public function getBuyVideo($uid)
{
$where[] = ['uid', '=', $uid];
$where[] = ['type', '=', 2];
$where[] = ['video_keyword', '<>', ''];
$where[] = ['created_at', '>=', date('Y-m-d H:i:s', time()-86400)];
$result = $this->where($where)->result()->toArray();
return array_column($result, 'video_keyword');
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'uid' => '用戶ID',
'type' => '帳變類型',
'money_before' => '变动前点数',
'money_add' => '变动点数',
'money_after' => '变动后点数',
'description' => '描述',
];
}
<file_sep>/app/Http/Controllers/WebController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Video\VideoService;
use App\Services\System\MessageService;
use App\Repositories\Video\VideoRepository;
use App\Repositories\Video\VideoTagsRepository;
use App\Repositories\User\UserRepository;
use App\Repositories\User\UserMoneyLogRepository;
use App\Repositories\System\AdsRepository;
use Illuminate\Support\Facades\Redis;
use Exception;
use Auth;
/**
* 過渡期程式-前端接手後廢除
*/
class WebController extends Controller
{
protected $videoService;
protected $messageService;
protected $videoRepository;
protected $videoTagsRepository;
protected $userRepository;
protected $userMoneyLogRepository;
protected $adsRepository;
public function __construct(
VideoService $videoService,
MessageService $messageService,
VideoRepository $videoRepository,
VideoTagsRepository $videoTagsRepository,
UserRepository $userRepository,
UserMoneyLogRepository $userMoneyLogRepository,
AdsRepository $adsRepository
) {
$this->videoService = $videoService;
$this->messageService = $messageService;
$this->videoRepository = $videoRepository;
$this->videoTagsRepository = $videoTagsRepository;
$this->userRepository = $userRepository;
$this->userMoneyLogRepository = $userMoneyLogRepository;
$this->adsRepository = $adsRepository;
session(['per_page'=>12]);
}
public function index(Request $request)
{
$request->per_page = $request->per_page ?? 40;
$video = $this->videoService->getList($request);
//上方廣告
$search['domain'] = $request->server('HTTP_HOST');
$search['enabled'] = 1;
$search['type'] = 1;
$ads_up = $this->adsRepository->search($search)->result();
//下方廣告
$search['type'] = 2;
$ads_down = $this->adsRepository->search($search)->result();
//會員數
$members = round((time() - strtotime('2019-01-01')) / 88888);
//觀看數
$watchs = round((time() - strtotime(date('Y-m-d'))) * 1.111);
//新進影片
$newvideo = round((strtotime(date('Y-m-d')) - strtotime(date('Y-m-01'))+86400) / 86400 * 6.666);
//累計影片時數
$videohours = round((time() - strtotime('2000-01-01')) / 14400);
return view('web.index', [
'page' => 'index',
'video' => $video['list'],
'ads_up' => $ads_up,
'ads_down' => $ads_down,
'members' => $members,
'watchs' => $watchs,
'newvideo' => $newvideo,
'videohours' => $videohours,
]);
}
public function detail(Request $request, $keyword)
{
$row = $this->videoRepository->search(['keyword'=>$keyword])->result_one();
if ($row === null) {
$url = route('web.index');
echo "<script>alert('查无此影片');location.href='$url';</script>";
}
if ($row['status'] == 0) {
$url = route('web.index');
echo "<script>alert('该影片已过期');location.href='$url';</script>";
}
//更多影片
$tags = explode(',', $row['tags']);
$where[] = ['keyword', '<>', $keyword];
$search['tags'] = $tags[0] ?? '';
$search['status'] = 1;
$more = $this->videoRepository->where($where)->search($search)
->order(['rand()','asc'])->limit([0,16])->result();
//上一部
$where = [];
$where[] = ['publish', '>=', $row['publish']];
$where[] = ['keyword', '>', $row['keyword']];
$where[] = ['status', '=', 1];
$prev = $this->videoRepository->where($where)->order(['publish'=>'asc','keyword'=>'asc'])->result_one();
//下一部
$where = [];
$where[] = ['publish', '<=', $row['publish']];
$where[] = ['keyword', '<', $row['keyword']];
$where[] = ['status', '=', 1];
$next = $this->videoRepository->where($where)->order(['publish'=>'desc','keyword'=>'desc'])->result_one();
$all = $request->secret == 'iloveav';
$user = [];
//判斷是否登入
if (Auth::guard('web')->check()) {
$user = Auth::guard('web')->user();
//24H內購買過的清單
$buy = $this->userMoneyLogRepository->getBuyVideo($user['id']);
if (in_array($row['keyword'], $buy)) {
$all = true;
}
//免費看
if (strtotime($user['free_time']) > time()) {
$all = true;
}
}
//廣告
$search['domain'] = $request->server('HTTP_HOST');
$search['enabled'] = 1;
$search['type'] = 11;
$ads = $this->adsRepository->search($search)->result();
return view('web.detail', [
'page' => 'detail',
'user' => $user,
'all' => $all,
'more' => $more,
'prev_url' => $prev['keyword'] ?? '',
'next_url' => $next['keyword'] ?? '',
'video' => $row,
'ads' => $ads,
]);
}
public function search(Request $request)
{
$data = $this->videoService->list($request->input());
$data['page'] = 'search';
return view('web.search', $data);
}
public function video(Request $request)
{
$data = $this->videoService->list($request->input());
$data['page'] = 'video';
return view('web.video', $data);
}
public function tags(Request $request)
{
//標籤
$result = $this->videoTagsRepository->search(['hot'=>1])->result();
$tags = [];
foreach ($result as $row) {
$tags[] = $row['name'];
}
//影片列表
$data = $this->videoService->list($request->input());
$data['page'] = 'tags';
$data['tags'] = $tags;
$data['param'] = $request->input();
return view('web.tags', $data);
}
public function forgot(Request $request)
{
return view('web.forgot', [
'page' => 'forgot',
]);
}
public function forgotAction(Request $request)
{
$this->validate($request, [
'mobile' => 'required|telphone',
'verify_code' => 'required',
'password' => '<PASSWORD>',
'repassword' => '<PASSWORD>:<PASSWORD>',
]);
try {
if (!$forgot = Redis::get("forgot:phone:$request[mobile]")) {
throw new Exception('重置验证码错误(err01)');
}
$forgot = json_decode($forgot, true);
if ($forgot['code'] != $request['verify_code']) {
throw new Exception('重置验证码错误(err02)');
}
$user = $this->userRepository->getDataByUsername($request->mobile);
$this->userRepository->update([
'password' => $request->password
], $user->id);
Redis::del("forgot:phone:$request[mobile]");
$url = route('web.login');
return "<script>alert('密码修改完成!');location.href='$url';</script>";
} catch (Exception $e) {
return back()->withErrors($e->getMessage());
}
}
public function profile(Request $request)
{
$user = \Auth::user();
//推薦紀錄
$result = $this->userRepository->getReferrerList($user->id);
foreach ($result as $key => $row) {
$row->username = substr($row->username, 0, 3).'*****'.substr($row->username, -3);
$row->created_at = date('Y-m-d H:i:s', strtotime($row->created_at));
$result[$key] = $row;
}
//帳變明細
$moneylog = $this->userMoneyLogRepository->search(['uid'=>$user->id])
->order(['created_at','desc'])->limit([0,10])->result();
foreach ($moneylog as $key => $row) {
if ($row['type'] == 1) {
$row->description = mb_substr($row->description, 0, -8).'*****'.mb_substr($row->description, -3);
}
if ($row['type'] == 2) {
$url = route('web.detail', ['keyword'=>$row['video_keyword']]);
$row->description = str_replace($row['video_keyword'], "<a href='$url' target=\"_blank\">$row[video_keyword]</a>", $row['description']);
}
$moneylog[$key] = $row;
}
return view('web.profile', [
'page' => 'profile',
'result' => $result,
'moneylog' => $moneylog,
'user' => [
'id' => $user->id,
'username' => $user->username,
'money' => $user->money,
'free_time' => $user->free_time,
'status' => $user->status,
'created_at' => date('Y-m-d H:i:s', strtotime($user->created_at)),
],
]);
}
public function moneylog(Request $request)
{
$user = \Auth::user();
//推薦紀錄
$result = $this->userRepository->getReferrerList($user->id);
$reflist = [];
foreach ($result as $row) {
$reflist[] = [
'username' => substr($row->username, 0, 7).'****',
'money' => $row->money,
'status' => $row->status,
'login_time' => $row->login_time,
'created_at' => date('Y-m-d H:i:s', strtotime($row->created_at)),
];
}
return view('web.moneylog', [
'page' => 'profile',
'reflist' => $reflist,
'user' => [
'id' => $user->id,
'username' => $user->username,
'money' => $user->money,
'status' => $user->status,
'created_at' => date('Y-m-d H:i:s', strtotime($user->created_at)),
],
]);
}
public function buy(Request $request)
{
try {
$validator = \Validator::make($request->all(), [
'keyword' => 'required|exists:video',
]);
if ($validator->fails()) {
$message = implode("\n", $validator->errors()->all());
throw new Exception($message, 422);
}
$user = \Auth::user();
$buy = $this->userMoneyLogRepository->getBuyVideo($user['id']);
if (in_array($request->keyword, $buy)) {
throw new Exception('该视频已购买过!', 422);
}
if ($user['money'] <= 0) {
throw new Exception('余额不足!', 422);
}
//帳變明細
$this->userRepository->addMoney($user['id'], 2, -1, "观看影片-$request->keyword", $request->keyword);
return response()->json([
'success' => true,
]);
} catch (Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
public function message(Request $request)
{
return view('web.message', $this->messageService->create($request->input()));
}
public function messageStore(Request $request)
{
$this->validate($request, [
'type' => 'required',
'content' => 'required',
], [
'type.required' => '请选择一项问题类型',
'content.required' => '问题描述 不能为空',
]);
try {
//判斷是否登入
$uid = 0;
if (Auth::guard('web')->check()) {
$uid = Auth::user()->id;
}
$this->messageService->store([
'uid' => $uid,
'type' => $request->type,
'content' => $request->content,
]);
$url = route('web.message');
return "<script>alert('留言已送出!');location.href='$url';</script>";
} catch (Exception $e) {
return back()->withErrors($e->getMessage());
}
}
}
<file_sep>/app/Http/Middleware/NavData.php
<?php
namespace App\Http\Middleware;
use View;
use Route;
use Closure;
use Models\Admin\AdminRole;
use App\Repositories\Admin\AdminNavRepository;
class NavData
{
protected $adminNavRepository;
public function __construct(AdminNavRepository $adminNavRepository)
{
$this->adminNavRepository = $adminNavRepository;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//取得當前Route
$route = Route::currentRouteName();
$share['route'] = $route;
$action = explode('.', $route);
$share['controller'] = "$action[0]";
//導航列表
$nav = $this->adminNavRepository->allNav();
$share['allNav'] = $nav;
//導航權限
$role = AdminRole::find(session('roleid'))->toArray();
$permition = $role !== null && $role['allow_nav'] != '' ? json_decode($role['allow_nav'], true) : [];
$routes = [];
foreach ($nav as $row) {
if ($row['pid'] > 0) {
$routes[$row['route']] = $row;
if ($row['route1'] != '') {
$routes[$row['route1']] = $row;
}
if ($row['route2'] != '') {
$routes[$row['route2']] = $row;
}
}
//子路由寫入權限
if (in_array($row['route'], $permition)) {
if ($row['route1'] != '') {
$permition[] = $row['route1'];
}
if ($row['route2'] != '') {
$permition[] = $row['route2'];
}
}
}
$permition = array_merge_recursive($permition, config('global.no_need_perm'));
$share['allow_url'] = array_unique($permition);
//導航路徑
$navid = isset($routes[$route]) ? $routes[$route]['id'] : 0;
$share['breadcrumb'] = $this->getBreadcrumb($nav, $navid);
//內頁Title
$share['title'] = isset($routes[$route]) ? $routes[$route]['name'] : '首页';
//導航樹狀
$share['navList'] = $this->treeNav($nav);
View::share($share);
return $next($request);
}
/**
* 遞迴整理導航樹狀結構
*
* @param array $result 導航清單
* @param integer $pid 上層導航ID
* @return array
*/
private function treeNav($result, $pid = 0)
{
$data = [];
foreach ($result as $row) {
if ($row['pid'] == $pid) {
$row['sub'] = $this->treeNav($result, $row['id']);
$row['subNavs'] = array_column($row['sub'], 'route');
$data[] = $row;
}
}
return $data;
}
/**
* 遞迴取得導航路徑
*
* @param array $result 導航清單
* @param integer $id 導航ID
* @return array
*/
private function getBreadcrumb($result, $id)
{
if ($id == 0) {
return [];
}
$data = $this->getBreadcrumb($result, $result[$id]['pid']);
$data[] = $result[$id];
return $data;
}
}
<file_sep>/app/Http/Controllers/Video/VideoActorsController.php
<?php
namespace App\Http\Controllers\Video;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Video\VideoActorsService;
class VideoActorsController extends Controller
{
protected $videoActorsService;
public function __construct(VideoActorsService $videoActorsService)
{
$this->videoActorsService = $videoActorsService;
}
public function index(Request $request)
{
return view('video.actors', $this->videoActorsService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'video_actors'));
}
public function save(Request $request, $id)
{
$this->videoActorsService->save($request->post(), $id);
return 'done';
}
}
<file_sep>/app/Repositories/Admin/AdminNavRepository.php
<?php
namespace App\Repositories\Admin;
use App\Repositories\AbstractRepository;
use Models\Admin\AdminNav;
class AdminNavRepository extends AbstractRepository
{
public function __construct(AdminNav $entity)
{
parent::__construct($entity);
}
private function _preAction($row)
{
$row['path'] = 0;
if ($row['pid'] > 0) {
$parent = $this->row($row['pid']);
$row['path'] = $parent['path'] . '-' . $row['pid'];
}
return $row;
}
public function create($row)
{
$row = $this->_preAction($row);
return parent::create($row);
}
public function update($row, $id=0)
{
$row = $this->_preAction($row);
return parent::update($row, $id);
}
public function _do_search()
{
if (isset($this->_search['pid'])) {
$this->db = $this->db->where('pid', '=', $this->_search['pid']);
}
if (isset($this->_search['name'])) {
$this->db = $this->db->where('name', 'like', '%'.$this->_search['name'].'%');
}
if (isset($this->_search['route'])) {
$this->db = $this->db->where('route', 'like', '%'.$this->_search['route'].'%');
}
if (isset($this->_search['status'])) {
$this->db = $this->db->where('status', '=', $this->_search['status']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
/**
* 取得所有導航資料
*
* @return array
*/
public function allNav()
{
$where[] = ['status', '=', 1];
$where[] = ['route', '<>', ''];
$result = $this->where($where)->order(['sort', 'asc'])->result()->toArray();
return array_column($result, null, 'id');
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '流水号',
'pid' => '父级ID',
'icon' => 'ICON',
'name' => '导航名称',
'route' => '主路由',
'route1' => '次路由1',
'route2' => '次路由2',
'path' => '阶层路径',
'sort' => '排序',
'status' => '状态',
];
}
<file_sep>/app/Repositories/Pmtools/ConcurrentUserRepository.php
<?php
namespace App\Repositories\Pmtools;
use App\Repositories\AbstractRepository;
use Models\Pmtools\ConcurrentUser;
class ConcurrentUserRepository extends AbstractRepository
{
public function __construct(ConcurrentUser $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['per'])) {
$this->db = $this->db->where('per', '=', $this->_search['per']);
}
if (isset($this->_search['minute_time'])) {
$this->db = $this->db->where('minute_time', '=', $this->_search['minute_time']);
}
if (isset($this->_search['minute_time1'])) {
$this->db = $this->db->where('minute_time', '>=', $this->_search['minute_time1']);
}
if (isset($this->_search['minute_time2'])) {
$this->db = $this->db->where('minute_time', '<=', $this->_search['minute_time2']);
}
return $this;
}
}
<file_sep>/app/Http/Controllers/System/DomainSettingController.php
<?php
namespace App\Http\Controllers\System;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\System\DomainSettingForm;
use App\Services\System\DomainSettingService;
class DomainSettingController extends Controller
{
protected $domainSettingService;
public function __construct(DomainSettingService $domainSettingService)
{
$this->domainSettingService = $domainSettingService;
}
public function index(Request $request)
{
return view('domain_setting.index', $this->domainSettingService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'domain_setting'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('domain_setting.create', $this->domainSettingService->create($request->input()));
}
public function store(DomainSettingForm $request)
{
$this->domainSettingService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function edit($id)
{
View::share('sidebar', false);
return view('domain_setting.edit', $this->domainSettingService->show($id));
}
public function update(DomainSettingForm $request, $id)
{
$this->domainSettingService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function destroy(Request $request)
{
$this->domainSettingService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/app/Repositories/Video/VideoRepository.php
<?php
namespace App\Repositories\Video;
use App\Repositories\AbstractRepository;
use Models\Video\Video;
class VideoRepository extends AbstractRepository
{
public function __construct(Video $entity)
{
parent::__construct($entity);
$this->is_action_log = false;
}
public function _do_search()
{
if (isset($this->_search['keyword'])) {
$this->db = $this->db->where('keyword', '=', $this->_search['keyword']);
}
if (isset($this->_search['name'])) {
$this->db = $this->db->where('name', 'like', '%'.$this->_search['name'].'%');
}
if (isset($this->_search['actors'])) {
$this->db = $this->db->whereRaw("FIND_IN_SET('".$this->_search['actors']."', actors)");
unset($this->_search['actors']);
}
if (isset($this->_search['tags'])) {
$this->db = $this->db->whereRaw("FIND_IN_SET('".$this->_search['tags']."', tags)");
unset($this->_search['tags']);
}
if (isset($this->_search['publish1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['publish1']);
}
if (isset($this->_search['publish2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['publish2']);
}
if (isset($this->_search['search'])) {
$this->db = $this->db->where(function ($query) {
$query->where('name', 'like', '%'.$this->_search['search'].'%')
->orWhereRaw("FIND_IN_SET('".$this->_search['search']."', actors)")
->orWhereRaw("FIND_IN_SET('".$this->_search['search']."', tags)");
});
}
if (isset($this->_search['status'])) {
$this->db = $this->db->where('status', '=', $this->_search['status']);
}
if (isset($this->_search['updated_at1'])) {
$this->db = $this->db->where('updated_at', '>=', $this->_search['updated_at1']);
}
if (isset($this->_search['updated_at2'])) {
$this->db = $this->db->where('updated_at', '<=', $this->_search['updated_at2']);
}
return $this;
}
}
<file_sep>/app/Http/Controllers/System/AdsController.php
<?php
namespace App\Http\Controllers\System;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\System\AdsForm;
use App\Services\System\AdsService;
class AdsController extends Controller
{
protected $adsService;
public function __construct(AdsService $adsService)
{
$this->adsService = $adsService;
}
public function index(Request $request)
{
return view('ads.index', $this->adsService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'ads'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('ads.create', $this->adsService->create($request->input()));
}
public function store(AdsForm $request)
{
$this->adsService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function edit($id)
{
View::share('sidebar', false);
return view('ads.edit', $this->adsService->show($id));
}
public function update(AdsForm $request, $id)
{
$this->adsService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function destroy(Request $request)
{
$this->adsService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/app/Console/Command/SetDailyRetention.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\User\UserRepository;
use App\Repositories\Pmtools\DailyRetentionRepository;
class SetDailyRetention extends Command
{
//命令名稱
protected $signature = 'pmtools:daily_retention {--enforce=} {--date=}';
//說明文字
protected $description = '[統計]留存率';
protected $userRepository;
protected $dailyRetentionRepository;
public function __construct(
UserRepository $userRepository,
DailyRetentionRepository $dailyRetentionRepository
) {
parent::__construct();
$this->userRepository = $userRepository;
$this->dailyRetentionRepository = $dailyRetentionRepository;
}
/**
* @param string $date 指定執行日期
* @param int $enforce 強制重新執行
*/
public function handle()
{
$date = $this->option('date') ?: date('Y-m-d', time()-86400);
$enforce = $this->option('enforce') ?: 0;
//強制執行 先刪除已存在的資料
if ($enforce) {
$this->dailyRetentionRepository->search(['date'=>$date])->delete();
}
//判斷是否已執行過(有資料)
if ($this->dailyRetentionRepository->search(['date'=>$date])->count() == 0) {
$now = date('Y-m-d H:i:s');
//總數
$all = $this->userRepository->search(['status'=>1])->count();
$insert = [];
for ($i = 1; $i <= 6; $i++) {
$data = $this->userRepository->retention($i);
$insert[] = [
'date' => $date,
'type' => $i,
'all_count' => $all,
'day_count' => $data['day_count'] ?? 0,
'avg_money' => $data['avg_money'] ?? 0,
'created_at' => $now,
];
}
$this->dailyRetentionRepository->insert_batch($insert);
}
}
}
<file_sep>/database/migrations/2019_11_11_083324_create_video_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVideoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'video';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('keyword', 50)->comment('視頻Keyword')->unique();
$table->string('name')->default('')->comment('片名');
$table->date('publish')->default('1970-01-01')->comment('發行日期');
$table->string('actors')->default('')->comment('女優(逗號分隔)');
$table->string('tags')->default('')->comment('Tags(逗號分隔)');
$table->string('pic_b')->default('')->comment('封面圖-大');
$table->string('pic_s')->default('')->comment('封面圖-小');
$table->string('url')->default('')->comment('視頻連結');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->index('created_at');
});
DB::statement("ALTER TABLE `$tableName` comment '影片列表'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('video');
}
}
<file_sep>/app/Console/Command/GetVideoTagsApi.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Repositories\Video\VideoActorsRepository;
use App\Repositories\Video\VideoTagsRepository;
class GetVideoTagsApi extends Command
{
//命令名稱
protected $signature = 'api:video_tags';
//說明文字
protected $description = '[API] 取得影片標籤及女優';
protected $videoActorsRepository;
protected $videoTagsRepository;
public function __construct(
VideoActorsRepository $videoActorsRepository,
VideoTagsRepository $videoTagsRepository
) {
parent::__construct();
$this->videoActorsRepository = $videoActorsRepository;
$this->videoTagsRepository = $videoTagsRepository;
}
// Console 執行的程式
public function handle()
{
//女優更新
$actors = $this->videoActorsRepository->getAllName();
$result = getVideoApi('actors');
$insert = [];
foreach ($result['data']['actors'] as $row) {
if (!in_array($row['name'], $actors)) {
$insert[] = [
'name' => $row['name'],
'created_at' => date('Y-m-d H:i:s'),
'created_by' => 'schedule',
'updated_at' => date('Y-m-d H:i:s'),
'updated_by' => 'schedule',
];
}
}
if ($insert !== []) {
$this->videoActorsRepository->insert_batch($insert);
}
//標籤更新
$tags = $this->videoTagsRepository->getAllName();
$result = getVideoApi('tags');
$insert = [];
foreach ($result['data']['tags'] as $row) {
if (!in_array($row['name'], $tags)) {
$insert[] = [
'name' => $row['name'],
'created_at' => date('Y-m-d H:i:s'),
'created_by' => 'schedule',
'updated_at' => date('Y-m-d H:i:s'),
'updated_by' => 'schedule',
];
}
}
if ($insert !== []) {
$this->videoTagsRepository->insert_batch($insert);
}
}
}
<file_sep>/app/Http/Middleware/Frontend.php
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use View;
use App\Repositories\System\DomainSettingRepository;
class Frontend
{
protected $domainSettingRepository;
public function __construct(DomainSettingRepository $domainSettingRepository)
{
$this->domainSettingRepository = $domainSettingRepository;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::guard('web')->check()) {
$user = Auth::guard('web')->user();
$user->active_time = date('Y-m-d H:i:s');
$user->save();
}
//有推薦碼則寫入session 註冊預先帶入
if (isset($request->refcode)) {
$request->refcode = str_replace('?', '', $request->refcode);
session(['referrer_code'=>$request->refcode]);
}
$domain = $request->server('HTTP_HOST');
$share['seo'] = $this->domainSettingRepository->search(['domain'=>$domain])->result_one();
View::share($share);
return $next($request);
}
}
<file_sep>/database/migrations/2019_12_18_135452_create_daily_retention_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDailyRetentionUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'daily_retention_user';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->date('date')->default('1970-01-01')->comment('日期');
$table->tinyInteger('type')->comment('類型 1.1天前新帳號,2.3天前新帳號,3.7天前新帳號,4.15天前新帳號,5.30天前新帳號');
$table->integer('all_count')->default(0)->comment('總數');
$table->integer('day_count')->default(0)->comment('人數');
$table->integer('percent')->default(0)->comment('百分比');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->unique(['date','type']);
});
DB::statement("ALTER TABLE `$tableName` comment '每日統計-新帳號留存率'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('daily_retention_user');
}
}
<file_sep>/app/Models/Pmtools/DailyRetentionUser.php
<?php
namespace Models\Pmtools;
use Models\Model;
class DailyRetentionUser extends Model
{
const UPDATED_AT = null;
protected $table = 'daily_retention_user';
protected $fillable = [
'date',
'type',
'all_count',
'day_count',
'percent',
];
const TYPE = [
1 => '1天前新用户',
2 => '3天前新用户',
3 => '7天前新用户',
4 => '15天前新用户',
5 => '30天前新用户',
];
}
<file_sep>/app/Http/Controllers/System/SysconfigController.php
<?php
namespace App\Http\Controllers\System;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\System\SysconfigForm;
use App\Services\System\SysconfigService;
class SysconfigController extends Controller
{
protected $sysconfigService;
public function __construct(SysconfigService $sysconfigService)
{
$this->sysconfigService = $sysconfigService;
}
public function index(Request $request)
{
return view('sysconfig.index', $this->sysconfigService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'sysconfig'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('sysconfig.create', $this->sysconfigService->create($request->input()));
}
public function store(SysconfigForm $request)
{
$this->sysconfigService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function update(Request $request, $id)
{
$this->sysconfigService->update($request->post());
session()->flash('message', '编辑成功!');
return redirect(route('sysconfig.index', ['groupid'=>$id]));
}
public function destroy(Request $request)
{
$this->sysconfigService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/app/Models/System/Message.php
<?php
namespace Models\System;
use Models\Model;
class Message extends Model
{
protected $table = 'message';
protected $fillable = [
'uid',
'type',
'content',
'created_by',
'updated_by',
];
const TYPE = [
1 => '帐号问题',
2 => '点数问题',
3 => '播放问题',
4 => '其他问题',
];
public function user()
{
return $this->belongsTo('Models\User\User', 'uid');
}
}
<file_sep>/database/migrations/2019_11_07_041234_create_admin_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'admin';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('token', 50)->default('')->comment('Token');
$table->string('username')->default('')->comment('用戶名')->unique();
$table->string('password')->default('')->comment('密碼');
$table->smallInteger('roleid')->default(0)->comment('角色ID');
$table->string('login_ip', 50)->default('')->comment('登入IP');
$table->dateTime('login_time')->default('1970-01-01 00:00:00')->comment('登入時間');
$table->integer('login_count')->default(0)->comment('登入次數');
$table->tinyInteger('status')->default(1)->comment('狀態 1:開啟 0:關閉');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->index('created_at');
});
DB::statement("ALTER TABLE `$tableName` comment '系統帳號'");
DB::table($tableName)->insert([
'id' => 1,
'username' => 'admin',
'password' => <PASSWORD>('<PASSWORD>'),
'roleid' => 1,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admin');
}
}
<file_sep>/app/Http/Requests/System/DomainSettingForm.php
<?php
namespace App\Http\Requests\System;
use App\Http\Requests\FormRequest;
use Illuminate\Validation\Rule;
final class DomainSettingForm extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'domain' => ['required',Rule::unique('domain_setting')->ignore($this->route('domain_setting'))],
'title' => 'required',
'keyword' => 'required',
'description' => 'required',
];
}
}
<file_sep>/app/Http/Requests/Admin/AdminNavForm.php
<?php
namespace App\Http\Requests\Admin;
use App\Http\Requests\FormRequest;
final class AdminNavForm extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'route' => 'required',
];
}
/**
* 獲取已定義驗證規則的錯誤消息。
*
* @return array
*/
public function messages()
{
return [
'name.required' => '导航名称 不可空白',
'route.required' => '主路由 不可空白',
];
}
}
<file_sep>/app/Services/Pmtools/ConcurrentUserService.php
<?php
namespace App\Services\Pmtools;
use App\Repositories\Pmtools\ConcurrentUserRepository;
class ConcurrentUserService
{
protected $concurrentUserRepository;
public function __construct(ConcurrentUserRepository $concurrentUserRepository)
{
$this->concurrentUserRepository = $concurrentUserRepository;
}
public function list($input)
{
$search_params = param_process($input, ['minute_time', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['per'] = $search['per'] ?? 1;
$search['minute_time2'] = $search['minute_time2'] ?? date('Y-m-d H:i:00', time()-60);
$search['minute_time1'] = $search['minute_time1'] ?? date('Y-m-d H:i:00', time()-1800);
//預設值
$table = $chart_data = $chart = [];
for ($i=strtotime($search['minute_time1']);$i<=strtotime($search['minute_time2']);$i+=60*$search['per']) {
$minute = date('i', $i);
$mod = $minute % $search['per'];
$i += $mod == 0 ? 0:($search['per'] - $mod) * 60;
$chart_data[$i] = 0;
}
$count = $this->concurrentUserRepository
->select(['minute_time','count'])
->search($search)
->order($order)
->count();
if ($count <= 200) {
$result = $this->concurrentUserRepository
->select(['minute_time','count'])
->search($search)
->order($order)
->result();
//填入人數
foreach ($result as $key => $row) {
$chart_data[strtotime($row['minute_time'])] = $row['count'];
}
//轉換格式
foreach ($chart_data as $key => $val) {
$chart[] = [date('m-d H:i', $key),(int)$val];
$table[] = [
'time' => date('m-d H:i', $key),
'count' => $val
];
}
krsort($table);
}
return [
'count' => $count,
'table' => $table,
'chart' => $chart,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/app/Http/Controllers/Admin/AdminRoleController.php
<?php
namespace App\Http\Controllers\Admin;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\Admin\AdminRoleForm;
use App\Services\Admin\AdminRoleService;
class AdminRoleController extends Controller
{
protected $adminRoleService;
public function __construct(AdminRoleService $adminRoleService)
{
$this->adminRoleService = $adminRoleService;
}
public function index(Request $request)
{
return view('admin_role.index', $this->adminRoleService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'admin'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('admin_role.create', $this->adminRoleService->create($request->input()));
}
public function store(AdminRoleForm $request)
{
$this->adminRoleService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function edit($id)
{
View::share('sidebar', false);
return view('admin_role.edit', $this->adminRoleService->show($id));
}
public function update(AdminRoleForm $request, $id)
{
$this->adminRoleService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function save(Request $request, $id)
{
$this->adminRoleService->save($request->post(), $id);
return 'done';
}
public function destroy(Request $request)
{
$this->adminRoleService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/app/Http/Controllers/User/UserController.php
<?php
namespace App\Http\Controllers\User;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\User\UserForm;
use App\Services\User\UserService;
class UserController extends Controller
{
protected $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function index(Request $request)
{
return view('user.index', $this->userService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'user'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('user.create', $this->userService->create($request->input()));
}
public function store(UserForm $request)
{
$this->userService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function edit($id)
{
View::share('sidebar', false);
return view('user.edit', $this->userService->show($id));
}
public function update(UserForm $request, $id)
{
$this->userService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function money($id)
{
View::share('sidebar', false);
return view('user.money', $this->userService->show($id));
}
public function money_update(Request $request, $id)
{
$this->validate($request, [
'money' => 'required|integer|not_in:0',
'description' => 'required',
], ['money.not_in'=>'增减点数 不可为0']);
$input = $request->post();
$input['type'] = $input['money'] < 0 ? 5:4;
$input['description'] .= '-由'.session('username').'操作';
$this->userService->addMoney($input, $id);
session()->flash('message', '人工加减点完成!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function free($id)
{
View::share('sidebar', false);
return view('user.free', $this->userService->show($id));
}
public function free_update(Request $request, $id)
{
$this->validate($request, [
'free_day' => 'integer|min:0'
], ['free_day.min'=>'免费天数不可为负数']);
$this->userService->update([
'free_time' => date('Y-m-d H:i:s', time() + 86400 * $request->free_day)
], $id);
session()->flash('message', '设定完成!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function save(Request $request, $id)
{
$this->userService->save($request->post(), $id);
return 'done';
}
public function destroy(Request $request)
{
$this->userService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
public function export(Request $request)
{
$this->userService->export($request->input());
}
}
<file_sep>/app/Models/Admin/AdminActionLog.php
<?php
namespace Models\Admin;
use Models\Model;
class AdminActionLog extends Model
{
const UPDATED_AT = null;
protected $table = 'admin_action_log';
protected $fillable = [
'adminid',
'route',
'message',
'sql_str',
'ip',
'status',
'created_by',
];
const STATUS = [
1 => '成功',
0 => '失败',
];
public function admin()
{
return $this->belongsTo('Models\Admin\Admin', 'adminid');
}
}
<file_sep>/app/Services/Pmtools/DailyRetentionService.php
<?php
namespace App\Services\Pmtools;
use App\Repositories\User\UserRepository;
use App\Repositories\Pmtools\DailyRetentionRepository;
use App\Repositories\Pmtools\DailyRetentionUserRepository;
use Models\Pmtools\DailyRetention;
use Models\Pmtools\DailyRetentionUser;
class DailyRetentionService
{
protected $dailyRetentionRepository;
protected $dailyRetentionUserRepository;
protected $userRepository;
public function __construct(
DailyRetentionRepository $dailyRetentionRepository,
DailyRetentionUserRepository $dailyRetentionUserRepository,
UserRepository $userRepository
) {
$this->dailyRetentionRepository = $dailyRetentionRepository;
$this->dailyRetentionUserRepository = $dailyRetentionUserRepository;
$this->userRepository = $userRepository;
}
public function list($input)
{
$search_params = param_process($input, ['date', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['date'] = $search['date'] ?? date('Y-m-d', time()-86400);
$result = $this->dailyRetentionRepository
->search($search)
->order($order)
->result()->toArray();
foreach ($result as $key => $row) {
$percent = round($row['day_count']/$row['all_count']*100, 2);
$row['percent'] = $row['all_count'] == 0 ? 0 : $percent;
$result[$key] = $row;
}
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function chart($input)
{
$search_params = param_process($input, ['date', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['date1'] = $search['date1'] ?? date('Y-m-d', time()-86400*10);
$search['date2'] = $search['date2'] ?? date('Y-m-d', time()-86400);
$date = $table = $chart = [];
for ($i=strtotime($search['date1']);$i<=strtotime($search['date2']);$i+=86400) {
$date[] = date('Y-m-d', $i);
}
for ($i=1;$i<=6;$i++) {
for ($j=strtotime($search['date1']);$j<=strtotime($search['date2']);$j+=86400) {
$table[$i][$j] = 0;
}
}
$result = $this->dailyRetentionRepository
->search($search)
->order($order)
->result()->toArray();
foreach ($result as $row) {
$table[$row['type']][strtotime($row['date'])] = $row['day_count'];
}
foreach ($table as $type => $row) {
$arr = [];
foreach ($row as $val) {
$arr[] = (int)$val;
}
$chart[] = [
'name' => DailyRetention::TYPE[$type],
'data' => $arr,
'color' => DailyRetention::TYPE_COLOR[$type],
];
}
return [
'table' => $table,
'chart' => $chart,
'date' => $date,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function analysis($input)
{
$search_params = param_process($input, ['date', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['status'] = 1;
$search['created_at1'] = $search['created_at1'] ?? date('Y-m-d', time()-86400*30);
$search['created_at2'] = $search['created_at2'] ?? date('Y-m-d', time()-86400);
$total = $this->userRepository->search($search)->count();
$result = [];
for ($i=1;$i<=8;$i++) {
$row = $this->userRepository->retentionAnalysis($search['created_at1'], $search['created_at2'], $i);
$row['type'] = $i;
$row['percent'] = $total == 0 ? 0:round($row['count']/$total*100, 2);
$result[] = $row;
}
return [
'result' => $result,
'total' => $total,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function user($input)
{
$search_params = param_process($input, ['date', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['date1'] = $search['date1'] ?? date('Y-m-d', time()-86400*6);
$search['date2'] = $search['date2'] ?? date('Y-m-d', time()-86400);
$date = $table = $chart = [];
for ($i=strtotime($search['date1']);$i<=strtotime($search['date2']);$i+=86400) {
$date[] = date('Y-m-d', $i);
}
for ($i=1;$i<=5;$i++) {
for ($j=strtotime($search['date1']);$j<=strtotime($search['date2']);$j+=86400) {
$table[$i][$j] = '0%(0/0)';
}
}
// get main data.
$result = $this->dailyRetentionUserRepository
->search($search)
->order($order)
->result();
$table2 = $table;
foreach ($result as $row) {
$percent = $row['all_count'] == 0 ? 0:round($row['day_count'] / $row['all_count'] * 100, 2);
$table[$row['type']][strtotime($row['date'])] = $percent."%($row[day_count]/$row[all_count])";
$table2[$row['type']][strtotime($row['date'])] = $percent;
}
foreach ($table2 as $type => $row) {
$arr = [];
foreach ($row as $val) {
$arr[] = (int)$val;
}
$chart[] = [
'name' => DailyRetentionUser::TYPE[$type],
'data' => $arr,
];
}
return [
'table' => $table,
'chart' => $chart,
'date' => $date,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/app/Services/Video/VideoActorsService.php
<?php
namespace App\Services\Video;
use App\Repositories\Video\VideoActorsRepository;
class VideoActorsService
{
protected $videoActorsRepository;
public function __construct(VideoActorsRepository $videoActorsRepository)
{
$this->videoActorsRepository = $videoActorsRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'asc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->videoActorsRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function save($row, $id)
{
$this->videoActorsRepository->save($row, $id);
}
}
<file_sep>/app/Services/User/UserLoginLogService.php
<?php
namespace App\Services\User;
use App\Repositories\User\UserLoginLogRepository;
use App\Repositories\User\UserRepository;
class UserLoginLogService
{
protected $userLoginLogRepository;
protected $userRepository;
public function __construct(
UserLoginLogRepository $userLoginLogRepository,
UserRepository $userRepository
) {
$this->userLoginLogRepository = $userLoginLogRepository;
$this->userRepository = $userRepository;
}
public function list($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$result = $this->userLoginLogRepository->search($search)
->order($order)->paginate(session('per_page'))
->result()->appends($input);
foreach ($result as $key => $row) {
$info = json_decode($row['ip_info'], true);
$row['country'] = empty($info) ? '' : "$info[country_name]/$info[region_name]";
$result[$key] = $row;
}
return [
'result' => $result,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
public function setLog($uid)
{
//當天第一次登入有簽到禮(排除免費看會員)
$user = $this->userRepository->row($uid);
if ($user['free_time'] < date('Y-m-d H:i:s')) {
$date = date('Y-m-d');
$result = $this->userLoginLogRepository->search([
'uid' => $uid,
'created_at1' => $date,
'created_at2' => $date,
])->result();
$sysconfig = view()->shared('sysconfig');
if ($result->toArray() === []) {
$this->userRepository->addMoney($uid, 3, $sysconfig['daily_signin'], '每日签到');
}
}
//寫入LOG
$this->userLoginLogRepository->create([
'uid' => $uid,
]);
}
public function loginMap($input)
{
$search_params = param_process($input, ['id', 'desc']);
$order = $search_params['order'];
$search = $search_params['search'];
$params_uri = $search_params['params_uri'];
$search['created_at1'] = $search['created_at1'] ?? date('Y-m-d H:i:s', time()-86400);
$search['created_at2'] = $search['created_at2'] ?? date('Y-m-d H:i:s');
$where[] = ['created_at', '>=', $search['created_at1']];
$where[] = ['created_at', '<=', $search['created_at2']];
$result = $this->userLoginLogRepository
->select(['uid','ip_info'])
->where($where)
->group(['uid','ip_info'])
->result();
$table = [];
foreach ($result as $row) {
$info = json_decode($row['ip_info'], true);
if ($info == []) {
continue;
}
$table[] = [
'lat' => (float)$info['latitude'],
'lng' => (float)$info['longitude']
];
}
return [
'table' => $table,
'search' => $search,
'order' => $order,
'params_uri' => $params_uri,
];
}
}
<file_sep>/database/migrations/2019_11_11_083342_create_video_tags_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVideoTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'video_tags';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('name')->default('')->comment('Tag名稱');
$table->tinyInteger('hot')->default(0)->comment('熱門 0:否 1:是');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->index('created_at');
});
DB::statement("ALTER TABLE `$tableName` comment 'Tag清單'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('video_tags');
}
}
<file_sep>/database/migrations/2019_12_20_145538_create_domain_setting_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDomainSettingTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'domain_setting';
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('domain')->default('')->comment('網域');
$table->string('title')->default(0)->comment('標題');
$table->string('keyword')->default(0)->comment('關鍵字');
$table->string('description')->default(0)->comment('描述');
$table->text('baidu')->comment('百度統計代碼');
$table->dateTime('created_at')->default('1970-01-01 00:00:00')->comment('建檔時間');
$table->string('created_by', 50)->default('')->comment('新增者');
$table->dateTime('updated_at')->default('1970-01-01 00:00:00')->comment('更新時間');
$table->string('updated_by', 50)->default('')->comment('更新者');
$table->unique(['domain']);
});
DB::statement("ALTER TABLE `$tableName` comment '網域設定'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('domain_setting');
}
}
<file_sep>/app/Repositories/Admin/AdminRepository.php
<?php
namespace App\Repositories\Admin;
use App\Repositories\AbstractRepository;
use Models\Admin\Admin;
class AdminRepository extends AbstractRepository
{
public function __construct(Admin $entity)
{
parent::__construct($entity);
}
private function _preAction($row)
{
if (isset($row['password'])) {
if ($row['password'] != '') {
$row['password'] = bcrypt($row['password']);
} else {
unset($row['password']);
}
}
return $row;
}
public function create($row)
{
$row = $this->_preAction($row);
return parent::create($row);
}
public function update($row, $id=0)
{
$row = $this->_preAction($row);
return parent::update($row, $id);
}
public function _do_search()
{
if (isset($this->_search['username'])) {
$this->db = $this->db->where('username', 'like', '%'.$this->_search['username'].'%');
}
if (isset($this->_search['mobile'])) {
$this->db = $this->db->where('mobile', '=', $this->_search['mobile']);
}
if (isset($this->_search['status'])) {
$this->db = $this->db->where('status', '=', $this->_search['status']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '流水号',
'username' => '用户名称',
'password' => '<PASSWORD>',
'mobile' => '手机号码',
'roleid' => '角色群组',
'status' => '状态',
'is_agent' => '是否为代理',
];
}
<file_sep>/app/Repositories/Admin/AdminRoleRepository.php
<?php
namespace App\Repositories\Admin;
use App\Repositories\AbstractRepository;
use Models\Admin\AdminRole;
class AdminRoleRepository extends AbstractRepository
{
public function __construct(AdminRole $entity)
{
parent::__construct($entity);
}
public function _do_search()
{
if (isset($this->_search['name'])) {
$this->db = $this->db->where('name', 'like', '%'.$this->_search['name'].'%');
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
public function getRoleList()
{
$where[] = ['id','>',1];
$result = $this->where($where)->result()->toArray();
return array_column($result, 'name', 'id');
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '流水号',
'name' => '角色名称',
'allow_operator' => '运营商权限',
'allow_nav' => '导航权限',
];
}
<file_sep>/app/Models/Video/Video.php
<?php
namespace Models\Video;
use Models\Model;
class Video extends Model
{
protected $table = 'video';
protected $fillable = [
'keyword',
'name',
'publish',
'actors',
'tags',
'pic_b',
'pic_s',
'url',
'hls',
'created_by',
'updated_by',
];
const STATUS = [
0 => '已过期',
1 => '正常',
];
}
<file_sep>/app/Http/Controllers/Pmtools/RetentionController.php
<?php
namespace App\Http\Controllers\Pmtools;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Pmtools\DailyRetentionService;
class RetentionController extends Controller
{
protected $dailyRetentionService;
public function __construct(DailyRetentionService $dailyRetentionService)
{
$this->dailyRetentionService = $dailyRetentionService;
}
public function index(Request $request)
{
return view('pmtools.retention', $this->dailyRetentionService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'retention'));
}
public function chart(Request $request)
{
return view('pmtools.retention_chart', $this->dailyRetentionService->chart($request->input()));
}
public function chartSearch(Request $request)
{
return redirect(get_search_uri($request->input(), 'retention_chart'));
}
public function analysis(Request $request)
{
return view('pmtools.retention_analysis', $this->dailyRetentionService->analysis($request->input()));
}
public function analysisSearch(Request $request)
{
return redirect(get_search_uri($request->input(), 'retention_analysis'));
}
public function user(Request $request)
{
return view('pmtools.retention_user', $this->dailyRetentionService->user($request->input()));
}
public function userSearch(Request $request)
{
return redirect(get_search_uri($request->input(), 'retention_user'));
}
}
<file_sep>/app/Repositories/System/DomainSettingRepository.php
<?php
namespace App\Repositories\System;
use App\Repositories\AbstractRepository;
use Models\System\DomainSetting;
class DomainSettingRepository extends AbstractRepository
{
public function __construct(DomainSetting $entity)
{
parent::__construct($entity);
}
public function _do_search()
{
if (isset($this->_search['domain'])) {
$this->db = $this->db->where('domain', '=', $this->_search['domain']);
unset($this->_search['domain']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1']);
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2']);
}
return $this;
}
/**
* For 操作日誌用
*
* @var array
*/
public static $columnList = [
'id' => '流水号',
'domain' => '网域',
'title' => '标题',
'keyword' => '关键字',
'description' => '描述',
'baidu' => '百度统计代码',
];
}
<file_sep>/app/Http/Controllers/Admin/AdminController.php
<?php
namespace App\Http\Controllers\Admin;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\Admin\AdminForm;
use App\Services\Admin\AdminService;
class AdminController extends Controller
{
protected $adminService;
public function __construct(AdminService $adminService)
{
$this->adminService = $adminService;
}
public function index(Request $request)
{
return view('admin.index', $this->adminService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'admin'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('admin.create', $this->adminService->create($request->input()));
}
public function store(AdminForm $request)
{
$this->adminService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function edit($id)
{
View::share('sidebar', false);
return view('admin.edit', $this->adminService->show($id));
}
public function update(AdminForm $request, $id)
{
$this->adminService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function editpwd()
{
View::share('sidebar', false);
return view('admin.editpwd');
}
public function updatepwd(Request $request)
{
$this->validate($request, [
'old_pwd' => 'required',
'password' => '<PASSWORD>',
'repassword' => 'required|same:password',
]);
$data = $this->adminService->show(session('id'));
if (! \Hash::check($request->old_pwd, $data['row']['password'])) {
return back()->withErrors(['old_pwd'=>'旧密码输入错误']);
}
$this->adminService->update($request->post(), session('id'));
return "<script>alert('修改完成');parent.window.layer.close();parent.location.reload();</script>";
}
public function save(Request $request, $id)
{
$this->adminService->save($request->post(), $id);
return 'done';
}
public function destroy(Request $request)
{
$this->adminService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/app/Http/Controllers/User/UserMoneyLogController.php
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\User\UserMoneyLogService;
class UserMoneyLogController extends Controller
{
protected $userMoneyLogService;
public function __construct(UserMoneyLogService $userMoneyLogService)
{
$this->userMoneyLogService = $userMoneyLogService;
}
public function index(Request $request)
{
return view('user_money_log.index', $this->userMoneyLogService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'user_money_log'));
}
}
<file_sep>/app/Repositories/User/UserLoginLogRepository.php
<?php
namespace App\Repositories\User;
use App\Repositories\AbstractRepository;
use App\Repositories\System\Ip2locationRepository;
use Models\User\UserLoginLog;
class UserLoginLogRepository extends AbstractRepository
{
protected $ip2locationRepository;
public function __construct(UserLoginLog $entity, Ip2locationRepository $ip2locationRepository)
{
parent::__construct($entity);
$this->ip2locationRepository = $ip2locationRepository;
$this->is_action_log = false;
}
public function create($row)
{
$ip = request()->getClientIp();
$ip_info = $this->ip2locationRepository->getIpData($ip);
$ip_info = $ip_info ?? [];
$row['ip'] = $ip;
$row['ip_info'] = json_encode($ip_info);
$row['ua'] = request()->server('HTTP_USER_AGENT');
return parent::create($row);
}
public function _do_search()
{
if (isset($this->_search['uid'])) {
$this->db = $this->db->where('uid', '=', $this->_search['uid']);
}
if (isset($this->_search['username'])) {
$this->db = $this->db->whereHas('user', function ($query) {
$query->where('username', 'like', '%'.$this->_search['username'].'%');
});
}
if (isset($this->_search['status'])) {
$this->db = $this->db->whereHas('user', function ($query) {
$query->where('status', '=', $this->_search['status']);
});
}
if (isset($this->_search['ip'])) {
$this->db = $this->db->where('ip', '=', $this->_search['ip']);
}
if (isset($this->_search['created_at1'])) {
$this->db = $this->db->where('created_at', '>=', $this->_search['created_at1'] . ' 00:00:00');
}
if (isset($this->_search['created_at2'])) {
$this->db = $this->db->where('created_at', '<=', $this->_search['created_at2'] . ' 23:59:59');
}
return $this;
}
/**
* 取得區間內不重複登入帳號數
*
* @param string $startdate 起始時間
* @param string $enddate 結束時間
* @return int 人數
*/
public function getLoginUsers($startdate, $enddate)
{
return $this->select(['uid'])->search([
'status' => 1,
'created_at1' => $startdate,
'created_at2' => $enddate,
])->group('uid')->result()->count();
}
}
<file_sep>/app/Http/Controllers/Admin/AdminNavController.php
<?php
namespace App\Http\Controllers\Admin;
use View;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\Admin\AdminNavForm;
use App\Services\Admin\AdminNavService;
class AdminNavController extends Controller
{
protected $adminNavService;
public function __construct(AdminNavService $adminNavService)
{
$this->adminNavService = $adminNavService;
}
public function index(Request $request)
{
return view('admin_nav.index', $this->adminNavService->list($request->input()));
}
public function search(Request $request)
{
return redirect(get_search_uri($request->input(), 'admin_nav'));
}
public function create(Request $request)
{
View::share('sidebar', false);
return view('admin_nav.create', $this->adminNavService->create($request->input()));
}
public function store(AdminNavForm $request)
{
$this->adminNavService->store($request->post());
session()->flash('message', '添加成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function edit($id)
{
View::share('sidebar', false);
return view('admin_nav.edit', $this->adminNavService->show($id));
}
public function update(AdminNavForm $request, $id)
{
$this->adminNavService->update($request->post(), $id);
session()->flash('message', '编辑成功!');
return "<script>parent.window.layer.close();parent.location.reload();</script>";
}
public function save(Request $request, $id)
{
$this->adminNavService->save($request->post(), $id);
return 'done';
}
public function destroy(Request $request)
{
$this->adminNavService->destroy($request->input('id'));
session()->flash('message', '删除成功!');
return 'done';
}
}
<file_sep>/.env.example
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://tv.f1good.com
WEB_DOMAIN=iqqtv
API_DOMAIN=api.iqqtv
ADMIN_DOMAIN=admin.iqqtv
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=iqqtv
DB_USERNAME=iqqtv
DB_PASSWORD=<PASSWORD>
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=465
MAIL_USERNAME=<EMAIL>
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=ssl
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
SMS_URL=http://v.juhe.cn/sms/send
SMS_KEY=<KEY>
VIDEO_DOMAIN=https://apif1.qcapp.xyz
VIDEO_AU=apif1
VIDEO_KEY=<KEY>
JWT_SECRET=<KEY>
| 6c19374db308513617e067afc647b4a68c650eb4 | [
"PHP",
"Shell"
] | 134 | PHP | caixin/video | 40f1258e4328dc028433fe7888a3aecfc2f61e93 | 833ccfe4cbebb6304ae16e7e6081ee8b6ad6cabc | |
refs/heads/master | <repo_name>cytechinformatica/home-page<file_sep>/app/scripts/i18n/translations.js
const _cy_translations = {
'contact_email': {
'en': '<EMAIL>',
'pt': '<EMAIL>'
},
'copyright': {
'pt': 'copyright © 2017'
},
'cytech_name': {
'en': 'Cytech Informática',
'pt': 'Cytech Informática'
},
'menu_about': {
'pt': 'Sobre'
},
'menu_hibrid': {
'pt': 'desenvolvimento multi-plataforma'
},
'menu_mobile': {
'pt': 'Aplicativos Móveis'
},
'menu_portfolio': {
'pt': 'Portfólio'
},
'menu_seo': {
'pt': 'SEO'
},
'menu_visual': {
'pt': 'Identidade Visual'
},
'menu_web': {
'en': 'menu_web',
'pt': 'Websites'
},
'page_name': {
'en': 'Cytech',
'pt': 'Cytech'
},
'portfolio_item_0_text': {
'pt': 'Um aplicativo Android gratuito para o gerenciamento de rotinas de estudo.'
},
'portfolio_item_0_title': {
'pt': 'Auxiliar de Rotina'
},
'portfolio_item_1_text': {
'pt': 'Radar Livre é um sistema de monitoramento aéreo com aplicações multiplataforma, desenvolvido na Universidade Federal do Ceará.'
},
'portfolio_item_1_title': {
'pt': 'Radar Livre'
},
'portfolio_item_2_text': {
'pt': 'O ícone é baseado nas especificações do Material Design e representa uma formação rochosa famosa na região, a Pedra da Galinha Choca.'
},
'portfolio_item_2_title': {
'pt': 'Ícone para UFC Campus Quixadá'
},
'portfolio_item_3_text': {
'pt': 'Animação criada para representar o carregamento das páginas do site da empresa IZOTX.'
},
'portfolio_item_3_title': {
'pt': 'Animação de progresso para empresa IZOTX'
},
'portfolio_item_4_text': {
'pt': 'Página inicial dos sistemas da Universidade Federal do Ceará no campus de Quixadá. O front-end foi implementado com o Framework Materialize.'
},
'portfolio_item_4_title': {
'pt': 'Sistemas UFC-Quixadá'
},
'portfolio_item_5_text': {
'pt': 'Sistema de atendimento a serviços de psicologia e nutrição para a comunidade acadêmica da Universidade Federal do Ceará.'
},
'portfolio_item_5_title': {
'pt': 'SINUTRI'
},
'portfolio_item_6_text': {
'pt': 'Ícone do aplicativo e Landing page para o aplicativo Celeration Charts.'
},
'portfolio_item_6_title': {
'pt': 'CELERATION CHARTS LANDING PAGE'
},
'section_about_text': {
'pt': 'Olá, somos a Cytech Informática. Nós desenvolvemos soluções de TI com foco na qualidade, oferecendo as melhores alternativas e respeitando prazos e orçamentos. Sinta-se à vontade para entrar em contato e falar sobre sua grande ideia.'
},
'section_about_title': {
'pt': 'Sobre Nós'
},
'section_hibrid_extra_text': {
'pt': 'Aumente o tráfego de usuários no seu site e esteja sempre entre os melhores, através da otimização de resultados de buscas (SEO - Search Engine Optimization).'
},
'section_hibrid_text': {
'pt': 'Um único aplicativo para várias plataformas. Economize tempo e dinheiro desenvolvendo sua grande ideia para Web, Android e IOS.'
},
'section_hibrid_title': {
'pt': 'Desenvolvimento multi-plataforma'
},
'section_mobile_extra_text': {
'pt': 'Os aplicativos móveis permitem atingir um número muito maior de clientes e proporcionar a estes uma experiência muito mais interessante e eficaz. Esse canal de comunicação direta entre empresa e cliente coloca os aplicativos no patamar máximo do potencial de sucesso como canal de marketing. Faça parte dessa tendência e desenvolva você também sua ideia para dispositivos móveis.'
},
'section_mobile_text': {
'pt': 'DESENVOLVEMOS APLICATIVOS QUE CABEM NO SEU BOLSO! :^) CRIE SUA IDEIA E A TORNE MAIS ACESSÍVEL AOS SEUS USUÁRIOS, COM UM APLICATIVO QUE FICA LINDO TANTO NO SMARTPHONE QUANTO NO TABLET.'
},
'section_mobile_title': {
'pt': 'Aplicativos Móveis'
},
'section_portfolio_title': {
'pt': 'Portfólio'
},
'section_portifolio_title': {
'pt': 'Portfólio'
},
'section_seo_extra_text': {
'pt': 'Aumente o tráfego de usuários no seu site e esteja sempre entre os melhores, através da otimização de resultados de buscas (SEO - Search Engine Optimization).'
},
'section_seo_text': {
'pt': 'Obtenha melhores resultados nos maiores mecanismos de buscas, como Google, Yahoo e Bing.'
},
'section_seo_title': {
'pt': 'Otimização de Mecanismos de Buscas'
},
'section_text_visual': {
'pt': 'Dê a sua ideia um visual moderno, sofisticado, que externe sua identidade e atinja o público certo. Dê a sua marca um visual único e destaque-se entre as outras.'
},
'section_title_visual': {
'pt': 'Dê a sua ideia um visual moderno, sofisticado, que externe sua identidade e atinja o público certo. Dê a sua marca um visual único e destaque-se entre as outras.'
},
'section_visual_extra_text': {
'pt': 'Dê a sua marca um visual único e destaque-se entre as outras.'
},
'section_visual_text': {
'pt': 'Dê a sua ideia um visual moderno, sofisticado, que externe sua identidade e atinja o público certo. Dê a sua marca um visual único e destaque-se entre as outras.'
},
'section_visual_title': {
'pt': 'Crie sua própria identidade visual'
},
'section_web_extra_text': {
'pt': 'Impulsione seu neǵocio e o torne visível na internet. Torne sua ideia realidade através da criação de um web site moderno, elegante e que represente seu sonho.'
},
'section_web_text': {
'pt': 'Desenvolva conosco desde sites pessoais a sistemas web complexos, como Lojas Virtuais e Sites Comerciais com atendimento ao público.'
},
'section_web_title': {
'pt': 'Websites'
},
'see_less_btn': {
'pt': 'menos'
},
'see_more_btn': {
'pt': 'ver mais'
},
'slide_1_text_1': {
'pt': 'Olá'
},
'slide_1_text_2': {
'pt': 'Somos a'
},
'slide_1_text_3': {
'pt': 'Cytech Informática!'
},
'slide_2_text_1': {
'pt': 'Somos apaixonados por'
},
'slide_2_text_2': {
'pt': 'desafios e'
},
'slide_2_text_3': {
'pt': 'novas ideias!'
},
'slide_3_text_1': {
'pt': 'E você, já pensou no seu grande projeto hoje?'
},
'slide_3_text_2': {
'pt': 'Entre em contato '
},
'slide_3_text_3': {
'pt': 'E compartilhe sua idea conosco! :)'
}
}<file_sep>/app/scripts/devices.js
$(() => {
$('.cy-device-auto-change').each((_, e) => {
const el = $(e)
const devices = [ 'imac', 'tablet', 'phone' ]
let index = 0
setInterval(() => {
el.removeClass(`cy-device-${devices[index % devices.length]}`)
el.addClass(`cy-device-${devices[++index % devices.length]}`)
}, 2000)
})
})<file_sep>/app/scripts/toolbar.js
$(() => {
if($(window).width() < 993) return;
const toolbarComponent = $('.cy-toolbar')
const headerFabComponent = $('.cy-header-fab')
const firstSectionComponent = $('.1st-section')
/**
* MENUS
*/
const wavesCount = 2
const waves = []
const waveTemplate = index =>
(`<div id="cy-toolbar-active-circle-${index}" class="cy-toolbar-active-circle"></div>`)
const state = {
menu: -1,
menus: [],
}
$('.cy-toolbar-menu').each((i, el) => {
state.menus.push($(el))
$(el).click(() => goToMenu(i))
})
const updateWaves = (index = state.menu) => {
for (let i = 0; i < wavesCount; i++) {
let wave = $(`#cy-toolbar-active-circle-${i}`)
if (wave.length === 0) {
wave = $($.parseHTML(waveTemplate(i)))
wave.css({ transition: `all ${(i + 1) + 5}00ms cubic-bezier(0.8, 0, 0.2, 1)` })
toolbarComponent.append(wave)
waves.push(wave)
}
}
const menu = state.menus[index]
if (menu) {
const menuPos = menu.position()
let size = menu.height() / 1.15
let factor = 1.618
waves.map((w, i) => {
size *= factor
w.css({
top: menuPos.top + menu.height() / 2 - size / 2,
left: menuPos.left + menu.width() / 2 - size / 2,
width: size,
height: size
})
})
} else {
waves.map(w => w.css({
top: 0,
left: '50%',
width: 0,
height: 0
}))
}
}
const goToMenu = (index) => {
state.menu = index
updateWaves(index)
}
state.menus.map((m, i) => {
const sectionId = m.attr('href').replace('#', '')
const element = document.getElementById(sectionId)
if(element) {
new Waypoint({
element: document.getElementById(sectionId),
handler: function (direction) {
if (direction == 'down') {
goToMenu(i)
} else {
goToMenu(i - 1)
}
},
offset: 100
})
}
})
/**
* END-MENUS
*/
/**
* TOOLBAR ANIM
*/
$(window).scroll(() => {
let windowScroll = $(window).scrollTop()
if (windowScroll >= $(window).height() - 52) {
toolbarComponent.removeClass('cy-toolbar-expanded')
headerFabComponent.addClass('cy-hided')
firstSectionComponent.css({ marginTop: 160 })
} else {
toolbarComponent.addClass('cy-toolbar-expanded')
headerFabComponent.removeClass('cy-hided')
firstSectionComponent.css({ marginTop: 0 })
}
windowScroll = Math.max(0, windowScroll - ($(window).height() - 52))
const factor = (80 - Math.min(windowScroll, 80))
toolbarComponent.css({ height: 80 + factor })
/**
* UPDATING MENU
*/
updateWaves()
})
})
<file_sep>/app/scripts/cool-grid.js
const __IZOTX_L_SVG = () => (`
<svg
width="162.56mm" height="162.56mm" version="1.1"
viewBox="0 0 16256 16256">
<g id="logo">
<path
class="left-leg"
d="M8128 8601l21 4607c-1781,-4 -3571,231 -5292,692l-2384 -4099c2412,-778 4984,-1200 7655,-1200z" />
<path
class="right-leg"
d="M8149 8601c2662,3 5225,423 7629,1198l-2379 4101c-1675,-449 -3434,-690 -5250,-692l0 -4607z" />
</g>
</svg>
`)
const __IZOTX_L = () => (`
<div class="izotx-loading">
<div class="izotx-loading-leg izotx-loading-leg-green">${__IZOTX_L_SVG()}</div>
<div class="izotx-loading-leg izotx-loading-leg-orange">${__IZOTX_L_SVG()}</div>
<div class="izotx-loading-leg izotx-loading-leg-blue">${__IZOTX_L_SVG()}</div>
<div class="izotx-loading-leg izotx-loading-leg-green just-right-leg">${__IZOTX_L_SVG()}</div>
</div>
`)
const __PORT_ITEMS = [
{
size: 1,
link: 'https://play.google.com/store/apps/details?id=routinehelp.view',
image: 'https://lh4.ggpht.com/KB3XcLlJQx6TBYMsxHsPKY_uYASgT0A7LiTLRTtIUlntNq-ApqBKa-wmPcMadD9Bugg=w300-rw',
},
{
size: 1,
link: 'http://www.radarlivre.com/',
image: 'https://media.cmcdn.net/b99ee4b190d495b5466b/33237717/500x500.png',
useImg: true,
},
{
size: 1,
image: 'https://media.cmcdn.net/8600c3c976fc7bd27e1c/33237727/500x500.png',
},
{
size: 1,
imageHTML: __IZOTX_L()
},
{
size: 2,
link: 'https://sistemas.quixada.ufc.br/',
image: 'https://media.cmcdn.net/e30366116458051e34c5/33237473/960x539.png'
},
{
size: 1,
link: 'https://sistemas.quixada.ufc.br/sinutri/login',
image: 'https://media.cmcdn.net/135853385d148278ab58/33237555/960x539.png'
},
{
size: 1,
link: 'https://celeration-charts.firebaseapp.com/',
image: 'images/celeration.png'
},
]
$(() => {
const portfolioItemsElement = $('.cy-cool-grid')
const portfolioItemTemplate = (item, i) => `
<a ${item.link ? `href="${item.link}" target="_blank"` : ''} class="cy-cool-grid-tile cy-cool-grid-tile-${item.size}" ${item.image ? `data-image="${item.image}"` : '' }>
<div class="cy-cool-grid-tile-background">
${item.imageHTML ? item.imageHTML : ''}
</div>
<div class="cy-cool-grid-tile-overlay">
<p translate>portfolio_item_${i}_title</p>
<p translate>portfolio_item_${i}_text</p>
</div>
</a>
`
__PORT_ITEMS.map((item, i) => portfolioItemsElement.append(portfolioItemTemplate(item, i)))
$('.cy-cool-grid-tile').each((_, el) => {
if($(el).data('image'))
$(el).css({
background: `url(${$(el).data('image')}) center/cover`
})
})
window.__updateTranslation? window.__updateTranslation() : false
})<file_sep>/app/scripts/main.js
$(() => {
$('.cy-btn-toggle-text').each((_, el) => {
$(el).click(e => {
e.preventDefault()
const toExpand = $(`${$(el).data('to-expand')}`)
const height = toExpand.find('p').outerHeight(true)
if($(el).data('collapsed')) {
toExpand.css({ height: 0 })
$(el).data('collapsed', false)
$(el).text($(el).data('collapsed-text'))
} else {
toExpand.css({ height: height })
$(el).data('collapsed', true)
$(el).data('collapsed-text', $(el).data('translation'))
$(el).text($(el).data('expanded-text'))
}
window.__updateTranslation? window.__updateTranslation() : false
})
})
$('.scrollspy').scrollSpy({ scrollOffset: 80 });
$('.cy-toolbar .cy-toolbar-cool-icons .cy-toolbar-menu').each((_, el) => {
const menu = $(el).clone()
menu.removeClass('hide-on-med-and-down')
const wrapper = $($.parseHTML('<li></li>'))
wrapper.append(menu)
$('#slide-out').append(wrapper)
})
$('.button-collapse').sideNav();
$('.side-nav').click(() => {
$('.button-collapse').sideNav('hide');
})
window.__updateTranslation? window.__updateTranslation() : false
})
| 440aef968f7e0f8172dc41ad643b51960cbd3385 | [
"JavaScript"
] | 5 | JavaScript | cytechinformatica/home-page | ec67f954c0c9d657c101a29e785cc6d00832fdb5 | 86a925020409bd901779f26bca5f5c5fbbccb89e | |
refs/heads/master | <repo_name>CaioMaxi/IGTI-dev-full-stack<file_sep>/index.js
import { promises as fs } from "fs";
import readline from "readline";
import { rejects } from "assert";
let arrStates = [];
let arrCities = [];
let citiesList = [];
let arrLength = [];
let allStatesQty = [];
let allCitiesWord = [];
let allCitiesWord2 = [];
let arrBigNames = [];
let arrSmallNames = [];
let sortedBigNames = [];
let sortedSmallNames = [];
// let smallNamesToSort = [];
// let bigNamesToSort = [];
readFile();
async function readFile() {
const states = await fs.readFile("Estados.json");
arrStates = await JSON.parse(states);
const cities = await fs.readFile("Cidades.json");
arrCities = await JSON.parse(cities);
organizeEverything();
checkUf();
checkWordCities();
}
async function organizeEverything() {
arrStates.forEach((state) => {
citiesList = [];
arrCities.forEach((city) => {
if (state.ID === city.Estado) {
citiesList.push(city);
}
});
let obj1 = {
uf: state.Sigla,
cities: citiesList,
};
createStateFile(state, obj1);
});
}
async function createStateFile(item, content) {
try {
await fs.writeFile(`${item.Sigla}.json`, JSON.stringify(content));
} catch (err) {
console.log(err);
}
}
async function checkUf() {
try {
arrStates.forEach((state) => {
quickRead(state.Sigla);
});
fiveUfMoreCities();
fiveUfLessCities();
biggestCityOfAll();
smallestCityOfAll();
} catch (err) {
console.log(err);
}
}
function fiveUfMoreCities() {
setTimeout(() => {
console.log(" Top 5 states with higher number of cities: ");
allStatesQty = allStatesQty.sort((a, b) => {
return b.qty - a.qty;
});
let arrMoreCities = [];
for (let i = 0; i < 5; i++) {
arrMoreCities.push(`${allStatesQty[i].uf} - ${allStatesQty[i].qty}`);
}
console.log(arrMoreCities);
}, 200);
}
function fiveUfLessCities() {
setTimeout(() => {
console.log(" Top 5 states with lesser number of cities: ");
allStatesQty = allStatesQty.sort((a, b) => {
return a.qty - b.qty;
});
let arrLessCities = [];
for (let i = 4; i >= 0; i--) {
arrLessCities.push(`${allStatesQty[i].uf} - ${allStatesQty[i].qty}`);
}
console.log(arrLessCities);
}, 200);
}
async function quickRead(uf) {
try {
let quickRead = await fs.readFile(`${uf}.json`);
let allCities = JSON.parse(quickRead);
let quantity = allCities.cities.length;
let obj2 = {
uf: uf,
qty: quantity,
};
arrLength = obj2;
allStatesQty.push(arrLength);
return arrLength;
} catch (err) {
console.log(err);
}
}
async function checkWordCities() {
try {
arrStates.forEach((state) => {
lookForCities(state.Sigla);
});
setTimeout(() => {
console.log(" Biggest city name of each state: ");
console.log(arrBigNames);
}, 300);
setTimeout(() => {
console.log(" Smallest city name of each state: ");
console.log(arrSmallNames);
}, 300);
} catch (err) {
console.log(err);
}
}
async function lookForCities(uf) {
try {
let lookForCities = await fs.readFile(`${uf}.json`);
allCitiesWord = JSON.parse(lookForCities);
allCitiesWord2 = allCitiesWord;
sortBigNames(uf);
sortSmallNames(uf);
} catch (err) {
console.log(err);
}
}
function sortBigNames(uf) {
allCitiesWord = allCitiesWord.cities.sort((a, b) => {
return b.Nome.length - a.Nome.length;
});
arrBigNames.push(`${allCitiesWord[0].Nome} - ${uf}`);
// bigNamesToSort.push(allCitiesWord[0]);
}
function sortSmallNames(uf) {
allCitiesWord2 = allCitiesWord2.cities.sort((a, b) => {
return a.Nome.length - b.Nome.length;
});
arrSmallNames.push(`${allCitiesWord2[0].Nome} - ${uf}`);
// smallNamesToSort.push(allCitiesWord2[0]);
}
function biggestCityOfAll() {
setTimeout(() => {
sortedBigNames = arrBigNames
.sort((a, b) => {
return a.localeCompare(b);
})
.sort((a, b) => {
return b.length - a.length;
});
console.log(" The biggest city name is:");
console.log(sortedBigNames[0]);
}, 500);
}
function smallestCityOfAll() {
setTimeout(() => {
sortedSmallNames = arrSmallNames
.sort((a, b) => {
return a.localeCompare(b);
})
.sort((a, b) => {
return a.length - b.length;
});
console.log(" The smallest city name is:");
console.log(sortedSmallNames[0]);
}, 500);
}
| e1de7ed8a8a202b8b6123dd0c2b733481b115755 | [
"JavaScript"
] | 1 | JavaScript | CaioMaxi/IGTI-dev-full-stack | f547e04f9e77d784d0664c48fddf1452f985d977 | 31ef8de2b409f58f607a89035a68f3cd7bb5e7a9 | |
refs/heads/main | <repo_name>GeorgeEBeresford/ContentExplorer<file_sep>/ContentExplorer/Core/Scripts/Common/Repositories/TagRepository.js
/**
* An object which sends and retrieves tag-related information to and from the server
* @class
*/
function TagRepository() {
/**
* An object which deals with sending HTTP requests to the server
* @type {HttpRequester}
*/
var httpRequester = new HttpRequester();
var controller = "Tag";
/**
* Adds the specified tags to the provided directory paths
* @param {Array<string>} directoryPaths
* @param {Array<string>} tags
* @param {string} mediaType
* @returns {JQuery.Promise<Array<any>>}
*/
this.addTagsToDirectories = function (directoryPaths, tags, mediaType) {
var deferred = $.Deferred();
var payload = {
directoryPaths: directoryPaths,
tags: tags,
mediaType: mediaType
};
httpRequester.postAsync("AddTagsToDirectories", controller, payload)
.then(function (isSuccess) {
if (isSuccess) {
deferred.resolve();
}
else {
alert("Failed to add tags to directories");
deferred.reject();
}
})
.fail(function (xhr) {
alert("[" + xhr.status + "] " + xhr.statusText);
deferred.reject();
});
return deferred.promise();
}
/**
* Adds the specified tags to the provided directory paths
* @param {Array<string>} filePaths
* @param {Array<string>} tags
* @param {string} mediaType
* @returns {JQuery.Promise<Array<any>>}
*/
this.addTagsToFiles = function (filePaths, tags, mediaType) {
var deferred = $.Deferred();
var payload = {
filePaths: filePaths,
tags: tags,
mediaType: mediaType
};
httpRequester.postAsync("AddTagsToFiles", controller, payload)
.then(function (isSuccess) {
if (isSuccess) {
deferred.resolve();
}
else {
alert("Failed to add tags to files");
deferred.reject();
}
})
.fail(function (xhr) {
alert("[" + xhr.status + "] " + xhr.statusText);
deferred.reject();
});
return deferred.promise();
}
/**
* Retrieves the tags for the given directory and mediaType
* @param {string} directoryPath -
* @param {string} mediaType -
* @param {string} filter -
* @returns {JQuery.Promise<any>}
*/
this.getTagsAsync = function (directoryPath, mediaType, filter) {
var deferred = $.Deferred();
var payload = {
directoryName: directoryPath,
mediaType: mediaType,
filter: filter
};
httpRequester.getAsync("GetDirectoryTags", controller, payload)
.then(function (tags) {
deferred.resolve(tags);
})
.fail(function (xhr) {
alert("[" + xhr.status + "] " + xhr.statusText);
deferred.reject();
});
return deferred.promise();
}
/**
* Retrieves the tags for the given file and mediaType
* @param {string} filePath -
* @param {string} mediaType -
* @returns {JQuery.Promise<any>}
*/
this.getFileTagsAsync = function(filePath, mediaType) {
var deferred = $.Deferred();
var payload = {
fileName: filePath,
mediaType: mediaType
};
httpRequester.getAsync("GetFileTags", controller, payload)
.then(function (tags) {
deferred.resolve(tags);
})
.fail(function (xhr) {
alert("[" + xhr.status + "] " + xhr.statusText);
deferred.reject();
});
return deferred.promise();
}
}<file_sep>/ContentExplorer.Tests/API/Test.cs
using System.Configuration;
using System.IO;
using ContentExplorer.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ContentExplorer.Tests.API
{
public abstract class Test
{
protected Test()
{
FakeHttpContext = new FakeHttpContext.FakeHttpContext();
}
private FakeHttpContext.FakeHttpContext FakeHttpContext { get; }
protected const string DefaultTestTagName = "TestTag";
protected const string DefaultTestImageName = "test.png";
protected static readonly string TestImagesDirectory = ConfigurationManager.AppSettings["ImagesPath"];
protected static readonly string DefaultTestImagePath = $"{TestImagesDirectory}\\{DefaultTestImageName}";
[TestInitialize]
public void Initialise()
{
bool tagsAreInitialised = Tag.InitialiseTable();
Assert.IsTrue(tagsAreInitialised);
string sql = "SELECT * FROM Tags LIMIT 1";
using (SqliteWrapper sqliteWrapper = new SqliteWrapper("AppDb"))
{
sqliteWrapper.GetDataRow(sql);
}
bool tagLinksAreInitialised = TagLink.InitialiseTable();
Assert.IsTrue(tagLinksAreInitialised);
sql = "SELECT * FROM TagLinks LIMIT 1";
using (SqliteWrapper sqliteWrapper = new SqliteWrapper("AppDb"))
{
sqliteWrapper.GetDataRow(sql);
}
}
[TestCleanup]
public void Cleanup()
{
FileInfo fileInfo = new FileInfo("database.db");
if (fileInfo.Exists)
{
fileInfo.Delete();
}
fileInfo = new FileInfo(DefaultTestImagePath);
if (fileInfo.Exists)
{
try
{
fileInfo.Delete();
}
// File may be in-use. Try again.
catch (IOException)
{
fileInfo.Delete();
}
}
FakeHttpContext.Dispose();
}
protected FileInfo CreateAndReturnImage(string relativeDirectory = null)
{
string cdnDiskPath = ConfigurationManager.AppSettings["BaseDirectory"];
string directoryPath = relativeDirectory == null
? $"{cdnDiskPath}\\{TestImagesDirectory}"
: $"{cdnDiskPath}\\{TestImagesDirectory}\\{relativeDirectory}";
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
if (directoryInfo.Exists != true)
{
directoryInfo.Create();
}
// We don't really need multiple files in a directory. Just attach multiple tag links to the same file.
string filePath = $"{cdnDiskPath}\\{DefaultTestImagePath}";
FileInfo createdFile = new FileInfo(filePath);
if (createdFile.Exists)
{
createdFile.Delete();
}
// The image doesn't have to be readable. We just have to be able to guess it's an image from the extension
using (StreamWriter streamWriter = new StreamWriter(new FileStream(filePath, FileMode.CreateNew)))
{
streamWriter.WriteLine("Test file");
}
FileInfo testFileInfo = new FileInfo(filePath);
return testFileInfo;
}
protected TagLink CreateAndReturnTagLink(string relativeDirectory = null, string tagName = null)
{
Tag tag = CreateAndReturnTag(tagName);
CreateAndReturnImage(relativeDirectory);
string filePath = relativeDirectory == null
? DefaultTestImagePath
: $"{TestImagesDirectory}\\{relativeDirectory}\\{DefaultTestImageName}";
TagLink tagLink = new TagLink
{
TagId = tag.TagId,
FilePath = filePath
};
bool isSuccess = tagLink.Create();
Assert.IsTrue(isSuccess, "TagLink was not successfully created");
Assert.AreNotEqual(0, tag.TagId, "TagLink ID was not set");
return tagLink;
}
protected Tag CreateAndReturnTag(string tagName = null)
{
Tag tag = new Tag
{
TagName = tagName ?? DefaultTestTagName
};
bool isSuccess = tag.Create();
Assert.IsTrue(isSuccess, "Tag was not successfully created");
Assert.AreNotEqual(0, tag.TagId, "Tag ID was not set");
return tag;
}
}
}<file_sep>/ContentExplorer/Services/IThumbnailService.cs
using System.IO;
namespace ContentExplorer.Services
{
public interface IThumbnailService
{
void CreateThumbnail(FileInfo fileInfo);
void DeleteThumbnailIfExists(FileInfo fileInfo);
FileInfo GetDirectoryThumbnail(DirectoryInfo directory);
FileInfo GetFileThumbnail(FileInfo fileInfo);
bool IsThumbnail(FileInfo fileInfo);
}
}<file_sep>/ContentExplorer/Models/ViewModels/DirectoryViewModel.cs
using System.Collections.Generic;
using System.IO;
namespace ContentExplorer.Models.ViewModels
{
public class DirectoryViewModel
{
public ICollection<DirectoryInfo> DirectoryInfos { get; set; }
public ICollection<FileInfo> FileInfos { get; set; }
public int FileCount { get; set; }
}
}<file_sep>/ContentExplorer.Tests/API/Models/TagLinkTest.cs
using System.Collections.Generic;
using ContentExplorer.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ContentExplorer.Tests.API.Models
{
[TestClass]
public class TagLinkTest : Test
{
[TestMethod]
public void GetTag()
{
Tag tag = CreateAndReturnTag();
TagLink createdTagLink = new TagLink
{
TagId = tag.TagId
};
Tag retrievedTag = createdTagLink.GetTag();
Assert.IsNotNull(retrievedTag, "Tag was not retrieved");
Assert.AreEqual(tag.TagId, retrievedTag.TagId);
TagLink tagLink = CreateAndReturnTagLink();
retrievedTag = tagLink.GetTag();
Assert.IsNotNull(tag, "Tag was not retrirved");
Assert.AreEqual(tagLink.TagId, retrievedTag.TagId);
}
[TestMethod]
public void GetTagLinkByDirectory()
{
CreateAndReturnTagLink();
ICollection<TagLink> directoryTagLinks = TagLink.GetByDirectory(TestImagesDirectory);
Assert.IsNotNull(directoryTagLinks, "Null was returned for directory tag links");
Assert.AreNotEqual(0, directoryTagLinks.Count, "No tag links were returned for directory");
}
[TestMethod]
public void GetAllTagLinks()
{
CreateAndReturnTagLink();
CreateAndReturnTagLink();
ICollection<TagLink> allTagLinks = TagLink.GetAll();
Assert.IsNotNull(allTagLinks, "Null was returned for directory tag links");
Assert.AreEqual(2, allTagLinks.Count);
}
[TestMethod]
public void GetTagLinkByFilteredDirectory()
{
// Default tag
CreateAndReturnTagLink();
CreateAndReturnTagLink("Nested");
// Second tag
CreateAndReturnTagLink(null, "Filtered");
CreateAndReturnTagLink("Nested", "Filtered");
// Non matching tags (to make sure it's actually filtered)
Tag nonMatchingTag = CreateAndReturnTag("NonMatchingFilter");
TagLink nonMatchingTagLink = new TagLink
{
TagId = nonMatchingTag.TagId,
FilePath = $"{TestImagesDirectory}\\test2.png"
};
nonMatchingTagLink.Create();
nonMatchingTagLink.FilePath = $"{TestImagesDirectory}\\Nested\\test2.png";
nonMatchingTagLink.Create();
// Add a new file with just the default tag so we can make sure multiple filters return the correct files
Tag singleMatchTag = CreateAndReturnTag();
TagLink singleMatchTagLink = new TagLink
{
TagId = singleMatchTag.TagId,
FilePath = $"{TestImagesDirectory}\\test3.png"
};
singleMatchTagLink.Create();
// Check for default tag
ICollection<TagLink> nonRecursiveTagLinks =
TagLink.GetByDirectory(TestImagesDirectory, new[] {DefaultTestTagName}, 0, -1);
Assert.IsNotNull(nonRecursiveTagLinks, "Returned tag links were null");
Assert.AreEqual(2, nonRecursiveTagLinks.Count);
ICollection<TagLink> recursiveTagLinks =
TagLink.GetByDirectory(TestImagesDirectory, new[] {DefaultTestTagName}, 0, -1, true);
Assert.IsNotNull(recursiveTagLinks, "Returned tag links were null");
Assert.AreEqual(3, recursiveTagLinks.Count);
// Check for two tags
nonRecursiveTagLinks =
TagLink.GetByDirectory(TestImagesDirectory, new[] {DefaultTestTagName, "Filtered"}, 0, -1);
Assert.IsNotNull(nonRecursiveTagLinks, "Returned tag links were null");
Assert.AreEqual(1, nonRecursiveTagLinks.Count);
recursiveTagLinks =
TagLink.GetByDirectory(TestImagesDirectory, new[] {DefaultTestTagName, "Filtered"}, 0, -1, true);
Assert.IsNotNull(recursiveTagLinks, "Returned tag links were null");
Assert.AreEqual(2, recursiveTagLinks.Count);
}
[TestMethod]
public void GetTagLinkByTagName()
{
CreateAndReturnTagLink();
CreateAndReturnTagLink();
ICollection<TagLink> tagLinks = TagLink.GetByTagName(DefaultTestTagName);
Assert.IsNotNull(tagLinks, "Returned tag links are null");
Assert.AreEqual(2, tagLinks.Count);
}
[TestMethod]
public void CreateTagLink()
{
TagLink tagLink = CreateAndReturnTagLink();
using (SqliteWrapper sqliteWrapper = new SqliteWrapper("AppDb"))
{
IDictionary<string, object> dataRow = sqliteWrapper.GetDataRow(
"SELECT * FROM TagLinks WHERE TagLinkId = @TagLinkId",
SqliteWrapper.GenerateParameter("@TagLinkId", tagLink.TagLinkId)
);
Assert.IsNotNull(dataRow);
}
}
[TestMethod]
public void DeleteTagLink()
{
TagLink tagLink = CreateAndReturnTagLink();
bool isSuccess = tagLink.Delete();
Assert.IsTrue(isSuccess, "TagLink was not successfully deleted");
using (SqliteWrapper sqliteWrapper = new SqliteWrapper("AppDb"))
{
IDictionary<string, object> dataRow = sqliteWrapper.GetDataRow(
"SELECT * FROM TagLinks WHERE TagLinkId = @TagLinkId",
SqliteWrapper.GenerateParameter("@TagLinkId", tagLink.TagLinkId)
);
Assert.IsNull(dataRow);
}
}
}
}<file_sep>/ContentExplorer/Core/Scripts/Index/VideoIndex.js
/**
* An object that displays a list of videos in a directory
* @class
*/
function VideoIndex() {
MediaIndex.call(this, "video", "Video");
this.$actions = $("[data-actions='video']");
}
VideoIndex.prototype = Object.create(MediaIndex.prototype);
VideoIndex.prototype.addMediaDependentActions = function () {
MediaIndex.prototype.addMediaDependentActions.call(this);
var $rebuildThumbnailsButton = $("<a>")
.attr("href", "../" + this.controller + "/" + "RebuildThumbnails?path=" + this.directoryPath)
.attr("target", "_blank")
.append(
$("<div>").addClass("btn btn-default").text("Rebuild Thumbnails")
);
var $reformatNames = $("<a>")
.attr("href", "../" + this.controller + "/" + "ReformatNames?path=" + this.directoryPath)
.attr("target", "_blank")
.append(
$("<div>").addClass("btn btn-default").text("Reformat Names")
);
var $convertUnplayableVideos = $("<a>")
.attr("href", "../" + this.controller + "/" + "ConvertUnplayableVideos?path=" + this.directoryPath)
.attr("target", "_blank")
.append(
$("<div>").addClass("btn btn-default").text("Convert Unplayable Videos")
);
this.$actions
.append($rebuildThumbnailsButton)
.append($reformatNames)
.append($convertUnplayableVideos);
}
$(function () {
var mediaIndex = new VideoIndex();
mediaIndex.initialiseAsync();
})<file_sep>/ContentExplorer/Core/Scripts/Index/MediaIndex.js
/**
* An object which displays a directory of media items in a way that allows
* the user to navigate between directories and media items
* @param {string} mediaType
* @param {string} controller
* @class
*/
function MediaIndex(mediaType, controller) {
this.$customFilter = $("[data-custom-filter]");
this.$applyFilter = $("[data-apply-filter]");
this.$selectableForTagging = $("[data-tag-selector]").not("[data-template] [data-tag-selector]");
this.$taggingContainer = $("[data-tagging]");
this.$tagList = this.$taggingContainer.find("[data-tags-for-folder]");
this.$tagName = this.$taggingContainer.find("[data-tag-name]");
this.$addTag = this.$taggingContainer.find("[data-add-tag]");
this.$clearFilter = $("[data-clear-filter]");
this.$steppingStones = $("[data-stepping-stones]");
this.$directoryTemplate = $("[data-template='directory']");
this.$fileTemplate = $("[data-template='file']");
this.$directoryList = $("[data-directory-list]");
this.$fileList = $("[data-file-list]");
this.$pages = $("[data-pages]");
this.directoryPath = $("[name='Path']").val();
this.cdnPath = $("[name='CdnPath']").val();
this.page = +$("[name='Page']").val();
this.filesPerPage = +$("[name='FilesPerPage']").val();
this.filter = $("[name='Filter']").val();
this.mediaType = mediaType;
this.controller = controller;
this.totalFiles = 0;
this.mediaRepository = new MediaRepository();
this.mediaUiFactory = new MediaUiFactory();
this.tagRepository = new TagRepository();
}
MediaIndex.prototype.renderPages = function () {
var totalPages = Math.ceil(this.totalFiles / this.filesPerPage);
if (totalPages > 1) {
var $pageList = this.$pages.find("[data-page-list]");
var $totalPages = this.$pages.find("[data-total-pages]");
$pageList.html("");
$totalPages.text(totalPages + " Pages Total");
for (var pageIndex = 1; pageIndex <= totalPages; pageIndex++) {
var $currentPage = $("<a>").text(pageIndex);
if (pageIndex != this.page) {
var url = "../" + this.controller + "/Index?path=" + this.directoryPath + "&page=" + pageIndex + "&filter=" + this.filter;
$currentPage.addClass("button_item").attr("href", url);
}
else {
$currentPage.addClass("button_item-current");
}
$pageList.append($currentPage);
}
this.$pages.show();
}
else {
this.$pages.hide();
}
}
MediaIndex.prototype.renderSubFilesAsync = function () {
var deferred = $.Deferred();
var self = this;
this.mediaRepository.getSubFilesAsync(this.directoryPath, this.mediaType, this.filter, (this.page - 1) * 50, 50)
.then(function (paginatedSubFiles) {
self.totalFiles = paginatedSubFiles.Total;
var $files = $("[data-files]");
if (paginatedSubFiles.CurrentPage.length !== 0) {
paginatedSubFiles.CurrentPage.forEach(function (subFileInfo, subMediaIndex) {
self.renderSubFile(subFileInfo, ((self.page - 1) * self.filesPerPage) + subMediaIndex + 1);
});
}
else {
$files.find("h1").remove();
}
$files.show();
self.$selectableForTagging = $("[data-tag-selector]").not("[data-template] [data-tag-selector]");
self.renderPages();
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
};
MediaIndex.prototype.renderSubFile = function (subFileInfo, subMediaIndex) {
var $filePreview = this.$fileTemplate
.clone()
.show()
.removeAttr("data-template");
var fileViewingPage = window.location.origin +
"/" +
this.controller +
"/" +
"View?path=" +
subFileInfo.Path +
"&page=" +
subMediaIndex +
"&filter=" +
this.filter;
$filePreview.find("a").attr("href", fileViewingPage);
$filePreview.find("[data-file-name]").text(subFileInfo.Name);
$filePreview.find("[data-tag-selector]").attr("data-path", subFileInfo.TaggingUrl);
$filePreview.css("background-image", "url(\"" + this.cdnPath + "/" + subFileInfo.ThumbnailUrl + "\")");
this.$fileList.append($filePreview);
}
MediaIndex.prototype.renderSubDirectoriesAsync = function () {
var deferred = $.Deferred();
var self = this;
this.mediaRepository.getSubDirectoriesAsync(this.directoryPath, this.mediaType, this.filter)
.then(function (subDirectoryInfos) {
var $directories = $("[data-directories]");
if (subDirectoryInfos.length !== 0) {
subDirectoryInfos.forEach(function (subDirectoryInfo) {
self.renderSubDirectory(subDirectoryInfo);
});
}
else {
$directories.find("h1").remove();
}
$directories.show();
self.$selectableForTagging = $("[data-tag-selector]").not("[data-template] [data-tag-selector]");
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
};
MediaIndex.prototype.renderSubDirectory = function (subDirectoryInfo) {
var $directoryPreview = this.$directoryTemplate
.clone()
.show()
.removeAttr("data-template");
$directoryPreview.find("a").attr("href", window.location.origin + window.location.pathname + "?path=" + subDirectoryInfo.Path + "&filter=" + this.filter);
$directoryPreview.find("[data-directory-name]").text(subDirectoryInfo.Name);
$directoryPreview.find("[data-tag-selector]").attr("data-path", subDirectoryInfo.TaggingUrl);
$directoryPreview.css("background-image", "url(\"" + this.cdnPath + "/" + subDirectoryInfo.ThumbnailUrl + "\")");
this.$directoryList.append($directoryPreview);
}
MediaIndex.prototype.renderSteppingStonesAsync = function () {
var self = this;
var deferred = $.Deferred();
this.mediaRepository.getDirectoryHierarchyAsync(this.directoryPath, this.mediaType)
.then(function (directoryHierarchy) {
var $steppingStones = self.mediaUiFactory.generateSteppingStones(self.controller, directoryHierarchy, self.filter);
self.$steppingStones.html($steppingStones);
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
/**
* Initialises the file index
* @param {string} mediaType
*/
MediaIndex.prototype.initialiseAsync = function () {
var deferred = $.Deferred();
var self = this;
this.addEventHandlers();
var renderAsynchronously = $.when(
this.renderSteppingStonesAsync(),
this.renderSubDirectoriesAsync(),
this.renderSubFilesAsync(),
this.renderTagListAsync()
);
renderAsynchronously
.then(function () {
var numberOfMediaItems = $("[data-files],[data-directories]").find("li").length;
if (numberOfMediaItems === 0) {
var $files = $("[data-files]");
var $noFilesMessage = $("<h1>").text(this.filter !== "" ? "No files found with filter " + self.filter : "No files found");
$files.html($noFilesMessage);
}
self.addMediaDependentActions();
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.addEventHandlers = function () {
var self = this;
this.$applyFilter.on("click",
function () {
self.applyFilter();
});
this.$customFilter.on("keypress",
function (event) {
var pressedKey = event.keyCode || event.which;
var enterKey = 13;
if (pressedKey === enterKey) {
self.applyFilter();
}
}
);
this.$addTag.on("click", function () {
self.addTagsAsync()
.then(function () {
alert("Tags added");
});
});
this.$tagName.on("keypress",
function (event) {
var pressedKey = event.keyCode || event.which;
var enterKey = 13;
if (pressedKey === enterKey) {
self.addTagsAsync()
.then(function () {
alert("Tags added")
});
}
}
);
this.$clearFilter.on("click", function () {
self.$customFilter.val("");
self.applyFilter();
});
}
/**
* Adds any actions to the page which require the files and directories to already be loaded
*/
MediaIndex.prototype.addMediaDependentActions = function () {
var self = this;
var numberOfFiles = $("[data-files]").find("li").length;
var numberOfDirectories = $("[data-directories]").find("li").length;
if (numberOfFiles === 0 && numberOfDirectories === 0) {
this.$taggingContainer.hide();
return;
}
this.$taggingContainer.show();
var $mediaSelection = $("[data-media-selection]");
var $selectAll = $("<button>")
.addClass("btn btn-primary")
.text("Select All")
.on("click", function () {
self.$selectableForTagging.prop("checked", true);
});
var $selectNone = $("<button>")
.addClass("btn btn-default")
.text("Select None")
.on("click", function () {
self.$selectableForTagging.prop("checked", false);
});
var $moveFiles = $("<button>")
.addClass("btn btn-default")
.text("Move selected")
.on("click", function () {
self.moveSelectedFilesAsync();
self.moveSelectedDirectoriesAsync();
});
$mediaSelection
.html("")
.append($selectAll)
.append($selectNone)
.append($moveFiles);
}
MediaIndex.prototype.addTagsAsync = function () {
var deferred = $.Deferred();
var self = this;
var addTagsToAll = $.when(
this.addTagsToFilesAsync(),
this.addTagsToDirectoriesAsync()
);
addTagsToAll
.then(function () {
self.$tagName.val("");
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.moveSelectedDirectoriesAsync = function () {
var self = this;
var deferred = $.Deferred();
var $selectedCheckboxes = this.$selectableForTagging.filter("[data-tag-type='directory']:checked");
if ($selectedCheckboxes.length === 0) {
deferred.reject();
return deferred.promise();
}
var newDirectoryPath = prompt("New Directory Path: ", this.directoryPath);
if (newDirectoryPath === "" || newDirectoryPath === null || typeof (newDirectoryPath) === "undefined") {
deferred.reject();
return deferred.promise();
}
var directoryPaths = [];
$selectedCheckboxes.each(function (_, selectedCheckbox) {
var $selectedCheckbox = $(selectedCheckbox);
var directoryPath = $selectedCheckbox.attr("data-path");
directoryPaths.push(directoryPath);
});
this.mediaRepository.moveSubDirectories(directoryPaths, newDirectoryPath, this.mediaType)
.then(function () {
self.$directoryList.html("");
self.$fileList.html("");
// We've just moved some files around. Recalculate which files we need to show
self.initialiseAsync()
.then(function () {
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.moveSelectedFilesAsync = function () {
var self = this;
var deferred = $.Deferred();
var $selectedCheckboxes = this.$selectableForTagging.filter("[data-tag-type='file']:checked");
if ($selectedCheckboxes.length === 0) {
deferred.reject();
return deferred.promise();
}
var newDirectoryPath = prompt("New Directory Path: ", this.directoryPath);
if (newDirectoryPath === "") {
deferred.reject();
return deferred.promise();
}
var filePaths = [];
$selectedCheckboxes.each(function (_, selectedCheckbox) {
var $selectedCheckbox = $(selectedCheckbox);
var filePath = $selectedCheckbox.attr("data-path");
filePaths.push(filePath);
});
this.mediaRepository.moveSubFiles(filePaths, newDirectoryPath, this.mediaType)
.then(function () {
self.$directoryList.html("");
self.$fileList.html("");
// We've just moved some files around. Recalculate which files we need to show
self.initialiseAsync()
.then(function () {
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.addTagsToDirectoriesAsync = function () {
var self = this;
var tagNames = this.$tagName.val();
var $selectedCheckboxes = this.$selectableForTagging.filter("[data-tag-type='directory']:checked");
var deferred = $.Deferred();
if (tagNames === "" || $selectedCheckboxes.length === 0) {
deferred.resolve();
return deferred.promise();
}
var directoryPaths = [];
$selectedCheckboxes.each(function (_, selectedCheckbox) {
var $selectedCheckbox = $(selectedCheckbox);
var filePath = $selectedCheckbox.attr("data-path");
directoryPaths.push(filePath);
});
var tags = tagNames.split(",");
this.tagRepository.addTagsToDirectories(directoryPaths, tags, this.mediaType)
.then(function () {
tags.forEach(function (tagName) {
self.addTagToList(tagName);
});
self.$tagName.val("");
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.addTagsToFilesAsync = function () {
var self = this;
var tagNames = this.$tagName.val();
var $selectedCheckboxes = this.$selectableForTagging.filter("[data-tag-type='file']:checked");
if (tagNames === "" || $selectedCheckboxes.length === 0) {
var deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
}
var filePaths = [];
$selectedCheckboxes.each(function (_, selectedCheckbox) {
var $selectedCheckbox = $(selectedCheckbox);
var filePath = $selectedCheckbox.attr("data-path");
filePaths.push(filePath);
});
var deferred = $.Deferred();
var tags = tagNames.split(",");
this.tagRepository.addTagsToFiles(filePaths, tags, this.mediaType)
.then(function () {
tags.forEach(function (tagName) {
self.addTagToList(tagName);
});
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.renderTagListAsync = function () {
var deferred = $.Deferred();
var self = this;
this.tagRepository.getTagsAsync(this.directoryPath, this.mediaType, this.filter)
.then(function (tag) {
tag.forEach(function (tag) {
self.addTagToList(tag.TagName);
});
deferred.resolve();
})
.fail(function () {
deferred.reject();
});
return deferred.promise();
}
MediaIndex.prototype.addTagToList = function (tagName) {
var self = this;
var regex = new RegExp("'");
var encodedTagName = tagName.replace(regex, "%23");
var $tagLink = $("[data-tag='" + encodedTagName + "']");
if ($tagLink.length !== 0) {
return;
}
$tagLink = $("<li>").attr("data-tag", encodedTagName).addClass("tagList_item").text(tagName);
$tagLink.on("click", function () {
var filterValue = self.$customFilter.val();
if (filterValue !== "") {
filterValue = (filterValue + "," + $tagLink.text());
}
else {
filterValue = $tagLink.text();
}
self.$customFilter.val(filterValue);
self.applyFilter();
});
this.$tagList.append($tagLink);
}
MediaIndex.prototype.applyFilter = function () {
var filterString = this.$customFilter.val();
window.location.search = "?filter=" + filterString + "&page=1&path=" + this.directoryPath;
}<file_sep>/ContentExplorer/Models/TagLink.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Data.Sqlite;
using NReco.VideoConverter;
namespace ContentExplorer.Models
{
public class TagLink
{
public TagLink()
{
}
public TagLink(IDictionary<string, object> rowValues) : this()
{
TagLinkId = Convert.ToInt32(rowValues["TagLinkId"]);
TagId = Convert.ToInt32(rowValues["TagId"]);
FilePath = Convert.ToString(rowValues["FilePath"]);
}
public int TagLinkId { get; set; }
public int TagId { get; set; }
public string FilePath { get; set; }
private Tag Tag { get; set; }
public Tag GetTag()
{
if (Tag != null)
{
return Tag;
}
Tag = Tag.GetById(TagId);
return Tag;
}
public static bool UpdateDirectoryPath(string oldDirectoryPath, string newDirectoryPath)
{
// The caller shouldn't have to care about which slash or case to use
oldDirectoryPath = oldDirectoryPath.Replace("/", "\\").ToLowerInvariant();
newDirectoryPath = newDirectoryPath.Replace("/", "\\").ToLowerInvariant();
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
oldDirectoryPath = oldDirectoryPath.TrimEnd("\\".ToCharArray());
newDirectoryPath = newDirectoryPath.TrimEnd("\\".ToCharArray());
// Replaces any instances of the old directory path it finds with the new one. This may change rows unexpectedly. E.g. pictures/test/pictures/test/2.jpg
// Todo - Find a better way to do this
string query = @"UPDATE TagLinks
SET FilePath = REPLACE(FilePath, @OldDirectoryPath, @NewDirectoryPath)
WHERE FilePath LIKE @OldDirectoryPathLike
AND FilePath NOT LIKE @OldDirectoryPathRecursionLike";
ICollection<SqliteParameter> dbParameters = new List<SqliteParameter>
{
SqliteWrapper.GenerateParameter("@NewDirectoryPath", $"{newDirectoryPath}\\"),
SqliteWrapper.GenerateParameter("@OldDirectoryPath", $"{oldDirectoryPath}\\"),
SqliteWrapper.GenerateParameter("@OldDirectoryPathLike", $"{oldDirectoryPath}\\%"),
SqliteWrapper.GenerateParameter("@OldDirectoryPathRecursionLike", $"{oldDirectoryPath}\\%\\%")
};
bool isSuccess;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
isSuccess = dbContext.ExecuteNonQuery(query, dbParameters);
}
return isSuccess;
}
public static bool UpdateFilePath(string oldFilePath, string newFilePath)
{
// The caller shouldn't have to care about which slash or case to use
oldFilePath = oldFilePath.Replace("/", "\\").ToLowerInvariant();
newFilePath = newFilePath.Replace("/", "\\").ToLowerInvariant();
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
oldFilePath = oldFilePath.TrimEnd("\\".ToCharArray());
newFilePath = newFilePath.TrimEnd("\\".ToCharArray());
string query = @"UPDATE TagLinks SET FilePath = @NewFilePath WHERE FilePath = @OldFilePath";
ICollection<SqliteParameter> dbParameters = new List<SqliteParameter>
{
SqliteWrapper.GenerateParameter("@NewFilePath", newFilePath),
SqliteWrapper.GenerateParameter("@OldFilePath", oldFilePath)
};
bool isSuccess;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
isSuccess = dbContext.ExecuteNonQuery(query, dbParameters);
}
return isSuccess;
}
public static ICollection<TagLink> GetByFileName(string filePath)
{
string cacheKey = $"[TagLinks][ByFile]{filePath}";
if (HttpContext.Current.Cache[cacheKey] is ICollection<TagLink> cachedTags)
{
return cachedTags;
}
// The caller shouldn't have to care about which slash or case to use
filePath = filePath.Replace("/", "\\").ToLowerInvariant();
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
filePath = filePath.TrimEnd("\\".ToCharArray());
string query = @"SELECT Tags.TagId, Tags.TagName, TagLinks.FilePath AS [FilePath], TagLinks.TagLinkId
FROM Tags
INNER JOIN TagLinks ON Tags.TagId = TagLinks.TagId
WHERE TagLinks.FilePath = @FullName";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query, SqliteWrapper.GenerateParameter("@FullName", filePath));
}
ICollection<TagLink> tagLinks = dataRows
.Select(dataRow =>
new TagLink(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tagLinks, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
return tagLinks;
}
public static ICollection<TagLink> GetAll()
{
string cacheKey = "[TagLinks][All]";
if (HttpContext.Current.Cache[cacheKey] is ICollection<TagLink> cachedTags)
{
return cachedTags;
}
string query = @"SELECT TagLinks.FilePath, TagLinks.TagLinkId, TagLinks.TagId
FROM TagLinks";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query);
}
ICollection<TagLink> tagLinks = dataRows
.Select(dataRow =>
new TagLink(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tagLinks, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
return tagLinks;
}
public static ICollection<TagLink> GetByDirectory(string directoryPath)
{
string cacheKey = $"[TagLinks][ByDirectory]{directoryPath}";
if (HttpContext.Current.Cache[cacheKey] is ICollection<TagLink> cachedTags)
{
return cachedTags;
}
// The caller shouldn't have to care about which slash or case to use
directoryPath = directoryPath.Replace("/", "\\").ToLowerInvariant();
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
directoryPath = directoryPath.TrimEnd("\\".ToCharArray());
string query =
@"SELECT Tags.TagId, Tags.TagName, TagLinks.FilePath AS [FilePath], TagLinks.TagLinkId
FROM Tags
INNER JOIN TagLinks ON Tags.TagId = TagLinks.TagId
WHERE TagLinks.FilePath LIKE @FilePath";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query,
SqliteWrapper.GenerateParameter("@FilePath", $"{directoryPath}\\%"));
}
ICollection<TagLink> tagLinks = dataRows.Select(dataRow =>
new TagLink(dataRow)
{
Tag = new Tag(dataRow)
}
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tagLinks, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
return tagLinks;
}
public static ICollection<TagLink> GetByDirectory(string directoryPath, string[] filters, int skip, int take,
bool isRecursive = false)
{
filters = filters.Select(filter => filter.ToLowerInvariant()).ToArray();
// The caller shouldn't have to care about which slash or case to use
directoryPath = directoryPath.Replace("/", "\\").ToLowerInvariant();
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
directoryPath = directoryPath.TrimEnd("\\".ToCharArray());
string cacheKey =
$"[TagLinks][ByDirectoryAndFilters]{directoryPath}|{string.Join(",", filters)}|{skip}|{take}|{isRecursive}|";
if (HttpContext.Current.Cache[cacheKey] is ICollection<TagLink> cachedTags)
{
return cachedTags;
}
string query = @"WITH FilePathTags AS (
SELECT
(',' || GROUP_CONCAT(Tags.TagName) || ',') AS [CombinedTags],
TagLinks.FilePath
FROM TagLinks
INNER JOIN Tags ON Tags.TagId = TagLinks.TagId
GROUP BY TagLinks.FilePath
)
SELECT
TagLinks.FilePath,
TagLinks.TagLinkId,
Tags.TagId,
Tags.TagName
FROM TagLinks
INNER JOIN Tags ON Tags.TagId = TagLinks.TagId
INNER JOIN FilePathTags ON FilePathTags.FilePath = TagLinks.FilePath
WHERE TagLinks.FilePath LIKE @FilePath";
List<SqliteParameter> dbParameters = new List<SqliteParameter>();
for (int filterIndex = 0; filterIndex < filters.Length; filterIndex++)
{
string stringParameter = $"@{filterIndex}";
query += $" AND FilePathTags.CombinedTags LIKE {stringParameter}";
dbParameters.Add(SqliteWrapper.GenerateParameter(stringParameter, $"%,{filters[filterIndex]},%"));
}
// Add the file path parameter to the end of the array
dbParameters.Add(SqliteWrapper.GenerateParameter("@FilePath", $"{directoryPath}\\%"));
if (isRecursive != true)
{
query += " AND TagLinks.FilePath NOT LIKE @ExcludedFilePath";
dbParameters.Add(SqliteWrapper.GenerateParameter("@ExcludedFilePath", $"{directoryPath}\\%\\%"));
}
query += " GROUP BY TagLinks.FilePath LIMIT @Take OFFSET @Skip";
dbParameters.Add(SqliteWrapper.GenerateParameter("@Skip", skip));
dbParameters.Add(SqliteWrapper.GenerateParameter("@Take", take));
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query, dbParameters);
}
ICollection<TagLink> tagLinks = dataRows
.Select(dataRow =>
new TagLink(dataRow)
{
Tag = new Tag(dataRow)
}
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tagLinks, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
return tagLinks;
}
public static int GetFileCount(string directoryPath, string[] filters, int skip, int take,
bool isRecursive = false)
{
filters = filters.Select(filter => filter.ToLowerInvariant()).ToArray();
// The caller shouldn't have to care about which slash or case to use
directoryPath = directoryPath.Replace("/", "\\").ToLowerInvariant();
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
directoryPath = directoryPath.TrimEnd("\\".ToCharArray());
string cacheKey =
$"[TagLinks][CountByDirectoryAndFilters]{directoryPath}|{string.Join(",", filters)}|{skip}|{take}|{isRecursive}|";
if (HttpContext.Current.Cache[cacheKey] is int cachedCount)
{
return cachedCount;
}
string query = @"WITH FilePathTags AS (
SELECT
(',' || GROUP_CONCAT(Tags.TagName) || ',') AS [CombinedTags],
TagLinks.FilePath
FROM TagLinks
INNER JOIN Tags ON Tags.TagId = TagLinks.TagId
GROUP BY TagLinks.FilePath
)
SELECT COUNT(DISTINCT TagLinks.FilePath)
FROM TagLinks
INNER JOIN Tags ON Tags.TagId = TagLinks.TagId
INNER JOIN FilePathTags ON FilePathTags.FilePath = TagLinks.FilePath
WHERE TagLinks.FilePath LIKE @FilePath";
List<SqliteParameter> dbParameters = new List<SqliteParameter>();
for (int filterIndex = 0; filterIndex < filters.Length; filterIndex++)
{
string stringParameter = $"@{filterIndex}";
query += $" AND FilePathTags.CombinedTags LIKE {stringParameter}";
dbParameters.Add(SqliteWrapper.GenerateParameter(stringParameter, $"%,{filters[filterIndex]},%"));
}
// Add the file path parameter to the end of the array
dbParameters.Add(SqliteWrapper.GenerateParameter("@FilePath", $"{directoryPath}\\%"));
if (isRecursive != true)
{
query += " AND TagLinks.FilePath NOT LIKE @ExcludedFilePath";
dbParameters.Add(SqliteWrapper.GenerateParameter("@ExcludedFilePath", $"{directoryPath}\\%\\%"));
}
int numberOfRecords;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
numberOfRecords = Convert.ToInt32(dbContext.GetScalar(query, dbParameters));
}
HttpContext.Current.Cache.Insert(cacheKey, numberOfRecords, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
return numberOfRecords;
}
public static ICollection<TagLink> GetByTagName(string tagName)
{
tagName = tagName.ToLowerInvariant();
string cacheKey = $"[TagLinks][ByTagName]{tagName}";
if (HttpContext.Current.Cache[cacheKey] is ICollection<TagLink> cachedTags)
{
return cachedTags;
}
string query =
@"SELECT TagLinks.TagLinkId, TagLinks.FilePath AS [FilePath], TagLinks.TagId
FROM TagLinks
INNER JOIN Tags ON TagLinks.TagId = Tags.TagId
WHERE Tags.TagName = @TagName";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query, SqliteWrapper.GenerateParameter("@TagName", tagName));
}
ICollection<TagLink> tagLinks = dataRows.Select(dataRow =>
new TagLink(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tagLinks, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
return tagLinks;
}
public static bool InitialiseTable()
{
string query = @"CREATE TABLE IF NOT EXISTS TagLinks (
TagLinkId INTEGER PRIMARY KEY,
TagId INT,
FilePath TEXT NOT NULL,
FOREIGN KEY(TagId) REFERENCES Tags(TagId)
)";
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
try
{
dbContext.ExecuteNonQuery(query);
return true;
}
catch (SqliteException)
{
return false;
}
}
}
/// <summary>
/// Creates multiple tag links at once. For performance reasons, the ID is not set.
/// </summary>
/// <param name="tagLinks"></param>
/// <returns></returns>
public static bool CreateRange(IEnumerable<TagLink> tagLinks)
{
ICollection<SqliteParameter> parameters = new List<SqliteParameter>();
string query = "INSERT INTO TagLinks (TagId, FilePath) VALUES";
int tagLinkIndex = 1;
bool isSuccess = true;
foreach (TagLink tagLink in tagLinks)
{
// We may need to search for paths later and we don't want to be dealing with differences in slashes
tagLink.FilePath = tagLink.FilePath.ToLower().Replace("/", "\\");
parameters.Add(SqliteWrapper.GenerateParameter($@"TagId{tagLinkIndex}", tagLink.TagId));
parameters.Add(SqliteWrapper.GenerateParameter($"FilePath{tagLinkIndex}", tagLink.FilePath));
query += $" (@TagId{tagLinkIndex}, @FilePath{tagLinkIndex}),";
// Quick fix for "too many SQL variables" as I'm tired. // Todo - Refactor this
if (tagLinkIndex % 499 == 0)
{
query = query.TrimEnd(',');
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
isSuccess &= dbContext.ExecuteNonQuery(query, parameters);
}
parameters = new List<SqliteParameter>();
query = "INSERT INTO TagLinks (TagId, FilePath) VALUES";
}
tagLinkIndex++;
}
if (query == "INSERT INTO TagLinks (TagId, FilePath) VALUES")
{
return isSuccess;
}
query = query.TrimEnd(',');
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
isSuccess &= dbContext.ExecuteNonQuery(query, parameters);
}
ClearCaches();
return isSuccess;
}
private static void ClearCaches()
{
foreach (DictionaryEntry cacheEntry in HttpContext.Current.Cache)
{
string cacheKey = cacheEntry.Key.ToString();
if (cacheKey.StartsWith("[TagLinks]"))
{
HttpContext.Current.Cache.Remove(cacheKey);
}
}
}
public bool Create()
{
// We may need to search for paths later and we don't want to be dealing with differences in slashes
FilePath = FilePath.ToLowerInvariant().Replace("/", "\\");
const string query =
@"INSERT INTO TagLinks (TagId, FilePath) VALUES (@TagId, @FilePath); SELECT last_insert_rowid()";
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
TagLinkId = Convert.ToInt32(dbContext.GetScalar(query, GenerateParameters()));
}
bool isSuccess = TagLinkId != 0;
ClearCaches();
return isSuccess;
}
public bool Delete()
{
const string query = @"DELETE FROM TagLinks WHERE TagLinkId = @TagLinkId";
bool isSuccess;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
isSuccess = dbContext.ExecuteNonQuery(query, GenerateParameters());
}
ClearCaches();
return isSuccess;
}
public bool Update()
{
// We may need to search for paths later and we don't want to be dealing with differences in slashes
FilePath = FilePath.ToLowerInvariant().Replace("/", "\\");
const string query =
@"UPDATE TagLinks SET TagId = @TagId, FilePath = @FilePath WHERE TagLinkId = @TagLinkId";
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dbContext.GetScalar(query, GenerateParameters());
}
bool isSuccess = TagLinkId != 0;
ClearCaches();
return isSuccess;
}
private ICollection<SqliteParameter> GenerateParameters()
{
return new List<SqliteParameter>
{
SqliteWrapper.GenerateParameter("@TagLinkId", TagLinkId),
SqliteWrapper.GenerateParameter("@TagId", TagId),
SqliteWrapper.GenerateParameter("@FilePath", FilePath)
};
}
}
}<file_sep>/ContentExplorer/README.md
**Before Running on IIS**
Rename Example.Web.Config to Web.Config and change the AppSettings accordingly<file_sep>/ContentExplorer/Services/VideoThumbnailService.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NReco.VideoConverter;
namespace ContentExplorer.Services
{
public class VideoThumbnailService : IThumbnailService
{
public void CreateThumbnail(FileInfo fileInfo)
{
FileInfo fileThumbnail = GetFileThumbnail(fileInfo);
if (fileThumbnail.Exists)
{
return;
}
CreateThumbnail(fileInfo, 240);
FileInfo thumbnailInfo = GetFileThumbnail(fileInfo);
if (thumbnailInfo.Exists == false || thumbnailInfo.Length == 0)
{
CreateThumbnail(fileInfo, 120);
}
thumbnailInfo = GetFileThumbnail(fileInfo);
if (thumbnailInfo.Exists == false || thumbnailInfo.Length == 0)
{
CreateThumbnail(fileInfo, 60);
}
thumbnailInfo = GetFileThumbnail(fileInfo);
if (thumbnailInfo.Exists == false || thumbnailInfo.Length == 0)
{
CreateThumbnail(fileInfo, 1);
}
// If the video is less than 1 second long, it should really be a gif
thumbnailInfo = GetFileThumbnail(fileInfo);
if (thumbnailInfo.Exists == false || thumbnailInfo.Length == 0)
{
fileInfo.MoveTo(fileInfo.FullName + ".shouldbegif");
}
}
public void DeleteThumbnailIfExists(FileInfo fileInfo)
{
FileInfo thumbnail = GetFileThumbnail(fileInfo);
if (thumbnail.Exists)
{
thumbnail.Delete();
}
}
public FileInfo GetDirectoryThumbnail(DirectoryInfo directory)
{
FileTypeService fileTypeService = new FileTypeService();
FileInfo previewImage = directory
.EnumerateFiles()
.FirstOrDefault(file => fileTypeService.IsFileVideo(file.Name));
if (previewImage != null)
{
return previewImage;
}
IEnumerable<DirectoryInfo> subDirectories =
directory.EnumerateDirectories("*", SearchOption.AllDirectories);
FileInfo firstPreview = subDirectories
.Select(GetDirectoryThumbnail)
.FirstOrDefault(thumbnail => thumbnail != null);
return firstPreview;
}
public FileInfo GetFileThumbnail(FileInfo fileInfo)
{
string thumbnailPath = $"{fileInfo.FullName}.jpg";
FileInfo directoryThumbnail = new FileInfo(thumbnailPath);
return directoryThumbnail;
}
public bool IsThumbnail(FileInfo fileInfo)
{
bool isThumbnail = fileInfo.Name.EndsWith(".jpg");
return isThumbnail;
}
private void CreateThumbnail(FileInfo videoFileInfo, int frametime)
{
FileInfo thumbnailLocation = GetFileThumbnail(videoFileInfo);
using (Stream jpgStream = new FileStream(thumbnailLocation.FullName, FileMode.Create))
{
FFMpegConverter ffMpeg = new FFMpegConverter();
try
{
ffMpeg.GetVideoThumbnail(videoFileInfo.FullName, jpgStream, frametime);
}
catch (FFMpegException exception)
{
// File can not be properly read so no thumbnail for us
if (exception.ErrorCode == 69)
{
videoFileInfo.MoveTo(videoFileInfo.FullName + ".broken");
}
}
}
}
}
}<file_sep>/ContentExplorer/Services/IFileSystemFilteringService.cs
using ContentExplorer.Models;
using System.Collections.Generic;
using System.IO;
namespace ContentExplorer.Services
{
public interface IFileSystemFilteringService
{
bool TagLinkMatchesFilter(IEnumerable<TagLink> tagLinksforFile, string[] filters);
bool TagsMatchFilter(IEnumerable<Tag> tags, IEnumerable<string> filters);
bool FileMatchesFilter(FileInfo fileInfo, string[] filters);
bool DirectoryMatchesFilter(DirectoryInfo directoryInfo, string[] filters, string mediaType);
}
}
<file_sep>/ContentExplorer/Models/ViewModels/ImageViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ContentExplorer.Models.ViewModels
{
public class ImageViewModel
{
public string ImagePath { get; set; }
public string ImageName { get; set; }
}
}<file_sep>/ContentExplorer/App_Start/BundleConfig.cs
using System.Web.Optimization;
namespace ContentExplorer
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
RegisterStyles(bundles);
RegisterScripts(bundles);
}
private static void RegisterStyles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Core/Styles/site.min.css"));
}
private static void RegisterScripts(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/scripts/common").Include(
"~/Core/Scripts/Common/jquery-{version}.js",
"~/Core/Scripts/Common/modernizr-*",
"~/Core/Scripts/Common/bootstrap.js",
"~/Core/Scripts/Common/HttpRequester.js",
"~/Core/Scripts/Common/Repositories/MediaRepository.js",
"~/Core/Scripts/Common/Repositories/TagRepository.js",
"~/Core/Scripts/Common/Factories/MediaUiFactory.js"
));
bundles.Add(new ScriptBundle("~/bundles/scripts/image/view")
.Include(
"~/Core/Scripts/View/MediaView.js",
"~/Core/Scripts/View/ImageView.js"
)
);
bundles.Add(new ScriptBundle("~/bundles/scripts/video/view")
.Include(
"~/Core/Scripts/View/MediaView.js",
"~/Core/Scripts/View/VideoView.js"
)
);
bundles.Add(new ScriptBundle("~/bundles/scripts/image/index")
.Include(
"~/Core/Scripts/Index/MediaIndex.js",
"~/Core/Scripts/Index/ImageIndex.js"
)
);
bundles.Add(new ScriptBundle("~/bundles/scripts/video/index")
.Include(
"~/Core/Scripts/Index/MediaIndex.js",
"~/Core/Scripts/Index/VideoIndex.js"
)
);
}
}
}
<file_sep>/ContentExplorer/Services/VideoConversionService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NReco.VideoConverter;
namespace ContentExplorer.Services
{
public class VideoConversionService
{
public void ConvertUnplayableVideos(DirectoryInfo directory)
{
IEnumerable<DirectoryInfo> subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
ConvertUnplayableVideos(subDirectory);
}
IEnumerable<FileInfo> unplayableVideos = directory
.EnumerateFiles()
.Where(potentialVideo =>
UnplayableVideoTypes.Any(unplayableVideoType =>
potentialVideo.Extension.Equals(unplayableVideoType, StringComparison.OrdinalIgnoreCase)
)
);
FFMpegConverter ffMpegConverter = new FFMpegConverter();
foreach (FileInfo unplayableVideo in unplayableVideos)
{
int indexOfExtension = unplayableVideo.Name.LastIndexOf(".");
string videoType = unplayableVideo.Name.Substring(indexOfExtension + 1);
ffMpegConverter.ConvertMedia(unplayableVideo.FullName, $"{unplayableVideo.FullName}.mp4", "mp4");
unplayableVideo.MoveTo(Path.Combine(unplayableVideo.Directory.FullName, unplayableVideo.Name + ".old"));
}
}
private static readonly string[] UnplayableVideoTypes = new[]
{
".avi",
".mkv"
};
}
}<file_sep>/ContentExplorer/Models/Tag.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Data.Sqlite;
namespace ContentExplorer.Models
{
public class Tag
{
private static readonly List<string> CacheKeys = new List<string>();
public Tag()
{
}
public Tag(IDictionary<string, object> rowValues) : this()
{
TagId = Convert.ToInt32(rowValues["TagId"]);
TagName = Convert.ToString(rowValues["TagName"]);
}
public string TagName { get; set; }
public int TagId { get; set; }
private static void ClearCaches()
{
foreach (string cacheKey in CacheKeys)
{
HttpContext.Current.Cache.Remove(cacheKey);
}
}
public static ICollection<Tag> GetAll()
{
string cacheKey = "[Tags]";
if (HttpContext.Current.Cache[cacheKey] is ICollection<Tag> cachedTags)
{
return cachedTags;
}
string query = @"SELECT Tags.TagId, Tags.TagName
FROM Tags";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dbContext.GetDataRows(query);
dataRows = dbContext.GetDataRows(query);
}
ICollection<Tag> tags = dataRows.Select(dataRow =>
new Tag(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tags, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
CacheKeys.Add(cacheKey);
return tags;
}
public static ICollection<Tag> GetByFile(string filePath)
{
string cacheKey = $"[TagsByFile]{filePath}";
if (HttpContext.Current.Cache[cacheKey] is ICollection<Tag> cachedTags)
{
return cachedTags;
}
// The caller shouldn't have to care about which slash to use
filePath = filePath.Replace("/", "\\");
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
filePath = filePath.ToLowerInvariant().TrimEnd("/\\".ToCharArray());
string query = @"SELECT Tags.TagId, Tags.TagName
FROM Tags
INNER JOIN TagLinks ON Tags.TagId = TagLinks.TagId
WHERE TagLinks.FilePath = @FilePath
GROUP BY Tags.TagId, Tags.TagName";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query, SqliteWrapper.GenerateParameter("@FilePath", filePath));
}
ICollection<Tag> tags = dataRows.Select(dataRow =>
new Tag(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tags, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
CacheKeys.Add(cacheKey);
return tags;
}
public static ICollection<Tag> GetByDirectory(string directoryPath, string[] filters, bool isRecursive = false)
{
string cacheKey = $"[TagsByDirectoryAndFilters]{directoryPath}{string.Join(",", filters)}";
if (HttpContext.Current.Cache[cacheKey] is ICollection<Tag> cachedTags)
{
return cachedTags;
}
string[] stringParameters = new string[filters.Length];
SqliteParameter[] dbParameters = new SqliteParameter[filters.Length + 2];
for (int filterIndex = 0; filterIndex < filters.Length; filterIndex++)
{
string stringParameter = $"@{filterIndex}";
stringParameters[filterIndex] = stringParameter;
dbParameters[filterIndex] = SqliteWrapper.GenerateParameter(stringParameter, filters[filterIndex]);
}
// Add the file path parameter to the end of the array
dbParameters[filters.Length] = SqliteWrapper.GenerateParameter("@FilePath", $"{directoryPath}\\%");
string query = $@"SELECT Tags.TagId, Tags.TagName, TagLinks.FilePath, TagLinks.TagLinkId
FROM Tags
INNER JOIN TagLinks ON Tags.TagId = TagLinks.TagId
WHERE TagLinks.FilePath LIKE @FilePath
AND Tags.TagName IN ({string.Join(",", stringParameters)})
GROUP BY Tags.TagId, Tags.TagName";
if (isRecursive != true)
{
query += " AND FilePath NOT LIKE @ExcludedFilePath";
dbParameters[filters.Length + 1] = SqliteWrapper.GenerateParameter("@ExcludedFilePath", $"{directoryPath}\\%\\%");
}
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query, dbParameters);
}
ICollection<Tag> tags = dataRows
.Select(dataRow =>
new Tag(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tags, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
CacheKeys.Add(cacheKey);
return tags;
}
public static Tag GetById(int tagId)
{
string cacheKey = $"[TagsById]{tagId}";
if (HttpContext.Current.Cache[cacheKey] is Tag cachedTags)
{
return cachedTags;
}
string query = @"SELECT TagId, TagName
FROM Tags
WHERE TagId = @TagId";
IDictionary<string, object> dataRow;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRow = dbContext.GetDataRow(query, SqliteWrapper.GenerateParameter("@TagId", tagId));
}
Tag tag = dataRow != null ? new Tag(dataRow) : null;
if (tag != null)
{
HttpContext.Current.Cache.Insert(cacheKey, tag, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
CacheKeys.Add(cacheKey);
}
return tag;
}
public static ICollection<Tag> GetByFile(string filePath, string[] filters)
{
string cacheKey = $"[TagsByFile]{filePath}";
if (HttpContext.Current.Cache[cacheKey] is ICollection<Tag> cachedTags)
{
return cachedTags;
}
// The caller shouldn't have to care about which slash to use
filePath = filePath.Replace("/", "\\");
// We need to distinguish between files and directories with the same name but the caller shouldn't have to worry about it
filePath = filePath.ToLowerInvariant().TrimEnd("/\\".ToCharArray());
string query = @"SELECT Tags.TagId, Tags.TagName
FROM Tags
INNER JOIN TagLinks ON Tags.TagId = TagLinks.TagId
WHERE TagLinks.FilePath = @FilePath
GROUP BY Tags.TagId, Tags.TagName";
ICollection<IDictionary<string, object>> dataRows;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRows = dbContext.GetDataRows(query, SqliteWrapper.GenerateParameter("@FilePath", filePath));
}
ICollection<Tag> tags = dataRows.Select(dataRow =>
new Tag(dataRow)
)
.ToList();
HttpContext.Current.Cache.Insert(cacheKey, tags, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
CacheKeys.Add(cacheKey);
return tags;
}
public static Tag GetByTagName(string tagName)
{
string cacheKey = $"[TagByTagName]{tagName}";
if (HttpContext.Current.Cache[cacheKey] is Tag cachedTags)
{
return cachedTags;
}
tagName = tagName.ToLowerInvariant();
string query = @"SELECT TagId, TagName
FROM Tags
WHERE TagName = @TagName";
IDictionary<string, object> dataRow;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
dataRow = dbContext.GetDataRow(query, SqliteWrapper.GenerateParameter("@TagName", tagName));
}
Tag tag = dataRow != null ? new Tag(dataRow) : null;
if (tag != null)
{
HttpContext.Current.Cache.Insert(cacheKey, tag, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
CacheKeys.Add(cacheKey);
}
return tag;
}
public static bool InitialiseTable()
{
string query = @"CREATE TABLE IF NOT EXISTS Tags (
TagId INTEGER PRIMARY KEY,
TagName TEXT NOT NULL
)";
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
try
{
dbContext.ExecuteNonQuery(query);
return true;
}
catch (SqliteException)
{
return false;
}
}
}
public bool Create()
{
const string query = @"INSERT INTO Tags (TagName) VALUES (@TagName); SELECT last_insert_rowid()";
TagName = TagName.ToLowerInvariant();
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
TagId = Convert.ToInt32(dbContext.GetScalar(query, GenerateParameters()));
}
ClearCaches();
bool isSuccess = TagId != 0;
return isSuccess;
}
public bool Delete()
{
const string query = @"DELETE FROM Tags WHERE TagId = @TagId";
bool isSuccess;
using (SqliteWrapper dbContext = new SqliteWrapper("AppDb"))
{
isSuccess = dbContext.ExecuteNonQuery(query, GenerateParameters());
}
ClearCaches();
return isSuccess;
}
private ICollection<SqliteParameter> GenerateParameters()
{
return new List<SqliteParameter>
{
SqliteWrapper.GenerateParameter("@TagId", TagId),
SqliteWrapper.GenerateParameter("@TagName", TagName)
};
}
}
}<file_sep>/ContentExplorer/Controllers/TagController.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContentExplorer.Models;
using ContentExplorer.Services;
namespace ContentExplorer.Controllers
{
public class TagController : Controller
{
[HttpPost]
public JsonResult AddTagsToFiles(string[] filePaths, string[] tags, string mediaType)
{
// Filter inputs that would make no sense
filePaths = filePaths
.Where(filePath => filePath != "")
.Select(HttpUtility.UrlDecode)
.ToArray();
tags = tags.Where(tag => tag != "").Select(tag => tag.Trim()).ToArray();
string rootDirectory = GetRootDirectory(mediaType);
IEnumerable<string> diskLocations = filePaths
.Select(filePath => Path.Combine(rootDirectory, filePath))
.ToArray();
bool isSuccess = AddTags(diskLocations, tags);
return Json(isSuccess);
}
[HttpPost]
public JsonResult AddTagsToDirectories(string[] directoryPaths, string[] tags, string mediaType)
{
// Filter inputs that would make no sense
directoryPaths = directoryPaths
.Where(filePath => filePath != "")
.Select(HttpUtility.UrlDecode)
.ToArray();
tags = tags.Where(tag => tag != "").Select(tag => tag.Trim()).ToArray();
string cdnDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string rootDirectory = Path.Combine(cdnDiskLocation, GetRootDirectory(mediaType));
directoryPaths = directoryPaths.Select(directoryPath => Path.Combine(rootDirectory, directoryPath)).ToArray();
bool isSuccess = true;
foreach (string directoryPath in directoryPaths)
{
DirectoryInfo directory = new DirectoryInfo(directoryPath);
if (directory.Exists)
{
IEnumerable<string> fileNames = directory.EnumerateFiles("*.*", SearchOption.AllDirectories)
.Select(subFile => subFile.FullName.Substring(cdnDiskLocation.Length + 1));
isSuccess &= AddTags(fileNames, tags);
}
}
return Json(isSuccess);
}
[HttpGet]
public JsonResult GetFileTags(string fileName, string mediaType)
{
fileName = GetRootDirectory(mediaType) + "\\" + fileName;
IFileSystemFilteringService fileSystemFilteringService = new FileSystemFilteringService();
ICollection<Tag> tagLinksForFile = Tag.GetByFile(fileName)
.OrderBy(tag => tag.TagName)
.ToArray();
return Json(tagLinksForFile, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetDirectoryTags(string directoryName, string mediaType, string filter)
{
directoryName = GetRootDirectory(mediaType) + "\\" + directoryName;
string[] filters = filter.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
IFileSystemFilteringService fileSystemFilteringService = new FileSystemFilteringService();
ICollection<TagLink> tagLinks = TagLink.GetByDirectory(directoryName);
var tagLinksGroupedByFile = tagLinks.GroupBy(tagLink => tagLink.FilePath);
var filteredTagLinks = tagLinksGroupedByFile
.Where(tagsLinksForFile =>
fileSystemFilteringService.TagLinkMatchesFilter(tagsLinksForFile, filters)
).ToList();
IEnumerable<Tag> tagsForDirectory = filteredTagLinks
.SelectMany(tagLinksForFile =>
tagLinksForFile.Select(tagLinkForFile =>
tagLinkForFile.GetTag()
)
)
.GroupBy(tag => tag.TagName)
.Select(grouping => grouping.First())
.OrderBy(tag => tag.TagName)
.ToArray();
return Json(tagsForDirectory, JsonRequestBehavior.AllowGet);
}
private string GetRootDirectory(string mediaType)
{
if (mediaType.Equals("video", StringComparison.OrdinalIgnoreCase))
{
return ConfigurationManager.AppSettings["VideosPath"];
}
else if (mediaType.Equals("image", StringComparison.OrdinalIgnoreCase))
{
return ConfigurationManager.AppSettings["ImagesPath"];
}
else
{
throw new InvalidOperationException("Media type is unsupported.");
}
}
public JsonResult DeleteAllTags()
{
IEnumerable<Tag> tags = Tag.GetAll();
foreach (Tag tag in tags)
{
IEnumerable<TagLink> tagLinks = TagLink.GetByTagName(tag.TagName);
foreach (TagLink tagLink in tagLinks)
{
tagLink.Delete();
}
tag.Delete();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult DeleteUnusedTags()
{
IEnumerable<TagLink> allTagLinks = TagLink.GetAll();
string cdnDiskPath = ConfigurationManager.AppSettings["BaseDirectory"];
IEnumerable<TagLink> unusedTagLinks = allTagLinks
.Where(tagLink => new FileInfo($"{cdnDiskPath}\\{tagLink.FilePath}").Exists != true);
foreach (TagLink tagLink in unusedTagLinks)
{
tagLink.Delete();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
private bool AddTags(IEnumerable<string> filePaths, ICollection<string> tagNames)
{
IEnumerable<Tag> requestedTags = tagNames
.Select(GetOrCreateTag);
var filesMappedToTags = filePaths
.Select(filePath =>
new
{
FilePath = filePath,
TagsByFileName = Tag.GetByFile(filePath)
}
)
.ToList();
IEnumerable<TagLink> missingTagLinks = filesMappedToTags
.SelectMany(fileMappedToTags =>
requestedTags.Where(requestedTag =>
fileMappedToTags.TagsByFileName.All(existingTag =>
existingTag.TagId != requestedTag.TagId
)
)
.Select(missingTag => new TagLink
{
TagId = missingTag.TagId,
FilePath = fileMappedToTags.FilePath
})
)
.ToList();
bool isSuccess = TagLink.CreateRange(missingTagLinks);
return isSuccess;
}
private Tag GetOrCreateTag(string tagName)
{
Tag savedTag = Tag.GetByTagName(tagName);
if (savedTag != null)
{
return savedTag;
}
// If the tag hasn't been saved yet, save it
savedTag = new Tag
{
TagName = tagName
};
bool isSuccess = savedTag.Create();
return isSuccess ? savedTag : null;
}
}
}<file_sep>/ContentExplorer/Core/Scripts/Index/ImageIndex.js
function ImageIndex() {
MediaIndex.call(this, "image", "Image");
this.$actions = $("[data-actions='image']");
}
ImageIndex.prototype = Object.create(MediaIndex.prototype);
ImageIndex.prototype.addMediaDependentActions = function () {
MediaIndex.prototype.addMediaDependentActions.call(this);
var $rebuildThumbnailsButton = $("<a>")
.attr("href", "../" + this.controller + "/" + "RebuildThumbnails?path=" + this.directoryPath)
.attr("target", "_blank")
.append(
$("<div>").addClass("btn btn-default").text("Rebuild Thumbnails")
);
var $reformatNames = $("<a>")
.attr("href", "../" + this.controller + "/" + "ReformatNames?path=" + this.directoryPath)
.attr("target", "_blank")
.append(
$("<div>").addClass("btn btn-default").text("Reformat Names")
);
this.$actions
.append($rebuildThumbnailsButton)
.append($reformatNames);
}
$(function () {
var mediaIndex = new ImageIndex();
mediaIndex.initialiseAsync();
})<file_sep>/ContentExplorer/Models/ViewModels/MediaPreviewViewModel.cs
namespace ContentExplorer.Models.ViewModels
{
public class MediaPreviewViewModel
{
public string Name { get; set; }
public string Path { get; set; }
public string ContentUrl { get; set; }
public string ThumbnailUrl { get; set; }
public string TaggingUrl { get; set; }
}
}<file_sep>/ContentExplorer/Controllers/ImageController.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using ContentExplorer.Models;
using ContentExplorer.Services;
namespace ContentExplorer.Controllers
{
public class ImageController : Controller
{
[HttpGet]
public ActionResult Index(string path = "", int? page = 1, string filter = null)
{
if (page == null || page < 1)
{
page = 1;
}
if (path == null)
{
path = "";
}
else
{
// Remove any dangerous characters to prevent escaping the current context
path = path.Trim("/\\.".ToCharArray());
}
if (filter == null)
{
filter = "";
}
DirectoryInfo directoryInfo = GetCurrentDirectory(path);
if (directoryInfo.Exists == false)
{
return RedirectToAction("Index", new { page, filter });
}
ViewBag.FilesPerPage = 50;
ViewBag.Directory = directoryInfo;
ViewBag.Page = page;
ViewBag.Filter = filter;
return View();
}
[HttpGet]
public ActionResult ReformatNames(string path = "")
{
DirectoryInfo baseDirectory = GetCurrentDirectory(path);
IEnumerable<FileInfo> subFiles = baseDirectory.EnumerateFiles("*", SearchOption.AllDirectories);
NameFormatService nameFormatService = new NameFormatService();
string cdnDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
foreach (FileInfo subFile in subFiles)
{
FileInfo newFileName = nameFormatService.FormatFileName(subFile);
if (subFile.Name.Equals(newFileName.Name, StringComparison.OrdinalIgnoreCase) != true)
{
ICollection<TagLink> tagLinksForFile = TagLink.GetByFileName(subFile.FullName);
foreach (TagLink tagLink in tagLinksForFile)
{
tagLink.FilePath = newFileName.FullName.Substring(cdnDiskLocation.Length + 1);
tagLink.Update();
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult RebuildThumbnails(string path = "")
{
IThumbnailService imageThumbnailService = new ImageThumbnailService();
DirectoryInfo baseDirectory = GetCurrentDirectory(path);
IEnumerable<FileInfo> images = baseDirectory.EnumerateFiles("*", SearchOption.AllDirectories)
.Where(image => imageThumbnailService.IsThumbnail(image) != true);
foreach (FileInfo image in images)
{
imageThumbnailService.DeleteThumbnailIfExists(image);
imageThumbnailService.CreateThumbnail(image);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ViewResult View(string path, int page, string filter = "")
{
if (page < 1)
{
page = 1;
}
if (filter == null)
{
filter = "";
}
ViewBag.Path = path;
ViewBag.Id = page;
ViewBag.Filter = filter;
return View();
}
private DirectoryInfo GetCurrentDirectory(string relativePath)
{
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(ConfigurationManager.AppSettings["BaseDirectory"], ConfigurationManager.AppSettings["ImagesPath"], relativePath));
return directoryInfo;
}
}
}<file_sep>/ContentExplorer/Services/NameFormatService.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ContentExplorer.Services
{
public class NameFormatService
{
public FileInfo FormatFileName(FileInfo fileInfo)
{
string formattedFileName = HttpUtility.UrlDecode(fileInfo.Name);
formattedFileName = formattedFileName
.Replace("\\", " ")
.Replace("/", " ")
.Replace(":", " - ");
string[] wordsToRemoveFromNames = ConfigurationManager.AppSettings["WordsToRemoveFromNames"]?.Split('|');
if (wordsToRemoveFromNames != null)
{
foreach (string wordToRemoveFromNames in wordsToRemoveFromNames)
{
formattedFileName = formattedFileName.Replace($"{wordToRemoveFromNames} ", "");
}
}
// Max length
bool isTooLong = fileInfo.FullName.Length >= 250;
if (isTooLong)
{
formattedFileName = formattedFileName.Remove(50);
formattedFileName += fileInfo.Extension;
}
string formattedFullName = Path.Combine(fileInfo.Directory.FullName, formattedFileName);
if (fileInfo.Name != formattedFileName)
{
try
{
if (new FileInfo(formattedFullName).Exists)
{
formattedFileName = $"{formattedFileName}~{Guid.NewGuid()}";
formattedFullName = Path.Combine(fileInfo.Directory.FullName, formattedFileName + fileInfo.Extension);
}
}
catch (NotSupportedException)
{
throw new NotSupportedException($"The file path {formattedFullName} is not supported by FileInfo.Exists");
}
string oldPath = isTooLong != true ? fileInfo.FullName : $@"\\?\{fileInfo.FullName}";
try
{
File.Move(oldPath, formattedFullName);
}
catch (DirectoryNotFoundException)
{
throw new DirectoryNotFoundException($"Could not find either directory {oldPath} or directory {formattedFullName}");
}
}
FileInfo renamedFile = new FileInfo(formattedFullName);
return renamedFile;
}
}
}<file_sep>/ContentExplorer/Controllers/MediaController.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using ContentExplorer.Models;
using ContentExplorer.Models.ViewModels;
using ContentExplorer.Services;
using Microsoft.Ajax.Utilities;
namespace ContentExplorer.Controllers
{
public class MediaController : Controller
{
[HttpGet]
public JsonResult GetDirectoryHierarchy(string currentDirectory, string mediaType)
{
DirectoryInfo currentDirectoryInfo = GetCurrentDirectory(currentDirectory, mediaType);
if (!currentDirectoryInfo.Exists)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
DirectoryInfo hierarchyRootInfo = GetHierarchicalRootInfo(mediaType);
DirectoryHierarchyViewModel directoryHierarchy =
GetDirectoryAsHierarchy(currentDirectoryInfo, hierarchyRootInfo);
return Json(directoryHierarchy, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetSubDirectories(string currentDirectory, string mediaType, string filter)
{
string hierarchyRoot = GetHierarchyRoot(mediaType);
string websiteDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string hierarchyRootDiskLocation = Path.Combine(websiteDiskLocation, hierarchyRoot);
string currentDirectoryPath = Path.Combine(hierarchyRootDiskLocation, currentDirectory);
DirectoryInfo currentDirectoryInfo = new DirectoryInfo(currentDirectoryPath);
if (!currentDirectoryInfo.Exists)
{
return Json(new List<MediaPreviewViewModel>(), JsonRequestBehavior.AllowGet);
}
string[] filters = filter.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DirectoryInfo hierarchyRootInfo = new DirectoryInfo(hierarchyRootDiskLocation);
IEnumerable<DirectoryInfo> matchingDirectories = GetMatchingSubDirectories(currentDirectoryInfo, filters, mediaType, 0, -1);
ICollection<MediaPreviewViewModel> directoryPreviews = matchingDirectories
.Select(subDirectoryInfo =>
GetMediaPreviewFromSubDirectory(subDirectoryInfo, hierarchyRootInfo, mediaType)
)
.Where(mediaPreview => mediaPreview != null)
.ToList();
return Json(directoryPreviews, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult MoveSubDirectories(string[] directoryPaths, string newDirectoryPath, string mediaType)
{
directoryPaths = directoryPaths
.Where(filePath => string.IsNullOrEmpty(filePath) != true)
.Select(HttpUtility.UrlDecode)
.ToArray();
if (directoryPaths.Any() != true || string.IsNullOrEmpty(newDirectoryPath))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
string websiteDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string hierarchyRoot = GetHierarchyRoot(mediaType);
string hierarchyRootDiskLocation = Path.Combine(websiteDiskLocation, hierarchyRoot);
IThumbnailService thumbnailService = GetThumbnailService(mediaType);
foreach (string directoryPath in directoryPaths)
{
DirectoryInfo directoryInfo = new DirectoryInfo($"{hierarchyRootDiskLocation}\\{directoryPath}");
DirectoryInfo newDirectoryInfo = new DirectoryInfo($"{hierarchyRootDiskLocation}\\{newDirectoryPath}\\{directoryInfo.Name}");
if (newDirectoryInfo.Exists != true)
{
newDirectoryInfo.Create();
}
IEnumerable<FileInfo> directoryFiles = directoryInfo
.EnumerateFiles("*", SearchOption.TopDirectoryOnly)
.Where(subFile => thumbnailService.IsThumbnail(subFile) != true);
foreach (FileInfo fileInfo in directoryFiles)
{
FileInfo thumbnail = thumbnailService.GetFileThumbnail(fileInfo);
if (thumbnail.Exists)
{
string newThumbnailPath = $"{hierarchyRootDiskLocation}\\{newDirectoryPath}\\{directoryInfo.Name}\\{thumbnail.Name}";
thumbnail.MoveTo(newThumbnailPath);
}
if (fileInfo.Exists)
{
string newFilePath =
$"{hierarchyRootDiskLocation}\\{newDirectoryPath}\\{directoryInfo.Name}\\{fileInfo.Name}";
fileInfo.MoveTo(newFilePath);
}
}
TagLink.UpdateDirectoryPath(
$"{hierarchyRoot}\\{directoryPath}",
$"{hierarchyRoot}\\{newDirectoryPath}\\{directoryInfo.Name}\\"
);
bool areRemainingFiles = directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories).Any();
if (areRemainingFiles != true)
{
directoryInfo.Delete(true);
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult MoveSubFiles(string[] filePaths, string newDirectoryPath, string mediaType)
{
filePaths = filePaths
.Where(filePath => string.IsNullOrEmpty(filePath) != true)
.Select(HttpUtility.UrlDecode)
.ToArray();
if (filePaths.Any() != true || string.IsNullOrEmpty(newDirectoryPath))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
string websiteDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string hierarchyRoot = GetHierarchyRoot(mediaType);
string hierarchyRootDiskLocation = Path.Combine(websiteDiskLocation, hierarchyRoot);
DirectoryInfo newDirectoryInfo = new DirectoryInfo($"{hierarchyRootDiskLocation}\\{newDirectoryPath}");
if (newDirectoryInfo.Exists != true)
{
newDirectoryInfo.Create();
}
IThumbnailService thumbnailService = GetThumbnailService(mediaType);
FileInfo firstFileInfo = new FileInfo($"{hierarchyRootDiskLocation}\\{filePaths[0]}");
string directoryParentPath = firstFileInfo.DirectoryName;
foreach (string filePath in filePaths)
{
FileInfo fileInfo = new FileInfo($"{hierarchyRootDiskLocation}\\{filePath}");
string newFilePath = $"{hierarchyRootDiskLocation}\\{newDirectoryPath}\\{fileInfo.Name}";
FileInfo thumbnail = thumbnailService.GetFileThumbnail(fileInfo);
if (thumbnail.Exists)
{
string newThumbnailPath = $"{hierarchyRootDiskLocation}\\{newDirectoryPath}\\{thumbnail.Name}";
thumbnail.MoveTo(newThumbnailPath);
}
if (fileInfo.Exists)
{
fileInfo.MoveTo(newFilePath);
}
TagLink.UpdateFilePath(
$"{hierarchyRoot}\\{filePath}",
$"{hierarchyRoot}\\{newDirectoryPath}\\{fileInfo.Name}"
);
}
DirectoryInfo parentDirectory = new DirectoryInfo(directoryParentPath);
bool areRemainingFiles = parentDirectory.EnumerateFiles("*", SearchOption.AllDirectories).Any();
if (areRemainingFiles != true)
{
parentDirectory.Delete(true);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetSubFiles(string currentDirectory, string mediaType, string filter, int skip, int take)
{
string hierarchyRoot = GetHierarchyRoot(mediaType);
string websiteDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string hierarchyRootDiskLocation = Path.Combine(websiteDiskLocation, hierarchyRoot);
string[] filters = filter.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string currentDirectoryPath = Path.Combine(hierarchyRootDiskLocation, currentDirectory);
DirectoryInfo currentDirectoryInfo = new DirectoryInfo(currentDirectoryPath);
if (!currentDirectoryInfo.Exists)
{
return Json(new PaginatedViewModel<MediaPreviewViewModel>()
{
CurrentPage = new List<MediaPreviewViewModel>(),
Total = 0
}, JsonRequestBehavior.AllowGet);
}
DirectoryInfo hierarchyRootInfo = new DirectoryInfo(hierarchyRootDiskLocation);
IEnumerable<FileInfo> subFiles =
GetMatchingSubFiles(currentDirectoryInfo, filters, mediaType, skip, take, false);
ICollection<MediaPreviewViewModel> filePreviews = subFiles
.Select(subFile => GetMediaPreviewFromSubFile(subFile, hierarchyRootInfo, mediaType))
.ToArray();
int totalNumberOfFiles = filters.Any() != true
? GetDirectoryFilesByMediaType(currentDirectoryInfo, mediaType, false).Count()
: TagLink.GetFileCount($"{hierarchyRoot}\\{currentDirectory}", filters, skip, take);
PaginatedViewModel<MediaPreviewViewModel> paginatedViewModel = new PaginatedViewModel<MediaPreviewViewModel>
{
CurrentPage = filePreviews,
Total = totalNumberOfFiles
};
return Json(paginatedViewModel, JsonRequestBehavior.AllowGet);
}
private IEnumerable<FileInfo> GetDirectoryFilesByMediaType(DirectoryInfo directoryInfo, string mediaType,
bool includeSubDirectories)
{
IEnumerable<FileInfo> subFiles = includeSubDirectories
? directoryInfo.EnumerateFiles("*.*", SearchOption.AllDirectories)
: directoryInfo.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
FileTypeService fileTypeService = new FileTypeService();
if (mediaType == "image")
{
IThumbnailService thumbnailService = new ImageThumbnailService();
subFiles = subFiles
.Where(fileInfo =>
fileTypeService.IsFileImage(fileInfo.Name) &&
thumbnailService.IsThumbnail(fileInfo) != true
);
}
else
{
subFiles = subFiles
.Where(fileInfo =>
fileTypeService.IsFileVideo(fileInfo.Name)
);
}
return subFiles;
}
[HttpGet]
public JsonResult GetSubFile(string currentDirectory, int page, string mediaType, string filter)
{
DirectoryInfo currentDirectoryInfo = GetCurrentDirectory(currentDirectory, mediaType);
string[] filters = filter.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
FileInfo mediaItem = GetMatchingSubFiles(currentDirectoryInfo, filters, mediaType, page - 1, 1, false)
.FirstOrDefault();
if (mediaItem == null)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
DirectoryInfo hierarchicalRootInfo = GetHierarchicalRootInfo(mediaType);
MediaPreviewViewModel imageViewModel = GetMediaPreviewFromSubFile(mediaItem, hierarchicalRootInfo, mediaType);
return Json(imageViewModel, JsonRequestBehavior.AllowGet);
}
private MediaPreviewViewModel GetMediaPreviewFromSubDirectory(DirectoryInfo subDirectory,
DirectoryInfo hierarchicalDirectoryInfo, string mediaType)
{
IEnumerable<FileInfo> matchingSubFiles = subDirectory.EnumerateFiles("*.*", SearchOption.AllDirectories);
IEnumerable<FileInfo> orderedSubFiles = OrderAlphabetically(matchingSubFiles);
FileInfo firstMatchingImage = orderedSubFiles.FirstOrDefault();
if (firstMatchingImage == null)
{
return null;
}
IThumbnailService thumbnailService = GetThumbnailService(mediaType);
thumbnailService.CreateThumbnail(firstMatchingImage);
MediaPreviewViewModel mediaPreview = new MediaPreviewViewModel
{
Name = subDirectory.Name,
Path = GetUrl(subDirectory).Substring(hierarchicalDirectoryInfo.Name.Length).TrimStart('/'),
ContentUrl = GetUrl(subDirectory),
ThumbnailUrl = GetUrl(thumbnailService.GetFileThumbnail(firstMatchingImage)),
TaggingUrl = GetUrl(subDirectory).Substring(hierarchicalDirectoryInfo.Name.Length).TrimStart('/')
};
return mediaPreview;
}
private IThumbnailService GetThumbnailService(string mediaType)
{
IThumbnailService thumbnailService;
switch (mediaType)
{
case "image":
thumbnailService = new ImageThumbnailService();
break;
case "video":
thumbnailService = new VideoThumbnailService();
break;
default:
throw new NotImplementedException($"Media type {mediaType} is not supported");
}
return thumbnailService;
}
private MediaPreviewViewModel GetMediaPreviewFromSubFile(FileInfo subFile,
DirectoryInfo hierarchicalDirectoryInfo, string mediaType)
{
IThumbnailService thumbnailService = GetThumbnailService(mediaType);
if (thumbnailService.GetFileThumbnail(subFile).Exists != true)
{
thumbnailService.CreateThumbnail(subFile);
}
MediaPreviewViewModel mediaPreview = new MediaPreviewViewModel
{
Name = subFile.Name,
Path = GetUrl(subFile.Directory).Substring(hierarchicalDirectoryInfo.Name.Length).TrimStart('/'),
ContentUrl = $"{ConfigurationManager.AppSettings["CDNPath"]}/{GetUrl(subFile)}",
ThumbnailUrl = GetUrl(thumbnailService.GetFileThumbnail(subFile)),
TaggingUrl = GetUrl(subFile).Substring(hierarchicalDirectoryInfo.Name.Length).TrimStart('/')
};
return mediaPreview;
}
private IEnumerable<TFilesystemInfo> OrderAlphabetically<TFilesystemInfo>(
IEnumerable<TFilesystemInfo> unorderedEnumerable) where TFilesystemInfo : FileSystemInfo
{
IEnumerable<TFilesystemInfo> orderedEnumerable = unorderedEnumerable
.OrderBy(subFile => subFile.FullName)
.ThenBy(file =>
{
Match numbersInName = Regex.Match(file.Name, "[0-9]+");
bool isNumber = int.TryParse(numbersInName.Value, out int numericalMatch);
return isNumber ? numericalMatch : 0;
});
return orderedEnumerable;
}
private IEnumerable<DirectoryInfo> GetMatchingSubDirectories(DirectoryInfo currentDirectoryInfo, string[] filters, string mediaType, int skip, int take)
{
IEnumerable<DirectoryInfo> subDirectories =
currentDirectoryInfo.EnumerateDirectories("*", SearchOption.TopDirectoryOnly);
if (filters.Any() != true)
{
subDirectories = subDirectories.Skip(skip);
// Keep the filtering consistent with SQLite
if (take != -1)
{
subDirectories = subDirectories.Take(take);
}
return subDirectories;
}
string cdnDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
IEnumerable<TagLink> directoryTagLinks = subDirectories.SelectMany(subDirectory =>
TagLink.GetByDirectory(subDirectory.FullName.Substring(cdnDiskLocation.Length + 1), filters, skip, take, true)
);
IEnumerable<FileInfo> matchingSubFiles = directoryTagLinks
.Select(directoryTagLink => new FileInfo($"{cdnDiskLocation}\\{directoryTagLink.FilePath}"));
IEnumerable<DirectoryInfo> matchingSubDirectories = matchingSubFiles
.Select(subFile => subFile.Directory)
.DistinctBy(subFile => subFile.Parent.FullName);
return matchingSubDirectories;
}
private IEnumerable<FileInfo> GetMatchingSubFiles(DirectoryInfo currentDirectoryInfo, string[] filters, string mediaType, int skip, int take, bool includeSubDirectories)
{
if (filters.Any() != true)
{
IEnumerable<FileInfo> subFiles =
GetDirectoryFilesByMediaType(currentDirectoryInfo, mediaType, includeSubDirectories);
subFiles = subFiles.Skip(skip);
if (take != -1)
{
subFiles = subFiles.Take(take);
}
return subFiles;
}
// If we're filtering the files, any files without a tag will be skipped anyway. We may as well go solely off the tag links
string cdnDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string directoryPath = currentDirectoryInfo.FullName.Substring(cdnDiskLocation.Length + 1);
IEnumerable<TagLink> directoryTagLinks = TagLink.GetByDirectory(directoryPath, filters, skip, take);
IEnumerable<FileInfo> filesFromTagLinks =
directoryTagLinks.Select(tagLink => new FileInfo($"{cdnDiskLocation}\\{tagLink.FilePath}"));
return filesFromTagLinks;
}
private DirectoryInfo GetCurrentDirectory(string relativePath, string mediaType)
{
DirectoryInfo hierarchicalRootInfo = GetHierarchicalRootInfo(mediaType);
string currentDirectoryPath = Path.Combine(hierarchicalRootInfo.FullName, relativePath);
DirectoryInfo currentDirectoryInfo = new DirectoryInfo(currentDirectoryPath);
return currentDirectoryInfo;
}
private DirectoryInfo GetHierarchicalRootInfo(string mediaType)
{
string hierarchyRoot = GetHierarchyRoot(mediaType);
string websiteDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string hierarchyRootDiskLocation = Path.Combine(websiteDiskLocation, hierarchyRoot);
DirectoryInfo hierarchicalRootInfo = new DirectoryInfo(hierarchyRootDiskLocation);
return hierarchicalRootInfo;
}
private DirectoryHierarchyViewModel GetDirectoryAsHierarchy(DirectoryInfo directoryInfo,
DirectoryInfo hierarchyRootInfo)
{
DirectoryHierarchyViewModel directoryWithParents = new DirectoryHierarchyViewModel
{
Name = directoryInfo.Name,
ContentUrl = GetUrl(directoryInfo),
Path = GetUrl(directoryInfo).Substring(hierarchyRootInfo.Name.Length).TrimStart('/')
};
if (directoryInfo.Parent != null && directoryInfo.Parent.FullName != hierarchyRootInfo.Parent?.FullName)
{
directoryWithParents.Parent = GetDirectoryAsHierarchy(directoryInfo.Parent, hierarchyRootInfo);
}
return directoryWithParents;
}
private string GetUrl(FileSystemInfo fileSystemInfo)
{
string rawUrl =
fileSystemInfo.FullName.Substring(ConfigurationManager.AppSettings["BaseDirectory"].Length + 1);
string encodedUrl = rawUrl
.Replace("'", "%27")
.Replace("\\", "/")
.Replace("#", "%23");
return encodedUrl;
}
private string GetHierarchyRoot(string mediaType)
{
mediaType = mediaType.ToLowerInvariant();
switch (mediaType)
{
case "image":
return ConfigurationManager.AppSettings["ImagesPath"];
case "video":
return ConfigurationManager.AppSettings["VideosPath"];
default:
Response.StatusCode = 422;
throw new InvalidOperationException("Media type is not supported");
}
}
}
}<file_sep>/ContentExplorer/Models/ViewModels/PaginatedViewModel.cs
using System.Collections.Generic;
namespace ContentExplorer.Models.ViewModels
{
public class PaginatedViewModel<TPaginatedItems>
{
public int Total { get; set; }
public ICollection<TPaginatedItems> CurrentPage { get; set; }
}
}<file_sep>/ContentExplorer/Services/FileTypeService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ContentExplorer.Services
{
public class FileTypeService
{
public bool IsFileVideo(string fileName)
{
string fileExtension = fileName.Split('.').LastOrDefault();
bool isVideo = VideoExtensions.Any(validExtension => validExtension == fileExtension);
return isVideo;
}
public bool IsFileImage(string fileName)
{
string fileExtension = fileName.Split('.').LastOrDefault();
bool isImage = ImageExtensions.Any(validExtension =>
validExtension == fileExtension ||
fileName.EndsWith($".thumbnail.{validExtension}")
);
return isImage;
}
private static readonly string[] VideoExtensions =
{
"mp4",
"mpeg",
"webm",
"mkv",
"avi",
"mov",
"m4v"
};
private static readonly string[] ImageExtensions =
{
"jpg",
"jpeg",
"gif",
"png",
"tga",
"bmp"
};
}
}<file_sep>/ContentExplorer/Services/ImageThumbnailService.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
namespace ContentExplorer.Services
{
public class ImageThumbnailService : IThumbnailService
{
private const int MaximumThumbnailSize = 400;
public void CreateThumbnail(FileInfo fileInfo)
{
FileInfo fileThumbnail = GetFileThumbnail(fileInfo);
if (fileThumbnail.Exists)
{
return;
}
using (Image imageOnDisk = Image.FromFile(fileInfo.FullName))
{
Size thumbnailSize = GetThumbnailDimensions(imageOnDisk.Width, imageOnDisk.Height);
using (Image thumbnailImage = new Bitmap(thumbnailSize.Width, thumbnailSize.Height))
{
using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnailImage))
{
thumbnailGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
thumbnailGraphics.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraphics.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (ImageAttributes imageAttributes = new ImageAttributes())
{
imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
Rectangle newBounds = new Rectangle(new Point(0, 0), thumbnailSize);
thumbnailGraphics.DrawImage(
imageOnDisk,
newBounds,
0,
0,
imageOnDisk.Width,
imageOnDisk.Height,
GraphicsUnit.Pixel,
imageAttributes
);
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
ImageCodecInfo imageCodecInfo = GetImageCodeInfo("image/jpeg");
thumbnailImage.Save(fileThumbnail.FullName, imageCodecInfo, encoderParameters);
}
}
}
}
}
public void DeleteThumbnailIfExists(FileInfo fileInfo)
{
FileInfo thumbnail = GetFileThumbnail(fileInfo);
if (thumbnail.Exists)
{
thumbnail.Delete();
}
}
public FileInfo GetDirectoryThumbnail(DirectoryInfo directory)
{
FileTypeService fileTypeService = new FileTypeService();
FileInfo previewImage = directory
.EnumerateFiles()
.FirstOrDefault(file => fileTypeService.IsFileImage(file.Name));
if (previewImage != null)
{
return previewImage;
}
IEnumerable<DirectoryInfo> subDirectories =
directory.EnumerateDirectories("*", SearchOption.AllDirectories);
FileInfo firstPreview = subDirectories
.Select(GetDirectoryThumbnail)
.FirstOrDefault(thumbnail => thumbnail != null);
return firstPreview;
}
public FileInfo GetFileThumbnail(FileInfo fileInfo)
{
string thumbnailPath = $"{fileInfo.FullName}.thumb.jpg";
FileInfo fileThumbnail = new FileInfo(thumbnailPath);
return fileThumbnail;
}
public bool IsThumbnail(FileInfo fileInfo)
{
bool isThumbnail = fileInfo.Name.EndsWith(".thumb.jpg");
return isThumbnail;
}
private Size GetThumbnailDimensions(int originalWidth, int originalHeight)
{
int newWidth;
int newHeight;
if (originalWidth > originalHeight)
{
newWidth = MaximumThumbnailSize;
newHeight = Convert.ToInt32((double)originalHeight / originalWidth * MaximumThumbnailSize);
}
else
{
newHeight = MaximumThumbnailSize;
newWidth = Convert.ToInt32((double)originalWidth / originalHeight * MaximumThumbnailSize);
}
return new Size(newWidth, newHeight);
}
private ImageCodecInfo GetImageCodeInfo(string mimeType)
{
ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo matchingCodecInfo = imageEncoders.FirstOrDefault(potentialCodec =>
potentialCodec.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase)
);
return matchingCodecInfo;
}
}
}<file_sep>/ContentExplorer/Models/SqliteWrapper.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Linq;
using Microsoft.Data.Sqlite;
namespace ContentExplorer.Models
{
public class SqliteWrapper : IDisposable
{
public SqliteWrapper(string connectionString)
{
try
{
SqlConnection = GenerateConnection(connectionString);
}
catch (ArgumentException)
{
// If we've passed the name of a connection string instead, try to get the value instead
connectionString = GetConnectionStringFromName(connectionString);
SqlConnection = GenerateConnection(connectionString);
}
}
private string GetConnectionStringFromName(string connectionStringName)
{
ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
string connectionString = connectionStringSettings.ToString();
return connectionString;
}
private SqliteConnection SqlConnection { get; }
public static SqliteParameter GenerateParameter(string name, object value)
{
SqliteParameter parameter = new SqliteParameter(name, value);
return parameter;
}
public void Dispose()
{
SqlConnection?.Dispose();
}
public bool ExecuteNonQuery(string query)
{
return ExecuteNonQuery(query, parameters: null);
}
public bool ExecuteNonQuery(string query, SqliteParameter parameter)
{
return ExecuteNonQuery(query, new SqliteParameter[] { parameter });
}
public bool ExecuteNonQuery(string query, IEnumerable<SqliteParameter> parameters)
{
SqliteCommand command = GenerateCommand(query, parameters);
int updatedRecordCount = command.ExecuteNonQuery();
bool isSuccess = updatedRecordCount != 0;
return isSuccess;
}
public ICollection<IDictionary<string, object>> GetDataRows(string query)
{
return GetDataRows(query, new SqliteParameter[0]);
}
public ICollection<IDictionary<string, object>> GetDataRows(string query, SqliteParameter parameter)
{
return GetDataRows(query, new SqliteParameter[] { parameter });
}
public ICollection<IDictionary<string, object>> GetDataRows(string query, IEnumerable<SqliteParameter> parameters)
{
SqliteCommand command = GenerateCommand(query, parameters);
SqliteDataReader dataReader = command.ExecuteReader();
ICollection<IDictionary<string, object>> dataRows = GetDataRows(dataReader);
return dataRows;
}
public IDictionary<string, object> GetDataRow(string query)
{
return GetDataRow(query, new SqliteParameter[0]);
}
public IDictionary<string, object> GetDataRow(string query, SqliteParameter parameter)
{
return GetDataRow(query, new SqliteParameter[] { parameter });
}
public IDictionary<string, object> GetDataRow(string query, IEnumerable<SqliteParameter> parameters)
{
SqliteCommand command = GenerateCommand(query, parameters);
SqliteDataReader dataReader = command.ExecuteReader(CommandBehavior.SingleRow);
IDictionary<string, object> dataRow = GetDataRows(dataReader).FirstOrDefault();
return dataRow;
}
public object GetScalar(string query)
{
return GetScalar(query, new SqliteParameter[0]);
}
public object GetScalar(string query, SqliteParameter parameter)
{
return GetScalar(query, new SqliteParameter[] { parameter });
}
public object GetScalar(string query, IEnumerable<SqliteParameter> parameters)
{
SqliteCommand command = GenerateCommand(query, parameters);
object scalar = command.ExecuteScalar();
return scalar;
}
/// <summary>
/// Creates a new SQLite connection
/// </summary>
/// <param name="connectionString">A string which maps to a configured connection string</param>
/// <exception cref="SqliteException">An exception occured while opening the database</exception>
/// <returns></returns>
private static SqliteConnection GenerateConnection(string connectionString)
{
SqliteConnection connection = new SqliteConnection(connectionString);
connection.Open();
return connection;
}
private ICollection<IDictionary<string, object>> GetDataRows(SqliteDataReader dataReader)
{
DataTable table = dataReader.GetSchemaTable();
ICollection<string> columnNames = Enumerable.Range(0, dataReader.FieldCount)
.Select(dataReader.GetName)
.ToArray();
ICollection<IDictionary<string, object>> dataRows = new List<IDictionary<string, object>>();
while (dataReader.Read())
{
Dictionary<string, object> dataRow = columnNames
.Select(columnName =>
new KeyValuePair<string, object>(columnName, dataReader[columnName])
)
.ToDictionary(keyPair => keyPair.Key, keyPair => keyPair.Value);
dataRows.Add(dataRow);
}
return dataRows;
}
private SqliteCommand GenerateCommand(string query, IEnumerable<SqliteParameter> parameters)
{
SqliteCommand command = new SqliteCommand(query, SqlConnection)
{
CommandTimeout = 120
};
if (parameters != null)
{
parameters = parameters.Where(parameter => parameter?.Value != null);
command.Parameters.AddRange(parameters);
}
return command;
}
}
}<file_sep>/ContentExplorer/Models/ViewModels/DirectoryHeirarchyViewModel.cs
namespace ContentExplorer.Models.ViewModels
{
public class DirectoryHierarchyViewModel
{
public string Name { get; set; }
public string ContentUrl { get; set; }
public string Path { get; set; }
public DirectoryHierarchyViewModel Parent { get; set; }
}
}<file_sep>/ContentExplorer/Core/Scripts/View/VideoView.js
/// <reference path="./MediaView.js"/>
function VideoView() {
MediaView.call(this, "video", "Video");
this.$videoContainer = $("[data-video-container]");
this.$video = null;
this.$mediaSource = null;
this.extensionsToMimeTypes = {
"mp4": "video/mp4",
"ogg": "video/ogg"
};
}
VideoView.prototype = Object.create(MediaView.prototype);
VideoView.prototype.refreshMediaDisplay = function (subFilePreview, previousMediaInformation) {
// Make current page navigatable
this.$pageButtons.find(".button_medialink-disabled")
.removeClass("button_medialink-disabled")
.addClass("button_medialink")
.attr("href", "/Video/View?path=" + this.relativeDirectory + "&page=" + previousMediaInformation.pageId + "&filter=" + this.filter);
MediaView.prototype.refreshMediaDisplay.call(this, subFilePreview, previousMediaInformation);
if (this.$video === null) {
this.$video = $("<video>")
.attr({
"controls": "controls",
"loop": "loop",
"data-video": "data-video"
})
.addClass("mediaView_media");
}
if (this.$mediaSource == null) {
this.$mediaSource = $("<source>");
}
this.$mediaSource.attr("src", subFilePreview.ContentUrl);
var contentUrlParts = subFilePreview.ContentUrl.split(".");
var extension = contentUrlParts[contentUrlParts.length - 1];
var detectedMimeType = this.extensionsToMimeTypes[extension];
if (typeof (detectedMimeType) !== "undefined") {
this.$mediaSource.attr("type", detectedMimeType);
}
if (this.$videoContainer.find("[data-video]").length === 0) {
this.$videoContainer.append(this.$video);
}
if (this.$video.find("[data-media-source]").length === 0) {
this.$video.append(this.$mediaSource);
}
}
/**
* Ensures any thumbnail urls passed to page buttons have the correct formatting
* @param {string} thumbnailUrl
*/
VideoView.prototype.formatThumbnailUrl = function (thumbnailUrl) {
return thumbnailUrl;
}
$(function () {
var mediaView = new VideoView();
mediaView.initialiseAsync();
})<file_sep>/ContentExplorer/Core/Scripts/View/ImageView.js
/// <reference path="./MediaView.js"/>
function ImageView() {
MediaView.call(this, "image", "Image");
}
ImageView.prototype = Object.create(MediaView.prototype);
ImageView.prototype.refreshMediaDisplay = function (subFilePreview, previousMediaInformation) {
// Make current page navigatable
this.$pageButtons.find(".button_medialink-disabled")
.removeClass("button_medialink-disabled")
.addClass("button_medialink")
.attr("href", "/Image/View?path=" + this.relativeDirectory + "&page=" + previousMediaInformation.pageId + "&filter=" + this.filter);
MediaView.prototype.refreshMediaDisplay.call(this, subFilePreview, previousMediaInformation);
this.$media.attr("src", subFilePreview.ContentUrl).attr("alt", subFilePreview.Name);
this.$mediaLink.attr("href", subFilePreview.ContentUrl);
if (!this.isSlideshowEnabled) {
this.unsetFocusedMediaDimensions();
}
else {
this.setFocusedMediaDimensions();
}
}
$(function () {
var mediaView = new ImageView();
mediaView.initialiseAsync();
})<file_sep>/ContentExplorer/Services/FileSystemFilteringService.cs
using ContentExplorer.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
namespace ContentExplorer.Services
{
public class FileSystemFilteringService : IFileSystemFilteringService
{
public bool FileMatchesFilter(FileInfo fileInfo, string[] filters)
{
if (filters.Any() != true)
{
return true;
}
string websiteDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string filePath = fileInfo.FullName.Substring(websiteDiskLocation.Length + 1);
bool isMatch = true;
// Make sure the file matches all of our filters
for (int filterIndex = 0; filterIndex < filters.Length && isMatch; filterIndex++)
{
string filter = filters[filterIndex];
IEnumerable<Tag> tagsForFile = Tag.GetByFile(filePath, filters);
isMatch = tagsForFile.Any(tag =>
tag.TagName.Equals(filter, StringComparison.OrdinalIgnoreCase)
);
}
return isMatch;
}
public bool TagsMatchFilter(IEnumerable<Tag> tags, IEnumerable<string> filters)
{
bool tagsMatchFilter = filters.All(filter =>
tags.Any(tag =>
filter.Equals(tag.TagName, StringComparison.OrdinalIgnoreCase)
)
);
return tagsMatchFilter;
}
public bool TagLinkMatchesFilter(IEnumerable<TagLink> tagLinks, string[] filters)
{
if (filters.Any() != true)
{
return true;
}
string[] tagsForFile = tagLinks
.GroupBy(tagLink => tagLink.GetTag().TagName)
.Select(tagGrouping => tagGrouping.Key)
.ToArray();
if (tagsForFile.Any() != true)
{
return false;
}
// Make sure the file matches all of our filters
bool isMatch = true;
for (int filterIndex = 0; filterIndex < filters.Length && isMatch; filterIndex++)
{
string filter = filters[filterIndex];
isMatch = tagsForFile.Any(tagName =>
tagName.Equals(filter, StringComparison.OrdinalIgnoreCase)
);
}
return isMatch;
}
public bool DirectoryMatchesFilter(DirectoryInfo directoryInfo, string[] filters, string mediaType)
{
string cdnDiskLocation = ConfigurationManager.AppSettings["BaseDirectory"];
string directoryPath = directoryInfo.FullName.Substring(cdnDiskLocation.Length + 1);
ICollection<Tag> directoryTags = Tag.GetByDirectory(directoryPath, filters, true);
bool directoryContainsMatchingFile = directoryTags.Any();
return directoryContainsMatchingFile;
}
}
}<file_sep>/ContentExplorer.Tests/API/Models/TagTest.cs
using System.Collections.Generic;
using ContentExplorer.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ContentExplorer.Tests.API.Models
{
[TestClass]
public class TagTest : Test
{
[TestMethod]
public void CreateTag()
{
Tag tag = CreateAndReturnTag();
using (SqliteWrapper sqliteWrapper = new SqliteWrapper("AppDb"))
{
IDictionary<string, object> dataRow = sqliteWrapper.GetDataRow(
"SELECT * FROM Tags WHERE TagId = @TagId",
SqliteWrapper.GenerateParameter("@TagId", tag.TagId)
);
Assert.IsNotNull(dataRow);
}
}
[TestMethod]
public void DeleteTag()
{
Tag tag = CreateAndReturnTag();
bool isSuccess = tag.Delete();
Assert.IsTrue(isSuccess, "Tag was not successfully deleted");
using (SqliteWrapper sqliteWrapper = new SqliteWrapper("AppDb"))
{
IDictionary<string, object> dataRow = sqliteWrapper.GetDataRow(
"SELECT * FROM Tags WHERE TagId = @TagId",
SqliteWrapper.GenerateParameter("@TagId", tag.TagId)
);
Assert.IsNull(dataRow);
}
}
[TestMethod]
public void GetTagByName()
{
Tag tag = CreateAndReturnTag();
Tag foundTag = Tag.GetByTagName(tag.TagName);
Assert.IsNotNull(foundTag);
Assert.AreEqual(tag.TagId, foundTag.TagId);
Assert.AreEqual(tag.TagName, foundTag.TagName);
}
[TestMethod]
public void GetByFile()
{
TagLink tagLink = CreateAndReturnTagLink();
ICollection<Tag> tags = Tag.GetByFile(tagLink.FilePath);
Assert.IsNotNull(tags, "Returned tag collection was null");
Assert.AreNotEqual(0, tags.Count, "No matching tags were found");
}
[TestMethod]
public void GetByFileAndFilters()
{
TagLink tagLink = CreateAndReturnTagLink();
ICollection<Tag> tags = Tag.GetByFile(tagLink.FilePath, new []{ DefaultTestTagName });
Assert.IsNotNull(tags, "Returned tag collection was null");
Assert.AreNotEqual(0, tags.Count, "No matching tags were found");
}
[TestMethod]
public void GetAll()
{
Tag tag = CreateAndReturnTag();
ICollection<Tag> tags = Tag.GetAll();
Assert.IsNotNull(tags, "Returned tag collection was null");
Assert.AreNotEqual(0, tags.Count, "No matching tags were found");
}
}
}<file_sep>/ContentExplorer/Controllers/VideoController.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using ContentExplorer.Models;
using ContentExplorer.Services;
namespace ContentExplorer.Controllers
{
public class VideoController : Controller
{
[HttpGet]
public ActionResult Index(string path = "", int? page = 1, string filter = null)
{
if (page == null || page < 1)
{
page = 1;
}
if (path == null)
{
path = "";
}
else
{
// Remove any dangerous characters to prevent escaping the current context
path = path.Trim("/\\.".ToCharArray());
}
if (filter == null)
{
filter = "";
}
DirectoryInfo directoryInfo = GetCurrentDirectory(path);
if (directoryInfo.Exists == false)
{
return RedirectToAction("Index", new { page, filter });
}
ViewBag.FilesPerPage = 50;
ViewBag.Directory = directoryInfo;
ViewBag.Page = page;
ViewBag.Filter = filter;
return View();
}
[HttpGet]
public ViewResult View(string path, int page, string filter = "")
{
if (page < 1)
{
page = 1;
}
if (filter == null)
{
filter = "";
}
ViewBag.Path = path;
ViewBag.Id = page;
ViewBag.Filter = filter;
// Zero-based index
int pageIndex = page - 1;
int startingPreview = pageIndex - 7 < 1 ? 1 : page - 7;
ViewBag.StartingPreview = startingPreview;
return View();
}
[HttpGet]
public ActionResult RebuildThumbnails(string path = "")
{
IThumbnailService videoThumbnailService = new VideoThumbnailService();
DirectoryInfo baseDirectory = GetCurrentDirectory(path);
IEnumerable<FileInfo> videos = baseDirectory.EnumerateFiles("*", SearchOption.AllDirectories)
.Where(image => videoThumbnailService.IsThumbnail(image) != true);
foreach (FileInfo video in videos)
{
videoThumbnailService.DeleteThumbnailIfExists(video);
videoThumbnailService.CreateThumbnail(video);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult ReformatNames(string path = "")
{
DirectoryInfo baseDirectory = GetCurrentDirectory(path);
ReformatNames(baseDirectory);
return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult ConvertUnplayableVideos(string path = "")
{
DirectoryInfo baseDirectory = GetCurrentDirectory(path);
VideoConversionService videoConversionService = new VideoConversionService();
videoConversionService.ConvertUnplayableVideos(baseDirectory);
return Json(true, JsonRequestBehavior.AllowGet);
}
private ActionResult ReformatNames(DirectoryInfo directory)
{
IEnumerable<DirectoryInfo> subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
ReformatNames(subDirectory);
}
NameFormatService nameFormatService = new NameFormatService();
IEnumerable<FileInfo> videos = directory.EnumerateFiles("*", SearchOption.AllDirectories);
foreach (FileInfo video in videos)
{
nameFormatService.FormatFileName(video);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
private DirectoryInfo GetCurrentDirectory(string relativePath)
{
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(ConfigurationManager.AppSettings["BaseDirectory"], ConfigurationManager.AppSettings["VideosPath"], relativePath));
return directoryInfo;
}
}
} | 6b30e73f095b6cb5c7caf012931e1f6979ce5171 | [
"JavaScript",
"C#",
"Markdown"
] | 31 | JavaScript | GeorgeEBeresford/ContentExplorer | 0390f33808a7a2c8ede89f52475f47b44d7868e5 | 385eadf8a313bc759627216289fa39019cdfe81e | |
refs/heads/master | <repo_name>Chadarr/3_bars<file_sep>/README.md
# 3_bars
- First of all, you have to download data file from this URL: http://data.mos.ru/opendata/export/1796/json/2/1
- Unzip it somewhere and input it's filepath to program
- Enter your longitude and latitude to find the closest bar.<file_sep>/bars.py
import json
import os
from math import sqrt
def load_bar_data(filepath):
if not os.path.exists(filepath):
return None
with open(filepath, encoding='utf-8') as handle:
return json.load(handle)
def bar_name(_data_to_use):
return _data_to_use['Cells']['Name']
def bar_capacity(_data_to_use):
return _data_to_use['Cells']['SeatsCount']
def bar_coordinates(_data_to_use):
return _data_to_use['Cells']['geoData']['coordinates'][0], _data_to_use['Cells']['geoData']['coordinates'][1]
def get_biggest_bar_name(_data_to_use):
return bar_name(max(_data_to_use, key=bar_capacity))
def get_smallest_bar_name(_data_to_use):
return bar_name(min(_data_to_use, key=bar_capacity))
def get_closest_bar_name(_data, longitude, latitude):
def get_distance(_data):
x, y = bar_coordinates(_data)
return sqrt((float(longitude) - x) ** 2 + (float(latitude) - y) ** 2)
return bar_name(min(_data, key=get_distance))
if __name__ == '__main__':
path = input("Please tell me the path to your JSON file\r\n")
data_to_use = load_bar_data(path)
biggest_bar = get_biggest_bar_name(data_to_use)
print('The biggest bar(-s): "{}"\n'.format(get_biggest_bar_name(data_to_use)))
print('The smallest bar(-s): "{}"\n'.format(get_smallest_bar_name(data_to_use)))
_coords = input(
'Type 2 numbers - that would be your latitude and longtitude. Fractional numbers should be entered through dot.\r\n')
_coords = _coords.split(' ')
print(
'The closest bar(-s): "{}"\r\n'.format(get_closest_bar_name(data_to_use, float(_coords[0]), float(_coords[1]))))
| 13cddd93ebcd3e82cd4193b1954a9130e538ebd8 | [
"Markdown",
"Python"
] | 2 | Markdown | Chadarr/3_bars | fd2436424e7b85b8f5c6d7da10786b4260202a34 | 27b40857059ddfa1676b6130189d8424ec391204 | |
refs/heads/master | <repo_name>vinamramaliwal/DesignPatterns<file_sep>/TicTacToe.cpp
Pubic class User{
string name;
CellType c;
}
public class Game{
Board* board;
User* a;
User* b;
Game(User* a,User* b)
{
this.a=a;
this.b=b;
board=new Board();
}
bool checkifUserWon(User* user)
{
}
void endGame{
}
}
public class Board{
public:
list<Cell*> listofCell;
list<EmptyCell*> lisofEmptyCell;
Board()
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
Cell* c=new Cell(i,j);
listofCell.push_back(c);
lisofEmptyCell.push_back(c);
}
}
}
Cell* getCell(int i,int j)
{
for(auto it=listofCell.begin();it!=listofCell.end();it++)
{
cell *c=*it;
if(c->row==i&&c->col==j)
return c;
}
return NULL;
}
bool move(int i,int j,CellType c)
{
Cell *cell=getCell(i,j);
if(cell==NULL)
return false;
cell->celltype=c;
listofemptycell.erase(cell);
return true;
}
}
enum CellType{CROSS,CIRCLE,EMPTY};
public class Cell{
public:
CellType celltype;
int row;
int col;
Cell(int i,int j)
{
row=i;
col=j;
cellType=CellType::EMPTY;
}
}
<file_sep>/MovieBooking.cpp
#include<bits/stdc++.h>
using namespace std;
public class Movie{
int id;
string name;
//other metadata
}
public class SeatLock {
private Seat seat;
private Show show;
private Integer timeoutInSeconds;
private Date lockTime;
private String lockedBy;
public boolean isLockExpired() {
final Instant lockInstant = lockTime.toInstant().plusSeconds(timeoutInSeconds);
final Instant currentInstant = new Date().toInstant();
return lockInstant.isBefore(currentInstant);
}
}
public class Booking{
Movie* movie;
Threatre* theatre;
Screen* screen;
Show* show;
List<seats*> seatsBooked;
}
public class Theatre{
int id;
string name;
list<Screen*> lisofScreens;
set<Movie*> setofMovies;
}
public class Screen{
int id;
string name;
list<Show*> lisofShows;
Theatre* Theatre;
}
public class Show{
Movie* curr_movie;
int startTime;
int endTime;
Screen* screen;
List<Seats*> listofSeats;
};
public class Seat{
int rownum;
int colnum;
Seatstatus st;
int price;
};
public enum Seatstatus{Booked,Available,Not_Available};
int main()
{
}
<file_sep>/RideSharingApp.cpp
#include<bits/stdc++.h>
using namespace std;
enum RideStatus {IDLE,CREATED,WITHDRAWN,COMPLETED};
class Ride;
class Driver
{
public:
string name;
Ride* ride_assigned;
Driver(string name)
{
this->name=name;
ride_assigned=NULL;
}
};
class Ride{
public:
int id;
int origin;
int destination;
int seats;
int amount;
static const int AMT_PER_KM= 20;
RideStatus rideStatus;
Driver* driverAssigned;
Ride(int id,int origin,int destination,int seats)
{
this->id=id;
this->origin=origin;
this->destination=destination;
this->seats=seats;
}
int calculateAmout(bool isPriorityRider)
{
int numerOfKilometers=destination-origin;
if(seats>=2)
amount=numerOfKilometers*seats*(isPriorityRider?0.75:1);
else if(seats==1)
amount=numerOfKilometers*AMT_PER_KM*(isPriorityRider?0.75:1);
return amount;
}
};
class Rider
{
public:
string name;
list<Ride*> ridesBooked;
Rider(string name)
{
this->name=name;
}
Ride* createRide(int id,int origin,int destination,int seats)
{
Ride* newRide=new Ride(id,origin,destination,seats);
newRide->rideStatus=CREATED;
ridesBooked.push_back(newRide);
return newRide;
}
void updateRide(int id,int origin,int destination,int seats)
{
auto it=ridesBooked.rbegin();
for(;it!=ridesBooked.rend();it++)
{
if((*it)->id==id)
break;
}
if((*it)->rideStatus!=RideStatus::CREATED)
{
cout<<"Ride Not in Progress,Can't Update"<<endl;
return;
}
(*it)->origin=origin;
(*it)->destination=destination;
(*it)->seats=seats;
}
void withdrawRide(Ride* ride)
{
ride->rideStatus=RideStatus::WITHDRAWN;
ridesBooked.remove(ride);
}
int closRide(Ride* ride)
{
int amount=ride->calculateAmout(ridesBooked.size()>=10);
Driver* d1=ride->driverAssigned;
d1->ride_assigned=NULL;
ride->rideStatus=RideStatus::COMPLETED;
return amount;
}
};
class RideSharingApp
{
public:
list<Rider*> listOfRiders;
list<Driver*> listOfDrivers;
Driver* addDriver(string name)
{
Driver* d1=new Driver(name);
listOfDrivers.push_back(d1);
return d1;
}
Rider* addRider(string name)
{
Rider* r1=new Rider(name);
listOfRiders.push_back(r1);
return r1;
}
void showdrivers()
{
cout<<"Drivers Available"<<endl;
for(auto it=listOfDrivers.begin();it!=listOfDrivers.end();it++)
{
cout<<(*it)->name<<" ";
}
cout<<endl;
}
};
int main() {
RideSharingApp* Uber=new RideSharingApp();
Uber->addDriver("Ayush");
Uber->addDriver("Abhishek");
Uber->addDriver("Avanish");
Uber->addDriver("Kuldeep");
Uber->addDriver("Nikhil");
Uber->showdrivers();
Rider* r1=Uber->addRider("Vinamra");
cout<<"Enter details for Rider Vinamra"<<endl;
Ride* ride1=r1->createRide(0,50,60,2);
cout<<"Ride started"<<endl;
auto it=Uber->listOfDrivers.begin();
for(;it!=Uber->listOfDrivers.end();it++)
{
if((*it)->ride_assigned==NULL)
{
(*it)->ride_assigned=ride1;
break;
}
}
ride1->driverAssigned=*it;
cout<<"Driver assigned="<<ride1->driverAssigned->name<<endl;
int e=r1->closRide(ride1);
cout<<"Ride ended:Amout charged="<<e<<endl;
}
<file_sep>/MeetingScheduler.cpp
#include<bits/stdc++.h>
using namespace std;
class Room;
class Meeting
{
int start;
int end;
Room* assigned_room;
public:
Meeting(int start,int end,Room* assigned_room)
{
this->start=start;
this->end=end;
this->assigned_room=assigned_room;
}
int getStart(){return start;}
int getEnd(){return end;}
};
class Room{
int id;
string name;
vector<Meeting*> calendar;
public:
Room(int id,string name)
{
this->id=id;
this->name=name;
}
int getId(){return id;};
vector<Meeting*> getCalendar(){return calendar;};
void updateCalendar(Meeting* m)
{
calendar.push_back(m);
return;
}
bool bookRoom(int start,int end)
{
int i;
for(i=0;i<calendar.size();i++)
{
int x=calendar[i]->getStart();
int y=calendar[i]->getEnd();
if(end<=x||start>=y)
continue;
else
{
cout<<"Room not available for these timings. Choose another Room"<<endl;
return false;
}
}
Meeting *newMeeting=new Meeting(start,end,this);
this->updateCalendar(newMeeting);
cout<<"Meeting scheduled successfully"<<endl;
return true;
}
};
class Scheduler
{
vector<Room*> listOfRooms;
public:
Room* createRoom(int id,string name)
{
Room* newRoom=new Room(id,name);
listOfRooms.push_back(newRoom);
return newRoom;
}
bool bookRoom(int start,int end,int id)
{
Room *r;
int i;
for(i=0;i<listOfRooms.size();i++)
{
r=listOfRooms[i];
if(r->getId()==id)
break;
}
if(i==listOfRooms.size())
{
cout<<"Invalid Room id"<<end;
return false;
}
return r->bookRoom(start,end);
}
void showScheduleOfAllRooms()
{
for(int i=0;i<listOfRooms.size();i++)
{
Room *p=listOfRooms[i];
cout<<"Room Id="<<p->getId()<<endl<<"Meeting timings are"<<endl;
vector<Meeting*> v=p->getCalendar();
for(int j=0;j<v.size();j++)
{
cout<<v[j]->getStart()<<" "<<v[j]->getEnd()<<endl;
}
}
}
};
int main()
{
Scheduler* Jeera=new Scheduler();
Jeera->createRoom(1,"Conference Hall-1");
Jeera->createRoom(2,"Conference Hall-2");
Jeera->createRoom(3,"Conference Hall-3");
Jeera->bookRoom(9,11,1);
Jeera->bookRoom(10,12,1);
Jeera->bookRoom(10,15,2);
Jeera->bookRoom(15,16,2);
Jeera->showScheduleOfAllRooms();
}
<file_sep>/SnakeGame.cpp
enum Celltype{EMPTY,FOOD,SNAKE_NODE};
class cell
{
public:
Celltype ctp;
int i;
int j;
cell();
cell(int i,int j)
{
this->i=i;
this->j=j;
this->ctp=EMPTY;
}
void setCelltype(Celltype name)
{
this->ctp=name;
}
Celltype getCelltype()
{
return this->ctp;
}
};
class Snake
{
public:
list<cell*> mysnake;
cell* head;
Snake(cell* initpos)
{
head=initpos;
initpos->setCelltype(SNAKE_NODE);
mysnake.push_back(initpos);
}
void grow(cell* nextcell)
{
cout<<"Snake is growing to "<<nextcell->i<<" "<<nextcell->j<<endl;
nextcell->setCelltype(SNAKE_NODE);
mysnake.push_front(nextcell);
head=nextcell;
}
bool checkcrash(cell* nextcell)
{
cout<<"Going to check for crash"<<endl;
for(auto it=mysnake.begin();it!=mysnake.end();it++)
{
if((*it)->i==nextcell->i&&(*it)->j==nextcell->j)
return true;
}
return false;
}
void move(cell* nextcell)
{
cout<<"Snake is moving to "<<nextcell->i<<" "<<nextcell->j<<endl;
head=nextcell;
cell *c=mysnake.back();
(*c).setCelltype(EMPTY);
nextcell->setCelltype(SNAKE_NODE);
mysnake.push_front(nextcell);
mysnake.pop_back();
}
};
class Board
{
public:
int n,m;
vector<vector<cell*>> matrix;
Board(int n,int m)
{
this->n=n;
this->m=m;
int i,j;
matrix.resize(n);
for(i=0;i<n;i++)
{
matrix[i].resize(j);
for(j=0;j<m;j++)
matrix[i][j]=new cell(i,j);
}
}
void generateFood()
{
cout<<"Going to generate food"<<endl;
int x,y;
while(1)
{
x=rand()%n;
y=rand()%m;
if((*matrix[x][y]).getCelltype()!=SNAKE_NODE||(*matrix[x][y]).getCelltype()!=FOOD)
{
break;
}
}
matrix[x][y]->setCelltype(FOOD);
return;
}
};
class Game
{
public:
static const int DIRECTION_NONE=0,DIRECTION_RIGHT = 1,DIRECTION_LEFT = -1,DIRECTION_UP = 2,DIRECTION_DOWN = -2;
Snake* snake;
Board* board;
int direction;
bool gameOver;
Game(Snake* snake,Board *board)
{
this->snake=snake;
this->board=board;
}
void update()
{
cout<<"Going to update game"<<endl;
if(!gameOver&&direction!=DIRECTION_NONE)
{
cell* nextcell=getNextCell(snake->head);
if(gameOver)
return;
if(snake->checkcrash(nextcell))
{
direction=DIRECTION_NONE;
gameOver=true;
}
else
{
if (nextcell->ctp==FOOD) {
snake->grow(nextcell);
board->generateFood();
}
else
snake->move(nextcell);
}
}
}
cell* getNextCell(cell* currentPosition)
{
cout<<"Going to find next cell"<<endl;
int row=currentPosition->i;
int col=currentPosition->j;
if (direction == DIRECTION_RIGHT) {
col++;
}
else if (direction == DIRECTION_LEFT) {
col--;
}
else if (direction == DIRECTION_UP) {
row--;
}
else if (direction == DIRECTION_DOWN) {
row++;
}
if(row<0||row>=10||col<0||col>=10)
{
gameOver=true;
cout<<"NextCell out of Range::Game Over"<<endl;
return NULL;
}
return board->matrix[row][col];
}
};
int main() {
std::cout <<"Going to start game";
cell* initPos = new cell(0, 0);
Snake *initSnake = new Snake(initPos);
Board* board = new Board(10, 10);
Game* newGame = new Game(initSnake, board);
newGame->gameOver = false;
newGame->direction = Game::DIRECTION_RIGHT;
while(1)
{
for (int i = 0; i < 5; i++)
{
if (i == 0)
newGame->direction = Game::DIRECTION_DOWN;
if (i == 2)
newGame->board->generateFood();
newGame->update();
if (i == 3)
newGame->direction = Game::DIRECTION_RIGHT;
if (newGame->gameOver == true)
return 0;
}
}
return 0;
}
<file_sep>/README.md
# DesignPatterns
This Repository contains the DesignPattern Questions code.
<file_sep>/SnakeLadder.cpp
#include <bits/stdc++.h>
using namespace std;
class Dice
{
public:
int throwDice()
{
return rand()%6+1;
}
};
class Player:public Dice
{
private:
int position;
public:
string name;
Player(string name)
{
this->position=0;
this->name=name;
}
void setPosition(int x)
{
this->position=x;
}
int getPosition()
{
return this->position;
}
};
class Board
{
public:
map<int,int> ladder;
map<int,int> snake;
void addSnake(int a ,int b)
{
this->snake[a]=b;
}
void addLadder(int a,int b)
{
this->ladder[a]=b;
}
};
int main() {
Board bd;
cout<<"Enter the number of snakes"<<endl;
int i,j,k,l,m,n,a,b,p,q;
cin>>l;
for(i=1;i<=l;i++)
{
cin>>a>>b;
bd.addSnake(a,b);
}
cout<<"Enter the number of ladders"<<endl;
cin>>l;
for(i=1;i<=l;i++)
{
cin>>a>>b;
bd.addLadder(a,b);
}
Player x("Gaurav");
Player y("Sagar");
srand(time(0));
m=1;
while(1)
{
a=x.getPosition();
b=y.getPosition();
if(a==100||b==100)
break;
if(m==1)
{
m=0;
k=x.throwDice();
if(a+k>100)
{
x.setPosition(a);
}
else{
j=a+k;
x.setPosition(j);
if(bd.snake.find(j)!=bd.snake.end())
{
x.setPosition(bd.snake[j]);
}
if(bd.ladder.find(j)!=bd.ladder.end())
{
x.setPosition(bd.ladder[j]);
}
}
p=x.getPosition();
cout<<x.name<<" rolled a "<<k<<" and moved from "<<a<<" to "<<p<<endl;
}
else{
m=1;
k=y.throwDice();
if(b+k>100)
{
y.setPosition(b);
}
else{
j=b+k;
y.setPosition(j);
if(bd.snake.find(j)!=bd.snake.end())
{
y.setPosition(bd.snake[j]);
}
if(bd.ladder.find(j)!=bd.ladder.end())
{
y.setPosition(bd.ladder[j]);
}
}
p=y.getPosition();
cout<<y.name<<" rolled a "<<k<<" and moved from "<<b<<" to "<<p<<endl;
}
}
if(a==100)
cout<<"Gaurav won the game"<<endl;
else if(b==100)
cout<<"Sagar won the game"<<endl;
return 0;
}
| a531b82a5530fc7159289422b71baf3ef23cb83a | [
"Markdown",
"C++"
] | 7 | C++ | vinamramaliwal/DesignPatterns | e006e5d1f20277b80d432c939f14d8c18c762181 | 83c149a12d3314c036c516ae338c9273cd862861 | |
refs/heads/master | <repo_name>AbelTarazona/vue-firebase<file_sep>/src/main.js
import Vue from 'vue'
import firebase from 'firebase'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false;
let app = '';
firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "implementacion-b0389.firebaseapp.com",
databaseURL: "https://implementacion-b0389.firebaseio.com",
projectId: "implementacion-b0389",
storageBucket: "",
messagingSenderId: "99166295648",
appId: "1:99166295648:web:781541d66c2269a4"
});
firebase
.auth()
.onAuthStateChanged(() => {
if (!app) {
app = new Vue({
router,
render: h => h(App)
}).$mount('#app')
}
});
<file_sep>/README.md
# vue-firebase
## Instalar dependencias
```
npm install
```
### Compilar servidor
```
npm run serve
```
| 8f4d10875744ecf5fe9fd5f596e0ffe813166f1e | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | AbelTarazona/vue-firebase | 1044b1d635b26aa15997417eb5f3391969f66696 | 1581a2da8a2b3375c3931c7b7bbc06f8725cb6e5 | |
refs/heads/main | <file_sep>#ifndef MYTHERMOMETER_H
#define MYTHERMOMETER_H
#include <QWidget>
class MyThermometer : public QWidget
{
Q_OBJECT
private:
double temperature;
public:
MyThermometer(QWidget *parent = 0);
void paintEvent(QPaintEvent *);
void setTemperature(double temperature);
};
#endif
<file_sep>#include "mythermometer.h"
#include <QPen>
#include <QPainter>
MyThermometer::MyThermometer(QWidget *parent) :
QWidget(parent)
{
}
void MyThermometer::paintEvent(QPaintEvent *)
{
QPainter painter(this); // 创建QPainter一个对象
QPen pen;
QBrush brush; //画刷 填充几何图形的调色板,由颜色和填充风格组成
brush.setStyle(Qt::SolidPattern);
if (37.2 > temperature){
pen.setColor(Qt::green); // 设置画笔颜色
brush.setColor(Qt::green);
}
if (37.2 <= temperature) {
pen.setColor(Qt::red);
brush.setColor(Qt::red);
}
painter.setPen(pen); // 设置画笔
painter.drawRect(QRect(0, 0, 200, 30 ));
painter.setBrush(brush);
painter.drawRect(QRect(0, 0, temperature*2, 30 ));
}
void MyThermometer::setTemperature(double temperature)
{
this->temperature=temperature;
}
<file_sep>/*
* This file was generated by qdbusxml2cpp version 0.8
* Command line was: qdbusxml2cpp com.qdbus.demo.xml -p mainwindowinterface
*
* qdbusxml2cpp is Copyright (C) 2017 The Qt Company Ltd.
*
* This is an auto-generated file.
* This file may have been hand-edited. Look for HAND-EDIT comments
* before re-generating it.
*/
#include "mainwindowinterface.h"
/*
* Implementation of interface class ComQdbusServerInterface
*/
ComQdbusServerInterface::ComQdbusServerInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent)
: QDBusAbstractInterface(service, path, staticInterfaceName(), connection, parent)
{
}
ComQdbusServerInterface::~ComQdbusServerInterface()
{
}
<file_sep>/*
* This file was generated by qdbusxml2cpp version 0.8
* Command line was: qdbusxml2cpp com.qdbus.demo.xml -i mainwindow.h -a mainwindowadaptor
*
* qdbusxml2cpp is Copyright (C) 2017 The Qt Company Ltd.
*
* This is an auto-generated file.
* Do not edit! All changes made to it will be lost.
*/
#include "mainwindowadaptor.h"
#include <QtCore/QMetaObject>
#include <QtCore/QByteArray>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
/*
* Implementation of adaptor class ServerAdaptor
*/
ServerAdaptor::ServerAdaptor(QObject *parent)
: QDBusAbstractAdaptor(parent)
{
// constructor
setAutoRelaySignals(true);
}
ServerAdaptor::~ServerAdaptor()
{
// destructor
}
void ServerAdaptor::server_get(const QString &name, int age, const QString &id, const QString &tel, const QString &adress, double temperature)
{
// handle method call com.qdbus.server.server_get
QMetaObject::invokeMethod(parent(), "server_get", Q_ARG(QString, name), Q_ARG(int, age), Q_ARG(QString, id), Q_ARG(QString, tel), Q_ARG(QString, adress), Q_ARG(double, temperature));
}
<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
class MainWindowPrivate
{
Q_DECLARE_PUBLIC(MainWindow)
public:
QGSettings* m_settings;
Dialog* m_dialog;
thermometer* m_thermometer;
QRegExp id_exp;
QRegExp tel_exp;
MainWindow* q_ptr;
ComQdbusServerInterface *m_demoInter;
MainWindowPrivate(MainWindow* parent)
{
q_ptr=parent;
}
};
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, d_ptr(new MainWindowPrivate(this))
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QDBusConnection::sessionBus().connect("com.qdbus.server", "/com/qdbus/server", "com.qdbus.server", "send_to_client_ok", this, SLOT(client_get_ok(void)));
QDBusConnection::sessionBus().connect("com.qdbus.server", "/com/qdbus/server", "com.qdbus.server", "send_to_client_error", this, SLOT(client_get_error(void)));
Q_D(MainWindow);
//id_exp.setPattern("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
d->id_exp.setPattern("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
//tel_exp.setPattern("^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\\d{8}$");
d->tel_exp.setPattern("^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\\d{8}$");
d->m_demoInter = new ComQdbusServerInterface("com.qdbus.server","/com/qdbus/server",QDBusConnection::sessionBus(),this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
Q_D(MainWindow);
//绑定QGSetting与xml
//m_settings = new QGSettings("com.QGSettingDemo.test","/com/QGSettingDemo/test/");
d->m_settings = new QGSettings("com.QGSettingDemo.test","/com/QGSettingDemo/test/");
//获取QGSetting发出的KEY值改变信号,在界面同步更新
//connect (m_settings,&QGSettings::changed,[=](const QString key)
connect (d->m_settings, &QGSettings::changed, [=](const QString key)
{
if ("name" == key) {
QString name = d->m_settings->get("name").toString();
ui->lineEdit_name->setText(name);
}
if ("age" == key) {
QString age = d->m_settings->get("age").toString();
ui->lineEdit_age->setText(age);
}
if ("id" == key) {
QString id = d->m_settings->get("id").toString();
ui->lineEdit_id->setText(id);
}
if ("tel" == key) {
QString tel = d->m_settings->get("tel").toString();
ui->lineEdit_tel->setText(tel);
}
if ("adress" == key) {
QString adress = d->m_settings->get("adress").toString();
ui->lineEdit_adress->setText(adress);
}
if("temperature" == key) {
QString temperature = d->m_settings->get("temperature").toString();
ui->lineEdit_temperature->setText(temperature);
}
});
do{
if (false == ui->lineEdit_name->text().isEmpty()) {
QString name = ui->lineEdit_name->text();
if (d->m_settings) {
d->m_settings->trySet("name",name);
}
} else {
d->m_dialog = new Dialog(this);
d->m_dialog->setLabel("请输入姓名");
d->m_dialog->show();
break;
}
if ( ui->lineEdit_age->text().toInt() > 0 ) {
int age = ui->lineEdit_age->text().toInt();
if (d->m_settings) {
d->m_settings->trySet("age",age);
}
} else {
d->m_dialog = new Dialog(this);
d->m_dialog->setLabel("请输入正确年龄");
d->m_dialog->show();
break;
}
if (d->id_exp.exactMatch(ui->lineEdit_id->text())) {
QString id = ui->lineEdit_id->text();
if (d->m_settings) {
d->m_settings->trySet("id",id);
}
} else {
d->m_dialog = new Dialog(this);
d->m_dialog->setLabel("请输入正确的身份证号");
d->m_dialog->show();
break;
}
if ( d->tel_exp.exactMatch(ui->lineEdit_tel->text())) {
QString tel = ui->lineEdit_tel->text();
if (d->m_settings) {
d->m_settings->trySet("tel",tel);
}
} else {
d->m_dialog = new Dialog(this);
d->m_dialog->setLabel("请输入正确的手机号");
d->m_dialog->show();
break;
}
if (false == ui->lineEdit_tel->text().isEmpty()) {
QString adress = ui->lineEdit_adress->text();
if (d->m_settings) {
d->m_settings->trySet("adress",adress);
}
} else {
d->m_dialog = new Dialog(this);
d->m_dialog->setLabel("请输入地址");
d->m_dialog->show();
break;
}
if (35.0 < ui->lineEdit_temperature->text().toDouble()) {
double temperature = ui->lineEdit_temperature->text().toDouble();
if (d->m_settings) {
d->m_settings->trySet("temperature",temperature);
}
} else {
d->m_dialog = new Dialog(this);
d->m_dialog->setLabel("请输入正确的体温");
d->m_dialog->show();
break;
}
// Message 方式调用接口提供的函数
// QDBusMessage message = QDBusMessage::createMethodCall(
// "com.qdbus.server",
// "/com/qdbus/server",
// "com.qdbus.server",
// "server_get");
// message << ui->lineEdit_name->text()
// << ui->lineEdit_age->text().toInt()
// << ui->lineEdit_id->text()
// << ui->lineEdit_tel->text()
// << ui->lineEdit_adress->text()
// << ui->lineEdit_temperature->text().toDouble();
// QDBusConnection::sessionBus().call(message);
// 适配器方式调用接口提供的函数
d->m_demoInter->server_get(ui->lineEdit_name->text(),
ui->lineEdit_age->text().toInt(),
ui->lineEdit_id->text(),
ui->lineEdit_tel->text(),
ui->lineEdit_adress->text(),
ui->lineEdit_temperature->text().toDouble());
} while(0);
}
void MainWindow::client_get_error()
{
Q_D(MainWindow);
d->m_thermometer= new thermometer(this);
d->m_thermometer->setLabel("体温异常,禁止通行");
d->m_thermometer->setProgressBar(ui->lineEdit_temperature->text().toDouble());
d->m_thermometer->show();
}
void MainWindow::client_get_ok()
{
Q_D(MainWindow);
d->m_thermometer = new thermometer(this);
d->m_thermometer->setLabel("体温正常,允许通行");
d->m_thermometer->setProgressBar(ui->lineEdit_temperature->text().toDouble());
d->m_thermometer->show();
}
<file_sep>#ifndef THERMOMETER_H
#define THERMOMETER_H
#include <QDialog>
namespace Ui {
class thermometer;
}
class thermometer : public QDialog
{
Q_OBJECT
public:
explicit thermometer(QWidget *parent = nullptr);
~thermometer();
void setLabel(QString bugInfo);
void setProgressBar(double temperature);
private:
Ui::thermometer *ui;
};
#endif // THERMOMETER_H
<file_sep>Qt疫情软件分成Server和Client通过dbus数据总线通信
该Demo用以熟悉Qt插件机制,dbus 和 gsetting
Clinet部分利用正则表达式检测输入,通过Server注册的Dbus服务发送疫情数据给Server,Server判断是否通行


<file_sep>#ifndef ECHOINTERFACE_H
#define ECHOINTERFACE_H
#include <QString>
#include <QtPlugin>
//定义接口
class EchoInterface
{
public:
virtual ~EchoInterface() = 0;
virtual QString echo(const QString &message) = 0;
};
#define EchoInterface_iid "Examples.Plugin.EchoInterface"
QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(EchoInterface, EchoInterface_iid)
QT_END_NAMESPACE
#endif // ECHOINTERFACE_H
<file_sep>#include "mythermometer.h"
#include "mythermometerplugin.h"
#include <QtPlugin>
MyThermometerPlugin::MyThermometerPlugin(QObject *parent)
: QObject(parent)
{
m_initialized = false;
}
void MyThermometerPlugin::initialize(QDesignerFormEditorInterface * /* core */)
{
if (m_initialized)
return;
// Add extension registrations, etc. here
m_initialized = true;
}
bool MyThermometerPlugin::isInitialized() const
{
return m_initialized;
}
QWidget *MyThermometerPlugin::createWidget(QWidget *parent)
{
return new MyThermometer(parent);
}
QString MyThermometerPlugin::name() const
{
return QLatin1String("MyThermometer");
}
QString MyThermometerPlugin::group() const
{
return QLatin1String("MyThermometer");
}
QIcon MyThermometerPlugin::icon() const
{
return QIcon();
}
QString MyThermometerPlugin::toolTip() const
{
return QLatin1String("");
}
QString MyThermometerPlugin::whatsThis() const
{
return QLatin1String("");
}
bool MyThermometerPlugin::isContainer() const
{
return false;
}
QString MyThermometerPlugin::domXml() const
{
return QLatin1String("<widget class=\"MyThermometer\" name=\"myThermometer\">\n</widget>\n");
}
QString MyThermometerPlugin::includeFile() const
{
return QLatin1String("mythermometer.h");
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(mythermometerplugin, MyThermometerPlugin)
#endif // QT_VERSION < 0x050000
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "dialog.h"
#include "thermometer.h"
#include "mainwindowinterface.h"
#include <QRegularExpression>
#include <QtDBus/QtDBus>
#include <QGSettings>
#include <QPainter>
#include <QMainWindow>
#include <QGlobalStatic>
namespace Ui {
class MainWindow;
}
class MainWindowPrivate;
class MainWindow : public QMainWindow
{
Q_OBJECT
Q_DECLARE_PRIVATE(MainWindow)
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
//录入输入框信息保存于GSettting xml
void on_pushButton_clicked();
//接受send_to_client是否通行信号
void client_get_ok(void);
void client_get_error(void);
private:
MainWindowPrivate* d_ptr;
Ui::MainWindow *ui;
/*
QGSettings* m_settings;
Dialog* m_dialog;
thermometer* m_thermometer;
QRegExp id_exp;
QRegExp tel_exp;
*/
};
#endif // MAINWINDOW_H
<file_sep>#ifndef INTERFACEPLUGIN_H
#define INTERFACEPLUGIN_H
#include <QtPlugin>
//定义接口
class InterfacePlugin
{
public:
virtual ~InterfacePlugin() = 0 ;
virtual void SetTemp(const double temp) = 0;
};
//唯一标识符
#define InterfacePlugin_iid "Test.Plugin.InterfacePlugin"
Q_DECLARE_INTERFACE(InterfacePlugin, InterfacePlugin_iid)
#endif // INTERFACEPLUGIN_H
<file_sep>/*
* This file was generated by qdbusxml2cpp version 0.8
* Command line was: qdbusxml2cpp com.qdbus.demo.xml -i mainwindow.h -a mainwindowadaptor
*
* qdbusxml2cpp is Copyright (C) 2017 The Qt Company Ltd.
*
* This is an auto-generated file.
* This file may have been hand-edited. Look for HAND-EDIT comments
* before re-generating it.
*/
#ifndef MAINWINDOWADAPTOR_H
#define MAINWINDOWADAPTOR_H
#include <QtCore/QObject>
#include <QtDBus/QtDBus>
#include "mainwindow.h"
QT_BEGIN_NAMESPACE
class QByteArray;
template<class T> class QList;
template<class Key, class Value> class QMap;
class QString;
class QStringList;
class QVariant;
QT_END_NAMESPACE
/*
* Adaptor class for interface com.qdbus.server
*/
class ServerAdaptor: public QDBusAbstractAdaptor
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "com.qdbus.server")
Q_CLASSINFO("D-Bus Introspection", ""
" <interface name=\"com.qdbus.server\">\n"
" <signal name=\"send_to_client_ok\"/>\n"
" <signal name=\"send_to_client_error\"/>\n"
" <method name=\"server_get\">\n"
" <arg direction=\"in\" type=\"s\" name=\"name\"/>\n"
" <arg direction=\"in\" type=\"i\" name=\"age\"/>\n"
" <arg direction=\"in\" type=\"s\" name=\"id\"/>\n"
" <arg direction=\"in\" type=\"s\" name=\"tel\"/>\n"
" <arg direction=\"in\" type=\"s\" name=\"adress\"/>\n"
" <arg direction=\"in\" type=\"d\" name=\"temperature\"/>\n"
" </method>\n"
" </interface>\n"
"")
public:
ServerAdaptor(QObject *parent);
virtual ~ServerAdaptor();
public: // PROPERTIES
public Q_SLOTS: // METHODS
void server_get(const QString &name, int age, const QString &id, const QString &tel, const QString &adress, double temperature);
Q_SIGNALS: // SIGNALS
void send_to_client_error();
void send_to_client_ok();
};
#endif
<file_sep>/*
* This file was generated by qdbusxml2cpp version 0.8
* Command line was: qdbusxml2cpp com.qdbus.demo.xml -p mainwindowinterface
*
* qdbusxml2cpp is Copyright (C) 2017 The Qt Company Ltd.
*
* This is an auto-generated file.
* Do not edit! All changes made to it will be lost.
*/
#ifndef MAINWINDOWINTERFACE_H
#define MAINWINDOWINTERFACE_H
#include <QtCore/QObject>
#include <QtCore/QByteArray>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
#include <QtDBus/QtDBus>
/*
* Proxy class for interface com.qdbus.server
*/
class ComQdbusServerInterface: public QDBusAbstractInterface
{
Q_OBJECT
public:
static inline const char *staticInterfaceName()
{ return "com.qdbus.server"; }
public:
ComQdbusServerInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = nullptr);
~ComQdbusServerInterface();
public Q_SLOTS: // METHODS
inline QDBusPendingReply<> server_get(const QString &name, int age, const QString &id, const QString &tel, const QString &adress, double temperature)
{
QList<QVariant> argumentList;
argumentList << QVariant::fromValue(name) << QVariant::fromValue(age) << QVariant::fromValue(id) << QVariant::fromValue(tel) << QVariant::fromValue(adress) << QVariant::fromValue(temperature);
return asyncCallWithArgumentList(QStringLiteral("server_get"), argumentList);
}
Q_SIGNALS: // SIGNALS
void send_to_client_error();
void send_to_client_ok();
};
namespace com {
namespace qdbus {
typedef ::ComQdbusServerInterface server;
}
}
#endif
<file_sep>#ifndef ECHOPLUGIN_H
#define ECHOPLUGIN_H
#include "../Server/echointerface.h"
class EchoPlugin : public QObject, public EchoInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID EchoInterface_iid)
Q_INTERFACES(EchoInterface)
public:
explicit EchoPlugin(QObject *parent = 0);
QString echo(const QString &message);
};
#endif // ECHOPLUGIN_H
<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "echointerface.h"
#include <QDebug>
class MainWindowPrivate
{
Q_DECLARE_PUBLIC(MainWindow)
public:
int count;
QStandardItemModel *model;
MainWindow *q_ptr;
bool LoadPlugin();
EchoInterface *echoInterface;
MainWindowPrivate(MainWindow* parent)
{
count = 0;
model = new QStandardItemModel();
q_ptr=parent;
}
};
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, d_ptr(new MainWindowPrivate(this))
, ui(new Ui::MainWindow)
{
Q_D(MainWindow);
ui->setupUi(this);
//获得主窗口的大小
int width = this->width();
int height = this->height();
//调整tableView窗口大小和主窗口一致
ui->tableView->resize(width, height);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//设置表格样式
d->model->setColumnCount(7);
d->model->setHeaderData(0,Qt::Horizontal,QString::fromLocal8Bit("姓名"));
d->model->setHeaderData(1,Qt::Horizontal,QString::fromLocal8Bit("年龄"));
d->model->setHeaderData(2,Qt::Horizontal,QString::fromLocal8Bit("身份证号"));
d->model->setHeaderData(3,Qt::Horizontal,QString::fromLocal8Bit("手机号"));
d->model->setHeaderData(4,Qt::Horizontal,QString::fromLocal8Bit("住址"));
d->model->setHeaderData(5,Qt::Horizontal,QString::fromLocal8Bit("体温"));
d->model->setHeaderData(6,Qt::Horizontal,QString::fromLocal8Bit("是否放行"));
ui->tableView->setModel(d->model);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::server_get(QString name , int age , QString id , QString tel , QString adress , double temperature)
{
Q_D(MainWindow);
d->model->setItem(d->count,0,new QStandardItem(name));
d->model->setItem(d->count,1,new QStandardItem(QString::number(age)));
d->model->setItem(d->count,2,new QStandardItem(id));
d->model->setItem(d->count,3,new QStandardItem(tel));
d->model->setItem(d->count,4,new QStandardItem(adress));
d->model->setItem(d->count,5,new QStandardItem(QString::number(temperature)));
if (37.2 <= temperature ) {
d->model->setItem(d->count, 6, new QStandardItem(QString("否")));
emit send_to_client_error();
}
if (temperature < 37.2) {
d->model->setItem(d->count , 6, new QStandardItem(QString("是")));
emit send_to_client_ok();
}
d->count++;
if(d->LoadPlugin()){
d->echoInterface->echo(QString::number(temperature));
}
}
bool MainWindowPrivate::LoadPlugin()
{
bool ret = true;
//获取当前应用程序所在路径
QDir pluginsDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() =="release"){
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS")
{
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#elif defined(Q_OS_LINUX)
pluginsDir.cdUp();
#endif
//切换到插件目录
pluginsDir.cd("plugins");
//遍历plugins目录下所有文件
foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader.instance();
if (plugin) {
//插件名称
QString pluginName = plugin->metaObject()->className();
//对插件初始化
if (pluginName == "EchoPlugin") {
echoInterface = qobject_cast<EchoInterface*>(plugin);
if (echoInterface)
ret = true;
break;
}
else {
ret = false;
}
}
}
return ret;
}
<file_sep>#include "echoplugin.h"
#include <QDebug>
EchoPlugin::EchoPlugin(QObject *parent) :
QObject(parent)
{
}
QString EchoPlugin::echo(const QString &message)
{
qDebug() << message;
return message;
}
<file_sep>#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, m_dialog(new Ui::Dialog)
{
m_dialog->setupUi(this);
}
Dialog::~Dialog()
{
delete m_dialog;
}
void Dialog::setLabel(QString bugInfo)
{
m_dialog->label->setText(bugInfo);
}
<file_sep>#include "mythermometer.h"
#include <QPen>
#include <QPainter>
MyThermometer::MyThermometer(QWidget *parent) :
QWidget(parent)
{
}
void MyThermometer::paintEvent(QPaintEvent *)
{
QPainter painter(this); // 创建QPainter一个对象
QPen pen;
if (37.2 <= temperature){
pen.setColor(Qt::green); // 设置画笔颜色
}
if (37.2 > temperature) {
pen.setColor(Qt::red);
}
painter.setPen(pen); // 设置画笔
painter.drawRect(QRect(1, 1, 300, 100));
painter.restore();
}
void MyThermometer::setTemperature(double temperature)
{
this->temperature=temperature;
}
<file_sep>#include "mainwindow.h"
#include <QApplication>
#include "mainwindowadaptor.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
//建立Dbus连接
QDBusConnection connection = QDBusConnection::sessionBus();
//注册Dbus服务
connection.registerService("com.qdbus.server");
//注册Dbus对象
//用Object来导出信号和槽函数
//connection.registerObject("/com/qdbus/server", &w, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals);
//用适配器方式来导出信号和槽函数
ServerAdaptor adaptor(&w);
connection.registerObject("/com/qdbus/server", &w);
return a.exec();
}
<file_sep>#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
//提供接口给主窗口修改错误信息接口
void setLabel(QString bugInfo);
private:
Ui::Dialog* m_dialog;
};
#endif // DIALOG_H
<file_sep>#include "thermometer.h"
#include "ui_thermometer.h"
thermometer::thermometer(QWidget *parent) :
QDialog(parent),
ui(new Ui::thermometer)
{
ui->setupUi(this);
}
thermometer::~thermometer()
{
delete ui;
}
void thermometer::setLabel(QString bugInfo)
{
ui->label->setText(bugInfo);
}
void thermometer::setProgressBar(double temperature)
{
ui->myThermometer->setTemperature(temperature);
}
| 2244588e6ed8148ee004fad2e280fa35c3dcdc7a | [
"Markdown",
"C++"
] | 21 | C++ | rororwwww/QtDbusDemo | abc897955be148f3ddd2b852ccda25493918505e | dea0393ac2f7a2189340b26eb2aa70bda9f01728 | |
refs/heads/master | <file_sep>**Artificial Intelligence Frameworks:**
- Frameworks:
- Caffee
- Theano
- PyTroch
- Distbelief
- Tensorflow: Set of APIs and data structures
**Website for datasets:**
- seach for datasets:
- https://www.kaggle.com/datasets
- https://cocodataset.org/#explore
- http://www.image-net.org/
- https://archive.ics.uci.edu/ml/datasets.php
- http://yann.lecun.com/exdb/mnist/
- search for websites:
- https://datasetsearch.research.google.com/
- https://www.kdnuggets.com/datasets/index.html
**Pre-Trained Networks in Keras:**
- VGG16
- VGG19
- Resnet50
- Inception V3
- Xception
- MobileNet
**Object Detection Approaches:**
- RCNN (https://arxiv.org/abs/1311.2524)
- Fast RCNN (https://arxiv.org/abs/1504.08083)
- Faster RCNN (https://arxiv.org/abs/1506.01497)
- Yolo - you only look once
- Implementation unsing TensorFlow
- SSD (https://arxiv.org/pdf/1512.02325.pdf):
- Key challange: number of objects is unknown (How many bounding boxes? How many classifictions?)
- proviode a fixed number of bounding boxes+classifications(maximum)
- classify bounding boxes as "object" or "not an object" -> only considering "objects" to produce variable number of boxes+classifications
- Training:
- True classifications and bounding boxes are known
- Secify the output:
- Split imput data into 3x3 cells
- for each cell:
<img src="https://github.com/gitkatrin/gesture_project/blob/master/images/Training_vector.PNG" width="250">
- Cell that contains the center point of the object is associated to the object:
-> identify cell with center point of bounding box
-> conpare bounding box with different anchor boxes in this cell
-> associate object to ancher box with most sililar shape (higherst IoU)
- Multiple anchor boxes in each cell (anchor box: initial guess for a bounding box with fixed size)
-> output one y for every anchor box
- Testing:
- basic probelm: obtain too many bounding boxes; trainined network would output a vector y for every anchor box
- remove all bounding boxes which are p < 0,5 (p: Probability that its an object)
- normally left with a few bounding boxes for each object (many anchor boxes overlap with object because of the 19x19 grid)
- Non-maximum suppression:
1. Remove all anchor boxes: p < 0,5
2. Find anchor box with the largest probability of being an object and store that to set of object detections (bounding box i)
3. Remove all anchor boxes:
- the same most probable class is the same than bpunding box i
- bounding box overlaps substantially with bounding box i
4. Repeat until fixed bounding boxes
- **Paper:**
- The convolutional model for predicting detections is different for each feature layer
- Model: Default boxes and aspect ratios:
- associate set of default bounding boxes with each feature map cell (one cell with set of bounding boxes) for multiple feature maps at the top of the network
- default boxes tile the feature map in a convolutional manner -> position of each box is fixed to corresponding cell
- in each feature map cell:
- predict **offsets relative** to the default box shapes
- per-class **scores** that indicate the presence of a class instance (in each box)
- compute relative to original default box shape, for each box out of k at a given location the c class scores and 4 offsets
-> (c + 4)k filters, applied around each location in the feature map -> (c + 4)kmn outputs (for m x n feature map)
- like anchor boxes (Faster R-CNN) but apply them on several feature maps of different resolutions
- allowing different default box shapes in severat feature maps -> discretize the space of possible output box shapes
- Training:
- ground truth information needs to be assigned to specific outputs in the fixed set of detector outputs
- assignment determined -> loss function and back propagation are applied end-to-end
- choosing the set of default boxes and scales for detection
- scales for detection hard negative mining and data augmentation strategies
- matching strategy:
-
<file_sep>#!/usr/bin/env python
# coding: utf-8
"""
Object Detection (On Image) From TF2 Saved Model
=====================================
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
import pathlib
import tensorflow as tf
import cv2
import argparse
tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2)
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='Folder that the Saved Model is Located In',
default='exported-models/my_mobilenet_model')
parser.add_argument('--labels', help='Where the Labelmap is Located',
default='exported-models/my_mobilenet_model/saved_model/label_map.pbtxt')
parser.add_argument('--image', help='Name of the single image to perform detection on',
default='JENGA_LIVINGROOM_S_T_frame_1650.jpg')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.3)
args = parser.parse_args()
# Enable GPU dynamic memory allocation
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# PROVIDE PATH TO IMAGE DIRECTORY
IMAGE_PATHS = args.image
# PROVIDE PATH TO MODEL DIRECTORY
PATH_TO_MODEL_DIR = args.model
# PROVIDE PATH TO LABEL MAP
PATH_TO_LABELS = args.labels
# PROVIDE THE MINIMUM CONFIDENCE THRESHOLD
MIN_CONF_THRESH = float(args.threshold)
# LOAD THE MODEL
import time
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
PATH_TO_SAVED_MODEL = PATH_TO_MODEL_DIR + "/saved_model"
print('Loading model...', end='')
start_time = time.time()
# LOAD SAVED MODEL AND BUILD DETECTION FUNCTION
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)
end_time = time.time()
elapsed_time = end_time - start_time
print('Done! Took {} seconds'.format(elapsed_time))
# LOAD LABEL MAP DATA FOR PLOTTING
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,
use_display_name=True)
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
from collections import namedtuple
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the image
Returns:
uint8 numpy array with shape (img_height, img_width, 3)
"""
return np.array(Image.open(path))
print('Running inference for {}... '.format(IMAGE_PATHS), end='')
#==========================================================================
# define the `Detection` object (gt= ground truth, pred= prediction)
Detection = namedtuple("Detection", ["image_path", "gt", "pred"])
def batch_iou(boxA, boxB):
# COORDINATES OF THE INTERSECTION BOXES
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
# hier die csv einlesen !!!!!!!!!!!!!!!!!
# define the list of example detections
examples = [
Detection("JENGA_LIVINGROOM_S_T_frame_1650.jpg", [633, 383, 845, 578], [630, 380, 842, 575])]
# loop over the example detections
#for detection in examples:
# # load the image
# image = cv2.imread(detection.image_path)
# # draw the ground-truth bounding box along with the predicted
# # bounding box
# cv2.rectangle(image, tuple(detection.gt[:2]),
# tuple(detection.gt[2:]), (0, 255, 0), 2)
# cv2.rectangle(image, tuple(detection.pred[:2]),
# tuple(detection.pred[2:]), (0, 0, 255), 2)
# # compute the intersection over union and display it
# iou = batch_iou(detection.gt, detection.pred)
# cv2.putText(image, "IoU: {:.4f}".format(iou), (10, 30),
# cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# print("{}: {:.4f}".format(detection.image_path, iou))
# # show the output image
# cv2.imshow("Image", image)
# cv2.waitKey(0)
#============================================================================
image = cv2.imread(IMAGE_PATHS)
image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
imH, imW, _ = image.shape
image_expanded = np.expand_dims(image_rgb, axis=0)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis, ...]
# input_tensor = np.expand_dims(image_np, 0)
detections = detect_fn(input_tensor)
# All outputs are batches tensors.
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
# We're only interested in the first num_detections.
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
scores = detections['detection_scores']
boxes = detections['detection_boxes']
classes = detections['detection_classes']
count = 0
for i in range(len(scores)):
if ((scores[i] > MIN_CONF_THRESH) and (scores[i] <= 1.0)):
#increase count
count += 1
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = category_index[int(classes[i])]['name'] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(image, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(image, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
pred_box = np.array([xmin, ymin, xmax, ymax])
truth_box = np.array([633, 383, 845, 578])
cv2.rectangle(image, (633,383), (845,578), (255, 0, 0), 2)
print(pred_box, truth_box)
iou = batch_iou(truth_box, pred_box)
#cv2.rectangle(image, (xmax, label_ymin-labelSize[1]-10), (xmax+labelSize[4], label_ymin+baseLine-10), (0, 0, 0), cv2.FILLED) # Draw white box to put label text in
cv2.putText(image, "IoU: {:.4f}".format(iou), (xmax, label_ymin-7),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
cv2.putText (image,'Total Detections : ' + str(count),(10,25),cv2.FONT_HERSHEY_SIMPLEX,1,(70,235,52),2,cv2.LINE_AA)
print('Done')
# DISPLAYS OUTPUT IMAGE
cv2.imshow('Object Counter', image)
# CLOSES WINDOW ONCE KEY IS PRESSED
cv2.waitKey(0)
# CLEANUP
cv2.destroyAllWindows()
<file_sep>#!/usr/bin/env python
# coding: utf-8
"""
Object Detection (On Image) From TF2 Saved Model
=====================================
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
import pathlib
import tensorflow as tf
import cv2
import argparse
tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2)
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='Folder that the Saved Model is Located In',
default='exported-models/my_mobilenet_model')
parser.add_argument('--labels', help='Where the Labelmap is Located',
default='exported-models/my_mobilenet_model/saved_model/label_map.pbtxt')
parser.add_argument('--image', help='Name of the single image to perform detection on',
default='./img')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.3)
args = parser.parse_args()
# Enable GPU dynamic memory allocation
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# PROVIDE PATH TO IMAGE DIRECTORY
IMAGE_PATHS = args.image
# PROVIDE PATH TO MODEL DIRECTORY
PATH_TO_MODEL_DIR = args.model
# PROVIDE PATH TO LABEL MAP
PATH_TO_LABELS = args.labels
# PROVIDE THE MINIMUM CONFIDENCE THRESHOLD
MIN_CONF_THRESH = float(args.threshold)
# LOAD THE MODEL ==============================================================
import time
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
PATH_TO_SAVED_MODEL = PATH_TO_MODEL_DIR + "/saved_model"
print('Loading model...', end='')
start_time = time.time()
# LOAD SAVED MODEL AND BUILD DETECTION FUNCTION
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)
end_time = time.time()
elapsed_time = end_time - start_time
print('Done! Took {} seconds'.format(elapsed_time))
# LOAD LABEL MAP DATA FOR PLOTTING
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,
use_display_name=True)
# LOAD IMAGE ==================================================================
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
from collections import namedtuple
import os
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the image
Returns:
uint8 numpy array with shape (img_height, img_width, 3)
"""
return np.array(Image.open(path))
print('Running inference for {}... '.format(IMAGE_PATHS), '\n')
# ORDNER EINLESEN & BILDER ABFRAGEN ===========================================
import glob
def load_img_folder(img_folder_path):
img_names = []
img_data = []
for img in glob.glob(img_folder_path):
# create image name list
img_name = img.split('/')[-1]
img_names.append(img_name)
#create image data list
img_data.append(cv2.imread(img))
# create image name array
file_names = np.genfromtxt(img_names ,delimiter=',', usecols=0, dtype=str)
return img_names, img_data, file_names
# CSV DATEI EINLESEN & BILDNAMEN VERGLEICHEN ==================================
def read_csv(image_name): # ein Bild kommt hier rein
csv_data = np.genfromtxt('test_labels_2.csv',delimiter=',',skip_header=1,
usecols= (4, 5, 6, 7), missing_values = {0: str})
csv_names = np.genfromtxt('test_labels_2.csv',delimiter=',', skip_header=1,
usecols=0, dtype=str)
truth_boxes = []
for i in range(len(csv_names)): # lenght = 4320
if image_name in csv_names[i]:
truth_boxes.append(csv_data[i])
return truth_boxes
# CALCULATE IOU ===============================================================
def batch_iou(boxA, boxB):
# COORDINATES OF THE INTERSECTION BOXES
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
def possible_iou(truthbox_list, prediction_box):
possible_iou_list = []
for box in truthbox_list:
iou = batch_iou(box, prediction_box)
possible_iou_list.append(iou) # Liste mit möglichen iou's
return possible_iou_list
# WRITE NEW CSV FILE WITH CALCULATED IOU ======================================
import csv
def create_new_csv(data):
with open('output.csv', 'w') as csv_file:
# Überschriften erstellen
fieldnames = ['image name', 'gt_xmin', 'gt_ymin', 'gt_xmax', 'gt_ymax',
'pred_xmin', 'pred_ymin', 'pred_max', 'pred_ymax', 'iou', 'score']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
writer = csv.writer(csv_file, delimiter=',')
writer.writerows(data)
#==============================================================================
k = 0
img_names, img_data, file_names = load_img_folder('./img/*.jpg')
data_for_csv = []
iou_img_name = []
iou_used = []
used_tboxes = []
chosen_tboxes = []
best_ious = []
pred_boxes = []
while k < len(img_names):
# truth_boxes = [array([557., 505., 817., 719.]), array([ 937., 385., 1130., 555.]), array([760., 371., 931., 527.])]
truth_boxes = read_csv(str(img_names[k]))
image = img_data[k]
#image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
imH, imW, _ = image.shape
#image_expanded = np.expand_dims(image_rgb, axis=0)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis, ...]
# input_tensor = np.expand_dims(image_np, 0)
detections = detect_fn(input_tensor)
# All outputs are batches tensors.
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
# We're only interested in the first num_detections.
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
scores = detections['detection_scores']
boxes = detections['detection_boxes']
classes = detections['detection_classes']
count = 0
for i in range(len(scores)): # für jede predicition
if ((scores[i] > MIN_CONF_THRESH) and (scores[i] <= 1.0)):
#increase count
count += 1
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = category_index[int(classes[i])]['name'] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(image, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(image, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
pred_box = np.array([xmin, ymin, xmax, ymax])
score = scores[i]*100
pred_boxes.append(pred_box)
possible_iou_list = possible_iou(truth_boxes, pred_box)
best_iou = max(possible_iou_list) # bester iou für diese prediction errechnen
n = possible_iou_list.index(max(possible_iou_list)) # index des besten ious
best_ious.append(best_iou) # beste ious aller predicition in liste
chosen_tbox = truth_boxes[n] # beste truth box pro prediction
chosen_tboxes.append(chosentbox) # beste truth boxen aller predictions in liste
while len(used_tboxes) < count: # solange Länge der Liste used_tboxes < count
for c_tbox in range(len(chosen_tboxes)): # für jeden wert für die Länge der iou_img_names (also von 0 bis count) -- eine gewählte box kommt rein
for u_tbox in range(len(used_tboxes)):
for p_box in range(len(pred_boxes)):
if chosen_tboxes[c_tbox] in used_tboxes[u_tbox]:
if best_ious[c_tbox] > iou_used[u_tbox]:
del used_tboxes[u_tbox]
del iou_used[u_tbox]
del pred_boxes[p_box]
used_tboxes.append(chosen_tboxes[c_tbox])
iou_used.append(best_ious[c_tbox])
else:
used_tboxes.append(chosen_tboxes[c_tbox])
iou_used.append(best_ious[c_tbox])
else:
used_tboxes.append(chosen_tboxes[c_tbox])
iou_used.append(best_ious[c_tbox])
if chosen_tboxes[c_tbox] in used_boxes[u_tbox]:
# truth_boxes = [array([557., 505., 817., 719.]), array([ 937., 385., 1130., 555.]), array([760., 371., 931., 527.])]
real_truth_box = box[]
minx = int(real_truth_box[0])
miny = int(real_truth_box[1])
maxx = int(real_truth_box[2])
maxy = int(real_truth_box[3])
cv2.rectangle(image, (minx,miny), (maxx,maxy), (255, 0, 0), 2)
# for i in range(len(csv_names)): # lenght = 4320
#
# if image_name in csv_names[i]:
# truth_boxes.append(csv_data[i])
iou = batch_iou(real_truth_box, pred_box)
print('Image:', img_names[k])
print('Predictionbox:', pred_box, ' ', 'Ground truth box:', real_truth_box, '\033[1m' +'\nIoU=', iou, '\033[0m')
data = [str(img_names[k]), minx, miny, maxx, maxy, xmin, ymin, xmax, ymax, iou, score]
data_for_csv.append(data)
# [['CARDS_LIVINGROOM_H_S_frame_2149.jpg', '[728.0, 470.0, 1008.0, 719.0]', '[ 738 476 1016 717]', '0.9085141163106419'],
# ['CARDS_LIVINGROOM_H_S_frame_2149.jpg', '[674.0, 400.0, 847.0, 510.0]', '[674 403 874 501]', '0.7834629553827261'], ...
#print(data_for_csv)
cv2.putText(image, "IoU: {:.4f}".format(iou), (xmax, label_ymin-7),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
k += 1
cv2.putText (image,'Total Detections : ' + str(count),(10,25),cv2.FONT_HERSHEY_SIMPLEX,1,(70,235,52),2,cv2.LINE_AA)
create_new_csv(data_for_csv)
print('\nDone')
# display output image and destroy after 5 seconds
cv2.imshow('Object Counter', image)
cv2.waitKey(0)
cv2.destroyWindow('Object Counter')
# CLOSES WINDOW ONCE KEY IS PRESSED
cv2.waitKey(0)
# CLEANUP
cv2.destroyAllWindows()
<file_sep>#!/usr/bin/env python
# coding: utf-8
"""
Object Detection (On Image) From TF2 Saved Model
=====================================
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
import pathlib
import tensorflow as tf
import cv2
import argparse
tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2)
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='Folder that the Saved Model is Located In',
default='exported-models/my_mobilenet_model')
parser.add_argument('--labels', help='Where the Labelmap is Located',
default='exported-models/my_mobilenet_model/saved_model/label_map.pbtxt')
parser.add_argument('--image', help='Name of the single image to perform detection on',
default='./img')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.3)
args = parser.parse_args()
# Enable GPU dynamic memory allocation
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# PROVIDE PATH TO IMAGE DIRECTORY
IMAGE_PATHS = args.image
# PROVIDE PATH TO MODEL DIRECTORY
PATH_TO_MODEL_DIR = args.model
# PROVIDE PATH TO LABEL MAP
PATH_TO_LABELS = args.labels
# PROVIDE THE MINIMUM CONFIDENCE THRESHOLD
MIN_CONF_THRESH = float(args.threshold)
# LOAD THE MODEL ==============================================================
import time
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
PATH_TO_SAVED_MODEL = PATH_TO_MODEL_DIR + "/saved_model"
print('Loading model...', end='')
start_time = time.time()
# LOAD SAVED MODEL AND BUILD DETECTION FUNCTION
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL)
end_time = time.time()
elapsed_time = end_time - start_time
print('Done! Took {} seconds'.format(elapsed_time))
# LOAD LABEL MAP DATA FOR PLOTTING
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,
use_display_name=True)
# LOAD IMAGE ==================================================================
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
from collections import namedtuple
import os
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the image
Returns:
uint8 numpy array with shape (img_height, img_width, 3)
"""
return np.array(Image.open(path))
print('Running inference for {}... '.format(IMAGE_PATHS), '\n')
# ORDNER EINLESEN & BILDER ABFRAGEN ===========================================
import glob
def load_img_folder(img_folder_path):
img_names = []
img_data = []
for img in glob.glob(img_folder_path):
# create image name list
img_name = img.split('/')[-1]
img_names.append(img_name)
#create image data list
img_data.append(cv2.imread(img))
# create image name array
file_names = np.genfromtxt(img_names ,delimiter=',', usecols=0, dtype=str)
return img_names, img_data, file_names
# CSV DATEI EINLESEN & BILDNAMEN VERGLEICHEN ==================================
def read_csv(image_name): # ein Bild kommt hier rein
csv_data = np.genfromtxt('test_labels_2.csv',delimiter=',',skip_header=1,
usecols= (4, 5, 6, 7), missing_values = {0: str})
csv_names = np.genfromtxt('test_labels_2.csv',delimiter=',', skip_header=1,
usecols=0, dtype=str)
truth_boxes = []
for i in range(len(csv_names)): # lenght = 4320
if image_name in csv_names[i]:
truth_boxes.append(csv_data[i])
return truth_boxes
# CALCULATE IOU ===============================================================
def batch_iou(boxA, boxB):
# COORDINATES OF THE INTERSECTION BOXES
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
import scipy.optimize
def match_bboxes(bbox_gt, bbox_pred, IOU_THRESH=0.5):
'''
Given sets of true and predicted bounding-boxes,
determine the best possible match.
Parameters
----------
bbox_gt, bbox_pred : N1x4 and N2x4 np array of bboxes [x1,y1,x2,y2].
The number of bboxes, N1 and N2, need not be the same.
Returns
-------
(idxs_true, idxs_pred, ious, labels)
idxs_true, idxs_pred : indices into gt and pred for matches
ious : corresponding IOU value of each match
labels: vector of 0/1 values for the list of detections
'''
n_true = bbox_gt.shape[0] # Anzahl der truth boxes
n_pred = bbox_pred.shape[0] # Anzahl der prediction boxen
MAX_DIST = 1.0
MIN_IOU = 0.0
# NUM_GT x NUM_PRED
iou_matrix = np.zeros((n_true, n_pred))
for i in range(n_true): # für jede truth box
for j in range(n_pred): # für jede pred box
iou_matrix[i, j] = batch_iou(bbox_gt[i,:], bbox_pred[j,:]) # iou berechnen aus einzelner gt box und pred box
if n_pred > n_true:
# there are more predictions than ground-truth - add dummy rows
diff = n_pred - n_true
print("hier sind mehr predictions als gt")
iou_matrix = np.concatenate( (iou_matrix,
np.full((diff, n_pred), MIN_IOU)),
axis=0)
if n_true > n_pred:
# more ground-truth than predictions - add dummy columns
diff = n_true - n_pred
#print("hier sind mehr gt als pred")
iou_matrix = np.concatenate( (iou_matrix,
np.full((n_true, diff), MIN_IOU)),
axis=1)
#print('2', iou_matrix)
# call the Hungarian matching
idxs_true, idxs_pred = scipy.optimize.linear_sum_assignment(1 - iou_matrix) # truth boxen und pred box arrays in gleicher Reihenfolge
if (not idxs_true.size) or (not idxs_pred.size):
ious = np.array([])
else:
ious = iou_matrix[idxs_true, idxs_pred] # ious in der selben reihenfolge wie truth boxen und pred boxen im array
# remove dummy assignments
sel_pred = idxs_pred<n_pred # hat das array der neuen reihenfolge eine kleinere anzahl an elemenzen als n_pred? [True True True] für 3 elemente in reihenfolge
idx_pred_actual = idxs_pred[sel_pred] # aktuelle neue reihenfole der pred boxen speichern
print(idx_pred_actual)
idx_gt_actual = idxs_true[sel_pred] # aktuelle neue reihenfole der gt boxen speichern
print(idx_gt_actual)
ious_actual = iou_matrix[idx_gt_actual, idx_pred_actual] # aklteulle ious in array nach neuer reihenfolge gespeichter (wenn doppelte = 0)
print(ious_actual)
sel_valid = (ious_actual > IOU_THRESH) # wenn iou=0 dann false, sonst true in array
label = sel_valid.astype(int) # true = 1, false = 0
return idx_gt_actual[sel_valid], idx_pred_actual[sel_valid], ious_actual[sel_valid], label
# WRITE NEW CSV FILE WITH CALCULATED IOU ======================================
import csv
#from itertools import zip_longest
import operator
from functools import reduce
def create_new_csv(data):
with open('output.csv', 'w') as csv_file:
# Überschriften erstellen
fieldnames = ['image name', 'gt_xmin', 'gt_ymin', 'gt_xmax', 'gt_ymax',
'pred_xmin', 'pred_ymin', 'pred_max', 'pred_ymax', 'iou',
'score', 'true positive = 1, false positive = 0']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
writer = csv.writer(csv_file, delimiter=',')
#d = [data, true_positives]
#export_data = zip_longest(*d, fillvalue = '')
#writer.writerows(zip(data, true_positives))
#print(true_positives)
writer.writerows(data)
#writer.writerows(positives_data)
#writer.writerows(export_data)
#=======================================bboxes=======================================
k = 0
img_names, img_data, file_names = load_img_folder('./img/*.jpg')
data_for_csv = []
pred_boxes = []
true_positives = []
false_positives = []
while k < len(img_names):
# truth_boxes = [array([557., 505., 817., 719.]), array([ 937., 385., 1130., 555.]), array([760., 371., 931., 527.])]
truth_boxes = read_csv(str(img_names[k]))
image = img_data[k]
#image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
imH, imW, _ = image.shape
#image_expanded = np.expand_dims(image_rgb, axis=0)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis, ...]
# input_tensor = np.expand_dims(image_np, 0)
detections = detect_fn(input_tensor)
# All outputs are batches tensors.
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
# We're only interested in the first num_detections.
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
scores = detections['detection_scores']
boxes = detections['detection_boxes']
classes = detections['detection_classes']
count = 0
for i in range(len(scores)):
if ((scores[i] > MIN_CONF_THRESH) and (scores[i] <= 1.0)):
#increase count
count += 1
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = category_index[int(classes[i])]['name'] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
#cv2.rectangle(image, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
#cv2.putText(image, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
pred_box = np.array([xmin, ymin, xmax, ymax])
score = scores[i]*100
pred_boxes.append(pred_box)
for box in truth_boxes:
iou = batch_iou(box, pred_box)
if (iou > 0.5):
real_truth_box = box
minx = int(real_truth_box[0])
miny = int(real_truth_box[1])
maxx = int(real_truth_box[2])
maxy = int(real_truth_box[3])
cv2.rectangle(image, (minx,miny), (maxx,maxy), (255, 0, 0), 2)
iou = batch_iou(real_truth_box, pred_box)
print('Image:', img_names[k])
print('Predictionbox:', pred_box, ' ', 'Ground truth box:', real_truth_box, '\033[1m' +'\nIoU=', iou, '\033[0m')
data = [str(img_names[k]), minx, miny, maxx, maxy, xmin, ymin, xmax, ymax, iou, score]
data_for_csv.append(data)
#print(data_for_csv)
# [['CARDS_LIVINGROOM_H_S_frame_2149.jpg', 728, 470, 1008, 719, 738, 476, 1016, 717, 0.9085141163106419, 98.49727153778076],
# ['CARDS_LIVINGROOM_H_S_frame_2149.jpg', 674, 400, 847, 510, 674, 403, 874, 501, 0.7834629553827261, 95.0812578201294], ...
#cv2.putText(image, "IoU: {:.4f}".format(iou), (xmax, label_ymin-7),
# cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
k += 1
truth_boxes_arr = np.array(truth_boxes)
print(truth_boxes_arr)
pred_boxes_arr = np.array(pred_boxes)
print(pred_boxes_arr)
# hier kommen nur die Werte an, die true sind, also größer als 0 (außer bei Label, da sind alle drin [bsp: 1 1 0])
idx_gt_actual, idx_pred_actual, ious_actual, label = match_bboxes(truth_boxes_arr, pred_boxes_arr, IOU_THRESH=0.5)
print("2:" 'Predictionbox:', idx_pred_actual, ' ', 'Ground truth box:', idx_gt_actual, '\033[1m' +'\nIoU=', ious_actual, '\033[0m')
print("in While:", idx_pred_actual)
print(idx_gt_actual, ious_actual, label)
label_list = label.tolist()
true_positives.append(label_list)
#print(true_positives)
# if np.count_nonzero(label==0) > 0: # wenn die anzahl der nullen > als 0 sind
# zero_place = np.where(label == 0)[0] # an welchen stellen im array sind die nullen?
#
# print(zero_place)
cv2.putText (image,'Total Detections : ' + str(count),(10,25),cv2.FONT_HERSHEY_SIMPLEX,1,(70,235,52),2,cv2.LINE_AA)
print('\nDone')
pred_boxes.clear()
# display output image and destroy after 5 seconds
cv2.imshow('Object Counter', image)
cv2.waitKey(0)
cv2.destroyWindow('Object Counter')
true_positives_list = reduce(operator.concat, true_positives)
print(true_positives_list)
for o in range(len(data_for_csv)):
data_module = data_for_csv[o]
data_module.append(true_positives_list[o])
#print(data_for_csv)
create_new_csv(data_for_csv)
#label_list = label.tolist()
#true_positives.append(label_list)
#new_list = reduce(operator.concat, true_positives)
#print(new_list)
# CLOSES WINDOW ONCE KEY IS PRESSED
cv2.waitKey(0)
# CLEANUP
cv2.destroyAllWindows()
<file_sep># gesture_project
This repository shows all about my project "gesture recognition".
---
Here you can find the informations about [how to train a model with tensorflow](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md).
---
Credits:
- https://github.com/gustavz/deeptraining_hands
- https://github.com/armaanpriyadarshan/Training-a-Custom-TensorFlow-2.X-Object-Detector
- calculate IoU:
- http://ronny.rest/tutorials/module/localization_001/iou/
- https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
---
**Hand detection:**
- datasets: [Egohands](http://vision.soic.indiana.edu/projects/egohands/), [Oxford](http://www.robots.ox.ac.uk/~vgg/data/hands/)
- first try of object detection (tablets):
- [YouTube: Training a Custom Object Detector with TensorFlow 2.0 Custom Object Detection API 2020](https://www.youtube.com/watch?v=oqd54apcgGE)
- [GitHub: Training-a-Custom-TensorFlow-2.X-Object-Detector](https://github.com/armaanpriyadarshan/Training-a-Custom-TensorFlow-2.x-Object-Detector)
<file_sep># How to train hand datasets with the SSD with Mobilenet v2
- [1. File Structure](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#1-file-structure)
- [1.1 Model Folder from Tensorflow](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#11-model-folder-from-tensorflow)
- [1.2 Workspace and Scripts Folders](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#12-workspace-and-scripts-folders)
- [2. Preparing Settings](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#2-preparing-settings)
- [2.1 Software](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#21-software)
- [2.2 Preparing Files](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#22-preparing-files)
- [2.2.1 Create Label Map File](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#221-create-label-map-file)
- [2.2.2 Generate .tfrecord-File from .csv-File](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#222-generate-tfrecord-file-from-csv-file)
- [2.2.3 Change Configuration File](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#223-change-configuration-file)
- [3. Training](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#3-training)
- [3.1 Train the Model](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#31-train-the-model)
- [3.2 Monitoring realtime Training (optional)](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#32-monotoring-realtime-training-optional)
- [3.3 Exporting the Interference Graph](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#33-exporting-the-inference-graph)
- [4. Evaluation](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#4-evaluation)
- [4.1 Evaluate the Model](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#41-evaluate-the-model)
- [4.2 Monotoring realtime Evaluation (optional)](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#42-monotoring-realtime-evaluation-optional)
- [5. Testing](https://github.com/gitkatrin/gesture_project/blob/master/train_hand_datasets.md#5-testing)
# 1. File Structure
## 1.1 Model Folder from Tensorflow
```
detection_folder/
|-- models # from tensorflow https://github.com/tensorflow/models
| |-- ...
| |-- research
| | |-- ...
| | |-- object_detection
| | | |-- ...
| | | |-- configs # configurations for all TF2 models
| | | |-- ...
| | | |-- models # all usable models
| | | |-- packages # setup files for tf1 and tf2
| | | |-- predictors # all usable predictors
| | | |-- ...
| | | |-- samples # some usable configuration samples
| | | |-- ...
| | |-- ...
| | |-- model_main_tf2.py
| | |-- README.md
| | `-- setup.py
| `-- ...
```
## 1.2 Workspace and Scripts Folders
```
detection_folder/
|-- ...
|-- scripts # helpful scripts for data preparation (in this repository: https://github.com/gitkatrin/gesture_project/tree/master/scripts)
|-- workspace
| `-- training_demo
| |-- annotations
| | |-- label_map.pbtxt
| | |-- test.record
| | `-- train.record
| |-- exported-models # this is empty at the beginning of training, your new trained model will be here
| |-- images
| | |-- test
| | |-- train
| |-- models # model which you use for training
| | `-- my_ssd_mobilenet_v2_fpnlite # here where
| | `-- my_ssd_mobilenet_v2.config # copy .config from pre-trained model // This folder is empty at the beginning, later there will be the folders "eval" and "train" inside. In this folder will be the checkpoints as ".data-00000-of-00001" and ".index" format and the ".config" file. In eval and train folder will be the events in n ".v2" format.
| |-- pre-trained-models # pre-trained model which you use for training (download it here: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md)
| | `-- ssd_mobilenet_v1_fpn_640x640_coco17_tpu-8
| | |-- checkpoint
| | |-- saved_model
| | `-- pipeline.config # configuration file
| |-- exporter_main_v2.py
| |-- model_main_tf2.py
| |-- TF-image-object-counting.py
| |-- TF-image-od.py
| |-- TF-video-object-counting.py
| |-- TF-video-od.py
| `-- TF-webcam-opencv.py
`-- Training-a-Custom-TensorFlow-2.X-Object-Detector-master.zip
```
[comment]: # (---------------------------------------------------------------------------------------------------------------------------------------------------------------)
# 2. Preparing Settings
## 2.1 Software
- Tensorflow, Tensorflow-gpu
- Python 3
- [Tensorflow models](https://github.com/tensorflow/models)
- Python environement (```python3 -m venv --system-site-packages ./venv```)
- ```pip3 install protobuf```
- [scripts for data preparation](https://github.com/gitkatrin/gesture_project/tree/master/scripts)
- [Pre-trained Model](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md) (in this case: SSD MobileNet V2 FPNLite 640x640)
- Datasets: [Oxford Dataset](https://www.robots.ox.ac.uk/~vgg/data/hands/), [Egohands Dataset](http://vision.soic.indiana.edu/projects/egohands/)
## 2.2 Preparing Files
### 2.2.1 Create Label Map File
1. create a file named ```label_map.pbtxt``` in this folder: ```direction_folder/workspace/training_demo/annotations```
2. open the file and identify your items that you would like to detect. It should look like this:
```
item {
id: 1
name: 'hand'
}
item {
id: 2
name: 'face'
}
```
the file for hand detection is [here](https://github.com/gitkatrin/gesture_project/blob/master/scripts/label_map.pbtxt)
### 2.2.2 Generate .tfrecord-File from .csv-File
1. go to the research folder in models with ```cd models/reseach``` without virtual environment
2. compile the protos with:
```
protoc object_detection/protos/*.proto --python_out=.
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
sudo python3 setup.py install
```
3. open the [csv_to_tfrecord.py](https://github.com/gitkatrin/gesture_project/blob/master/scripts/csv_to_tfrecord.py) file
4. change the path directories in the main function for:
- Line 72: your image path
- Line 73: your csv path
- Line 74: your output path
- Line 75: your label map path
5. go back into the terminal and go to path ```cd workspace/training_demo```
6. run the script with ```python3 csv_to_tfrecord.py```
### 2.2.3 Change Configuration File
1. copy the configuration file ```detection_folder/workspace/training_demo/pre-trained-model/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8/pipeline.config``` to ```detection_folder/workspace/training_demo/models/my_ssd_mobilenet_v2_fpnlite``` folder
2. open the configuration file in ```detection_folder/workspace/training_demo/models/my_ssd_mobilenet_v2_fpnlite``` folder
3. do the following changes:
- Line 3: change ```num_classes``` to this value of different objects you want to detect
- Line 135: change ```batch_size``` to 4
- Line 165: change ```fine_tune_checkpoint``` to your path (```pre-trained-models/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8/checkpoint/ckpt-0```) for transfer learning
- Line 171: change ```fine_tune_checkpoint_type``` to ```detection```
- Line 175: change ```label_map_path``` to your path (```annotation/label_map.pbtxt```)
- Line 177: change ```input_path``` to your path (```annotation/train.record```)
- Line 185: change ```label_map_path``` to your path (```annotation/label_map.pbtxt```)
- Line 189: change ```input_path``` to your path (```annotation/test.record```)
(keep in mind: if you choose a different model, than the line numbers will be different)
[comment]: # (---------------------------------------------------------------------------------------------------------------------------------------------------------------)
# 3. Training
## 3.1 Train the Model
in the **virtual environment**, in file ```cd detection_folder/workspace/training_demo``` use the following command:
```
python3 model_main_tf2.py --model_dir=models/my_ssd_mobilenet_v2_fpnlite --pipeline_config_path=models/my_ssd_mobilenet_v2_fpnlite/my_ssd_mobilenet_v2.config
```
At the end the **loss should be between 0.150 and 0.200** to prevents unnderfitting and overfitting.
## 3.2 Monotoring realtime Training (optional)
It is possible to show the traning process with TensorBoard. This is optional.
in the **virtual environment**, in file ```cd detection_folder/workspace/training_demo``` use the following command:
```
tensorboard --logdir=models/my_ssd_mobilenet_v2_fpnlite
```
It should open an URL-Link to the TensorBoard Server. Open this link in your web browser and you can continuously monitor training.
## 3.3 Exporting the Inference Graph
in the **virtual environment**, in file ```cd detection_folder/workspace/training_demo``` use the following command:
```
python3 ./exporter_main_v2.py --input_type image_tensor --pipeline_config_path ./models/my_ssd_mobilenet_v2_fpnlite/my_ssd_mobilenet_v2.config --trained_checkpoint_dir ./models/my_ssd_mobilenet_v2_fpnlite/ --output_directory ./exported-models/my_mobilenet_model
```
[comment]: # (---------------------------------------------------------------------------------------------------------------------------------------------------------------)
# 4. Evaluation
## 4.1 Evaluate the Model
in the **virtual environment**, in file ```cd detection_folder/workspace/training_demo``` use the following command:
```
python3 model_main_tf2.py --pipeline_config_path models/my_ssd_mobilenet_v2_fpnlite/my_ssd_mobilenet_v2.config --model_dir models/my_ssd_mobilenet_v2_fpnlite --checkpoint_dir models/my_ssd_mobilenet_v2_fpnlite --alsologtostderr
```
## 4.2 Monotoring realtime Evaluation (optional)
It is possible to show the evaluation process with TensorBoard. This is optional.
in the **virtual environment**, in file ```cd detection_folder/workspace/training_demo``` use the following command:
```
tensorboard --logdir=models/my_ssd_mobilenet_v2_fpnlite
```
It should open an URL-Link to the TensorBoard Server. Open this link in your web browser and you can continuously monitor evaluation.
[comment]: # (---------------------------------------------------------------------------------------------------------------------------------------------------------------)
# 5. Testing
First you need to copy your ```label_map.pbtxt``` from ```cd detection_folder/workspace/training_demo/annotations``` to your ```cd detection_folder/workspace/training_demo/exported-models/my_mobilenet_model/saved_model``` folder
in the **virtual environment**, in file ```cd detection_folder/workspace/training_demo``` use the following command:
```
python3 TF-image-od.py
```
There are also some other scripts for detection with different input:
- for detecting and coundting objects on an **image**: ```python3 TF-image-object-counting.py```
- for detecting objects in a **video**: ```python3 TF-video-od.py```
- for detecting and counting objects in a **video**: ```python3 TF-video-object-counting.py```
- for detecting objects live on **webcam**: ```python3 TF-webcam-opencv.py```
- for detecting objects live on **special webcam**: ```python3 TF-webcam-OV580.py```
You can also run this script with different arguments:
```
python3 TF-image-od.py [-h] [--model MODEL] [--labels LABELS] [--image IMAGE] [--threshold THRESHOLD]
optional arguments:
-h, --help show this help message and exit
--model MODEL Folder that the Saved Model is Located In
--labels LABELS Where the Labelmap is Located
--image IMAGE Name of the single image to perform detection on
--threshold THRESHOLD Minimum confidence threshold for displaying detected objects
```
| 792e1dcc95a5b834a18495a80932661e2a3fa1b6 | [
"Markdown",
"Python"
] | 6 | Markdown | neToX-live/gesture_project | 1be2a47d58e8511e4d92f7434e60922ff97ba4d4 | 4b34df2441218dd924dfa8973cc7a3f38ff6c841 | |
refs/heads/master | <repo_name>meowskers/BeirRun-1<file_sep>/BeirRun/Scenes/MenuScene.swift
//
// GGScene.swift
// BeirRun
//
// Created by <NAME> on 9/27/19.
// Copyright © 2019 BeirRunRCOS. All rights reserved.
//
import SpriteKit
class MenuScene: SKScene {
var menu: UILabel?
var playAgain = UIButton.init(type: .roundedRect)
override func didMove(to view: SKView) {
if view == self.view {
let background = SKSpriteNode()
background.color = .yellow
background.size = CGSize(width: (frame.width), height: (frame.height))
background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
addChild(background)
background.zPosition = -10000
playAgain.frame = CGRect(x: frame.width / 2 - 50, y: frame.height / 4, width: 100, height: 100)
playAgain.setImage(UIImage(named: "beer")?.withRenderingMode(.alwaysOriginal), for: .normal)
playAgain.setImage(UIImage(named: "jSubstrate")?.withRenderingMode(.alwaysOriginal), for: .highlighted)
playAgain.addTarget(self, action: #selector(MenuScene.buttonAction(_:)), for: .touchUpInside)
view.addSubview(playAgain)
menu = UILabel()
menu?.text = " MENU "
menu?.font = UIFont.boldSystemFont(ofSize:100)
//gameOver?.frame.size.width = 0
menu?.lineBreakMode = .byClipping
menu?.sizeToFit()
menu?.center = CGPoint(x: frame.width/2, y: frame.height/2)
view.addSubview(menu!)
}
}
@objc func buttonAction(_ sender:UIButton!)
{
let newGame = GameScene(size: self.size)
menu?.removeFromSuperview()
playAgain.removeFromSuperview()
let gameTrans = SKTransition.moveIn(with: .right, duration: 0.5)
playAgain.removeFromSuperview()
self.view?.presentScene(newGame, transition: gameTrans)
}
}
<file_sep>/BeirRun/ViewController/GGViewController.swift
//
// GGViewController.swift
// BeirRun
//
// Created by <NAME> on 9/27/19.
// Copyright © 2019 BeirRunRCOS. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GGViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
}
}
}
<file_sep>/BeirRun/Scenes/GameScene.swift
//
// GameScene.swift
//
// Created by <NAME> on 28.09.14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let setJoystickStickImageBtn = SKLabelNode()
let setJoystickSubstrateImageBtn = SKLabelNode()
let app: AppDelegate = UIApplication.shared.delegate as! AppDelegate
//var drinkCount: Int = 0
var player: SKSpriteNode?
var drink: SKSpriteNode?
var tableL: SKSpriteNode?
var tableR: SKSpriteNode?
var timerFill: SKSpriteNode?
var timerSubstrate: SKSpriteNode?
var drinkHitbox: CGRect?
var labelBox: CGRect?
var countLabel: UILabel?
var timeLabel: UILabel?
var timer = 6.0
var sTime = Timer()
let substrateImage = UIImage(named: "timerSubstrate")
let fillImage = UIImage(named: "timerFill")
let moveJoystick = 🕹(withDiameter: 100)
let rotateJoystick = TLAnalogJoystick(withDiameter: 100)
var isContact = 0
var fillWidth = CGFloat(0)
//var highScore = UserDefaults.init(suiteName: "HIGH SCORE")
var prevBeerX = CGFloat(0)
var prevBeerY = CGFloat(0)
var joystickStickImageEnabled = true {
didSet {
let image = joystickStickImageEnabled ? UIImage(named: "jStick-1") : nil
moveJoystick.handleImage = image
rotateJoystick.handleImage = image
}
}
var joystickSubstrateImageEnabled = true {
didSet {
let image = joystickSubstrateImageEnabled ? UIImage(named: "jSubstrate-1") : nil
moveJoystick.baseImage = image
rotateJoystick.baseImage = image
}
}
override func didMove(to view: SKView) {
/* Setup your scene here */
let background = SKSpriteNode(imageNamed: "Artboard 1")
background.size = CGSize(width: (frame.width), height: (frame.height))
background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
addChild(background)
background.zPosition = -10000
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
physicsWorld.contactDelegate = self
prevBeerX = frame.width / 2
prevBeerY = frame.height / 2
// physicsBody?.usesPreciseCollisionDetection = true
//Set UP
setupJoystick()
setUpTables()
setUpTimer()
setUpCount()
placeFirstDrink()
//MARK: Handlers begin
moveJoystick.on(.move) { [unowned self] joystick in
guard let player = self.player else {
return
}
let pVelocity = joystick.velocity;
var speed = CGFloat(0.1)
/*
var min1 : CGFloat = 0.0
var max1 : CGFloat = 0.0
if (self.drinkCount != 0) {
min1 = (.pi/(100.0/CGFloat(self.drinkCount)))
max1 = (.pi/(100.0/CGFloat(self.drinkCount)))
}
let newMin = joystick.angular - (min1)
let newMax = joystick.angular + (max1)
var aVelocity = CGFloat.random(in: newMin...newMax)
*/
var aVelocity = joystick.angular
if self.sTime.isValid == false {
speed = 0.0
aVelocity = 0.0
}
player.position = CGPoint(x: player.position.x + (pVelocity.x * speed), y: player.position.y + (pVelocity.y * speed))
player.run(SKAction.rotate(toAngle: (aVelocity + .pi / 2 ), duration: 0.01, shortestUnitArc: true))
}
view.isMultipleTouchEnabled = true
setupPlayer(CGPoint(x: frame.midX, y: frame.midY))
}
func placeFirstDrink() {
guard let drinkImage = UIImage(named: "beer") else {
return
}
let texture = SKTexture(image: drinkImage)
let d = SKSpriteNode(texture: texture)
/*
let posX = CGFloat.random(in: 100...(frame.width - 100))
let posY = CGFloat.random(in: 100...(frame.height - 100))
d.position = CGPoint(x: posX, y: posY)
*/
let posX = CGFloat.random(in: 100...(frame.width - 100))
let posY = CGFloat.random(in: 50...(frame.height - 50))
d.position = CGPoint(x: posX, y: posY)
d.size = CGSize(width: (43), height: (47))
d.physicsBody = SKPhysicsBody(texture: texture, size: d.size)
d.physicsBody!.affectedByGravity = false
d.name = "drink"
d.zPosition = -2
//d.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
addChild(d)
drink = d
}
func setupJoystick() {
joystickStickImageEnabled = true
joystickSubstrateImageEnabled = true
//only allows user to control joystick from left side of screen
let moveJoystickHiddenArea = TLAnalogJoystickHiddenArea(rect: CGRect(x: 0, y: 0, width: frame.midX, height: frame.height))
moveJoystickHiddenArea.joystick = moveJoystick
moveJoystick.isMoveable = true
moveJoystickHiddenArea.strokeColor = SKColor.clear
addChild(moveJoystickHiddenArea)
}
func setupPlayer(_ position: CGPoint) {
guard let playerImage = UIImage(named: "guy") else {
return
}
let texture = SKTexture(image: playerImage)
let p = SKSpriteNode(texture: texture)
p.size = CGSize(width: 48, height: 62)
p.physicsBody = SKPhysicsBody(texture: texture, size: p.size)
p.physicsBody!.affectedByGravity = false
p.physicsBody?.contactTestBitMask = drink!.physicsBody!.collisionBitMask
p.name = "player"
p.position = position
p.zPosition = -1
addChild(p)
player = p
}
func setUpTimer() {
let subTexture = SKTexture(image: substrateImage!)
let fillTexture = SKTexture(image: fillImage!)
let substrate = SKSpriteNode(texture: subTexture)
let fill = SKSpriteNode(texture: fillTexture)
fill.size = CGSize(width: fillImage!.size.width / 2, height: fillImage!.size.height / 2)
substrate.size = CGSize(width: substrateImage!.size.width / 2, height: substrateImage!.size.height / 2)
fillWidth = fillImage!.size.width
fill.zPosition = 2
substrate.zPosition = 1
substrate.position = CGPoint(x: (frame.width - (frame.width / 3)), y: frame.height - 40)
fill.position = CGPoint(x: (frame.width - (frame.width / 3)), y: frame.height - 40)
addChild(substrate)
addChild(fill)
timerSubstrate = substrate
timerFill = fill
timerFill?.run(SKAction.resize(toWidth: 0.0, duration: 6.0))
timerFill?.run(SKAction.moveTo(x: timerFill!.position.x - (timerFill!.size.width / 2), duration: 6))
sTime = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(displayTimer), userInfo: nil, repeats: true)
}
/*
timeLabel = UILabel()
timeLabel?.text = " \(timer) "
timeLabel?.textColor = .white
timeLabel?.font = UIFont.boldSystemFont(ofSize:36)
timeLabel?.frame.size.width = 0
timeLabel?.lineBreakMode = .byClipping
timeLabel?.sizeToFit()
timeLabel?.center = CGPoint(x: frame.width/4, y: 50)
view.addSubview(timeLabel!)
*/
func setUpTables() {
guard let tableImage = UIImage(named: "jSubstrate") else {
return
}
let texture = SKTexture(image: tableImage)
let tr = SKSpriteNode(texture: texture)
let tl = SKSpriteNode(texture: texture)
tr.size = tableImage.size
tl.size = tableImage.size
tr.physicsBody = SKPhysicsBody(texture: texture, size: tr.size)
tl.physicsBody = SKPhysicsBody(texture: texture, size: tl.size)
tr.physicsBody!.affectedByGravity = false
tl.physicsBody!.affectedByGravity = false
tr.physicsBody!.isDynamic = false
tl.physicsBody!.isDynamic = false
tr.name = "table"
tl.name = "table"
let Lx = CGFloat.random(in: 100...((frame.width / 2) - 50))
let Ly = CGFloat.random(in: 100...(frame.height - 100))
let midx = ( frame.width / 2 )
let Rx = CGFloat.random(in: midx...(frame.width - 100))
let Ry = CGFloat.random(in: 100...(frame.height - 100))
tr.position = CGPoint(x: Rx, y: Ry)
tl.position = CGPoint(x: Lx, y: Ly)
tr.zPosition = -1
tl.zPosition = -1
addChild(tr)
addChild(tl)
}
@objc func displayTimer() {
if view == self.view {
// Load the SKScene from 'GameScene.sks'
if timer > 0 {
let y = Double(round(timer*1000)/1000)
timeLabel?.text = " \(y) "
timer -= 0.1
}
else {
timeLabel?.text = " 0.0 "
if sTime.isValid == true {
sTime.invalidate()
}
player!.physicsBody?.isDynamic = false
drink!.removeFromParent()
endGame()
}
}
}
func setUpCount() {
if let view = self.view {
// Load the SKScene from 'GameScene.sks'
countLabel = UILabel()
countLabel?.text = " \(app.drinkCount) "
countLabel?.textColor = .green
countLabel?.font = UIFont.boldSystemFont(ofSize:36)
// countLabel?.frame.size.width = 0
countLabel?.lineBreakMode = .byClipping
countLabel?.sizeToFit()
countLabel?.center = CGPoint(x: frame.width - timerSubstrate!.position.x - 50, y: frame.height - timerSubstrate!.position.y)
view.addSubview(countLabel!)
}
}
func placeDrink() {
drink?.removeFromParent()
guard let drinkImage = UIImage(named: "beer") else {
return
}
let texture = SKTexture(image: drinkImage)
let d = SKSpriteNode(texture: texture)
var xLower = player!.position.x - 50
var xUpper = player!.position.x + 50
var yLower = player!.position.y - 50
var yUpper = player!.position.y + 50
if (xLower < 0) {
xLower = 50
}
if (xUpper > (frame.width - 50)) {
xUpper = frame.width - 50
}
if (yLower < 0) {
yLower = 50
}
if (yUpper > (frame.height - 50)) {
yUpper = frame.height - 50
}
let rect = CGRect(x: xLower, y: yLower, width: xUpper, height: yUpper)
var pos = CGPoint(x: 0, y: 0)
repeat {
let posX = CGFloat.random(in: 100...(frame.width - 100))
let posY = CGFloat.random(in: 100...(frame.height - 100))
pos = CGPoint(x: posX, y: posY)
}
while (rect.contains(pos))
d.position = pos
d.size = CGSize(width: (43), height: (47))
d.physicsBody = SKPhysicsBody(texture: texture, size: d.size)
d.physicsBody!.affectedByGravity = false
d.name = "drink"
d.zPosition = -2
//d.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
addChild(d)
drink = d
//prevent = 0
//drinkHitbox = CGRect(x: posX, y: posY, width: 43, height: 47)
}
func endGame() {
//let newScene = GGScene(fileNamed: "GGScene.swift")!
moveJoystick.stop()
player?.removeFromParent()
timeLabel?.removeFromSuperview()
countLabel?.removeFromSuperview()
tableL?.removeFromParent()
tableR?.removeFromParent()
timerSubstrate?.removeFromParent()
timerFill?.removeFromParent()
let ggScene = GGScene(size: self.size)
let GGTrans = SKTransition.moveIn(with: .right, duration: 0.5)
self.view?.presentScene(ggScene, transition: GGTrans)
// self.view?.presentScene(gameOverScene, transition: reveal)
/*
gameOver = UILabel()
gameOver?.text = " GAME OVER "
gameOver?.font = UIFont.boldSystemFont(ofSize:100)
//gameOver?.frame.size.width = 0
gameOver?.lineBreakMode = .byClipping
gameOver?.sizeToFit()
gameOver?.center = CGPoint(x: frame.width/2, y: frame.height/2)
view?.addSubview(gameOver!)
*/
}
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.node?.name == "drink" {
isContact = 1
drink!.removeFromParent()
placeDrink()
if timer > 0 {
timer = 6 - Double(app.drinkCount)*(0.1)
timerFill?.removeAllActions()
timerFill?.run(SKAction.resize(toWidth: fillWidth / 2, duration: 0.0))
timerFill?.run(SKAction.moveTo(x: timerSubstrate!.position.x, duration: 0.0))
timerFill?.run(SKAction.resize(toWidth: 0, duration: timer))
timerFill?.run(SKAction.moveTo(x: timerSubstrate!.position.x - (fillWidth / 4), duration: timer))
}
}
}
func getDrinkCount() -> Int {
return (app.drinkCount)
}
override func update(_ currentTime: TimeInterval) {
/* Called before each frame is rendered */
if isContact == 1 {
app.drinkCount += 1
if self.view != nil {
let num = String(app.drinkCount)
countLabel?.text = " " + num + " "
}
isContact = 0
}
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1)
}
}
| 21ed709d8fad0dfa933409684307a43b0ba12535 | [
"Swift"
] | 3 | Swift | meowskers/BeirRun-1 | eb09f1bd3da17d0df932d9a2f41adfc6e76773e8 | cb41714bc80eefedcb9fac8e96c7bbcec30e32b0 | |
refs/heads/main | <repo_name>al7r0/M5StickPlusClock<file_sep>/ClockM5Stick/ClockM5Stick.ino
#include "M5StickCPlus.h"
#include "AXP192.h"
#include "7seg70.h"
#include "ani.h"
#define grey 0x65DB
RTC_TimeTypeDef RTC_TimeStruct;
RTC_DateTypeDef RTC_DateStruct;
int bright[4]={8,9,10,12};
void setup() {
pinMode(39,INPUT_PULLUP);
pinMode(37,INPUT_PULLUP);
M5.begin();
M5.Lcd.setRotation(3);
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setSwapBytes(true);
M5.Lcd.setTextSize(1);
M5.Lcd.setTextColor(TFT_WHITE,TFT_BLACK);
//M5.Lcd.setTextColor(grey,TFT_BLACK);
//M5.Lcd.fillRect(112,12,40,40,TFT_RED);
// M5.Lcd.pushImage(112,12,40,40,ani[frame]);
M5.Axp.EnableCoulombcounter();
M5.Axp.ScreenBreath(bright[0]);
RTC_TimeTypeDef TimeStruct;
TimeStruct.Hours = 19;
TimeStruct.Minutes = 10;
TimeStruct.Seconds = 0;
// M5.Rtc.SetTime(&TimeStruct);
RTC_DateTypeDef DateStruct;
DateStruct.WeekDay = 4;
DateStruct.Month = 1;
DateStruct.Date = 7;
DateStruct.Year = 2021;
//M5.Rtc.SetData(&DateStruct);
}
int H=0;
int M=0;
String ho="";
String mi="";
String se="";
String days[7]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
int c=0;
int pres=0;
bool spavanje=0;
bool inv=0;
int frame=0;
void loop() {
spavanje=0;
if(digitalRead(37)==0)
{
if(pres==0)
{
pres=1;
c++;
if(c>3)
c=0;
M5.Axp.ScreenBreath(bright[c]);
}
}else{pres=0;}
M5.Rtc.GetTime(&RTC_TimeStruct);
M5.Rtc.GetData(&RTC_DateStruct);
M5.Lcd.setCursor(0, 15);
M5.Lcd.setTextFont(0);
M5.Lcd.drawString(String( M5.Axp.GetBatVoltage())+" V ",114,3);
M5.Lcd.setFreeFont(&DSEG7_Classic_Regular_64 );
if(H!=int(RTC_TimeStruct.Hours) || M!=int(RTC_TimeStruct.Minutes)){
ho=String(RTC_TimeStruct.Hours);
if(ho.length()<2)
ho="0"+ho;
mi=String(RTC_TimeStruct.Minutes);
if(mi.length()<2)
mi="0"+mi;
M5.Lcd.drawString(ho+":"+mi,2,56);
H=int(RTC_TimeStruct.Hours);
M=int(RTC_TimeStruct.Minutes);
}
// M5.Lcd.printf("Week: %d\n",RTC_DateStruct.WeekDay);
se=String(RTC_TimeStruct.Seconds);
if(se.length()<2)
se="0"+se;
M5.Lcd.drawString(se,180,0,4);
M5.Lcd.drawString(days[RTC_DateStruct.WeekDay-1]+" ",4,0,2);
M5.Lcd.setTextColor(grey,TFT_BLACK);
M5.Lcd.drawString(String(RTC_DateStruct.Date)+"/"+String(RTC_DateStruct.Month),4,20,4);
M5.Lcd.drawString(String(RTC_DateStruct.Year),70,28,2);
M5.Lcd.setTextColor(TFT_WHITE,TFT_BLACK);
if(digitalRead(39)==LOW){
while(digitalRead(39)==LOW);
M5.Lcd.invertDisplay(inv);
inv=!inv;
}
M5.Lcd.pushImage(112,12,40,40,ani[frame]);
frame++;
if(frame==132)
frame=0;
delay(12);
}
| 511089ccdbfc08d6962f91ed0e044ff2b741af1c | [
"C++"
] | 1 | C++ | al7r0/M5StickPlusClock | f38603a67053d09331d8dfbfc51d284627c76628 | 17846242fd34661508221bba77fbb0f478e5c7c6 | |
refs/heads/main | <repo_name>szmass/bash_aliases<file_sep>/.bash_aliases
function dnames-fn {
for ID in `docker ps | awk '{print $1}' | grep -v 'CONTAINER'`
do
docker inspect $ID | grep Name | head -1 | awk '{print $2}' | sed 's/,//g' | sed 's%/%%g' | sed 's/"//g'
done
}
function dip-fn {
echo "IP addresses of all named running containers"
for DOC in `dnames-fn`
do
IP=`docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' "$DOC"`
OUT+=$DOC'\t'$IP'\n'
done
echo -e $OUT | column -t
unset OUT
}
function dex-fn {
docker exec -it $1 ${2:-bash}
}
function di-fn {
docker inspect $1
}
function dl-fn {
docker logs -f $1
}
function drun-fn {
docker run -it $1 $2
}
function dcr-fn {
docker-compose run --rm $@
}
function dsr-fn {
docker stop $1;docker rm $1
}
function drmc-fn {
docker rm $(docker ps --all -q -f status=exited)
}
function drmid-fn {
imgs=$(docker images -q -f dangling=true)
[ ! -z "$imgs" ] && docker rmi "$imgs" || echo "no dangling images."
}
# in order to do things like dex $(dlab label) sh
function dlab {
docker ps --filter="label=$1" --format="{{.ID}}"
}
function dc-fn {
docker-compose $*
}
function d-aws-cli-fn {
docker run \
-e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
-e AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION \
-e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
amazon/aws-cli:latest $1 $2 $3
}
function kill-port {
PS3='Please enter your choice: '
options=$(lsof -PiTCP -sTCP:LISTEN | awk '{print $9}' | sed -n '1!p')
RED='\033[0;31m'
NC='\033[0m' # No Color
select port in $options
do
echo "Selected character: $port"
echo "Selected number: $REPLY"
var2=$(echo $port | cut -f2 -d:)
echo -e "killing ${RED}port $var2 ${NC}!"
echo $(lsof -ti tcp:$var2 | xargs kill)
exit 0
done
}
alias daws=d-aws-cli-fn
alias dc=dc-fn
alias dcu="docker-compose up -d"
alias dcd="docker-compose down"
alias dcr=dcr-fn
alias dex=dex-fn
alias dcl="docker-compose logs -f"
alias dclt="docker-compose logs -f --tail 300"
alias di=di-fn
alias dim="docker images"
alias dip=dip-fn
alias dl=dl-fn
alias dnames=dnames-fn
alias dps="docker ps"
alias dpsa="docker ps -a"
alias drmc=drmc-fn
alias drmid=drmid-fn
alias drun=drun-fn
alias dsp="docker system prune --all"
alias dsr=dsr-fn
alias sai='sudo apt install'
alias sau='sudo apt update'
alias saug='sudo apt upgrade'
alias sar='sudo apt remove'
alias ..='cd ..'
alias ...='cd ../..'
alias .3='cd ../../..'
alias .4='cd ../../../..'
alias .5='cd ../../../../..'
alias ls='exa -al --color=always --group-directories-first'
alias la='exa -a --color=always --group-directories-first'
alias ll='exa -l --color=always --group-directories-first'
alias l.='exa -a | egrep "^\."'
alias grep='grep --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias cp="cp -i"
alias df="df -h"
alias nf='neofetch'
alias sail="bash vendor/bin/sail"
alias cz="npx cz"
alias czr="npx cz --retry"
alias n="npm"
alias nr="npm run"
alias g="git"
alias gp="git push"
alias gpf="git push -f"
alias gl="git pull"
alias gf="git fetch --all"
alias gc="git checkout"
alias gcf="git checkout -f"
alias gb="git branch"
alias gbr="git branch --remote"
alias gd="git branch -d"
alias gsub="git submodule"
alias gsubinit="git submodule update --init --recursive"
alias giff="git diff"
alias gog="git log"
alias kport=kill-port
alias ve='python3 -m venv ./venv'
alias va='source ./venv/bin/activate'
| 26b6416b1ab5cd17003f82c312315147303aa905 | [
"Shell"
] | 1 | Shell | szmass/bash_aliases | d4dbc7e9d9de081b76ec83d39a5d54f2e549b542 | 4bf9af86c4171607e67f8834bffdaa05bc112723 | |
refs/heads/master | <repo_name>tarangparikh/GeeksForGeeks<file_sep>/src/CountDistinctElementsInEveryWindow.java
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
public class CountDistinctElementsInEveryWindow {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
String solve(int[] data,int k,int n){
int[] hash = new int[100005];
StringBuilder sb = new StringBuilder();
int distinct = 0;
for(int i = 0;i<k;i++){
if(hash[data[i]]++==0) distinct++;
//sb.append(distinct+" "+i).append("\n");
}
sb.append(distinct).append(" ");
for(int i = k,h=data.length;i<h;i++){
if(hash[data[i-k]]--==1) distinct--;
if(hash[data[i]]++==0) distinct++;
sb.append(distinct).append(" ");
}
return sb.toString().trim();
}
void run() throws IOException {
int t = getInt();
while (t-->0){
int[] c = ints(2);
int[] data = ints(c[0]);
sb.append(solve(data,c[1],c[0])).append("\n");
}
writer.println(sb.toString().trim());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
CountDistinctElementsInEveryWindow object;
if (local_system) object = new CountDistinctElementsInEveryWindow(new FileInputStream("input"), System.out);
else object = new CountDistinctElementsInEveryWindow(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public CountDistinctElementsInEveryWindow(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/ds/ST.java
package ds;
public class ST {
private int[] t;
public ST(int size){
this.t = new int[size<<1];
}
public void add(int i,int value){
i += t.length / 2;
t[i] += value;
for (; i > 1; i >>= 1)
t[i >> 1] = Math.min(t[i], t[i ^ 1]);
}
public int get(int i) {
return t[i + t.length / 2];
}
public int min(int a, int b) {
int res = Integer.MIN_VALUE;
for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) {
if ((a & 1) != 0)
res = Math.min(res, t[a]);
if ((b & 1) == 0)
res = Math.min(res, t[b]);
}
return res;
}
}
<file_sep>/src/Trie.java
import java.io.*;
import java.util.Arrays;
public class Trie {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
class TRIE {
private final int SIZE = 26;
private class Node{
Node[] children;
boolean isEnd;
Node(){
this.children = new TRIE.Node[SIZE];
Arrays.fill(this.children,null);
isEnd = false;
}
}
private Node root;
TRIE(){
root = new Node();
}
void insert(String data){
Node curr = this.root;
for(int i = 0,h=data.length();i<h;i++){
int index = data.charAt(i) - 'a';
if(curr.children[index]==null) curr.children[index] = new TRIE.Node();
curr = curr.children[index];
}
curr.isEnd = true;
}
boolean contains(String data){
Node curr = this.root;
for(int i = 0,h=data.length();i<h;i++){
int index = data.charAt(i) - 'a';
if(curr.children[index]==null) return false;
curr = curr.children[index];
}
return curr.isEnd;
}
}
int solve(String data,String search){
TRIE trie = new TRIE();
String[] tokens = data.split(" ");
Arrays.stream(tokens).forEach(trie::insert);
return trie.contains(search) ? 1 : 0;
}
void run() throws IOException {
int t = getInt();
while (t-->0){
getInt();
String data = bf.readLine().trim();
String search = bf.readLine().trim();
sb.append(solve(data,search)).append("\n");
}
writer.println(sb.toString().trim());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
Trie object;
if (local_system) object = new Trie(new FileInputStream("input"), System.out);
else object = new Trie(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public Trie(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/MaximumCircularArraySum.java
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
public class MaximumCircularArraySum {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
int solve(int[] data){
int[] ddata = new int[(data.length<<1) + 1];
int len = data.length;
System.arraycopy(data,0,ddata,1,data.length);
System.arraycopy(data,0,ddata,data.length+1,data.length);
for(int i = 1,h=ddata.length;i<h;i++) ddata[i] += ddata[i - 1];
//sb.append(Arrays.toString(ddata)).append("\n");
ArrayDeque<Integer> deque = new ArrayDeque<>();
for(int i = 1,h=data.length+1;i<h;i++){
if (!deque.isEmpty()) while (!deque.isEmpty() && ddata[deque.peekFirst()] <= ddata[i]) deque.pollFirst();
deque.addFirst(i);
}
//sb.append(deque).append("\n");
int sum = data[0];
for(int i = 0,h=data.length;i<h;i++){
int max = ddata[deque.peekLast()];
//sb.append(i).append(" ").append(max).append(" ").append(deque.peekLast()).append("\n");
sum = Math.max(sum,max-ddata[i]);
while (!deque.isEmpty()&&deque.peekLast()<=i+1) deque.pollLast();
while (!deque.isEmpty()&&ddata[deque.peekFirst()]<=ddata[i+len+1]) deque.pollFirst();
deque.addFirst(i+len+1);
}
return sum;
}
void run() throws IOException {
int t = getInt();
while (t-->0){
sb.append(solve(ints(getInt()))).append("\n");
}
writer.println(sb.toString().trim());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
MaximumCircularArraySum object;
if (local_system) object = new MaximumCircularArraySum(new FileInputStream("input"), System.out);
else object = new MaximumCircularArraySum(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public MaximumCircularArraySum(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/CircularTour.java
import java.io.*;
import java.util.Arrays;
public class CircularTour {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
int solve(int[] petrol,int[] distance){
int n = petrol.length;
int[] prefix = new int[(n<<1)];
for(int i = 0;i<n;i++){
prefix[i] = petrol[i] - distance[i];
prefix[i+n] = prefix[i];
}
int sum = 0;
int index = -1;
int len = 0;
for(int i = 0,h=prefix.length;i<h;i++){
if(index > n-1){
index = -1;
break;
}
if(index == -1){
if(sum + prefix[i] > 0){
index = i;
sum+=prefix[i];
len+=1;
}
}else{
if(len==n) break;
sum+=prefix[i];
if(sum < 0){
index = -1;
sum = 0;
}
}
}
return index;
}
void run() throws IOException {
int t = getInt();
while (t-->0){
int n = getInt();
int[] data = ints(n<<1);
int[] petrol = new int[n];
int[] distance = new int[n];
for(int i = 0;i<n;i++){
petrol[i] = data[i*2];
distance[i] = data[i*2 + 1];
}
System.out.println(Arrays.toString(petrol)+"\n"+ Arrays.toString(distance));
sb.append(solve(petrol,distance)).append("\n");
}
writer.println(sb.toString());
}
public static void main(String... args) throws IOException {
long start_time = System.currentTimeMillis();
CircularTour object;
if (local_system)
object = new CircularTour(Thread.currentThread().getContextClassLoader().getResourceAsStream("input"), System.out);
else object = new CircularTour(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public CircularTour(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/OccurencesOf2AsAdigit.java
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
public class OccurencesOf2AsAdigit {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
void run() throws IOException {
int[] data = new int[100005];
for(int i = 1;i<data.length;i++){
data[i] = data[i-1] + count(i);
}
int t = getInt();
while (t-->0){
sb.append(data[getInt()]).append("\n");
}
writer.println(sb.toString().trim());
}
int count(int n){
int count = 0;
while (n>0){
int crr = n%10;
count = crr == 2 ? count + 1 : count;
n/=10;
}
return count;
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
OccurencesOf2AsAdigit object;
if (local_system) object = new OccurencesOf2AsAdigit(new FileInputStream("input"), System.out);
else object = new OccurencesOf2AsAdigit(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public OccurencesOf2AsAdigit(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/SortingElementsOfAnArrayByFrequency.java
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
public class SortingElementsOfAnArrayByFrequency {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
String sort(int[] data){
int[][] hash = new int[11][2];
for(int i = 0,h=data.length;i<h;i++){
hash[data[i]][0] = data[i];
hash[data[i]][1]++;
}
StringBuilder ssb = new StringBuilder();
Arrays.sort(hash,(o1, o2) -> {
if(o1[1]!=o2[1]) return Integer.compare(o2[1],o1[1]);
return Integer.compare(o1[0],o2[0]);
});
//System.out.println(Arrays.deepToString(hash));
for(int i = 0,h=hash.length;i<h;i++){
if(hash[i][1]!=0)
for(int j = 0,v=hash[i][1];j<v;j++){
ssb.append(hash[i][0]).append(" ");
}
}
return ssb.toString().trim();
}
void run() throws IOException {
int t = getInt();
while (t-->0){
sb.append(sort(ints(getInt()))).append("\n");
}
writer.println(sb.toString().trim());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
SortingElementsOfAnArrayByFrequency object;
if (local_system) object = new SortingElementsOfAnArrayByFrequency(new FileInputStream("input"), System.out);
else object = new SortingElementsOfAnArrayByFrequency(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public SortingElementsOfAnArrayByFrequency(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/IsBinaryNumberMultipleOf3.java
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
public class IsBinaryNumberMultipleOf3 {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
void run() throws IOException {
int[][] state = new int[][]{{0,1},{2,0},{1,2}};
int t = getInt();
while (t-->0){
String data = bf.readLine().trim();
int curr = 0;
for(int i = 0,h=data.length();i<h;i++){
curr = state[curr][data.charAt(i) - '0'];
//System.out.println(curr);
}
sb.append(curr == 0 ? 1 : 0).append("\n");
}
writer.println(sb.toString().trim());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
IsBinaryNumberMultipleOf3 object;
if (local_system) object = new IsBinaryNumberMultipleOf3(new FileInputStream("input"), System.out);
else object = new IsBinaryNumberMultipleOf3(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public IsBinaryNumberMultipleOf3(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/MergeKSortedLinkedLists.java
import java.util.Arrays;
class List{
private class Node{
Integer data;
Node next;
Node(){
this.data = null;
this.next = null;
}
}
private Node last;
private Node head;
List(){
this.head = new Node();
this.last = this.head;
}
boolean isEmpty(){
return this.head.data == null;
}
void add(int data){
if (this.last.data != null) {
this.last.next = new Node();
this.last = this.last.next;
}
this.last.data = data;
}
public static List merge(List[] data){
return merge(data,0,data.length-1);
}
public static List merge(List[] data,int start,int end){
if(start == end) return data[start];
int mid = (start + end) / 2;
List p1 = merge(data,start,mid);
List p2 = merge(data,mid+1,end);
return merge(p1,p2);
}
public static List merge(List aa,List bb){
Node a = aa.head;
Node b = bb.head;
Node temp = null;
Node head = null;
while (a!=null&&b!=null&&a.data!=null&&b.data!=null){
if(a.data<=b.data){
if(temp == null){
temp = a;
head = temp;
}else {
temp.next = a;
temp = temp.next;
}
a = a.next;
}else{
if(temp == null){
temp = b;
head = temp;
}else {
temp.next = b;
temp = temp.next;
}
b = b.next;
}
}
while (a!=null&&a.data!=null){
if(temp == null){
temp = a;
head = temp;
}else {
temp.next = b;
temp = temp.next;
}
a = a.next;
}
while (b!=null&&b.data!=null){
if(temp == null){
temp = b;
head = temp;
}else {
temp.next = b;
temp = temp.next;
}
b = b.next;
}
if(head == null){
head = a;
}
List send = new List();
send.head = head;
return send;
}
public void addAll(int[] data){
Arrays.stream(data).forEach(this::add);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
Node temp = this.head;
while (temp!=null&&temp.data!=null&&temp.next!=null){
sb.append(temp.data);
sb.append(" ");
temp = temp.next;
}
if(temp.next==null){
sb.append(temp.data);
}
sb.append("]");
return sb.toString();
}
}
public class MergeKSortedLinkedLists {
public static void run(){
List[] lists = new List[4];
for(int i = 0,h=lists.length;i<h;i++){
lists[i] = new List();
}
lists[0].addAll(new int[]{1,2,3});
lists[1].addAll(new int[]{4,5});
lists[2].addAll(new int[]{5,6});
lists[3].addAll(new int[]{6,7});
System.out.println(List.merge(lists));
}
}
<file_sep>/src/LongestConsecutiveSubsequence.java
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
public class LongestConsecutiveSubsequence {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
int solve(int[] data){
Arrays.sort(data);
int mlen = 1;
int clen = 1;
int prev = data[0];
//sb.append(Arrays.toString(data)).append("\n");
for(int i = 1 , h = data.length ;i<h;i++ ){
if(prev==data[i]) continue;
if(prev == data[i]-1){
clen++;
mlen = Math.max(mlen,clen);
}else{
clen = 1;
}
prev = data[i];
}
return mlen;
}
int[] scaleLength(int[] data){
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i = 0,h=data.length;i<h;i++){
max = Math.max(max,data[i]);
min = Math.min(min,data[i]);
}
return new int[]{max,min};
}
int solve1(int[] data){
int[] mm = scaleLength(data);
int scale = mm[1];
int[] hash = new int[mm[0] - mm[1] + 1];
int len = data.length;
for (int i = 0; i < len; i++) {
int datum = data[i];
hash[datum - scale]++;
}
int clen = 0;
int mlen = 0;
for(int h = hash.length,i=0;i<h;i++){
if(hash[i]>0){
clen++;
mlen = Math.max(mlen,clen);
}else{
clen = 0;
}
}
return mlen;
}
int solve2(int[] data,int n){
int[] hash = new int[100005];
int hash_len = 100005;
for(int i = 0;i<n;i++) hash[data[i]] = 1;
int mlen = 0;
int clen = 0;
for(int i = 0;i<hash_len;i++){
if(hash[i]==1){
clen++;
mlen = clen > mlen ? clen : mlen;
}else clen = 0;
}
return mlen;
}
void run() throws IOException {
int t = getInt();
while (t-->0){
int s = getInt();
int d[] = ints(s);
sb.append(solve2(d,s)).append("\n");
}
writer.println(sb.toString().trim());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
LongestConsecutiveSubsequence object;
if (local_system) object = new LongestConsecutiveSubsequence(new FileInputStream("input"), System.out);
else object = new LongestConsecutiveSubsequence(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public LongestConsecutiveSubsequence(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
<file_sep>/src/ds/TRIE.java
package ds;
import java.util.Arrays;
public class TRIE {
private final int SIZE = 26;
private class Node{
Node[] children;
boolean isEnd;
Node(){
this.children = new Node[SIZE];
Arrays.fill(this.children,null);
isEnd = false;
}
}
private Node root;
TRIE(){
root = new Node();
}
void insert(String data){
Node curr = this.root;
for(int i = 0,h=data.length();i<h;i++){
int index = data.charAt(i) - 'a';
if(curr.children[index]==null) curr.children[index] = new Node();
curr = curr.children[index];
}
curr.isEnd = true;
}
boolean contains(String data){
Node curr = this.root;
for(int i = 0,h=data.length();i<h;i++){
int index = data.charAt(i) - 'a';
if(curr.children[index]==null) return false;
curr = curr.children[index];
}
return curr.isEnd;
}
}
<file_sep>/src/MinimumCostOfRopes.java
import java.io.*;
import java.util.PriorityQueue;
public class MinimumCostOfRopes {
BufferedReader bf;
PrintWriter writer;
StringBuilder sb;
static boolean local_system = true;
public void solve(long[] data){
PriorityQueue<Long> queue = new PriorityQueue<>();
for(long d : data) queue.add(d);
long count = 0;
//sb.append(queue).append("\n");
while (queue.size() > 1){
long a = queue.poll();
long b = queue.poll();
queue.add(a+b);
count+=(a+b);
}
sb.append(count).append("\n");
}
void run() throws IOException {
int t = getInt();
while (t-->0){
solve(longs(getInt()));
}
writer.println(sb.toString());
}
public static void main(String[] args) throws IOException {
long start_time = System.currentTimeMillis();
MinimumCostOfRopes object;
if (local_system)
object = new MinimumCostOfRopes(new FileInputStream("input"), System.out);
else object = new MinimumCostOfRopes(System.in, System.out);
object.run();
long end_time = System.currentTimeMillis();
if (local_system) object.writer.println("Time : " + (end_time - start_time));
object.close();
}
public MinimumCostOfRopes(InputStream in, OutputStream out) {
this.writer = new PrintWriter(out);
this.bf = new BufferedReader(new InputStreamReader(in));
this.sb = new StringBuilder();
}
public int getInt() throws IOException {
return Integer.parseInt(bf.readLine());
}
public long getLong() throws IOException {
return Long.parseLong(bf.readLine());
}
public int[] ints(int size) throws IOException {
String[] data = bf.readLine().split(" ");
int[] send = new int[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]);
return send;
}
public long[] longs(int size) throws IOException {
String[] data = bf.readLine().split(" ");
long[] send = new long[data.length];
for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]);
return send;
}
public void close() {
this.writer.flush();
this.writer.close();
}
}
| cdf68b768b7a93e480a0bfd457ab9c47cfaab32a | [
"Java"
] | 12 | Java | tarangparikh/GeeksForGeeks | 0315f6dd4602f9362c9df9b0dbf4bdca0d3fda90 | ba71be59100b8333c4a92bc951051bd52973b4a8 | |
refs/heads/master | <repo_name>ylzz1997/graduateDesign<file_sep>/app/src/main/java/com/lhy/ggraduatedesign/DateProcessor.java
package com.lhy.ggraduatedesign;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DateProcessor {
public final static double PER_TIME = 0.015;
private List<float[]> angal;
private List<float[]> accelerations;
private List<float[]> gyroscopes;
private List<Float> z = new ArrayList<>();
private List<Float> zx = new ArrayList<>();
private float gyroscopesAngel;
private float finalAngal;
private float finalSpeed;
public void setAngal(List<float[]> angal) {
this.angal = angal;
}
public void setAccelerations(List<float[]> accelerations) {
this.accelerations = accelerations;
}
public DateProcessor(List<float[]> angal, List<float[]> accelerations, List<float[]> gyroscopes) {
this.angal = angal;
this.accelerations = accelerations;
this.gyroscopes = gyroscopes;
gyroscopessum();
ProcessAngle();
speed();
}
private float PerProcessAngle(float[] i){
float z = i[2] - 90;
if(z<0){
return 0;
}else if(z>180){
return 180;
}else {
return z;
}
}
public float getFinalAngal() {
return finalAngal;
}
public float getFinalSpeed() {
return finalSpeed;
}
private void ProcessAngle(){
for(float[] i : angal){
z.add(PerProcessAngle(i));
zx.add(i[2]);
}
if(z.size()-1>=0){
int halfsize = (int)Math.ceil(zx.size()/2);
List list = zx.subList(0,halfsize+1);
float max = (float)Collections.max(list);
float n = max+gyroscopesAngel-90;
finalAngal = n;
}
else
finalAngal =0;
}
private void speed(){
float sum = 0;
for(int i =0;i<accelerations.size();i++){
double n = (accelerations.get(i))[0];
if(n<0){
n=-n;
}
sum+=n*PER_TIME;
}
finalSpeed = sum;
}
private void gyroscopessum(){
float sum = 0;
for(float[] n: gyroscopes){
sum+=Math.abs(n[1])*0.18;
}
gyroscopesAngel=sum;
}
}
<file_sep>/app/src/main/java/com/lhy/ggraduatedesign/DateBean.java
package com.lhy.ggraduatedesign;
public class DateBean {
private double vx;
private double vy;
private float angle;
private float speed;
private double distant;
private double height;
private float bodyHeight;
private double time;
final static float G = 9.8f;
final static double PI = Math.PI;
//h=Vyt-1/2gt^2+height;
//h=Vyt-1/2gt^2+height;
public DateBean(float angle, float speed, float bodyHeight) {
this.angle = angle;
this.speed = speed;
this.bodyHeight = bodyHeight;
vx = speed * Math.sin(angle*Math.PI/180);
vy = speed * Math.cos(angle*Math.PI/180);
height = bodyHeight + (vy*vy)/(2*G);
time = vy/G+Math.sqrt((height*2)/G);
distant = vx*time;
}
public double getVx() {
return vx;
}
public double getVy() {
return vy;
}
public double getDistant() {
return distant;
}
public double getHeight() {
return height;
}
public double getTime() {
return time;
}
public float getBodyHeight() {
return bodyHeight;
}
}
<file_sep>/app/src/main/java/com/lhy/ggraduatedesign/SensorUtil.java
package com.lhy.ggraduatedesign;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.SENSOR_SERVICE;
public class SensorUtil implements SensorEventListener {
private float[] r = new float[9];
private float[] values = new float[3];
private float[] gravity = null;
private float[] geomagnetic = null;
private float[] linerAcceleration = null;
private float[] gyroscope = null;
private SensorManager mSensorManager;
private Context context;
private float[] result= new float[3];
private List<float[]> angal = new ArrayList<>();
private List<float[]> accelerations = new ArrayList<>();
private List<float[]> gyroscopes = new ArrayList<>();
private Sensor acceleSensor;
private Sensor LacceleSensor;
private Sensor magSensor;
private Sensor gyroscrope;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what==0){
if(gravity!=null && geomagnetic!=null) {
accelerations.add(new float[]{linerAcceleration[0],linerAcceleration[1],linerAcceleration[2]});
gyroscopes.add(new float[]{gyroscope[0],gyroscope[1],gyroscope[2]});
if(SensorManager.getRotationMatrix(r, null, gravity, geomagnetic)) {
SensorManager.getOrientation(r, values);
result[0] = (float) ((360f+values[0]*180f/Math.PI)%360);
result[1] = (float) ((360f+values[1]*180f/Math.PI)%360);
result[2] = (float) ((360f+values[2]*180f/Math.PI)%360);
angal.add(new float[]{result[0],result[1],result[2]});
}
}
/*
result[0] = (float) ((360f+geomagnetic[0]*180f/Math.PI)%360);
result[1] = (float) ((360f+geomagnetic[1]*180f/Math.PI)%360);
result[2] = (float) ((360f+geomagnetic[2]*180f/Math.PI)%360);
angal.add(new float[]{result[0],result[1],result[2]});
TextView tv = ((Activity)context).findViewById(R.id.main_text);
tv.setText("x="+result[0]+"y="+result[1]+"z="+result[2]+" \n x="+gravity[0]+"y="+gravity[1]+"z="+gravity[2]);
*/
}
}
};
public SensorUtil(Context context) {
this.context = context;
mSensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
LacceleSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
acceleSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
gyroscrope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
}
public void Initialization(){
mSensorManager.registerListener(this, LacceleSensor, SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, acceleSensor, SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, magSensor, SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, gyroscrope, SensorManager.SENSOR_DELAY_GAME);
}
public void Pause(){
mSensorManager.unregisterListener(this);
handler.sendEmptyMessage(1);
}
@Override
public void onSensorChanged(SensorEvent event) {
System.out.print("执行中");
switch (event.sensor.getType()) {
case Sensor.TYPE_LINEAR_ACCELERATION:
linerAcceleration = event.values;
handler.sendEmptyMessage(0);
break;
case Sensor.TYPE_ACCELEROMETER:
gravity = event.values;
handler.sendEmptyMessage(0);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
geomagnetic = event.values;
handler.sendEmptyMessage(0);
break;
case Sensor.TYPE_GYROSCOPE:
gyroscope = event.values;
handler.sendEmptyMessage(0);
break;
}
}
public void Reset(){
angal = new ArrayList<>();
accelerations = new ArrayList<>();
gyroscopes = new ArrayList<>();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public List<float[]> getAngal() {
return angal;
}
public void setAngal(List<float[]> angal) {
this.angal = angal;
}
public List<float[]> getAccelerations() {
return accelerations;
}
public Sensor getLacceleSensor() {
return LacceleSensor;
}
public void setAccelerations(List<float[]> accelerations) {
this.accelerations = accelerations;
}
public List<float[]> getGyroscopes() {
return gyroscopes;
}
}
| 4cc3efbf5cc5da4f842217333f32fac1fb510e82 | [
"Java"
] | 3 | Java | ylzz1997/graduateDesign | 9bc70d3d8d99fd9de40b831cba46fc31594ad1e5 | b75e31b96ef40544641d1518cabec444e6d9a9e2 | |
refs/heads/master | <repo_name>VestedSkeptic/datagrab<file_sep>/reddit/config.py
import cLogger
clog = None
# --------------------------------------------------------------------------
def initializeCLogger():
global clog
clog = cLogger.cLogger(__name__)
clog.addTraceLoggingLevel()
clog.generateFuncDict()
clog.addConsoleLogger(cLogger.cLoggerLevel_INFO, "hConsole", cLogger.cLoggerFilter_None)
clog.addFileLogger("/home/delta/work/logs/out.txt", cLogger.cLoggerLevel_DEBUG, "hFile out", cLogger.cLoggerFile_archiveOlder, cLogger.cLoggerFilter_None)
clog.addFileLogger("/home/delta/work/logs/trace.txt", cLogger.cLoggerLevel_TRACE, "hFile trace", cLogger.cLoggerFile_overwriteOlder, cLogger.cLoggerFilter_SpecificLevelOnly)
clog.addFileLogger("/home/delta/work/logs/alert.txt", cLogger.cLoggerLevel_WARNING, "hFile alert", cLogger.cLoggerFile_appendOlder, cLogger.cLoggerFilter_GreaterThanOrEqualToLevel)
clog.setLoggerInfoLevel(cLogger.cLoggerLevel_TRACE)
clog.setMethodInfoLevel(cLogger.cLoggerLevel_DEBUG)
clog.dumpLoggerInfo()
<file_sep>/reddit/views/vthread.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # for pagination
from ..config import clog
from ..models import mthread
# *****************************************************************************
def list(request, subreddit):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
qs = mthread.objects.filter(subreddit__name=subreddit).order_by("-rcreated")
paginator = Paginator(qs, 20) # Show 20 per page
page = request.GET.get('page')
try:
threads = paginator.page(page)
except PageNotAnInteger:
threads = paginator.page(1) # If page is not an integer, deliver first page.
except EmptyPage:
threads = paginator.page(paginator.num_pages) # If page is out of range (e.g. 9999), deliver last page of results.
return render(request, 'vthread_list.html', {'threads': threads, 'subreddit':subreddit})
# *****************************************************************************
def delAll(request):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
vs = ''
qs = mthread.objects.all()
vs += str(qs.count()) + " mSubmissions deleted"
qs.delete()
clog.logger.info(vs)
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vbase.main', xData=sessionKey)
<file_sep>/reddit/models/msubreddit.py
from __future__ import unicode_literals
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from .mbase import mbase
from ..config import clog
from datetime import datetime
from django.utils import timezone
import pprint
# *****************************************************************************
class msubredditManager(models.Manager):
def addOrUpdate(self, name, prawSubreddit):
mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
try:
i_msubreddit = self.get(name=name)
redditFieldDict = i_msubreddit.getRedditFieldDict()
changedCount = i_msubreddit.updateRedditFields(prawSubreddit, redditFieldDict)
if changedCount == 0: i_msubreddit.addOrUpdateTempField = "oldUnchanged"
else: i_msubreddit.addOrUpdateTempField = "oldChanged"
except ObjectDoesNotExist:
i_msubreddit = self.create(name=name)
redditFieldDict = i_msubreddit.getRedditFieldDict()
i_msubreddit.addRedditFields(prawSubreddit, redditFieldDict)
i_msubreddit.addOrUpdateTempField = "new"
clog.logger.info("i_msubreddit = %s" % (pprint.pformat(vars(i_msubreddit))))
i_msubreddit.save()
return i_msubreddit
# *****************************************************************************
# class msubreddit(mbase, models.Model):
class msubreddit(mbase):
name = models.CharField(max_length=30)
# properties
ppoi = models.BooleanField(default=False)
# precentlyupdated = models.BooleanField(default=False)
pprioritylevel = models.IntegerField(default=0)
# pthreadupdatetimestamp = models.DateTimeField(default=datetime(2000, 1, 1, 1, 0, 0))
# pthreadupdatetimestamp = models.DateTimeField(default=timezone.now())
# pthreadupdatetimestamp = models.DateTimeField(default=timezone.now)
pthreadupdatetimestamp = models.DateTimeField(default=timezone.make_aware(datetime(2000, 1, 1, 1, 0, 0)))
pupdateswithnochanges = models.IntegerField(default=0)
pcountnew = models.IntegerField(default=0)
pcountOldUnchanged = models.IntegerField(default=0)
pcountOldChanged = models.IntegerField(default=0)
# Redditor fields
raccounts_active_is_fuzzed = models.BooleanField(default=False)
rcollapse_deleted_comments = models.BooleanField(default=False)
rpublic_traffic = models.BooleanField(default=False)
rquarantine = models.BooleanField(default=False)
rshow_media_preview = models.BooleanField(default=False)
rshow_media = models.BooleanField(default=False)
rspoilers_enabled = models.BooleanField(default=False)
rhide_ads = models.BooleanField(default=False)
rover18 = models.BooleanField(default=False)
raccounts_active = models.IntegerField(default=0)
rcomment_score_hide_mins = models.IntegerField(default=0)
rsubscribers = models.IntegerField(default=0)
rdescription = models.TextField(default='')
rpublic_description = models.TextField(default='')
rdisplay_name = models.CharField(max_length=100, default='', blank=True)
rlang = models.CharField(max_length=20, default='', blank=True)
rid = models.CharField(max_length=12, default='', blank=True)
rsubmission_type = models.CharField(max_length=12, default='', blank=True)
rsubreddit_type = models.CharField(max_length=12, default='', blank=True)
rtitle = models.CharField(max_length=101, default='', blank=True)
rurl = models.CharField(max_length=40, default='', blank=True)
rwhitelist_status = models.CharField(max_length=24, default='', blank=True)
rcreated_utc = models.DecimalField(default=0, max_digits=12,decimal_places=1)
rcreated = models.DecimalField(default=0, max_digits=12,decimal_places=1)
radvertiser_category = models.TextField(default='')
rwiki_enabled = models.TextField(default='')
objects = msubredditManager()
# -------------------------------------------------------------------------
def getRedditFieldDict(self):
mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
redditFieldDict = {
# mThreadFieldName redditFieldName convertMethodPtr
'raccounts_active_is_fuzzed': ("accounts_active_is_fuzzed", None), # bool
'rcollapse_deleted_comments': ("collapse_deleted_comments", None), # bool
'rpublic_traffic': ("public_traffic", None), # bool
'rquarantine': ("quarantine", None), # bool
'rshow_media_preview': ("show_media_preview", None), # bool
'rshow_media': ("show_media", None), # bool
'rspoilers_enabled': ("spoilers_enabled", None), # bool
'rhide_ads': ("hide_ads", None), # bool
'rover18': ("over18", None), # bool
'raccounts_active': ("accounts_active", int), # int
'rcomment_score_hide_mins': ("comment_score_hide_mins", int), # int
'rsubscribers': ("subscribers", int), # int
'rdescription': ("description", None), # string text area
'rpublic_description': ("public_description", None), # string text area
'rdisplay_name': ("display_name", None), # string
'rlang': ("lang", None), # string
'rid': ("id", None), # string
'rsubmission_type': ("submission_type", None), # string
'rsubreddit_type': ("subreddit_type", None), # string
'rtitle': ("title", None), # string
'rurl': ("url", None), # string
'rwhitelist_status': ("whitelist_status", self.getStringOrNoneAsEmptyString), # string
'rcreated_utc': ("created_utc", None), # 1493534605.0,
'rcreated': ("created", None), # 1493534605.0,
'radvertiser_category': ("advertiser_category", self.getStringOrNoneAsEmptyString), # string text area
'rwiki_enabled': ("wiki_enabled", self.getStringOrNoneAsEmptyString), # string text are
}
return redditFieldDict
# -------------------------------------------------------------------------
def __str__(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
s = self.name
# if self.ppoi: s += " (ppoi)"
return format(s)
# --------------------------------------------------------------------------
def getThreadsBestBeforeValue(self, prawReddit):
mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
# clog.logger.info("METHOD NOT COMPLETED")
return ''
# --------------------------------------------------------------------------
def threadsUpdated(self, countNew, countOldUnchanged, countOldChanged):
mi = clog.dumpMethodInfo()
# self.precentlyupdated =True
if countNew > 0:
self.pprioritylevel -= 1
self.pupdateswithnochanges = 0
if self.pprioritylevel < 0:
self.pprioritylevel = 0;
else:
self.pprioritylevel += 1
self.pupdateswithnochanges += 1
if self.pprioritylevel > 3:
self.pprioritylevel = 3;
self.pcountnew = countNew
self.pcountOldUnchanged = countOldUnchanged
self.pcountOldChanged = countOldChanged
# self.pthreadupdatetimestamp = datetime.now()
self.pthreadupdatetimestamp = timezone.now()
self.save()
return
# # ----------------------------------------------------------------------------
# # SUBREDDIT attributes
# {
# '_banned': None,
# '_comments': None,
# '_contributor': None,
# '_fetched': True,
# '_filters': None,
# '_flair': None,
# '_info_params': {},
# '_mod': None,
# '_moderator': None,
# '_modmail': None,
# '_muted': None,
# '_path': 'r/redditdev/',
# '_quarantine': None,
# '_reddit': <praw.reddit.Reddit object at 0x7f1474006e48>,
# '_stream': None,
# '_stylesheet': None,
# '_wiki': None,
# 'accounts_active_is_fuzzed': True,
# 'accounts_active': 9,
# 'advertiser_category': None,
# 'allow_images': False,
# 'banner_img': '',
# 'banner_size': None,
# 'collapse_deleted_comments': False,
# 'comment_score_hide_mins': 0,
# 'created_utc': 1213802177.0,
# 'created': 1213830977.0,
# 'description_html': '<!-- SC_OFF --><div class="md"><p>A subreddit for '
# 'description': 'A subreddit for discussion of reddit API clients and the ',
# 'display_name_prefixed': 'r/redditdev',
# 'display_name': 'redditdev',
# 'header_img': 'https://e.thumbs.redditmedia.com/bOToSJt13ylszjE4.png',
# 'header_size': [120, 40],
# 'header_title': None,
# 'hide_ads': False,
# 'icon_img': '',
# 'icon_size': None,
# 'id': '2qizd',
# 'key_color': '#ff4500',
# 'lang': 'en',
# 'name': 't5_2qizd',
# 'over18': False,
# 'public_description_html': '<!-- SC_OFF --><div class="md"><p>A subreddit for ',
# 'public_description': 'A subreddit for discussion of reddit API clients and ',
# 'public_traffic': True,
# 'quarantine': False,
# 'show_media_preview': False,
# 'show_media': False,
# 'spoilers_enabled': False,
# 'submission_type': 'self',
# 'submit_link_label': None,
# 'submit_text_html': '<!-- SC_OFF --><div class="md"><p>Get faster, better ',
# 'submit_text_label': None,
# 'submit_text': 'Get faster, better responses by including more information, ',
# 'subreddit_type': 'public',
# 'subscribers': 10887,
# 'suggested_comment_sort': None,
# 'title': 'reddit Development',
# 'url': '/r/redditdev/',
# 'user_is_banned': False,
# 'user_is_contributor': False,
# 'user_is_moderator': False,
# 'user_is_muted': False,
# 'user_is_subscriber': False,
# 'user_sr_theme_enabled': False,
# 'whitelist_status': 'all_ads',
# 'wiki_enabled': None
# }
<file_sep>/reddit/forms/fsubreddit.py
from django import forms
# *****************************************************************************
class fNewPoiSubreddit(forms.Form):
poiSubreddit = forms.CharField(label='Subreddit Name', max_length=30)
<file_sep>/reddit/views/vbase.py
from django.http import HttpResponse
from django.shortcuts import redirect
from ..config import clog
from ..models import mcomment, msubreddit, mthread, muser
from ..tasks.tmisc import TASK_generateModelCountData
# import pprint
# *****************************************************************************
def main(request, xData=None):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
vs = '<b>vuser</b>:'
vs += ' <a href="http://localhost:8000/reddit/vuser/list">list</a>'
vs += ', <b>add</b> <a href="http://localhost:8000/reddit/vuser/formNewPoiUser">newPoiUser</a>'
vs += '<br><b>vsubreddit</b>:'
vs += ' <a href="http://localhost:8000/reddit/vsubreddit/list">list</a>'
vs += ', <b>add</b> <a href="http://localhost:8000/reddit/vsubreddit/formNewPoiSubreddit">newPoiSubreddit</a>'
vs += '<br><a href="http://localhost:8000/reddit/vbase/map">map</a>'
# vs += ', <a href="http://localhost:8000/reddit/vuser/delAll">delAll</a>'
# vs += ', <a href="http://localhost:8000/reddit/vsubreddit/delAll">delAll</a>'
# vs += ' <a href="http://localhost:8000/reddit/vthread/delAll">delAll</a>'
vs += displayDatabaseModelCounts()
vs += '<br><a href="http://localhost:8000/reddit/vbase/test">vbase.test</a>'
vs += '<br>' + request.session.get(xData, '')
return HttpResponse(vs)
# *****************************************************************************
def displayDatabaseModelCounts():
mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
listOfModelCountStrings = TASK_generateModelCountData()
s = '<BR>============================'
s += '<font face="Courier New" color="green">'
for line in listOfModelCountStrings:
s += '<BR>'
s += line.replace(" ", " ")
s += '</font>'
s += '<BR>============================'
return s
# # *****************************************************************************
# def test(request):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
#
# vs = "vbase.test: EMPTY TEST"
#
# sessionKey = 'blue'
# request.session[sessionKey] = vs
# return redirect('vbase.main', xData=sessionKey)
# *****************************************************************************
def test(request):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
vs = ''
prawReddit = mcomment.getPrawRedditInstance()
prawSubmissionObject = prawReddit.submission(id='6fvbyb')
for duplicate in prawSubmissionObject.duplicates():
vs += duplicate.subreddit_name_prefixed
vs += ', '
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vbase.main', xData=sessionKey)
# *****************************************************************************
def generateMapLink():
vs = '<img src="'
vs += "https://maps.googleapis.com/maps/api/staticmap?"
# vs += "center=Quyon,Quebec"
# vs += "center=45.529997,-76.12571597" # compound
vs += "center=45.53716674,-76.14626169" # NW of compound, center of walking area
vs += "&zoom=14"
vs += "&size=1000x800"
vs += "&maptype=roadmap"
# vs += "&markers=color:blue%7Clabel:S%7C40.702147,-74.015794"
# vs += "&markers=color:green%7Clabel:G%7C40.711614,-74.012318"
# vs += "&markers=color:red%7Clabel:C%7C40.718217,-73.998284"
vs += "&style=feature:road%7Celement:geometry%7Ccolor:0x000000&size=480x360"
# my google api key
# <KEY>
vs += "&key=<KEY>"
vs += '">'
return vs
# *****************************************************************************
def map(request):
vs = generateMapLink()
return HttpResponse(vs)
<file_sep>/reddit/forms/fuser.py
from django import forms
# *****************************************************************************
class fNewPoiUser(forms.Form):
poiUser = forms.CharField(label='Users Name', max_length=30)
<file_sep>/reddit/views/vcomment.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.core.exceptions import ObjectDoesNotExist
# from django.utils.safestring import mark_safe
from ..config import clog
from ..models import mcomment
from ..forms import fuser
# import pprint
# *****************************************************************************
def user(request, username):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
# qs = mcomment.objects.filter(username=username).order_by('rcreated')
# qs = mcomment.objects.filter(username=username).order_by('-rcreated')
qs = mcomment.objects.filter(username=username).order_by('-rcreated_utc')
return render(request, 'vcomment_user.html', {'comments': qs, 'username': username})
<file_sep>/reddit/models/mcomment.py
from __future__ import unicode_literals
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from .mbase import mbase
from ..config import clog
# import praw
# import pprint
# *****************************************************************************
class mcommentManager(models.Manager):
def addOrUpdate(self, username, prawComment):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
# NOTE SIMILAR CHANGE AS MUSER TO HANDLE DUPLIICATE COMMENTS
try:
qs = mcomment.objects.filter(username=username, name=prawComment.name, thread=prawComment.link_id, subreddit=prawComment.subreddit_id)
if qs.count() > 0:
i_mcomment = qs[0]
redditFieldDict = i_mcomment.getRedditFieldDict()
changedCount = i_mcomment.updateRedditFields(prawComment, redditFieldDict)
if changedCount == 0: i_mcomment.addOrUpdateTempField = "oldUnchanged"
else: i_mcomment.addOrUpdateTempField = "oldChanged"
else:
i_mcomment = self.create(username=username, name=prawComment.name, thread=prawComment.link_id, subreddit=prawComment.subreddit_id)
redditFieldDict = i_mcomment.getRedditFieldDict()
i_mcomment.addRedditFields(prawComment, redditFieldDict)
i_mcomment.addOrUpdateTempField = "new"
except ObjectDoesNotExist:
i_mcomment = self.create(username=username, name=prawComment.name, thread=prawComment.link_id, subreddit=prawComment.subreddit_id)
redditFieldDict = i_mcomment.getRedditFieldDict()
i_mcomment.addRedditFields(prawComment, redditFieldDict)
i_mcomment.addOrUpdateTempField = "new"
i_mcomment.save()
return i_mcomment
# *****************************************************************************
# class mcomment(mbase, models.Model):
class mcomment(mbase):
name = models.CharField(max_length=12)
thread = models.CharField(max_length=12)
subreddit = models.CharField(max_length=12, db_index=True)
username = models.CharField(max_length=30, db_index=True)
# properties
pdeleted = models.BooleanField(default=False)
puseradded = models.BooleanField(default=False)
# Reddit fields
rapproved_by = models.CharField(max_length=21, default='', blank=True)
rbanned_by = models.CharField(max_length=21, default='', blank=True)
rid = models.CharField(max_length=10, default='', blank=True)
rparent_id = models.CharField(max_length=16, default='', blank=True)
rsubreddit_name_prefixed = models.CharField(max_length=64, default='', blank=True)
rbody = models.TextField(default='', blank=True)
rmod_reports = models.TextField(default='', blank=True)
ruser_reports = models.TextField(default='', blank=True)
rcontroversiality = models.IntegerField(default=0)
rdowns = models.IntegerField(default=0)
rscore = models.IntegerField(default=0)
rups = models.IntegerField(default=0)
rarchived = models.BooleanField(default=False)
rstickied = models.BooleanField(default=False)
rcreated = models.DecimalField(default=0, max_digits=12,decimal_places=1)
rcreated_utc = models.DecimalField(default=0, max_digits=12,decimal_places=1)
redited = models.DecimalField(default=0, max_digits=12,decimal_places=1)
objects = mcommentManager()
# -------------------------------------------------------------------------
def getRedditFieldDict(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
redditFieldDict = {
# mThreadFieldName redditFieldName convertMethodPtr
'rapproved_by': ("approved_by", self.getRedditUserNameAsString), # special
'rbanned_by': ("banned_by", self.getRedditUserNameAsString), # special
'rid': ("id", None), # string
'rparent_id': ("parent_id", None), # string
'rsubreddit_name_prefixed': ("subreddit_name_prefixed", None), # string
'rbody': ("body", None), # string
'rmod_reports': ("mod_reports", None), # [[u'mod reported text', u'stp2007']], OR [[u'Spam', u'stp2007']]
'ruser_reports': ("user_reports", None), # [[u'Text for other reason', 1]] OR [[u'Spam', 1]]
'rcontroversiality': ("controversiality", int), # int
'rdowns': ("downs", int), # int
'rscore': ("score", int), # int
'rups': ("ups", int), # int
'rarchived': ("archived", None), # bool
'rstickied': ("stickied", None), # bool
'rcreated': ("created", None), # 1493534605.0,
'rcreated_utc': ("created_utc", None), # 1493534605.0,
'redited': ("edited", self.getEditedOrFalseValueAsZero), # False or timestamp
}
return redditFieldDict
# -------------------------------------------------------------------------
def __str__(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
s = self.username
# s += " [" + self.name + "]"
# s += " [submisson_id=" + self.submission_id + "]"
# s += " [parent_id=" + self.parent_id + "]"
return format(s)
# # ----------------------------------------------------------------------------
# # COMMENT ATTRIBUTES COMING FROM A USER
# {
# '_fetched' : True,
# '_info_params' : {},
# '_mod' : None,
# '_reddit' : <praw.reddit.Reddit object at 0x7f4e76125eb8>,
# '_replies' : [],
# '_submission' : None,
# 'approved_by' : None,
# 'archived' : False,
# 'author_flair_css_class' : None,
# 'author_flair_text' : None,
# 'author' : Redditor(name='stp2007'),
# 'banned_by' : None,
# 'body_html' : '<div class="md"><p>Thanks</p>\n</div>',
# 'body' : 'Thanks\n',
# 'can_gild' : True,
# 'controversiality' : 0,
# 'created_utc' : 1492955714.0,
# 'created' : 1492984514.0,
# 'distinguished' : None,
# 'downs' : 0,
# 'edited' : False,
# 'gilded' : 0,
# 'id' : 'dgn3ae1',
# 'likes' : None,
# 'link_author' : 'stp2007',
# 'link_id' : 't3_66ybk6',
# 'link_permalink' : 'https://www.reddit.com/r/TheWarNerd/comments/66ybk6/radio_war_nerd_questions/',
# 'link_title' : 'Radio War Nerd questions',
# 'link_url' : 'https://www.reddit.com/r/TheWarNerd/comments/66ybk6/radio_war_nerd_questions/',
# 'mod_reports' : [],
# 'name' : 't1_dgn3ae1',
# 'num_comments' : 4,
# 'num_reports' : None,
# 'over_18' : False,
# 'parent_id' : 't1_dgmugew',
# 'quarantine' : False,
# 'removal_reason' : None,
# 'report_reasons' : None,
# 'saved' : False,
# 'score_hidden' : False,
# 'score' : 1,
# 'stickied' : False,
# 'subreddit_id' : 't5_3b93s',
# 'subreddit_name_prefixed' : 'r/TheWarNerd',
# 'subreddit_type' : 'public',
# 'subreddit' : Subreddit(display_name='TheWarNerd'),
# 'ups' : 1,
# 'user_reports' : []
# }
# # ----------------------------------------------------------------------------
# # COMMENT ATTRIBUTES COMING FROM A SUBMISSION
# {
# '_fetched': True,
# '_info_params': {},
# '_mod': None,
# '_reddit': <praw.reddit.Reddit object at 0x7fe085ff5f28>,
# '_replies': <praw.models.comment_forest.CommentForest object at 0x7fe085433d68>,
# '_submission': Submission(id='69a8hl'),
# 'approved_by': None,
# 'archived': False,
# 'author_flair_css_class': None,
# 'author_flair_text': None,
# 'author': Redditor(name='AutoModerator'),
# 'banned_by': None,
# 'body_html': '<div class="md"><p>As a reminder, this subreddit <a ',
# 'body': '\nAs a reminder, this subreddit [is for civil ',
# 'can_gild': True,
# 'controversiality': 0,
# 'created_utc': 1493930841.0,
# 'created': 1493959641.0,
# 'depth': 0,
# 'distinguished': 'moderator',
# 'downs': 0,
# 'edited': False,
# 'gilded': 0,
# 'id': 'dh4zdvm',
# 'likes': None,
# 'link_id': 't3_69a8hl',
# 'mod_reports': [],
# 'name': 't1_dh4zdvm',
# 'num_reports': None,
# 'parent_id': 't3_69a8hl',
# 'removal_reason': None,
# 'report_reasons': None,
# 'saved': False,
# 'score_hidden': True,
# 'score': 1,
# 'stickied': True,
# 'subreddit_id': 't5_2cneq',
# 'subreddit_name_prefixed': 'r/politics',
# 'subreddit_type': 'public',
# 'subreddit': Subreddit(display_name='politics'),
# 'ups': 1,
# 'user_reports': []
# }
<file_sep>/reddit/models/mbase.py
from __future__ import unicode_literals
from django.db import models
from ..config import clog
import praw
import inspect
# import pprint
CONST_CLIENT_ID = "kcksu9E4VgC0TQ"
CONST_SECRET = "<KEY>"
CONST_GRANT_TYPE = "client_credentials"
CONST_DEV_USERNAME = "OldDevLearningLinux"
CONST_DEV_PASSWORD = "<PASSWORD>"
CONST_USER_AGENT = "test app by /u/OldDevLearningLinux, ver 0.01"
# *****************************************************************************
class mbase(models.Model):
# p_updatePriority = models.IntegerField(default=0)
#
# class Meta:
# abstract = True
# def __str__(self):
# return format("mbase")
pass
# # -------------------------------------------------------------------------
# @staticmethod
# def getDictOfClassFieldNames(classModel):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
#
# rvDict = {}
# fields = classModel._meta.get_fields()
# for field in fields:
# rvDict[field.name] = None
# return rvDict
# -------------------------------------------------------------------------
@staticmethod
def getPrawRedditInstance():
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
prawReddit = praw.Reddit(
client_id=CONST_CLIENT_ID,
client_secret=CONST_SECRET,
user_agent=CONST_USER_AGENT,
username=CONST_DEV_USERNAME,
password=<PASSWORD>
)
return prawReddit
# -------------------------------------------------------------------------
def getRedditUserNameAsString(self, redditUser):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
if isinstance(redditUser, praw.models.Redditor): return redditUser.name # if it is a praw Reddit object
elif redditUser == None: return '[None]'
else: return redditUser # will also return values of '[deleted]' or ''[removed]'
# -------------------------------------------------------------------------
# if None will return ''
def getStringOrNoneAsEmptyString(self, inputString):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
if inputString == None: return ''
else: return inputString
# -------------------------------------------------------------------------
# Reddit edited field has a value of False or a timestamp.
# This method will return timestamp or a value of zero if it was False
def getEditedOrFalseValueAsZero(self, inputString):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
if inputString == False: return 0
else: return inputString
# -------------------------------------------------------------------------
def addRedditFields(self, prawData, redditFieldDict):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
for mFieldName in redditFieldDict:
redditFieldName = redditFieldDict[mFieldName][0] # ex: author
convertMethodPtr = redditFieldDict[mFieldName][1] # ex: self.getRedditUserNameAsString
redditValue = getattr(prawData, redditFieldName) # ex: prawData.author
if convertMethodPtr: setattr(self, mFieldName, convertMethodPtr(redditValue))
else: setattr(self, mFieldName, redditValue)
# -------------------------------------------------------------------------
# return count of fields that were changed or zero
def updateRedditFields(self, prawData, redditFieldDict):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
# clog.logger.debug("METHOD NOT COMPLETED")
for mFieldName in redditFieldDict:
redditFieldName = redditFieldDict[mFieldName][0] # ex: author
convertMethodPtr = redditFieldDict[mFieldName][1] # ex: self.getRedditUserNameAsString
redditValue = getattr(prawData, redditFieldName) # ex: prawData.author
# Instead of only putting value in self
# - get current value in self
# - see if different then new value
# - if different archive/backup current value
# - then replace current value with new value
# if convertMethodPtr: setattr(self, mFieldName, convertMethodPtr(redditValue))
# else: setattr(self, mFieldName, redditValue)
return 0
<file_sep>/reddit/lib/checkInternetStatus.py
#!/usr/bin/env python
import requests
import argparse
import time
# import os
# import sys
# import pprint
CONST_CONTINUE = 0
CONST_FINI_SUCCESS = 1
CONST_FINI_KEYBOARD_QUIT = 2
# *****************************************************************************
def doRequestToUrl(url, count, verbose):
processingStatus = CONST_CONTINUE
try:
r = requests.get(url)
processingStatus = CONST_FINI_SUCCESS
except KeyboardInterrupt:
processingStatus = CONST_FINI_KEYBOARD_QUIT
except:
if verbose:
print ("*** Try #%d to url %s failed." % (count, url))
else:
print ("*** Try #%d failed." % (count))
return processingStatus
# *****************************************************************************
def parseCommandLineArguments():
parser = argparse.ArgumentParser()
# --------------------
# Positional arguments
# args.url
parser.add_argument("url", help="URL to test");
# type and valid choices specified
# args.iterations
parser.add_argument("iterations", help="number of iterations to test. 0 = run forever.", type=int);
# --------------------
# Optional arguments
# Both -v and --verbose acceptable
# if specified then args.verbose will equal true otherwise false
# args.verbose
parser.add_argument("-v", "--verbose", help="verbosity of output message", action="store_true");
# Different way to specify option arguments
# args.signage
# allows input = -d -> args.delay = 1
# allows input = -dd -> args.delay = 2
# allows input = -ddd -> args.delay = 3
# default value if argument not provided
parser.add_argument("-d", "--delay", help="delay in seconds between tests", action="count", default=0);
args = parser.parse_args()
print ("")
print ("args.url = %s" %(args.url))
print ("args.iterations = %d" %(args.iterations))
print ("args.verbose = %s" %(args.verbose))
print ("args.delay = %d" %(args.delay))
return args
# *****************************************************************************
# url ex http://www.example.com
# verbose True or False
# iterations int, 0 = forever
# delay int, seconds, 0 = no delay
def checkInternet(url, verbose, iterations, delay):
print("===================")
processingStatus = CONST_CONTINUE
count = 1
while processingStatus == CONST_CONTINUE:
processingStatus = doRequestToUrl(url, count, verbose);
if iterations > 0 and count >= iterations:
print("Fini: %d iterations tested" % (iterations))
break
count += 1
if delay > 0 and processingStatus == CONST_CONTINUE:
time.sleep(delay)
if processingStatus == CONST_FINI_SUCCESS:
print("=================== success")
elif processingStatus == CONST_FINI_KEYBOARD_QUIT:
print("=================== keyboard quit")
# *****************************************************************************
if __name__ == "__main__":
args = parseCommandLineArguments()
checkInternet(args.url, args.verbose, args.iterations, args.delay)
<file_sep>/reddit/views/vuser.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.core.exceptions import ObjectDoesNotExist
from django.utils.safestring import mark_safe
from ..config import clog
from ..models import muser
from ..forms import fuser
# import pprint
# *****************************************************************************
def list(request, xData=None):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
qs = muser.objects.filter(ppoi=True).order_by('pprioritylevel','-pcommentsupdatetimestamp')
return render(request, 'vuser_list.html', {'users': qs, 'rightCol': mark_safe(request.session.get(xData, ''))})
# *****************************************************************************
def delAll(request):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
vs = ''
qs = muser.objects.all()
vs += str(qs.count()) + " musers deleted"
qs.delete()
clog.logger.info(vs)
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vbase.main', xData=sessionKey)
# *****************************************************************************
def formNewPoiUser(request):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
if request.method == 'POST': # if this is a POST request we need to process the form data
form = fuser.fNewPoiUser(request.POST) # create a form instance and populate it with data from the request:
if form.is_valid(): # check whether it's valid:
# process the data in form.cleaned_data as required
# pprint.pprint(form.cleaned_data)
# add user as poi
prawReddit = muser.getPrawRedditInstance()
prawRedditor = prawReddit.redditor(form.cleaned_data['poiUser'])
i_muser = muser.objects.addOrUpdate(prawRedditor)
i_muser.ppoi = True
i_muser.save()
vs = form.cleaned_data['poiUser']
if i_muser.addOrUpdateTempField == "new": vs += ' poi user added.'
else: vs += ' poi user already existed.'
clog.logger.info(vs)
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vbase.main', xData=sessionKey)
else: # if a GET (or any other method) we'll create a blank form
form = fuser.fNewPoiUser()
return render(request, 'fSimpleSubmitForm.html', {'form': form})
<file_sep>/reddit/tasks/treddit.py
from celery import task
from django.core.exceptions import ObjectDoesNotExist
import time
from ..config import clog
from ..models import mcomment
from ..models import msubreddit
from ..models import mthread
from ..models import muser
from .tbase import getBaseP, getBaseC
import praw
import prawcore
# import pprint
# --------------------------------------------------------------------------
@task()
def TASK_updateUsersForAllComments(numberToProcess):
mi = clog.dumpMethodInfo()
ts = time.time()
# create PRAW prawReddit instance
prawReddit = mcomment.getPrawRedditInstance()
countUsersAdded = 0
qsCount = mcomment.objects.filter(puseradded=False).count()
clog.logger.info("%s %d comments pending, processing %d" % (getBaseP(mi), qsCount, numberToProcess))
while qsCount > 0:
# Look at first result
i_mcomment = mcomment.objects.filter(puseradded=False)[0]
# AddOrUpdate that user
prawRedditor = prawReddit.redditor(i_mcomment.username)
i_muser = muser.objects.addOrUpdate(prawRedditor)
if i_muser.addOrUpdateTempField == "new":
countUsersAdded += 1
# set puseradded True for any false comments for that user
qs2 = mcomment.objects.filter(puseradded=False).filter(username=i_mcomment.username)
for item in qs2:
item.puseradded = True
item.save()
# are there any puseradded False comments left
qsCount = mcomment.objects.filter(puseradded=False).count()
numberToProcess -= 1
if numberToProcess <= 0:
break
clog.logger.info("%s %d comments pending, %d users added" % (getBaseC(mi, ts), qsCount, countUsersAdded))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_updateThreadCommentsByForest(numberToProcess):
mi = clog.dumpMethodInfo()
ts = time.time()
# create PRAW prawReddit instance
prawReddit = mcomment.getPrawRedditInstance()
countCommentsAdded = 0
qs = mthread.objects.filter(pdeleted=False, pforestgot=False).order_by("-rcreated")
clog.logger.info("%s %d threads pending, processing %d" % (getBaseP(mi), qs.count(), numberToProcess))
countNew = 0
countOldChanged = 0
countOldUnchanged = 0
countDeleted = 0
for i_mthread in qs:
try:
params={};
# params['before'] = i_mthread.getBestCommentBeforeValue(????)
prawSubmissionObject = prawReddit.submission(id=i_mthread.fullname[3:])
prawSubmissionObject.comment_sort = "new"
# prawSubmissionObject.comments.replace_more(limit=None)
prawSubmissionObject.comments.replace_more(limit=16)
for prawComment in prawSubmissionObject.comments.list():
if prawComment.author == None:
countDeleted += 1
else:
i_mcomment = mcomment.objects.addOrUpdate(prawComment.author.name, prawComment)
if i_mcomment.addOrUpdateTempField == "new": countNew += 1
if i_mcomment.addOrUpdateTempField == "oldUnchanged": countOldUnchanged += 1
if i_mcomment.addOrUpdateTempField == "oldChanged": countOldChanged += 1
except praw.exceptions.APIException as e:
clog.logger.info("%s %s PRAW_APIException: error_type = %s, message = %s" % (getBaseP(mi), username, e.error_type, e.message))
i_mthread.pforestgot = True
i_mthread.pcount += countNew
i_mthread.save()
numberToProcess -= 1
if numberToProcess <= 0:
break
clog.logger.info("%s %d new comments, %d old, %d oldChanged, %d deleted" % (getBaseC(mi, ts), countNew, countOldUnchanged, countOldChanged, countDeleted))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_updateCommentsForUser(username):
mi = clog.dumpMethodInfo()
ts = time.time()
try:
i_muser = muser.objects.get(name=username)
clog.logger.info("%s %s" % (getBaseP(mi), username))
prawReddit = i_muser.getPrawRedditInstance()
params={};
params['before'] = i_muser.getBestCommentBeforeValue(prawReddit)
# clog.logger.info("before = %s" % (params['before']))
# iterate through submissions saving them
countNew = 0
countOldChanged = 0
countOldUnchanged = 0
try:
for prawComment in prawReddit.redditor(i_muser.name).comments.new(limit=None, params=params):
i_mcomment = mcomment.objects.addOrUpdate(i_muser.name, prawComment)
if i_mcomment.addOrUpdateTempField == "new": countNew += 1
if i_mcomment.addOrUpdateTempField == "oldUnchanged": countOldUnchanged += 1
if i_mcomment.addOrUpdateTempField == "oldChanged": countOldChanged += 1
i_mcomment.puseradded = True
i_mcomment.save()
except praw.exceptions.APIException as e:
clog.logger.info("%s %s APIException: error_type = %s, message = %s" % (getBaseC(mi, ts), username, e.error_type, e.message))
except prawcore.exceptions.NotFound as e:
clog.logger.info("%s %s PrawcoreException: %s, *** USER PROBABLY DELETED ***" % (getBaseC(mi, ts), username, e))
i_muser.pdeleted = True
except prawcore.exceptions.PrawcoreException as e:
clog.logger.info("%s %s PrawcoreException: %s, *** USER PROBABLY SUSPENDED ***" % (getBaseC(mi, ts), username, e))
i_muser.pdeleted = True
beforeWarningString = ' [before]'
if countNew == 0 and params['before'] != '':
beforeWarningString = ' [** %s **]' % (params['before'])
clog.logger.info("%s %s %d new, %d old, %d oldC %s" % (getBaseC(mi, ts), username, countNew, countOldUnchanged, countOldChanged, beforeWarningString))
i_muser.commentsUpdated(countNew, countOldUnchanged, countOldChanged)
except ObjectDoesNotExist:
clog.logger.info("%s %s %s" % (getBaseC(mi, ts), username, "ERROR does not exist"))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_updateCommentsForAllUsers(userCount, priority):
mi = clog.dumpMethodInfo()
ts = time.time()
qs = None
if priority >= 0:
qs = muser.objects.filter(ppoi=True).filter(pprioritylevel=priority).filter(pdeleted=False).order_by('pcommentsupdatetimestamp','name')[:userCount]
else:
qs = muser.objects.filter(ppoi=True).filter(pdeleted=False).order_by('pcommentsupdatetimestamp','name')[:userCount]
if qs.count() > 0:
clog.logger.info("%s %d users being processed, priority = %d" % (getBaseP(mi), qs.count(), priority))
countOfTasksSpawned = 0
for i_muser in qs:
TASK_updateCommentsForUser.delay(i_muser.name)
countOfTasksSpawned += 1
clog.logger.info("%s %d tasks spawned" % (getBaseC(mi, ts), countOfTasksSpawned))
else:
clog.logger.info("%s zero users available at priority = %d" % (getBaseC(mi, ts), priority))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_updateThreadsForSubreddit(subredditName):
mi = clog.dumpMethodInfo()
ts = time.time()
try:
i_msubreddit = msubreddit.objects.get(name=subredditName)
clog.logger.info("%s %s" % (getBaseP(mi), subredditName))
prawReddit = i_msubreddit.getPrawRedditInstance()
params={};
params['before'] = i_msubreddit.getThreadsBestBeforeValue(prawReddit)
# clog.logger.info("before = %s" % (params['before']))
countNew = 0
countOldUnchanged = 0
countOldChanged = 0
try:
for prawThread in prawReddit.subreddit(i_msubreddit.name).new(limit=None, params=params):
i_mthread = mthread.objects.addOrUpdate(i_msubreddit, prawThread)
if i_mthread.addOrUpdateTempField == "new": countNew += 1
if i_mthread.addOrUpdateTempField == "oldUnchanged": countOldUnchanged += 1
if i_mthread.addOrUpdateTempField == "oldChanged": countOldChanged += 1
except praw.exceptions.APIException as e:
clog.logger.info("%s %s PRAW_APIException: error_type = %s, message = %s" % (getBaseC(mi, ts), subredditName, e.error_type, e.message))
clog.logger.info("%s %s: %d new, %d old, %d oldChanged" % (getBaseC(mi, ts), subredditName, countNew, countOldUnchanged, countOldChanged))
i_msubreddit.threadsUpdated(countNew, countOldUnchanged, countOldChanged)
except ObjectDoesNotExist:
clog.logger.info("%s %s, %s" % (getBaseC(mi, ts), subredditName, "ERROR does not exist"))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_updateThreadsForAllSubreddits(subredditCount, priority):
mi = clog.dumpMethodInfo()
ts = time.time()
qs = msubreddit.objects.filter(ppoi=True).filter(pprioritylevel=priority).order_by('pthreadupdatetimestamp','name')[:subredditCount]
if qs.count() > 0:
clog.logger.info("%s %d subreddits being processed, priority = %d" % (getBaseP(mi), qs.count(), priority))
countOfTasksSpawned = 0
for i_msubreddit in qs:
TASK_updateThreadsForSubreddit.delay(i_msubreddit.name)
countOfTasksSpawned += 1
clog.logger.info("%s %d tasks spawned" % (getBaseC(mi, ts), countOfTasksSpawned))
else:
clog.logger.info("%s zero subreddits available at priority = %d" % (getBaseC(mi, ts), priority))
return ""
<file_sep>/reddit/models/__init__.py
from .mbase import mbase
from .muser import muser
from .msubreddit import msubreddit
from .mthread import mthread
from .mcomment import mcomment
<file_sep>/reddit/urls.py
from django.conf.urls import url
from .views import vbase
from .views import vsubreddit
from .views import vthread
from .views import vuser
from .views import vcomment
from .views import vanalysis
urlpatterns = [
url(r'^vbase/main/$', vbase.main, name='vbase.main'),
url(r'^vbase/main/xData/(?P<xData>\w+)/$', vbase.main, name='vbase.main'),
url(r'^vbase/test/$', vbase.test, name='vbase.test'),
url(r'^vbase/map/$', vbase.map, name='vbase.map'),
url(r'^vcomment/user/(?P<username>\w+)/$', vcomment.user, name='vcomment.user'),
url(r'^vuser/list/$', vuser.list, name='vuser.list'),
url(r'^vuser/list/xData/(?P<xData>\w+)/$', vuser.list, name='vuser.list'),
url(r'^vuser/formNewPoiUser/$', vuser.formNewPoiUser, name='vuser.formNewPoiUser'),
url(r'^vsubreddit/list/$', vsubreddit.list, name='vsubreddit.list'),
url(r'^vsubreddit/list/xData/(?P<xData>\w+)/$', vsubreddit.list, name='vsubreddit.list'),
url(r'^vsubreddit/formNewPoiSubreddit/$', vsubreddit.formNewPoiSubreddit, name='vsubreddit.formNewPoiSubreddit'),
url(r'^vthread/list/(?P<subreddit>\w+)/$', vthread.list, name='vthread.list'),
url(r'^vanalysis/poiUsersOfSubreddit/(?P<subreddit>\w+)/(?P<minNumComments>\w+)/$', vanalysis.poiUsersOfSubreddit, name='vanalysis.poiUsersOfSubreddit'),
url(r'^vanalysis/moderatorsOfSubreddit/(?P<subreddit>\w+)/$', vanalysis.moderatorsOfSubreddit, name='vanalysis.moderatorsOfSubreddit'),
]
# url(r'^vuser/delAll/$', vuser.delAll, name='vuser.delAll'),
# url(r'^vsubreddit/delAll/$', vsubreddit.delAll, name='vsubreddit.delAll'),
# url(r'^vthread/delAll/$', vthread.delAll, name='vthread.delAll'),
<file_sep>/reddit/views/vsubreddit.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.core.exceptions import ObjectDoesNotExist
from django.utils.safestring import mark_safe
from ..config import clog
from ..models import msubreddit
from ..forms import fsubreddit
# import pprint
# *****************************************************************************
def list(request, xData=None):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
# qs = msubreddit.objects.all().order_by('name')
qs = msubreddit.objects.all().order_by('pprioritylevel','-pthreadupdatetimestamp')
return render(request, 'vsubreddit_list.html', {'subreddits': qs, 'rightCol': mark_safe(request.session.get(xData, ''))})
# *****************************************************************************
def delAll(request):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
vs = ''
qs = msubreddit.objects.all()
vs += str(qs.count()) + " msubreddits deleted"
qs.delete()
clog.logger.info(vs)
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vbase.main', xData=sessionKey)
# *****************************************************************************
def formNewPoiSubreddit(request):
mi = clog.dumpMethodInfo()
clog.logger.info(mi)
if request.method == 'POST': # if this is a POST request we need to process the form data
form = fsubreddit.fNewPoiSubreddit(request.POST) # create a form instance and populate it with data from the request:
if form.is_valid(): # check whether it's valid:
# process the data in form.cleaned_data as required
# pprint.pprint(form.cleaned_data)
# add subreddit as poi
prawReddit = msubreddit.getPrawRedditInstance()
prawSubreddit = prawReddit.subreddit(form.cleaned_data['poiSubreddit'])
i_msubreddit = msubreddit.objects.addOrUpdate(form.cleaned_data['poiSubreddit'], prawSubreddit)
i_msubreddit.ppoi = True
i_msubreddit.save()
vs = form.cleaned_data['poiSubreddit']
if i_msubreddit.addOrUpdateTempField == "new": vs += ' poi poiSubreddit added.'
else: vs += ' poi poiSubreddit already existed.'
clog.logger.info(vs)
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vbase.main', xData=sessionKey)
else: # if a GET (or any other method) we'll create a blank form
form = fsubreddit.fNewPoiSubreddit()
return render(request, 'fSimpleSubmitForm.html', {'form': form})
<file_sep>/reddit/models/muser.py
from __future__ import unicode_literals
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from .mbase import mbase
from ..config import clog
from datetime import datetime
from django.utils import timezone
import praw
# import pprint
# *****************************************************************************
class muserManager(models.Manager):
def addOrUpdate(self, prawRedditor):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
# NOTE: ENDED UP WITH MULITIPLE USERS WITH SAME NAME BECAUSE TWO TASKS operating
# AT THE SAME TIME CREATED BOTH USERS. THIS CAUSES THE GET CALL BELOW TO FAIL.
# FOR NOW, BEFORE FIXING THAT ISSUE AND WRITING CODE TO FIX DUPLICATE NAMES AM
# CHANGING QUERY TO FILTER AND HACKING IN DUPLICATE OF OJBECT DOE SNOT EXIST CODE
try:
qs = muser.objects.filter(name=prawRedditor.name)
if qs.count() > 0:
i_muser = qs[0]
redditFieldDict = i_muser.getRedditFieldDict()
changedCount = i_muser.updateRedditFields(prawRedditor, redditFieldDict)
if changedCount == 0: i_muser.addOrUpdateTempField = "oldUnchanged"
else: i_muser.addOrUpdateTempField = "oldChanged"
else: # hack put in object does not exist code below
i_muser = self.create(name=prawRedditor.name)
redditFieldDict = i_muser.getRedditFieldDict()
i_muser.addRedditFields(prawRedditor, redditFieldDict)
i_muser.addOrUpdateTempField = "new"
except ObjectDoesNotExist:
i_muser = self.create(name=prawRedditor.name)
redditFieldDict = i_muser.getRedditFieldDict()
i_muser.addRedditFields(prawRedditor, redditFieldDict)
i_muser.addOrUpdateTempField = "new"
i_muser.save()
return i_muser
# *****************************************************************************
# class muser(mbase, models.Model):
class muser(mbase):
name = models.CharField(max_length=30, db_index=True)
# properties
ppoi = models.BooleanField(default=False)
pprioritylevel = models.IntegerField(default=0)
pcommentsupdatetimestamp = models.DateTimeField(default=timezone.make_aware(datetime(2000, 1, 1, 1, 0, 0)))
pupdateswithnochanges = models.IntegerField(default=0)
pcountnew = models.IntegerField(default=0)
pcountOldUnchanged = models.IntegerField(default=0)
pcountOldChanged = models.IntegerField(default=0)
pdeleted = models.BooleanField(default=False)
# Redditor fields
r_path = models.CharField(max_length=40, default='', blank=True)
objects = muserManager()
# -------------------------------------------------------------------------
def getRedditFieldDict(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
redditFieldDict = {
# mThreadFieldName redditFieldName convertMethodPtr
'r_path': ("_path", None), # string
}
return redditFieldDict
# -------------------------------------------------------------------------
def __str__(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
s = self.name
if self.ppoi: s += " (ppoi)"
return format(s)
# --------------------------------------------------------------------------
def getBestCommentBeforeValue(self, prawReddit):
from .mcomment import mcomment
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
youngestRV = ''
qs = mcomment.objects.filter(username=self.name, pdeleted=False).order_by('-name')
for item in qs:
try:
# CAN I BATCH THIS QUERY UP TO GET MULTIPLE COMMENTS FROM REDDIT AT ONCE?
isValidComment = prawReddit.comment(item.name[3:])
# if isValidComment.author != None:
# if isValidComment.author != None and isValidComment.author.name != '[deleted]' and isValidComment.author.name != '[removed]':
if isValidComment.author != None and isValidComment.author != '[deleted]' and isValidComment.author != '[removed]':
youngestRV = item.name
# clog.logger.debug("youngestRV = %s" % (youngestRV))
break
else: # Update item as deleted.
item.pdeleted = True
item.save()
# clog.logger.debug("userCommentIndex %s flagged as deleted" % (item.name))
except praw.exceptions.APIException as e:
clog.logger.error("PRAW APIException: error_type = %s, message = %s" % (e.error_type, e.message))
return youngestRV
# --------------------------------------------------------------------------
def commentsUpdated(self, countNew, countOldUnchanged, countOldChanged):
mi = clog.dumpMethodInfo()
# self.precentlyupdated =True
if countNew > 0:
self.pprioritylevel -= 1
self.pupdateswithnochanges = 0
if self.pprioritylevel < 0:
self.pprioritylevel = 0;
else:
self.pprioritylevel += 1
self.pupdateswithnochanges += 1
if self.pprioritylevel > 3:
self.pprioritylevel = 3;
self.pcountnew = countNew
self.pcountOldUnchanged = countOldUnchanged
self.pcountOldChanged = countOldChanged
# self.pcommentsupdatetimestamp = datetime.now()
self.pcommentsupdatetimestamp = timezone.now()
self.save()
return
# # ----------------------------------------------------------------------------
# # REDDITOR attributes
# # Ex
# # rUser = reddit.redditor('stp2007')
# # logger.info(rUser.name) # to make it non-lazy
# # pprint.pprint(vars(rUser))
# {
# '_fetched': False,
# '_info_params': {},
# '_listing_use_sort': True,
# '_path': 'user/stp2007/',
# '_reddit': <praw.reddit.Reddit object at 0x7f45d99f9128>,
# 'name': 'stp2007'
# }
<file_sep>/reddit/tasks/ttest.py
from celery import task
import time
from django.db.models import Count
from ..config import clog
from ..models import mcomment
from ..models import msubreddit
from ..models import mthread
from ..models import muser
from .tbase import getBaseP, getBaseC
# import pprint
# --------------------------------------------------------------------------
@task()
def TASK_testLogLevels():
mi = clog.dumpMethodInfo()
ts = time.time()
clog.logger.critical("%s %s" % (getBaseC(mi, ts), 'critical'))
clog.logger.error ("%s %s" % (getBaseC(mi, ts), 'error'))
clog.logger.warning ("%s %s" % (getBaseC(mi, ts), 'warning'))
clog.logger.info ("%s %s" % (getBaseC(mi, ts), 'info'))
clog.logger.debug ("%s %s" % (getBaseC(mi, ts), 'debug'))
clog.logger.trace ("%s %s" % (getBaseC(mi, ts), 'trace'))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_testForDuplicateComments():
mi = clog.dumpMethodInfo()
ts = time.time()
clog.logger.info("%s" % (getBaseP(mi)))
qs = mcomment.objects.values('username','name','thread','subreddit').annotate(num_count=Count('name')).filter(num_count__gt=1)
if qs.count() > 0:
clog.logger.info("%s WARNING: at least %d duplicate comments" % (getBaseC(mi, ts), qs.count()))
for i_mac in qs:
value = int(i_mac['num_count'])
while value > 1:
clog.logger.info("%s WARNING: deleting %s, thread %s, subreddit %s, username %s" % (getBaseC(mi, ts), i_mac['name'], i_mac['thread'], i_mac['subreddit'], i_mac['username']))
qs2 = mcomment.objects.filter(username=i_mac['username'], name=i_mac['name'], thread=i_mac['thread'], subreddit=i_mac['subreddit'])
qs2.delete()
value -= 1
else:
clog.logger.info("%s no duplicate comments found" % (getBaseC(mi, ts)))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_testForDuplicateThreads():
mi = clog.dumpMethodInfo()
ts = time.time()
clog.logger.info("%s" % (getBaseP(mi)))
qs = mthread.objects.values('fullname').annotate(num_count=Count('fullname')).filter(num_count__gt=1)
if qs.count() > 0:
clog.logger.info("%s WARNING: at least %d duplicate threads" % (getBaseC(mi, ts), qs.count()))
for i_mac in qs:
value = int(i_mac['num_count'])
while value > 1:
clog.logger.info("%s WARNING: deleting %s" % (getBaseC(mi, ts), i_mac['fullname']))
qs2 = mthread.objects.filter(fullname=i_mac['fullname'])
qs2.delete()
value -= 1
else:
clog.logger.info("%s no duplicate threads found" % (getBaseC(mi, ts)))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_testForDuplicateUsers():
mi = clog.dumpMethodInfo()
ts = time.time()
clog.logger.info("%s" % (getBaseP(mi)))
qs = muser.objects.values('name').annotate(num_count=Count('name')).filter(num_count__gt=1)
if qs.count() > 0:
clog.logger.info("%s WARNING: at least %d duplicate users" % (getBaseC(mi, ts), qs.count()))
for i_mac in qs:
value = int(i_mac['num_count'])
while value > 1:
clog.logger.info("%s WARNING: deleting %s" % (getBaseC(mi, ts), i_mac['name']))
qs2 = muser.objects.filter(name=i_mac['name']).order_by('-pcommentsupdatetimestamp')
qs2.delete()
value -= 1
else:
clog.logger.info("%s no duplicate users found" % (getBaseC(mi, ts)))
return ""
<file_sep>/reddit/lib/cLogger.py
#!/usr/bin/env python
import logging
import datetime
import time
import inspect
import os
# import pprint
cLoggerLevel_CRITICAL = logging.CRITICAL # 50
cLoggerLevel_ERROR = logging.ERROR # 40
cLoggerLevel_WARNING = logging.WARNING # 30
cLoggerLevel_INFO = logging.INFO # 20
cLoggerLevel_DEBUG = logging.DEBUG # 10
cLoggerLevel_TRACE = 6 # 6, value of 5 conflicts with Celery "SUBDEBUG" level
cLoggerLevel_NOTSET = logging.NOTSET # 0
cLoggerFile_archiveOlder = 100
cLoggerFile_overwriteOlder = 200
cLoggerFile_appendOlder = 300
cLoggerFilter_None = 10
cLoggerFilter_SpecificLevelOnly = 20
cLoggerFilter_GreaterThanOrEqualToLevel = 30
# *****************************************************************************
# cLoggerFilter_SpecificLevelOnly
class filterSpecificLevelOnly(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
if logRecord.levelno == self.__level: return True
else: return False
# *****************************************************************************
# cLoggerFilter_GreaterThanOrEqualToLevel
class filterGreaterThanOrEqualToLevelOnly(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
if logRecord.levelno >= self.__level: return True
else: return False
# *****************************************************************************
class cLogger(object):
# --------------------------------------------------------------------------
def __init__(self, name):
self.name = name
self.baseLoggerLevel = logging.CRITICAL
self.handlerLevels = {}
self.loggerInfoLevel = logging.DEBUG
self.methodInfoLevel = logging.DEBUG
self.logger = logging.getLogger(self.name)
self.logger.setLevel(self.baseLoggerLevel)
self.funcdict = {}
# --------------------------------------------------------------------------
def getArchiveFilename(self, fNameKey, archiveIndex, fNameType):
return "%s%03d.%s" % (fNameKey, archiveIndex, fNameType)
# --------------------------------------------------------------------------
def archiveOlderVersions(self, pathFileName):
# get path and filename
pathFileTuple = pathFileName.rpartition('/') # if success: path = pathFileTuple[0], filename = pathFileTuple[2]
# get fname and ftype
nameTypeTuple = pathFileTuple[2].partition('.') # if success: fname = nameTypeTuple[0], type = nameTypeTuple[2]
# print("archiveOlderVersions A")
if not (pathFileTuple[0] and pathFileTuple[1] and nameTypeTuple[0] and nameTypeTuple[1]):
self.logger.critical("Error splitting %s into path and file and or %s into name and type" % (pathFileName, pathFileTuple[2]))
else:
# print("archiveOlderVersions B")
fNameKey = nameTypeTuple[0] # if success: fNameKey = element 0
fNameType = nameTypeTuple[2] # if success: fNameType = element 2
# get names of all previously archived files
fileList = []
for fname in os.listdir(pathFileTuple[0]):
# print("archiveOlderVersions C: fname = %s" % (fname))
if fname.startswith(fNameKey):
# print("archiveOlderVersions D: appending = %s" % (fname))
fileList.append(fname)
# remove base filename if in list
if (pathFileTuple[2] in fileList):
# print("archiveOlderVersions E: removing = %s" % (pathFileTuple[2]))
fileList.remove(pathFileTuple[2])
# reverse sort fileList
fileList.sort(reverse=True)
# len(fileList) = number of archived files found.
# therefore increment by one for archive_index for renaming
archiveIndex = len(fileList) + 1
# print("archiveOlderVersions f: archiveIndex = %s" % (archiveIndex))
# fileList is sorted with oldest names first: ex log_004.txt, log_003.txt, log_002.txt, log_001.txt
# for each rename with older archiveIndex
for x in fileList:
# print("archiveOlderVersions g renaming %s" % (x))
archiveFilename = self.getArchiveFilename(fNameKey, archiveIndex, fNameType)
# self.logger.critical("%s to be renamed to %s" % (x, archiveFilename))
os.rename(pathFileTuple[0]+'/'+x, pathFileTuple[0]+'/'+archiveFilename)
archiveIndex -= 1
# finally rename newest log file
archiveFilename = self.getArchiveFilename(fNameKey, archiveIndex, fNameType)
if (os.path.isfile(pathFileName)):
os.rename(pathFileName, pathFileTuple[0]+'/'+archiveFilename)
# --------------------------------------------------------------------------
def addConsoleLogger(self, loggingLevel, name, filterVal):
handler = logging.StreamHandler()
handler.setLevel(loggingLevel)
self.handlerLevels[name]=loggingLevel
formatter = logging.Formatter(self.getFormatString(), datefmt='%H:%M:%S')
formatter.converter = time.localtime
handler.setFormatter(formatter)
if filterVal == cLoggerFilter_GreaterThanOrEqualToLevel: handler.addFilter(filterGreaterThanOrEqualToLevelOnly(loggingLevel))
elif filterVal == cLoggerFilter_SpecificLevelOnly: handler.addFilter(filterSpecificLevelOnly(loggingLevel))
self.logger.addHandler(handler)
if loggingLevel < self.baseLoggerLevel:
self.baseLoggerLevel = loggingLevel
self.logger.setLevel(self.baseLoggerLevel)
# --------------------------------------------------------------------------
def getFileHandler(self, pathFileName, loggingLevel, name, archiveType, filterVal):
fileMode = 'w'
if archiveType == cLoggerFile_archiveOlder:
self.archiveOlderVersions(pathFileName)
elif archiveType == cLoggerFile_appendOlder:
fileMode = 'a'
# handler = logging.FileHandler(pathFileName, mode=fileMode, encoding=None, delay=False)
handler = logging.FileHandler(pathFileName, mode=fileMode, encoding=None, delay=True)
handler.setLevel(loggingLevel)
self.handlerLevels[name]=loggingLevel
formatter = logging.Formatter(self.getFormatString(), datefmt='%H:%M:%S')
formatter.converter = time.localtime
handler.setFormatter(formatter)
if filterVal == cLoggerFilter_GreaterThanOrEqualToLevel: handler.addFilter(filterGreaterThanOrEqualToLevelOnly(loggingLevel))
elif filterVal == cLoggerFilter_SpecificLevelOnly: handler.addFilter(filterSpecificLevelOnly(loggingLevel))
return handler
# --------------------------------------------------------------------------
def addFileLogger(self, pathFileName, loggingLevel, name, archiveType, filterVal):
handler = self.getFileHandler(pathFileName, loggingLevel, name, archiveType, filterVal)
self.logger.addHandler(handler)
if loggingLevel < self.baseLoggerLevel:
self.baseLoggerLevel = loggingLevel
self.logger.setLevel(self.baseLoggerLevel)
# --------------------------------------------------------------------------
def addTraceLoggingLevel(self):
logging.TRACE = cLoggerLevel_TRACE
logging.addLevelName(logging.TRACE, "TRACE")
def trace(self, message, *args, **kws):
if self.isEnabledFor(logging.TRACE):
self._log(logging.TRACE, message, args, **kws)
logging.Logger.trace = trace
# --------------------------------------------------------------------------
def generateFuncDict(self):
self.funcdict['CRITICAL'] = self.logger.critical
self.funcdict['ERROR'] = self.logger.error
self.funcdict['WARNING'] = self.logger.warning
self.funcdict['INFO'] = self.logger.info
self.funcdict['DEBUG'] = self.logger.debug
self.funcdict['TRACE'] = self.logger.trace
# --------------------------------------------------------------------------
# ref: https://docs.python.org/2/library/logging.html#logrecord-attributes
# %(levelname).1s has a precision of 1 so that many characters
def getFormatString(self):
return '%(asctime)-8s %(levelname).1s %(filename)-15s (line %(lineno)4s): %(message)s'
# --------------------------------------------------------------------------
def getMethodPtr(self, loggingLevel):
# self.logger.info("getMethodPtr")
# self.logger.info("loggingLevel = %s" % (loggingLevel))
# self.logger.info("loggingLevelName = %s" % (logging.getLevelName(loggingLevel)))
# self.logger.info("self.funcdict = %s" % (pprint.pformat(self.funcdict)))
methodPtr = self.funcdict[logging.getLevelName(loggingLevel)]
return methodPtr
# --------------------------------------------------------------------------
def setLoggerInfoLevel(self, loggingLevel):
self.loggerInfoLevel = loggingLevel
# --------------------------------------------------------------------------
def setMethodInfoLevel(self, loggingLevel):
self.methodInfoLevel = loggingLevel
# --------------------------------------------------------------------------
def dumpLoggerInfo(self):
mPtr = self.getMethodPtr(self.loggerInfoLevel)
now = datetime.datetime.now()
mPtr("************************************************************")
mPtr("%-24s: %s" % ("Initialized", self.name))
mPtr("%-24s: %s" % ("Time", str(now)))
mPtr("%-24s: %s" % ("Base Logger Level", logging.getLevelName(self.baseLoggerLevel)))
for k in self.handlerLevels:
mPtr("%-24s: %s" % (k, logging.getLevelName(self.handlerLevels[k])))
mPtr("%-24s: %s" % ("Logger Info Level", logging.getLevelName(self.loggerInfoLevel)))
mPtr("%-24s: %s" % ("Method Info Level", logging.getLevelName(self.methodInfoLevel)))
mPtr("************************************************************")
return
# --------------------------------------------------------------------------
# inspect.stack()[1] is parent of current or what called methodTrace.
# (
# <frame object at 0x7fcc7718e228>,
# '/media/shared/work/datagrab/reddit/vbase.py',
# 7,
# 'main',
# [' config.clog.methodTrace()\n'],
# 0
# )
# inspect.stack()[1][0]
def dumpMethodInfo(self):
methodName = inspect.stack()[1][3]
fileNameWithType = inspect.stack()[1][1].rpartition('/')[2] # right partition string by backslash and return third part of tuple
fileName = fileNameWithType.partition('.')[0]
os = "%-20s: " % (fileName + "." + methodName + "()")
args, _, _, values = inspect.getargvalues(inspect.stack()[1][0])
firstIteration = True
for i in args:
if firstIteration: os += "("
else: os += ", "
firstIteration = False
os += "%s=%s" % (i, values[i])
if not firstIteration: os += ")"
# Full methodInfo to TRACE
mPtr = self.getMethodPtr(cLoggerLevel_TRACE)
mPtr(os)
return methodName + "(): "
<file_sep>/datagrab/celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'datagrab.settings')
app = Celery('datagrab', broker='redis://localhost:6379/0')
# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Config options
# Restart worker after changing these
app.conf.worker_log_color=False
app.conf.worker_hijack_root_logger=False
app.conf.worker_log_format='%(asctime)-8s %(levelname).1s %(filename)-18s (line %(lineno)4s): %(message)s'
# ref: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
app.conf.timezone='Canada/Eastern'
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
<file_sep>/reddit/tasks/tbase.py
# from datagrab.celery import app as celery_app # for beat tasks
from celery import current_task
import time
# --------------------------------------------------------------------------
def getTaskId():
return current_task.request.id[:8]
# --------------------------------------------------------------------------
def getTaskP():
return 'P'
# return 'Processing'
# --------------------------------------------------------------------------
def getTaskC():
return 'C'
# return 'Completed '
# --------------------------------------------------------------------------
def getMI(mi):
rv = mi[:-2]
return rv.ljust(36,' ') # max length of task name plus trailing paranthesis is 36
# --------------------------------------------------------------------------
def getTimeDif(ts):
td = round(time.time()-ts, 0)
return '[' + str(int(td)) + ']'
# --------------------------------------------------------------------------
def getBaseP(mi):
return "%s: %s %s:" % (getTaskId(), getMI(mi), getTaskP())
# --------------------------------------------------------------------------
def getBaseC(mi, ts):
return "%s: %s %s: %s:" % (getTaskId(), getMI(mi), getTaskC(), getTimeDif(ts))
# --------------------------------------------------------------------------
def getLine():
return "*******************************************"
<file_sep>/datagrab/__init__.py
# *****************************************************************************
# Import datagrab/datagrab/celery.py
from __future__ import absolute_import, unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
__all__ = ['celery_app']
# *****************************************************************************
# Update sys.path to allow importing python files from libPython directory
import sys
sys.path.insert(0, "/home/delta/work/datagrab/reddit/lib")
# *****************************************************************************
# Set up logger
from reddit.config import initializeCLogger
initializeCLogger()
<file_sep>/reddit/tasks/__init__.py
from datagrab.celery import app as celery_app # for beat tasks
from celery.schedules import crontab # for crontab periodic tasks
from .tmisc import TASK_template, TASK_inspectTaskQueue, TASK_displayModelCounts
from .treddit import TASK_updateUsersForAllComments, TASK_updateCommentsForAllUsers, TASK_updateCommentsForUser, TASK_updateThreadsForAllSubreddits, TASK_updateThreadCommentsByForest
from .ttest import TASK_testLogLevels, TASK_testForDuplicateUsers, TASK_testForDuplicateComments, TASK_testForDuplicateThreads
CONST_SECONDS_05 = 5
CONST_MINUTES_01 = 60
CONST_MINUTES_02 = CONST_MINUTES_01*2
CONST_MINUTES_05 = CONST_MINUTES_01*5
CONST_MINUTES_10 = CONST_MINUTES_01*10
CONST_MINUTES_15 = CONST_MINUTES_01*15
CONST_MINUTES_20 = CONST_MINUTES_01*20
CONST_MINUTES_30 = CONST_MINUTES_01*30
CONST_HOURS___01 = CONST_MINUTES_01*60
CONST_HOURS___02 = CONST_HOURS___01*2
CONST_HOURS___03 = CONST_HOURS___01*3
CONST_HOURS___04 = CONST_HOURS___01*4
CONST_HOURS___05 = CONST_HOURS___01*5
CONST_HOURS___06 = CONST_HOURS___01*6
CONST_HOURS___07 = CONST_HOURS___01*7
CONST_HOURS___08 = CONST_HOURS___01*8
CONST_HOURS___09 = CONST_HOURS___01*9
CONST_HOURS___10 = CONST_HOURS___01*10
CONST_HOURS___11 = CONST_HOURS___01*11
CONST_HOURS___12 = CONST_HOURS___01*12
# --------------------------------------------------------------------------
# can add expires parameter (in seconds)
# Ex: sender.add_periodic_task(60.0, TASK_template.s(), expires=10)
@celery_app.on_after_finalize.connect
def setup_periodic_tasks(sender, **kwargs):
# sender.add_periodic_task(CONST_SECONDS_05, TASK_testLogLevels.s())
# sender.add_periodic_task(CONST_SECONDS_05, TASK_template.s())
sender.add_periodic_task(CONST_MINUTES_02, TASK_inspectTaskQueue.s(), expires=CONST_MINUTES_02-10)
sender.add_periodic_task(CONST_MINUTES_15, TASK_updateThreadsForAllSubreddits.s(20, 0), expires=CONST_MINUTES_15-10)
sender.add_periodic_task(CONST_HOURS___01, TASK_updateThreadsForAllSubreddits.s(20, 1), expires=CONST_HOURS___01-10)
sender.add_periodic_task(CONST_HOURS___02, TASK_updateThreadsForAllSubreddits.s(20, 2), expires=CONST_HOURS___02-10)
sender.add_periodic_task(CONST_HOURS___02, TASK_updateThreadsForAllSubreddits.s(20, 3), expires=CONST_HOURS___02-10)
sender.add_periodic_task(CONST_HOURS___01, TASK_updateCommentsForAllUsers.s(100, 0), expires=CONST_HOURS___01-10)
sender.add_periodic_task(CONST_HOURS___02, TASK_updateCommentsForAllUsers.s(100, 1), expires=CONST_HOURS___02-10)
sender.add_periodic_task(CONST_HOURS___03, TASK_updateCommentsForAllUsers.s(100, 2), expires=CONST_HOURS___03-10)
sender.add_periodic_task(CONST_HOURS___04, TASK_updateCommentsForAllUsers.s(100, 3), expires=CONST_HOURS___04-10)
sender.add_periodic_task(CONST_MINUTES_10, TASK_displayModelCounts.s(), expires=CONST_MINUTES_10-10)
sender.add_periodic_task(CONST_MINUTES_02, TASK_updateThreadCommentsByForest.s(30), expires=CONST_MINUTES_02-10)
sender.add_periodic_task(CONST_MINUTES_05, TASK_updateUsersForAllComments.s(100), expires=CONST_MINUTES_05-10)
sender.add_periodic_task(CONST_HOURS___03, TASK_testForDuplicateUsers.s(), expires=CONST_HOURS___03-10)
sender.add_periodic_task(CONST_HOURS___03, TASK_testForDuplicateComments.s(), expires=CONST_HOURS___03-10)
sender.add_periodic_task(CONST_HOURS___03, TASK_testForDuplicateThreads.s(), expires=CONST_HOURS___03-10)
pass
# --------------------------------------------------------------------------
@celery_app.on_after_finalize.connect
def launch_tasks_on_startup(sender, **kwargs):
# TASK_inspectTaskQueue.delay()
# TASK_displayModelCounts.delay()
# TASK_updateThreadCommentsByForest.delay(30)
# TASK_updateUsersForAllComments.delay(100)
# TASK_testForDuplicateUsers.delay()
# TASK_testForDuplicateComments.delay()
# TASK_testForDuplicateThreads.delay()
# TASK_updateCommentsForAllUsers.delay(2000, -1)
# TASK_updateThreadsForAllSubreddits.delay(51, 3)
# TASK_updateThreadsForAllSubreddits.delay(51, 2)
# TASK_updateThreadsForAllSubreddits.delay(51, 1)
# TASK_updateThreadsForAllSubreddits.delay(51, 0)
pass
# --------------------------------------------------------------------------
# sender.add_periodic_task(
# crontab(hour=7, minute=30, day_of_week=1),
# test.s('Happy Mondays!'),
# )
# task.delay(arg1,arg2) #will be async
# task.delay(arg1,arg2).get() #will be sync
# task.delay(arg1,arg2).get() #will be sync
<file_sep>/reddit/apps.py
from __future__ import unicode_literals
from django.apps import AppConfig
class RedditConfig(AppConfig):
name = 'reddit'
<file_sep>/reddit/views/vanalysis.py
from django.http import HttpResponse
from django.db.models import Count
from django.shortcuts import redirect
from django.core.exceptions import ObjectDoesNotExist
from ..config import clog
from ..models import msubreddit, mcomment, muser
import pprint
# # *****************************************************************************
def poiUsersOfSubreddit(request, subreddit, minNumComments):
mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
vs = mi
prawReddit = msubreddit.getPrawRedditInstance()
prawSubreddit = prawReddit.subreddit(subreddit)
subredditDict = {}
# Get a list of users who've posted in this subreddit
# and sort this by number of comments
qs = mcomment.objects.filter(subreddit=prawSubreddit.name).values('username').annotate(num_count=Count('username')).order_by('-num_count')
for i_mcommentAnnotatedUserCount in qs:
# {'num_count': 785, 'username': 'RobRoyWithTwist'}
if i_mcommentAnnotatedUserCount['num_count'] >= int(minNumComments):
# print(i_mcommentAnnotatedUserCount)
# Add this user as poi
prawRedditor = prawReddit.redditor(i_mcommentAnnotatedUserCount['username'])
i_muser = muser.objects.addOrUpdate(prawRedditor)
i_muser.ppoi = True
i_muser.save()
if i_muser.addOrUpdateTempField == "new":
vs += "<br>" + i_mcommentAnnotatedUserCount['username']
# # Get subreddits this person also comments in
qs2 = mcomment.objects.filter(username=i_mcommentAnnotatedUserCount['username']).values('rsubreddit_name_prefixed').annotate(num_count2=Count('rsubreddit_name_prefixed')).order_by('-num_count2')
for i_mcommentAnnotatedSubredditCount in qs2:
if i_mcommentAnnotatedSubredditCount['rsubreddit_name_prefixed'] not in subredditDict:
subredditDict[i_mcommentAnnotatedSubredditCount['rsubreddit_name_prefixed']] = 0
subredditDict[i_mcommentAnnotatedSubredditCount['rsubreddit_name_prefixed']] += i_mcommentAnnotatedSubredditCount['num_count2']
topCount = 10
vs += "<br>Top " + str(topCount) + " subreddits these poi also post to are:"
from operator import itemgetter
sortedList = sorted(subredditDict.items(), key=itemgetter(1), reverse=True)
for v in sortedList:
# print(v)
# # ('r/The_Donald', 34890)
# # ('r/politics', 224)
if topCount >= 1:
vs += "<br>" + v[0]
topCount -= 1
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vsubreddit.list', xData=sessionKey)
# # *****************************************************************************
def moderatorsOfSubreddit(request, subreddit):
mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
vs = mi
prawReddit = msubreddit.getPrawRedditInstance()
prawSubreddit = prawReddit.subreddit(subreddit)
for moderator in prawSubreddit.moderator():
# print('{}: {}'.format(moderator, moderator.mod_permissions))
# DatabaseCentral: ['wiki', 'posts', 'access', 'mail', 'config', 'flair']
# Add this user as poi
prawRedditor = prawReddit.redditor(moderator.name)
i_muser = muser.objects.addOrUpdate(prawRedditor)
i_muser.ppoi = True
i_muser.save()
if i_muser.addOrUpdateTempField == "new":
vs += "<br> added: " + moderator.name
# Get list of subreddits these mods also moderate
# Seems like there isn't an API endpoint for this in Reddit or Praw api.
# could manually scrape the page but nope not right now.
sessionKey = 'blue'
request.session[sessionKey] = vs
return redirect('vsubreddit.list', xData=sessionKey)
<file_sep>/reddit/admin.py
from django.contrib import admin
# from .models import subredditSubmissionRaw
#
# admin.site.register(subredditSubmissionRaw)
<file_sep>/reddit/models/mthread.py
from __future__ import unicode_literals
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from .mbase import mbase
from .msubreddit import msubreddit
from ..config import clog
# import praw
# import pprint
# *****************************************************************************
class mthreadManager(models.Manager):
def addOrUpdate(self, i_msubreddit, prawThread):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
try:
i_mthread = self.get(subreddit=i_msubreddit, fullname=prawThread.name)
redditFieldDict = i_mthread.getRedditFieldDict()
changedCount = i_mthread.updateRedditFields(prawThread, redditFieldDict)
if changedCount == 0: i_mthread.addOrUpdateTempField = "oldUnchanged"
else: i_mthread.addOrUpdateTempField = "oldChanged"
except ObjectDoesNotExist:
i_mthread = self.create(subreddit=i_msubreddit, fullname=prawThread.name)
redditFieldDict = i_mthread.getRedditFieldDict()
i_mthread.addRedditFields(prawThread, redditFieldDict)
i_mthread.addOrUpdateTempField = "new"
# clog.logger.debug("i_mthread = %s" % (pprint.pformat(vars(i_mthread))))
i_mthread.save()
return i_mthread
# *****************************************************************************
# class mthread(mbase, models.Model):
class mthread(mbase):
subreddit = models.ForeignKey(msubreddit, on_delete=models.CASCADE,)
fullname = models.CharField(max_length=12)
# properties
pdeleted = models.BooleanField(default=False)
pforestgot = models.BooleanField(default=False)
pcount = models.PositiveIntegerField(default=0)
# Redditor fields
rapproved_by = models.CharField(max_length=21, default='', blank=True)
rauthor = models.CharField(max_length=21, default='', blank=True)
rbanned_by = models.CharField(max_length=21, default='', blank=True)
rdomain = models.CharField(max_length=64, default='', blank=True)
rid = models.CharField(max_length=10, default='', blank=True)
rtitle = models.CharField(max_length=301, default='', blank=True)
rurl = models.CharField(max_length=2084, default='', blank=True)
rmod_reports = models.TextField(default='', blank=True)
rselftext = models.TextField(default='')
ruser_reports = models.TextField(default='', blank=True)
rdowns = models.IntegerField(default=0)
rnum_comments = models.IntegerField(default=0)
rscore = models.IntegerField(default=0)
rups = models.IntegerField(default=0)
rhidden = models.BooleanField(default=False)
ris_self = models.BooleanField(default=False)
rlocked = models.BooleanField(default=False)
rquarantine = models.BooleanField(default=False)
rcreated = models.DecimalField(default=0, max_digits=12,decimal_places=1)
rcreated_utc = models.DecimalField(default=0, max_digits=12,decimal_places=1)
redited = models.DecimalField(default=0, max_digits=12,decimal_places=1)
objects = mthreadManager()
# -------------------------------------------------------------------------
def getRedditFieldDict(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
redditFieldDict = {
# mThreadFieldName redditFieldName convertMethodPtr
'rapproved_by': ("approved_by", self.getRedditUserNameAsString), # special
'rauthor': ("author", self.getRedditUserNameAsString), # special
'rbanned_by': ("banned_by", self.getRedditUserNameAsString), # special
'rdomain': ("domain", None), # string
'rid': ("id", None), # string
'rtitle': ("title", None), # string
'rurl': ("url", None), # string
'rmod_reports': ("mod_reports", None), # [[u'mod reported text', u'stp2007']], OR [[u'Spam', u'stp2007']]
'rselftext': ("selftext", None), # string
'ruser_reports': ("user_reports", None), # [[u'Text for other reason', 1]] OR [[u'Spam', 1]]
'rdowns': ("downs", int), # int
'rnum_comments': ("num_comments", int), # int
'rscore': ("score", int), # int
'rups': ("ups", int), # int
'rhidden': ("hidden", None), # bool
'ris_self': ("is_self", None), # bool
'rlocked': ("locked", None), # bool
'rquarantine': ("quarantine", None), # bool
'rcreated': ("created", None), # 1493534605.0,
'rcreated_utc': ("created_utc", None), # 1493534605.0,
'redited': ("edited", self.getEditedOrFalseValueAsZero), # False or timestamp
}
return redditFieldDict
# -------------------------------------------------------------------------
def __str__(self):
# mi = clog.dumpMethodInfo()
# clog.logger.info(mi)
s = self.subreddit.name
s += " [" + self.fullname + "]"
s += " [" + str(self.pcount) + "]"
if self.pforestgot: s += " (pforestgot = True)"
else: s += " (pforestgot = False)"
return format(s)
# # ----------------------------------------------------------------------------
# # SUBMISSION attributes
# # EX:
# # subreddit = reddit.subreddit('redditdev')
# # submission = subreddit.hot(limit=1).next()
# # logger.info(submission.title) # to make it non-lazy
# # pprint.pprint(vars(submission))
# {
# '_comments_by_id': {},
# '_fetched': False,
# '_flair': None,
# '_info_params': {},
# '_mod': None,
# '_reddit': <praw.reddit.Reddit object at 0x7fee4ac8beb8>,
# 'approved_by': None,
# 'archived': False,
# 'author_flair_css_class': None,
# 'author_flair_text': None,
# 'author': Redditor(name='bboe'),
# 'banned_by': None,
# 'brand_safe': True,
# 'can_gild': True,
# 'clicked': False,
# 'comment_limit': 2048,
# 'comment_sort': 'best',
# 'contest_mode': False,
# 'created_utc': 1493534605.0,
# 'created': 1493563405.0,
# 'distinguished': None,
# 'domain': 'self.redditdev',
# 'downs': 0,
# 'edited': False,
# 'gilded': 0,
# 'hidden': False,
# 'hide_score': False,
# 'id': '68e6pp',
# 'is_self': True,
# 'likes': None,
# 'link_flair_css_class': None,
# 'link_flair_text': None,
# 'locked': False,
# 'media_embed': {},
# 'media': None,
# 'mod_reports': [],
# 'name': 't3_68e6pp',
# 'num_comments': 0,
# 'num_reports': None,
# 'over_18': False,
# 'permalink': '/r/redditdev/comments/68e6pp/praw_450_released/',
# 'quarantine': False,
# 'removal_reason': None, # This attribute is deprecated. Please use mod_reports and user_reports instead.
# 'report_reasons': None, # This attribute is deprecated. Please use mod_reports and user_reports instead.
# 'saved': False,
# 'score': 18,
# 'secure_media_embed': {},
# 'secure_media': None,
# 'selftext_html': '<!-- SC_OFF --><div class="md"><p>Notable additions:</p>\n',
# 'selftext': 'Notable additions:\n',
# 'spoiler': False,
# 'stickied': True,
# 'subreddit_id': 't5_2qizd',
# 'subreddit_name_prefixed': 'r/redditdev',
# 'subreddit_type': 'public',
# 'subreddit': Subreddit(display_name='redditdev'),
# 'suggested_sort': None,
# 'thumbnail': '',
# 'title': 'PRAW 4.5.0 Released',
# 'ups': 18,
# 'url': 'https://www.reddit.com/r/redditdev/comments/68e6pp/praw_450_released/',
# 'user_reports': [],
# 'view_count': None,
# 'visited': False
# }
<file_sep>/reddit/tasks/tmisc.py
from celery import task
from celery.task.control import inspect # for ispectTasks
import time
from ..config import clog
from .tbase import getBaseP, getBaseC, getLine
from ..models import mcomment
from ..models import msubreddit
from ..models import mthread
from ..models import muser
# import pprint
# --------------------------------------------------------------------------
@task()
def TASK_template():
mi = clog.dumpMethodInfo()
ts = time.time()
# # create PRAW prawReddit instance
# prawReddit = mcomment.getPrawRedditInstance()
clog.logger.info("%s" % (getBaseP(mi)))
clog.logger.info("%s" % (getBaseC(mi, ts)))
return ""
# --------------------------------------------------------------------------
heartbeatTickString = "TICK"
@task()
def TASK_inspectTaskQueue():
mi = clog.dumpMethodInfo()
ts = time.time()
thisTaskName = 'reddit.tasks.tmisc.TASK_inspectTaskQueue'
workerName = "celery<EMAIL>"
i = inspect()
# clog.logger.info("scheduled: %s" % (pprint.pformat(i.scheduled())))
# clog.logger.info("active: %s" % (pprint.pformat(i.active())))
# clog.logger.info("reserved: %s" % (pprint.pformat(i.reserved())))
# Scheduled Tasks
scheduledCount = 0
scheduled = i.scheduled()
if len(scheduled) > 0 and workerName in scheduled:
scheduledList = scheduled[workerName]
for item in scheduledList:
if item['name'] != thisTaskName: # Ignore THIS task
scheduledCount += 1
# Active Tasks
activeCount = 0
active = i.active()
if len(active) > 0 and workerName in active:
activeList = active[workerName]
for item in activeList:
if item['name'] != thisTaskName: # Ignore THIS task
activeCount += 1
# Reserved Tasks
reservedCount = 0
reserved = i.reserved()
if len(reserved) > 0 and workerName in reserved:
reservedList = reserved[workerName]
for item in reservedList:
if item['name'] != thisTaskName: # Ignore THIS task
reservedCount += 1
global heartbeatTickString
if heartbeatTickString == 'TICK': heartbeatTickString = 'tock'
else: heartbeatTickString = 'TICK'
if scheduledCount or activeCount or reservedCount:
clog.logger.info("%s %s: %d active, %d scheduled, %d reserved" % (getBaseC(mi, ts), heartbeatTickString, activeCount, scheduledCount, reservedCount))
else:
clog.logger.info("%s %s: %s" % (getBaseC(mi, ts), heartbeatTickString, "*** no pending tasks ***"))
return ""
# --------------------------------------------------------------------------
@task()
def TASK_generateModelCountData():
mi = clog.dumpMethodInfo()
users_poi = muser.objects.filter(ppoi=True).count()
users_notPoi = muser.objects.filter(ppoi=False).count()
users_poi_pri_0 = muser.objects.filter(ppoi=True).filter(pprioritylevel=0).count()
users_poi_pri_1 = muser.objects.filter(ppoi=True).filter(pprioritylevel=1).count()
users_poi_pri_2 = muser.objects.filter(ppoi=True).filter(pprioritylevel=2).count()
users_poi_pri_3 = muser.objects.filter(ppoi=True).filter(pprioritylevel=3).count()
comments_usersAdded = mcomment.objects.filter(puseradded=True).count()
comments_notUsersAdded = mcomment.objects.filter(puseradded=False).count()
subreddits_poi = msubreddit.objects.filter(ppoi=True).count()
subreddits_notPoi = msubreddit.objects.filter(ppoi=False).count()
subreddits_poi_pri_0 = msubreddit.objects.filter(ppoi=True).filter(pprioritylevel=0).count()
subreddits_poi_pri_1 = msubreddit.objects.filter(ppoi=True).filter(pprioritylevel=1).count()
subreddits_poi_pri_2 = msubreddit.objects.filter(ppoi=True).filter(pprioritylevel=2).count()
subreddits_poi_pri_3 = msubreddit.objects.filter(ppoi=True).filter(pprioritylevel=3).count()
threads_forestGot = mthread.objects.filter(pforestgot=True).count()
threads_notForestGot = mthread.objects.filter(pforestgot=False).count()
listOfModelCountStrings = []
listOfModelCountStrings.append("%-30s %8d" % ("Users poi", users_poi))
listOfModelCountStrings.append("%-30s %8d" % ("Users !poi", users_notPoi))
listOfModelCountStrings.append("%s" % ("---------------------------------------"))
listOfModelCountStrings.append("%-30s %8d" % ("Users poi priority 0", users_poi_pri_0))
listOfModelCountStrings.append("%-30s %8d" % ("Users poi priority 1", users_poi_pri_1))
listOfModelCountStrings.append("%-30s %8d" % ("Users poi priority 2", users_poi_pri_2))
listOfModelCountStrings.append("%-30s %8d" % ("Users poi priority 3", users_poi_pri_3))
listOfModelCountStrings.append("%s" % ("---------------------------------------"))
listOfModelCountStrings.append("%-30s %8d" % ("Comments users added", comments_usersAdded))
listOfModelCountStrings.append("%-30s %8d" % ("Comments !users added", comments_notUsersAdded))
listOfModelCountStrings.append("%-30s %8d" % ("Comments total", comments_usersAdded + comments_notUsersAdded))
listOfModelCountStrings.append("%s" % ("---------------------------------------"))
listOfModelCountStrings.append("%-30s %8d" % ("Subreddits poi", subreddits_poi))
listOfModelCountStrings.append("%-30s %8d" % ("Subreddits !poi", subreddits_notPoi))
listOfModelCountStrings.append("%s" % ("---------------------------------------"))
listOfModelCountStrings.append("%-30s %8d" % ("Subreddits poi priority 0", subreddits_poi_pri_0))
listOfModelCountStrings.append("%-30s %8d" % ("Subreddits poi priority 1", subreddits_poi_pri_1))
listOfModelCountStrings.append("%-30s %8d" % ("Subreddits poi priority 2", subreddits_poi_pri_2))
listOfModelCountStrings.append("%-30s %8d" % ("Subreddits poi priority 3", subreddits_poi_pri_3))
listOfModelCountStrings.append("%s" % ("---------------------------------------"))
listOfModelCountStrings.append("%-30s %8d" % ("Threads forestGot", threads_forestGot))
listOfModelCountStrings.append("%-30s %8d" % ("Threads !forestGot", threads_notForestGot))
listOfModelCountStrings.append("%-30s %8d" % ("Threads total", threads_forestGot + threads_notForestGot))
return listOfModelCountStrings
# --------------------------------------------------------------------------
@task()
def TASK_displayModelCounts():
mi = clog.dumpMethodInfo()
ts = time.time()
listOfModelCountStrings = TASK_generateModelCountData()
clog.logger.info("%s %s" % (getBaseC(mi, ts), getLine()))
for line in listOfModelCountStrings:
# clog.logger.info("%s * %s *" % (getBaseC(mi, ts), line))
clog.logger.info("%s %s " % (getBaseC(mi, ts), line))
clog.logger.info("%s %s" % (getBaseC(mi, ts), getLine()))
return
| 88dd02708e5a914a95d079fd9f6ca437dca66a39 | [
"Python"
] | 27 | Python | VestedSkeptic/datagrab | ad4c8b5185dce6c24a156d1e29b5b32af3257343 | 48caeb2bb7ea4af96d014369cf8f63c82bc45d3b | |
refs/heads/main | <file_sep>package profiling
import (
"net/http"
_ "net/http/pprof"
"runtime"
"github.com/pkg/errors"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/node"
"github.com/iotaledger/hive.go/configuration"
)
func init() {
Plugin = &node.Plugin{
Status: node.StatusEnabled,
Pluggable: node.Pluggable{
Name: "Profiling",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
Run: run,
},
}
}
var (
Plugin *node.Plugin
deps dependencies
)
type dependencies struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
}
func run() {
runtime.SetMutexProfileFraction(5)
runtime.SetBlockProfileRate(5)
bindAddr := deps.NodeConfig.String(CfgProfilingBindAddress)
go func() {
Plugin.LogInfof("You can now access the profiling server using: http://%s/debug/pprof/", bindAddr)
// pprof Server for Debugging
if err := http.ListenAndServe(bindAddr, nil); err != nil && !errors.Is(err, http.ErrServerClosed) {
Plugin.LogWarnf("Stopped profiling server due to an error (%s)", err)
}
}()
}
<file_sep>package gracefulshutdown
import (
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/shutdown"
)
func init() {
CorePlugin = &node.CorePlugin{
Pluggable: node.Pluggable{
Name: "Graceful Shutdown",
Provide: provide,
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Configure: configure,
},
}
}
var (
CorePlugin *node.CorePlugin
deps dependencies
)
type dependencies struct {
dig.In
ShutdownHandler *shutdown.ShutdownHandler
}
func provide(c *dig.Container) {
if err := c.Provide(func() *shutdown.ShutdownHandler {
return shutdown.NewShutdownHandler(CorePlugin.Logger(), CorePlugin.Daemon())
}); err != nil {
CorePlugin.Panic(err)
}
}
func configure() {
deps.ShutdownHandler.Run()
}
<file_sep>package pow
import (
"time"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/pow"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/configuration"
)
func init() {
CorePlugin = &node.CorePlugin{
Pluggable: node.Pluggable{
Name: "PoW",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
Provide: provide,
Run: run,
},
}
}
var (
CorePlugin *node.CorePlugin
deps dependencies
)
const (
powsrvInitCooldown = 30 * time.Second
)
type dependencies struct {
dig.In
Handler *pow.Handler
}
func provide(c *dig.Container) {
type handlerDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
MinPoWScore float64 `name:"minPoWScore"`
}
if err := c.Provide(func(deps handlerDeps) *pow.Handler {
// init the pow handler with all possible settings
powsrvAPIKey, err := utils.LoadStringFromEnvironment("POWSRV_API_KEY")
if err == nil && len(powsrvAPIKey) > 12 {
powsrvAPIKey = powsrvAPIKey[:12]
}
return pow.New(CorePlugin.Logger(), deps.MinPoWScore, deps.NodeConfig.Duration(CfgPoWRefreshTipsInterval), powsrvAPIKey, powsrvInitCooldown)
}); err != nil {
CorePlugin.Panic(err)
}
}
func run() {
// close the PoW handler on shutdown
if err := CorePlugin.Daemon().BackgroundWorker("PoW Handler", func(shutdownSignal <-chan struct{}) {
CorePlugin.LogInfo("Starting PoW Handler ... done")
<-shutdownSignal
CorePlugin.LogInfo("Stopping PoW Handler ...")
deps.Handler.Close()
CorePlugin.LogInfo("Stopping PoW Handler ... done")
}, shutdown.PriorityPoWHandler); err != nil {
CorePlugin.Panicf("failed to start worker: %s", err)
}
}
<file_sep>// TODO: obviously move all this into its separate pkg
package p2p
import (
"context"
"path/filepath"
"time"
"github.com/libp2p/go-libp2p"
connmgr "github.com/libp2p/go-libp2p-connmgr"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/p2p"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/logger"
)
func init() {
CorePlugin = &node.CorePlugin{
Pluggable: node.Pluggable{
Name: "P2P",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
InitConfigPars: initConfigPars,
Provide: provide,
Configure: configure,
Run: run,
},
}
}
var (
CorePlugin *node.CorePlugin
deps dependencies
)
type dependencies struct {
dig.In
Manager *p2p.Manager
Host host.Host
NodeConfig *configuration.Configuration `name:"nodeConfig"`
PeerStoreContainer *p2p.PeerStoreContainer
PeeringConfig *configuration.Configuration `name:"peeringConfig"`
PeeringConfigManager *p2p.ConfigManager
}
func initConfigPars(c *dig.Container) {
type cfgDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
}
type cfgResult struct {
dig.Out
P2PDatabasePath string `name:"p2pDatabasePath"`
P2PBindMultiAddresses []string `name:"p2pBindMultiAddresses"`
}
if err := c.Provide(func(deps cfgDeps) cfgResult {
return cfgResult{
P2PDatabasePath: deps.NodeConfig.String(CfgP2PDatabasePath),
P2PBindMultiAddresses: deps.NodeConfig.Strings(CfgP2PBindMultiAddresses),
}
}); err != nil {
CorePlugin.Panic(err)
}
}
func provide(c *dig.Container) {
type hostDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
DatabaseEngine database.Engine `name:"databaseEngine"`
P2PDatabasePath string `name:"p2pDatabasePath"`
P2PBindMultiAddresses []string `name:"p2pBindMultiAddresses"`
}
type p2presult struct {
dig.Out
PeerStoreContainer *p2p.PeerStoreContainer
NodePrivateKey crypto.PrivKey `name:"nodePrivateKey"`
Host host.Host
}
if err := c.Provide(func(deps hostDeps) p2presult {
res := p2presult{}
privKeyFilePath := filepath.Join(deps.P2PDatabasePath, p2p.PrivKeyFileName)
peerStoreContainer, err := p2p.NewPeerStoreContainer(filepath.Join(deps.P2PDatabasePath, "peers"), deps.DatabaseEngine, true)
if err != nil {
CorePlugin.Panic(err)
}
res.PeerStoreContainer = peerStoreContainer
// TODO: temporary migration logic
// this should be removed after some time / hornet versions (20.08.21: muXxer)
identityPrivKey := deps.NodeConfig.String(CfgP2PIdentityPrivKey)
migrated, err := p2p.MigrateDeprecatedPeerStore(deps.P2PDatabasePath, identityPrivKey, peerStoreContainer)
if err != nil {
CorePlugin.Panicf("migration of deprecated peer store failed: %s", err)
}
if migrated {
CorePlugin.LogInfof(`The peer store was migrated successfully!
Your node identity private key can now be found at "%s".
`, privKeyFilePath)
}
// make sure nobody copies around the peer store since it contains the private key of the node
CorePlugin.LogInfof(`WARNING: never share your "%s" folder as it contains your node's private key!`, deps.P2PDatabasePath)
// load up the previously generated identity or create a new one
privKey, newlyCreated, err := p2p.LoadOrCreateIdentityPrivateKey(deps.P2PDatabasePath, identityPrivKey)
if err != nil {
CorePlugin.Panic(err)
}
res.NodePrivateKey = privKey
if newlyCreated {
CorePlugin.LogInfof(`stored new private key for peer identity under "%s"`, privKeyFilePath)
} else {
CorePlugin.LogInfof(`loaded existing private key for peer identity from "%s"`, privKeyFilePath)
}
createdHost, err := libp2p.New(context.Background(),
libp2p.Identity(privKey),
libp2p.ListenAddrStrings(deps.P2PBindMultiAddresses...),
libp2p.Peerstore(peerStoreContainer.Peerstore()),
libp2p.DefaultTransports,
libp2p.ConnectionManager(connmgr.NewConnManager(
deps.NodeConfig.Int(CfgP2PConnMngLowWatermark),
deps.NodeConfig.Int(CfgP2PConnMngHighWatermark),
time.Minute,
)),
libp2p.NATPortMap(),
)
if err != nil {
CorePlugin.Panicf("unable to initialize peer: %s", err)
}
res.Host = createdHost
return res
}); err != nil {
CorePlugin.Panic(err)
}
type mngDeps struct {
dig.In
Host host.Host
Config *configuration.Configuration `name:"nodeConfig"`
AutopeeringRunAsEntryNode bool `name:"autopeeringRunAsEntryNode"`
}
if err := c.Provide(func(deps mngDeps) *p2p.Manager {
if !deps.AutopeeringRunAsEntryNode {
return p2p.NewManager(deps.Host,
p2p.WithManagerLogger(logger.NewLogger("P2P-Manager")),
p2p.WithManagerReconnectInterval(deps.Config.Duration(CfgP2PReconnectInterval), 1*time.Second),
)
}
return nil
}); err != nil {
CorePlugin.Panic(err)
}
type configManagerDeps struct {
dig.In
PeeringConfig *configuration.Configuration `name:"peeringConfig"`
PeeringConfigFilePath string `name:"peeringConfigFilePath"`
}
if err := c.Provide(func(deps configManagerDeps) *p2p.ConfigManager {
p2pConfigManager := p2p.NewConfigManager(func(peers []*p2p.PeerConfig) error {
if err := deps.PeeringConfig.Set(CfgPeers, peers); err != nil {
return err
}
return deps.PeeringConfig.StoreFile(deps.PeeringConfigFilePath, []string{"p2p"})
})
// peers from peering config
var peers []*p2p.PeerConfig
if err := deps.PeeringConfig.Unmarshal(CfgPeers, &peers); err != nil {
CorePlugin.Panicf("invalid peer config: %s", err)
}
for i, p := range peers {
multiAddr, err := multiaddr.NewMultiaddr(p.MultiAddress)
if err != nil {
CorePlugin.Panicf("invalid config peer address at pos %d: %s", i, err)
}
if err = p2pConfigManager.AddPeer(multiAddr, p.Alias); err != nil {
CorePlugin.LogWarnf("unable to add peer to config manager %s: %s", p.MultiAddress, err)
}
}
// peers from CLI arguments
peerIDsStr := deps.PeeringConfig.Strings(CfgP2PPeers)
peerAliases := deps.PeeringConfig.Strings(CfgP2PPeerAliases)
applyAliases := true
if len(peerIDsStr) != len(peerAliases) {
CorePlugin.LogWarnf("won't apply peer aliases: you must define aliases for all defined static peers (got %d aliases, %d peers).", len(peerAliases), len(peerIDsStr))
applyAliases = false
}
for i, peerIDStr := range peerIDsStr {
multiAddr, err := multiaddr.NewMultiaddr(peerIDStr)
if err != nil {
CorePlugin.Panicf("invalid CLI peer address at pos %d: %s", i, err)
}
var alias string
if applyAliases {
alias = peerAliases[i]
}
if err = p2pConfigManager.AddPeer(multiAddr, alias); err != nil {
CorePlugin.LogWarnf("unable to add peer to config manager %s: %s", peerIDStr, err)
}
}
p2pConfigManager.StoreOnChange(true)
return p2pConfigManager
}); err != nil {
CorePlugin.Panic(err)
}
}
func configure() {
CorePlugin.LogInfof("peer configured, ID: %s", deps.Host.ID())
if err := CorePlugin.Daemon().BackgroundWorker("Close p2p peer database", func(shutdownSignal <-chan struct{}) {
<-shutdownSignal
closeDatabases := func() error {
if err := deps.PeerStoreContainer.Flush(); err != nil {
return err
}
return deps.PeerStoreContainer.Close()
}
CorePlugin.LogInfo("Syncing p2p peer database to disk...")
if err := closeDatabases(); err != nil {
CorePlugin.Panicf("Syncing p2p peer database to disk... failed: %s", err)
}
CorePlugin.LogInfo("Syncing p2p peer database to disk... done")
}, shutdown.PriorityCloseDatabase); err != nil {
CorePlugin.Panicf("failed to start worker: %s", err)
}
}
func run() {
if deps.Manager == nil {
// Manager is optional, due to autopeering entry node
return
}
// register a daemon to disconnect all peers up on shutdown
if err := CorePlugin.Daemon().BackgroundWorker("Manager", func(shutdownSignal <-chan struct{}) {
CorePlugin.LogInfof("listening on: %s", deps.Host.Addrs())
go deps.Manager.Start(shutdownSignal)
connectConfigKnownPeers()
<-shutdownSignal
if err := deps.Host.Peerstore().Close(); err != nil {
CorePlugin.LogError("unable to cleanly closing peer store: %s", err)
}
}, shutdown.PriorityP2PManager); err != nil {
CorePlugin.Panicf("failed to start worker: %s", err)
}
}
// connects to the peers defined in the config.
func connectConfigKnownPeers() {
for _, p := range deps.PeeringConfigManager.Peers() {
multiAddr, err := multiaddr.NewMultiaddr(p.MultiAddress)
if err != nil {
CorePlugin.Panicf("invalid peer address: %s", err)
}
addrInfo, err := peer.AddrInfoFromP2pAddr(multiAddr)
if err != nil {
CorePlugin.Panicf("invalid peer address info: %s", err)
}
if err = deps.Manager.ConnectPeer(addrInfo, p2p.PeerRelationKnown, p.Alias); err != nil {
CorePlugin.LogInfof("can't connect to peer (%s): %s", multiAddr.String(), err)
}
}
}
<file_sep>package database
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/kvstore/pebble"
"github.com/iotaledger/hive.go/kvstore/rocksdb"
)
type databaseInfo struct {
Engine string `toml:"databaseEngine"`
}
// DatabaseEngine parses a string and returns an engine.
// Returns an error if the engine is unknown.
func DatabaseEngine(engine string) (Engine, error) {
switch engine {
case EngineRocksDB:
case EnginePebble:
default:
return "", fmt.Errorf("unknown database engine: %s, supported engines: pebble/rocksdb", engine)
}
return Engine(engine), nil
}
// CheckDatabaseEngine checks if the correct database engine is used.
// This function stores a so called "database info file" in the database folder or
// checks if an existing "database info file" contains the correct engine.
// Otherwise the files in the database folder are not compatible.
func CheckDatabaseEngine(dbPath string, createDatabaseIfNotExists bool, dbEngine ...Engine) (Engine, error) {
if createDatabaseIfNotExists && len(dbEngine) == 0 {
return EngineRocksDB, errors.New("the database engine must be specified if the database should be newly created")
}
// check if the database exists and if it should be created
_, err := os.Stat(dbPath)
if err != nil {
if !os.IsNotExist(err) {
return EngineUnknown, fmt.Errorf("unable to check database path (%s): %w", dbPath, err)
}
if !createDatabaseIfNotExists {
return EngineUnknown, fmt.Errorf("database not found (%s)", dbPath)
}
// database will be newly created
}
var targetEngine Engine
// check if the database info file exists and if it should be created
dbInfoFilePath := filepath.Join(dbPath, "dbinfo")
_, err = os.Stat(dbInfoFilePath)
if err != nil {
if !os.IsNotExist(err) {
return EngineUnknown, fmt.Errorf("unable to check database info file (%s): %w", dbInfoFilePath, err)
}
if len(dbEngine) == 0 {
return EngineUnknown, fmt.Errorf("database info file not found (%s)", dbInfoFilePath)
}
// if the dbInfo file does not exist and the dbEngine is given, create the dbInfo file.
if err := storeDatabaseInfoToFile(dbInfoFilePath, dbEngine[0]); err != nil {
return EngineUnknown, err
}
targetEngine = dbEngine[0]
} else {
dbEngineFromInfoFile, err := LoadDatabaseEngineFromFile(dbInfoFilePath)
if err != nil {
return EngineUnknown, err
}
// if the dbInfo file exists and the dbEngine is given, compare the engines.
if len(dbEngine) > 0 {
if dbEngineFromInfoFile != dbEngine[0] {
return EngineUnknown, fmt.Errorf(`database engine does not match the configuration: '%v' != '%v'
If you want to use another database engine, you can use the tool './hornet tool db-migration' to convert the current database.`, dbEngineFromInfoFile, dbEngine[0])
}
}
targetEngine = dbEngineFromInfoFile
}
return targetEngine, nil
}
// LoadDatabaseEngineFromFile returns the engine from the "database info file".
func LoadDatabaseEngineFromFile(path string) (Engine, error) {
var info databaseInfo
if err := utils.ReadTOMLFromFile(path, &info); err != nil {
return "", fmt.Errorf("unable to read database info file: %w", err)
}
return DatabaseEngine(info.Engine)
}
// storeDatabaseInfoToFile stores the used engine in a "database info file".
func storeDatabaseInfoToFile(filePath string, engine Engine) error {
dirPath := filepath.Dir(filePath)
if err := os.MkdirAll(dirPath, 0700); err != nil {
return fmt.Errorf("could not create database dir '%s': %w", dirPath, err)
}
info := &databaseInfo{
Engine: string(engine),
}
return utils.WriteTOMLToFile(filePath, info, 0660, "# auto-generated\n# !!! do not modify this file !!!")
}
// StoreWithDefaultSettings returns a kvstore with default settings.
// It also checks if the database engine is correct.
func StoreWithDefaultSettings(path string, createDatabaseIfNotExists bool, dbEngine ...Engine) (kvstore.KVStore, error) {
targetEngine, err := CheckDatabaseEngine(path, createDatabaseIfNotExists, dbEngine...)
if err != nil {
return nil, err
}
switch targetEngine {
case EnginePebble:
db, err := NewPebbleDB(path, nil, false)
if err != nil {
return nil, err
}
return pebble.New(db), nil
case EngineRocksDB:
db, err := NewRocksDB(path)
if err != nil {
return nil, err
}
return rocksdb.New(db), nil
default:
return nil, fmt.Errorf("unknown database engine: %s, supported engines: pebble/rocksdb", dbEngine)
}
}
<file_sep>package faucet
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"
"go.uber.org/dig"
"golang.org/x/time/rate"
"github.com/gohornet/hornet/pkg/model/faucet"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/gohornet/hornet/pkg/model/utxo"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/pow"
"github.com/gohornet/hornet/pkg/protocol/gossip"
"github.com/gohornet/hornet/pkg/restapi"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/pkg/tipselect"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/configuration"
iotago "github.com/iotaledger/iota.go/v2"
"github.com/iotaledger/iota.go/v2/ed25519"
)
const (
// RouteFaucetInfo is the route to give info about the faucet address.
// GET returns address and balance of the faucet.
RouteFaucetInfo = "/info"
// RouteFaucetEnqueue is the route to tell the faucet to pay out some funds to the given address.
// POST enqueues a new request.
RouteFaucetEnqueue = "/enqueue"
)
func init() {
Plugin = &node.Plugin{
Status: node.StatusDisabled,
Pluggable: node.Pluggable{
Name: "Faucet",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
Provide: provide,
Configure: configure,
Run: run,
},
}
}
var (
Plugin *node.Plugin
deps dependencies
)
type dependencies struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
RestAPIBindAddress string `name:"restAPIBindAddress"`
FaucetAllowedAPIRoute restapi.AllowedRoute `name:"faucetAllowedAPIRoute"`
Faucet *faucet.Faucet
Echo *echo.Echo
ShutdownHandler *shutdown.ShutdownHandler
}
func provide(c *dig.Container) {
privateKeys, err := utils.LoadEd25519PrivateKeysFromEnvironment("FAUCET_PRV_KEY")
if err != nil {
Plugin.Panicf("loading faucet private key failed, err: %s", err)
}
if len(privateKeys) == 0 {
Plugin.Panic("loading faucet private key failed, err: no private keys given")
}
if len(privateKeys) > 1 {
Plugin.Panic("loading faucet private key failed, err: too many private keys given")
}
privateKey := privateKeys[0]
if len(privateKey) != ed25519.PrivateKeySize {
Plugin.Panic("loading faucet private key failed, err: wrong private key length")
}
faucetAddress := iotago.AddressFromEd25519PubKey(privateKey.Public().(ed25519.PublicKey))
faucetSigner := iotago.NewInMemoryAddressSigner(iotago.NewAddressKeysForEd25519Address(&faucetAddress, privateKey))
type faucetDeps struct {
dig.In
Storage *storage.Storage
PowHandler *pow.Handler
UTXO *utxo.Manager
NodeConfig *configuration.Configuration `name:"nodeConfig"`
NetworkID uint64 `name:"networkId"`
BelowMaxDepth int `name:"belowMaxDepth"`
Bech32HRP iotago.NetworkPrefix `name:"bech32HRP"`
TipSelector *tipselect.TipSelector
MessageProcessor *gossip.MessageProcessor
}
if err := c.Provide(func(deps faucetDeps) *faucet.Faucet {
return faucet.New(
deps.Storage,
deps.NetworkID,
deps.BelowMaxDepth,
deps.UTXO,
&faucetAddress,
faucetSigner,
deps.TipSelector.SelectNonLazyTips,
deps.PowHandler,
deps.MessageProcessor.Emit,
faucet.WithLogger(Plugin.Logger()),
faucet.WithHRPNetworkPrefix(deps.Bech32HRP),
faucet.WithAmount(uint64(deps.NodeConfig.Int64(CfgFaucetAmount))),
faucet.WithSmallAmount(uint64(deps.NodeConfig.Int64(CfgFaucetSmallAmount))),
faucet.WithMaxAddressBalance(uint64(deps.NodeConfig.Int64(CfgFaucetMaxAddressBalance))),
faucet.WithMaxOutputCount(deps.NodeConfig.Int(CfgFaucetMaxOutputCount)),
faucet.WithIndexationMessage(deps.NodeConfig.String(CfgFaucetIndexationMessage)),
faucet.WithBatchTimeout(deps.NodeConfig.Duration(CfgFaucetBatchTimeout)),
faucet.WithPowWorkerCount(deps.NodeConfig.Int(CfgFaucetPoWWorkerCount)),
)
}); err != nil {
Plugin.Panic(err)
}
}
func configure() {
routeGroup := deps.Echo.Group("/api/plugins/faucet")
allowedRoutes := map[string][]string{
http.MethodGet: {
"/api/plugins/faucet/info",
},
}
rateLimiterSkipper := func(context echo.Context) bool {
// Check for which route we will skip the rate limiter
routesForMethod, exists := allowedRoutes[context.Request().Method]
if !exists {
return false
}
path := context.Request().URL.EscapedPath()
for _, prefix := range routesForMethod {
if strings.HasPrefix(path, prefix) {
return true
}
}
return false
}
rateLimiterConfig := middleware.RateLimiterConfig{
Skipper: rateLimiterSkipper,
Store: middleware.NewRateLimiterMemoryStoreWithConfig(
middleware.RateLimiterMemoryStoreConfig{
Rate: rate.Limit(1 / 300.0), // 1 request every 5 minutes
Burst: 10, // additional burst of 10 requests
ExpiresIn: 5 * time.Minute,
},
),
IdentifierExtractor: func(ctx echo.Context) (string, error) {
id := ctx.RealIP()
return id, nil
},
ErrorHandler: func(context echo.Context, err error) error {
return context.JSON(http.StatusForbidden, nil)
},
DenyHandler: func(context echo.Context, identifier string, err error) error {
return context.JSON(http.StatusTooManyRequests, nil)
},
}
routeGroup.Use(middleware.RateLimiterWithConfig(rateLimiterConfig))
routeGroup.GET(RouteFaucetInfo, func(c echo.Context) error {
resp, err := getFaucetInfo(c)
if err != nil {
return err
}
return restapi.JSONResponse(c, http.StatusOK, resp)
})
routeGroup.POST(RouteFaucetEnqueue, func(c echo.Context) error {
resp, err := addFaucetOutputToQueue(c)
if err != nil {
// own error handler to have nicer user facing error messages.
var statusCode int
var message string
var e *echo.HTTPError
if errors.As(err, &e) {
statusCode = e.Code
if errors.Is(err, restapi.ErrInvalidParameter) {
message = strings.Replace(err.Error(), ": "+errors.Unwrap(err).Error(), "", 1)
} else {
message = err.Error()
}
} else {
statusCode = http.StatusInternalServerError
message = fmt.Sprintf("internal server error. error: %s", err)
}
return c.JSON(statusCode, restapi.HTTPErrorResponseEnvelope{Error: restapi.HTTPErrorResponse{Code: strconv.Itoa(statusCode), Message: message}})
}
return restapi.JSONResponse(c, http.StatusAccepted, resp)
})
}
func run() {
// create a background worker that handles the enqueued faucet requests
if err := Plugin.Daemon().BackgroundWorker("Faucet", func(shutdownSignal <-chan struct{}) {
if err := deps.Faucet.RunFaucetLoop(shutdownSignal); err != nil {
deps.ShutdownHandler.SelfShutdown(fmt.Sprintf("faucet plugin hit a critical error: %s", err.Error()))
}
}, shutdown.PriorityFaucet); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
websiteEnabled := deps.NodeConfig.Bool(CfgFaucetWebsiteEnabled)
if websiteEnabled {
bindAddr := deps.NodeConfig.String(CfgFaucetWebsiteBindAddress)
e := echo.New()
e.HideBanner = true
e.Use(middleware.Recover())
setupRoutes(e)
go func() {
Plugin.LogInfof("You can now access the faucet website using: http://%s", bindAddr)
if err := e.Start(bindAddr); err != nil && !errors.Is(err, http.ErrServerClosed) {
Plugin.LogWarnf("Stopped faucet website server due to an error (%s)", err)
}
}()
}
}
<file_sep>module github.com/gohornet/hornet
go 1.16
replace github.com/labstack/gommon => github.com/muXxer/gommon v0.3.1-0.20210805133353-359faea1baf6
replace github.com/linxGnu/grocksdb => github.com/gohornet/grocksdb v1.6.34-0.20210518222204-d6ea5eedcfb9
require (
github.com/DataDog/zstd v1.4.8 // indirect
github.com/Microsoft/go-winio v0.5.0 // indirect
github.com/Shopify/sarama v1.29.1 // indirect
github.com/StackExchange/wmi v1.2.1 // indirect
github.com/bits-and-blooms/bitset v1.2.0
github.com/blang/vfs v1.0.0
github.com/cockroachdb/errors v1.8.6 // indirect
github.com/cockroachdb/pebble v0.0.0-20210831135706-8731fd6ed157
github.com/cockroachdb/redact v1.1.3 // indirect
github.com/containerd/containerd v1.5.5 // indirect
github.com/dgraph-io/ristretto v0.1.0 // indirect
github.com/docker/docker v20.10.8+incompatible
github.com/docker/go-connections v0.4.0
github.com/dustin/go-humanize v1.0.0
github.com/eclipse/paho.mqtt.golang v1.3.5
github.com/fhmq/hmq v0.0.0-20210810024638-1d6979189a22
github.com/gin-gonic/gin v1.7.4 // indirect
github.com/go-echarts/go-echarts v1.0.0
github.com/go-playground/validator/v10 v10.9.0 // indirect
github.com/gobuffalo/packr/v2 v2.8.1
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/google/go-querystring v1.1.0 // indirect
github.com/gorilla/websocket v1.4.2
github.com/hashicorp/go-version v1.3.0 // indirect
github.com/iotaledger/go-ds-kvstore v0.0.0-20210819121432-6e2ce2d41200
github.com/iotaledger/hive.go v0.0.0-20210830134454-9d969a8cc0a2
github.com/iotaledger/iota.go v1.0.0
github.com/iotaledger/iota.go/v2 v2.0.1-0.20210830162758-173bada804f9
github.com/ipfs/go-cid v0.1.0 // indirect
github.com/ipfs/go-datastore v0.4.6
github.com/ipfs/go-ds-badger v0.2.7
github.com/karrick/godirwalk v1.16.1 // indirect
github.com/labstack/echo/v4 v4.5.0
github.com/labstack/gommon v0.3.0
github.com/libp2p/go-libp2p v0.15.0-rc.1
github.com/libp2p/go-libp2p-connmgr v0.2.4
github.com/libp2p/go-libp2p-core v0.9.0
github.com/libp2p/go-libp2p-peerstore v0.2.9-0.20210814101051-ca567f210575
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/mr-tron/base58 v1.2.0
github.com/multiformats/go-multiaddr v0.4.0
github.com/pelletier/go-toml v1.9.3 // indirect
github.com/pelletier/go-toml/v2 v2.0.0-beta.3
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.11.0
github.com/segmentio/fasthash v1.0.3 // indirect
github.com/shirou/gopsutil v3.21.8+incompatible
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.7.1-0.20210427113832-6241f9ab9942
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e
github.com/tidwall/gjson v1.8.1 // indirect
github.com/tklauser/go-sysconf v0.3.9 // indirect
github.com/ugorji/go v1.2.6 // indirect
github.com/wollac/iota-crypto-demo v0.0.0-20210820085437-1a7b8ead2881
gitlab.com/powsrv.io/go/client v0.0.0-20210203192329-84583796cd46
go.uber.org/atomic v1.9.0
go.uber.org/dig v1.12.0
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
golang.org/x/exp v0.0.0-20210831221722-b4e88ed8e8aa // indirect
golang.org/x/net v0.0.0-20210825183410-e898025ed96a
golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e // indirect
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2 // indirect
)
<file_sep>package gossip
import (
"fmt"
"sync"
"time"
"github.com/gohornet/hornet/pkg/dag"
"github.com/gohornet/hornet/pkg/model/hornet"
"github.com/gohornet/hornet/pkg/model/milestone"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/syncutils"
)
// NewWarpSync creates a new WarpSync instance with the given advancement range and criteria func.
// If no advancement func is provided, the WarpSync uses AdvanceAtPercentageReached with DefaultAdvancementThreshold.
func NewWarpSync(advRange int, advanceCheckpointCriteriaFunc ...AdvanceCheckpointCriteria) *WarpSync {
ws := &WarpSync{
AdvancementRange: advRange,
Events: Events{
CheckpointUpdated: events.NewEvent(CheckpointCaller),
TargetUpdated: events.NewEvent(TargetCaller),
Start: events.NewEvent(SyncStartCaller),
Done: events.NewEvent(SyncDoneCaller),
},
}
if len(advanceCheckpointCriteriaFunc) > 0 {
ws.advCheckpointCriteria = advanceCheckpointCriteriaFunc[0]
} else {
ws.advCheckpointCriteria = AdvanceAtPercentageReached(DefaultAdvancementThreshold)
}
return ws
}
func SyncStartCaller(handler interface{}, params ...interface{}) {
handler.(func(target milestone.Index, newCheckpoint milestone.Index, msRange int32))(params[0].(milestone.Index), params[1].(milestone.Index), params[2].(int32))
}
func SyncDoneCaller(handler interface{}, params ...interface{}) {
handler.(func(delta int, referencedMessagesTotal int, dur time.Duration))(params[0].(int), params[1].(int), params[2].(time.Duration))
}
func CheckpointCaller(handler interface{}, params ...interface{}) {
handler.(func(newCheckpoint milestone.Index, oldCheckpoint milestone.Index, msRange int32, target milestone.Index))(params[0].(milestone.Index), params[1].(milestone.Index), params[2].(int32), params[3].(milestone.Index))
}
func TargetCaller(handler interface{}, params ...interface{}) {
handler.(func(checkpoint milestone.Index, target milestone.Index))(params[0].(milestone.Index), params[1].(milestone.Index))
}
// Events holds WarpSync related events.
type Events struct {
// Fired when a new set of milestones should be requested.
CheckpointUpdated *events.Event
// Fired when the target milestone is updated.
TargetUpdated *events.Event
// Fired when warp synchronization starts.
Start *events.Event
// Fired when the warp synchronization is done.
Done *events.Event
}
// AdvanceCheckpointCriteria is a function which determines whether the checkpoint should be advanced.
type AdvanceCheckpointCriteria func(currentConfirmed, previousCheckpoint, currentCheckpoint milestone.Index) bool
// DefaultAdvancementThreshold is the default threshold at which a checkpoint advancement is done.
// Per default an advancement is always done as soon the confirmed milestone enters the range between
// the previous and current checkpoint.
const DefaultAdvancementThreshold = 0.0
// AdvanceAtPercentageReached is an AdvanceCheckpointCriteria which advances the checkpoint
// when the current one was reached by >=X% by the current confirmed milestone in relation to the previous checkpoint.
func AdvanceAtPercentageReached(threshold float64) AdvanceCheckpointCriteria {
return func(currentConfirmed, previousCheckpoint, currentCheckpoint milestone.Index) bool {
// the previous checkpoint can be over the current confirmed milestone,
// as advancements move the checkpoint window above the confirmed milestone
if currentConfirmed < previousCheckpoint {
return false
}
checkpointDelta := currentCheckpoint - previousCheckpoint
progress := currentConfirmed - previousCheckpoint
return float64(progress)/float64(checkpointDelta) >= threshold
}
}
// WarpSync is metadata about doing a synchronization via STING messages.
type WarpSync struct {
sync.Mutex
// The used advancement range per checkpoint.
AdvancementRange int
// The Events of the warpsync.
Events Events
// The criteria whether to advance to the next checkpoint.
advCheckpointCriteria AdvanceCheckpointCriteria
// The current confirmed milestone of the node.
CurrentConfirmedMilestone milestone.Index
// The starting time of the synchronization.
StartTime time.Time
// The starting point of the synchronization.
InitMilestone milestone.Index
// The target milestone to which to synchronize to.
TargetMilestone milestone.Index
// The previous checkpoint of the synchronization.
PreviousCheckpoint milestone.Index
// The current checkpoint of the synchronization.
CurrentCheckpoint milestone.Index
// The amount of referenced messages during this warpsync run.
referencedMessagesTotal int
}
// UpdateCurrentConfirmedMilestone updates the current confirmed milestone index state.
func (ws *WarpSync) UpdateCurrentConfirmedMilestone(current milestone.Index) {
ws.Lock()
defer ws.Unlock()
if current <= ws.CurrentConfirmedMilestone {
return
}
ws.CurrentConfirmedMilestone = current
// synchronization not started
if ws.CurrentCheckpoint == 0 {
return
}
// finished
if ws.TargetMilestone != 0 && ws.CurrentConfirmedMilestone >= ws.TargetMilestone {
ws.Events.Done.Trigger(int(ws.TargetMilestone-ws.InitMilestone), ws.referencedMessagesTotal, time.Since(ws.StartTime))
ws.reset()
return
}
// check whether advancement criteria is fulfilled
if !ws.advCheckpointCriteria(ws.CurrentConfirmedMilestone, ws.PreviousCheckpoint, ws.CurrentCheckpoint) {
return
}
oldCheckpoint := ws.CurrentCheckpoint
if msRange := ws.advanceCheckpoint(); msRange != 0 {
ws.Events.CheckpointUpdated.Trigger(ws.CurrentCheckpoint, oldCheckpoint, msRange, ws.TargetMilestone)
}
}
// UpdateTargetMilestone updates the synchronization target if it is higher than the current one and
// triggers a synchronization start if the target was set for the first time.
func (ws *WarpSync) UpdateTargetMilestone(target milestone.Index) {
ws.Lock()
defer ws.Unlock()
if target <= ws.TargetMilestone {
return
}
ws.TargetMilestone = target
// as a special case, while we are warp syncing and within the last checkpoint range,
// new target milestones need to shift the checkpoint to the new target, in order
// to fire an 'updated checkpoint event'/respectively updating the request queue filter.
// since we will request missing parents for the new target, it will still solidify
// even though we discarded requests for a short period of time parents when the
// request filter wasn't yet updated.
if ws.CurrentCheckpoint != 0 && ws.CurrentCheckpoint+milestone.Index(ws.AdvancementRange) > ws.TargetMilestone {
oldCheckpoint := ws.CurrentCheckpoint
reqRange := ws.TargetMilestone - ws.CurrentCheckpoint
ws.CurrentCheckpoint = ws.TargetMilestone
ws.Events.CheckpointUpdated.Trigger(ws.CurrentCheckpoint, oldCheckpoint, int32(reqRange), ws.TargetMilestone)
}
if ws.CurrentCheckpoint != 0 {
// if synchronization was already started, only update the target
ws.Events.TargetUpdated.Trigger(ws.CurrentCheckpoint, ws.TargetMilestone)
return
}
// do not start the synchronization if current confirmed is newer than the target or the delta is smaller than 2
if ws.CurrentConfirmedMilestone >= ws.TargetMilestone || target-ws.CurrentConfirmedMilestone < 2 {
return
}
// start the synchronization
ws.StartTime = time.Now()
ws.InitMilestone = ws.CurrentConfirmedMilestone
ws.PreviousCheckpoint = ws.CurrentConfirmedMilestone
advancementRange := ws.advanceCheckpoint()
ws.Events.Start.Trigger(ws.TargetMilestone, ws.CurrentCheckpoint, advancementRange)
}
// AddReferencedMessagesCount adds the amount of referenced messages to collect stats.
func (ws *WarpSync) AddReferencedMessagesCount(referencedMessagesCount int) {
ws.Lock()
defer ws.Unlock()
ws.referencedMessagesTotal += referencedMessagesCount
}
// advances the next checkpoint by either incrementing from the current
// via the checkpoint range or max to the target of the synchronization.
// returns the chosen range.
func (ws *WarpSync) advanceCheckpoint() int32 {
if ws.CurrentCheckpoint != 0 {
ws.PreviousCheckpoint = ws.CurrentCheckpoint
}
advRange := milestone.Index(ws.AdvancementRange)
// make sure we advance max to the target milestone
if ws.TargetMilestone-ws.CurrentConfirmedMilestone <= advRange || ws.TargetMilestone-ws.CurrentCheckpoint <= advRange {
deltaRange := ws.TargetMilestone - ws.CurrentCheckpoint
if deltaRange > ws.TargetMilestone-ws.CurrentConfirmedMilestone {
deltaRange = ws.TargetMilestone - ws.CurrentConfirmedMilestone
}
ws.CurrentCheckpoint = ws.TargetMilestone
return int32(deltaRange)
}
// at start simply advance from the current confirmed
if ws.CurrentCheckpoint == 0 {
ws.CurrentCheckpoint = ws.CurrentConfirmedMilestone + advRange
return int32(advRange)
}
ws.CurrentCheckpoint = ws.CurrentCheckpoint + advRange
return int32(advRange)
}
// resets the warp sync.
func (ws *WarpSync) reset() {
ws.StartTime = time.Time{}
ws.InitMilestone = 0
ws.TargetMilestone = 0
ws.PreviousCheckpoint = 0
ws.CurrentCheckpoint = 0
ws.referencedMessagesTotal = 0
}
// NewWarpSyncMilestoneRequester creates a new WarpSyncMilestoneRequester instance.
func NewWarpSyncMilestoneRequester(storage *storage.Storage, requester *Requester, preventDiscard bool) *WarpSyncMilestoneRequester {
return &WarpSyncMilestoneRequester{
storage: storage,
requester: requester,
preventDiscard: preventDiscard,
traversed: make(map[string]struct{}),
}
}
// WarpSyncMilestoneRequester walks the cones of existing but non-solid milestones and memoizes already walked messages and milestones.
type WarpSyncMilestoneRequester struct {
syncutils.Mutex
storage *storage.Storage
requester *Requester
preventDiscard bool
traversed map[string]struct{}
}
// RequestMissingMilestoneParents traverses the parents of a given milestone and requests each missing parent.
// Already requested milestones or traversed messages will be ignored, to circumvent requesting
// the same parents multiple times.
func (w *WarpSyncMilestoneRequester) RequestMissingMilestoneParents(msIndex milestone.Index) {
w.Lock()
defer w.Unlock()
if msIndex <= w.storage.ConfirmedMilestoneIndex() {
return
}
cachedMs := w.storage.CachedMilestoneOrNil(msIndex) // milestone +1
if cachedMs == nil {
panic(fmt.Sprintf("milestone %d wasn't found", msIndex))
}
milestoneMessageID := cachedMs.Milestone().MessageID
cachedMs.Release(true) // message -1
// error is ignored because the next milestone will repeat the process anyway
_ = dag.TraverseParentsOfMessage(w.storage, milestoneMessageID,
// traversal stops if no more messages pass the given condition
// Caution: condition func is not in DFS order
func(cachedMsgMeta *storage.CachedMetadata) (bool, error) { // meta +1
defer cachedMsgMeta.Release(true) // meta -1
mapKey := cachedMsgMeta.Metadata().MessageID().ToMapKey()
if _, previouslyTraversed := w.traversed[mapKey]; previouslyTraversed {
return false, nil
}
w.traversed[mapKey] = struct{}{}
if cachedMsgMeta.Metadata().IsSolid() {
return false, nil
}
return true, nil
},
// consumer
nil,
// called on missing parents
func(parentMessageID hornet.MessageID) error {
w.requester.Request(parentMessageID, msIndex, w.preventDiscard)
return nil
},
// called on solid entry points
// Ignore solid entry points (snapshot milestone included)
nil,
false, nil)
}
// Cleanup cleans up traversed messages to free memory.
func (w *WarpSyncMilestoneRequester) Cleanup() {
w.Lock()
defer w.Unlock()
w.traversed = make(map[string]struct{})
}
<file_sep>package toolset
import (
"fmt"
"os"
"path/filepath"
"github.com/iotaledger/hive.go/configuration"
"github.com/libp2p/go-libp2p-core/peer"
p2pCore "github.com/gohornet/hornet/core/p2p"
"github.com/gohornet/hornet/pkg/jwt"
"github.com/gohornet/hornet/pkg/p2p"
"github.com/gohornet/hornet/plugins/restapi"
)
func generateJWTApiToken(nodeConfig *configuration.Configuration, args []string) error {
printUsage := func() {
println("Usage:")
println(fmt.Sprintf(" %s [P2P_DATABASE_PATH]", ToolJWTApi))
println()
println(" [P2P_DATABASE_PATH] - the path to the p2p database folder (optional)")
println()
println(fmt.Sprintf("example: %s %s", ToolJWTApi, "p2pstore"))
}
if len(args) > 1 {
printUsage()
return fmt.Errorf("too many arguments for '%s'", ToolJWTApi)
}
salt := nodeConfig.String(restapi.CfgRestAPIJWTAuthSalt)
if len(salt) == 0 {
return fmt.Errorf("'%s' should not be empty", restapi.CfgRestAPIJWTAuthSalt)
}
p2pDatabasePath := nodeConfig.String(p2pCore.CfgP2PDatabasePath)
if len(args) > 0 {
p2pDatabasePath = args[0]
}
privKeyFilePath := filepath.Join(p2pDatabasePath, p2p.PrivKeyFileName)
_, err := os.Stat(privKeyFilePath)
switch {
case os.IsNotExist(err):
// private key does not exist
return fmt.Errorf("private key file (%s) does not exist", privKeyFilePath)
case err == nil || os.IsExist(err):
// private key file exists
default:
return fmt.Errorf("unable to check private key file (%s): %w", privKeyFilePath, err)
}
privKey, err := p2p.ReadEd25519PrivateKeyFromPEMFile(privKeyFilePath)
if err != nil {
return fmt.Errorf("reading private key file for peer identity failed: %w", err)
}
peerID, err := peer.IDFromPublicKey(privKey.GetPublic())
if err != nil {
return fmt.Errorf("unable to get peer identity from public key: %w", err)
}
// API tokens do not expire.
jwtAuth, err := jwt.NewJWTAuth(salt,
0,
peerID.String(),
privKey,
)
if err != nil {
return fmt.Errorf("JWT auth initialization failed: %w", err)
}
jwtToken, err := jwtAuth.IssueJWT(true, false)
if err != nil {
return fmt.Errorf("issuing JWT token failed: %w", err)
}
fmt.Println("Your API JWT token: ", jwtToken)
return nil
}
<file_sep>package restapi
import (
"net/http"
"github.com/labstack/echo/v4"
)
func setupHealthRoute() {
deps.Echo.GET(nodeAPIHealthRoute, func(c echo.Context) error {
// node mode
if deps.Tangle != nil && !deps.Tangle.IsNodeHealthy() {
return c.NoContent(http.StatusServiceUnavailable)
}
return c.NoContent(http.StatusOK)
})
}
<file_sep>package faucet
import (
"time"
flag "github.com/spf13/pflag"
"github.com/gohornet/hornet/pkg/node"
iotago "github.com/iotaledger/iota.go/v2"
)
const (
// the amount of funds the requester receives.
CfgFaucetAmount = "faucet.amount"
// the amount of funds the requester receives if the target address has more funds than the faucet amount and less than maximum.
CfgFaucetSmallAmount = "faucet.smallAmount"
// the maximum allowed amount of funds on the target address.
CfgFaucetMaxAddressBalance = "faucet.maxAddressBalance"
// the maximum output count per faucet message.
CfgFaucetMaxOutputCount = "faucet.maxOutputCount"
// the faucet transaction indexation payload.
CfgFaucetIndexationMessage = "faucet.indexationMessage"
// the maximum duration for collecting faucet batches.
CfgFaucetBatchTimeout = "faucet.batchTimeout"
// the amount of workers used for calculating PoW when issuing faucet messages.
CfgFaucetPoWWorkerCount = "faucet.powWorkerCount"
// the bind address on which the faucet website can be accessed from
CfgFaucetWebsiteBindAddress = "faucet.website.bindAddress"
// whether to host the faucet website
CfgFaucetWebsiteEnabled = "faucet.website.enabled"
)
var params = &node.PluginParams{
Params: map[string]*flag.FlagSet{
"nodeConfig": func() *flag.FlagSet {
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.Int64(CfgFaucetAmount, 10000000, "the amount of funds the requester receives")
fs.Int64(CfgFaucetSmallAmount, 1000000, "the amount of funds the requester receives if the target address has more funds than the faucet amount and less than maximum")
fs.Int64(CfgFaucetMaxAddressBalance, 20000000, "the maximum allowed amount of funds on the target address")
fs.Int(CfgFaucetMaxOutputCount, iotago.MaxOutputsCount, "the maximum output count per faucet message")
fs.String(CfgFaucetIndexationMessage, "HORNET FAUCET", "the faucet transaction indexation payload")
fs.Duration(CfgFaucetBatchTimeout, 2*time.Second, "the maximum duration for collecting faucet batches")
fs.Int(CfgFaucetPoWWorkerCount, 0, "the amount of workers used for calculating PoW when issuing faucet messages")
fs.String(CfgFaucetWebsiteBindAddress, "localhost:8091", "the bind address on which the faucet website can be accessed from")
fs.Bool(CfgFaucetWebsiteEnabled, false, "whether to host the faucet website")
return fs
}(),
},
Masked: nil,
}
<file_sep>package database
import (
"encoding/json"
"errors"
"time"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/syncutils"
)
type Engine string
const (
EngineUnknown = "unknown"
EngineRocksDB = "rocksdb"
EnginePebble = "pebble"
)
var (
// ErrNothingToCleanUp is returned when nothing is there to clean up in the database.
ErrNothingToCleanUp = errors.New("Nothing to clean up in the databases")
)
type DatabaseCleanup struct {
Start time.Time
End time.Time
}
func (c *DatabaseCleanup) MarshalJSON() ([]byte, error) {
cleanup := struct {
Start int64 `json:"start"`
End int64 `json:"end"`
}{
Start: 0,
End: 0,
}
if !c.Start.IsZero() {
cleanup.Start = c.Start.Unix()
}
if !c.End.IsZero() {
cleanup.End = c.End.Unix()
}
return json.Marshal(cleanup)
}
func DatabaseCleanupCaller(handler interface{}, params ...interface{}) {
handler.(func(*DatabaseCleanup))(params[0].(*DatabaseCleanup))
}
type Events struct {
DatabaseCleanup *events.Event
DatabaseCompaction *events.Event
}
// New creates a new Database instance.
func New(log *logger.Logger, kvStore kvstore.KVStore, events *Events, compactionSupported bool, compactionRunningFunc func() bool) *Database {
return &Database{
log: log,
store: kvStore,
events: events,
compactionSupported: compactionSupported,
compactionRunningFunc: compactionRunningFunc,
}
}
// Database holds the underlying KVStore and database specific functions.
type Database struct {
log *logger.Logger
store kvstore.KVStore
events *Events
compactionSupported bool
compactionRunningFunc func() bool
garbageCollectionLock syncutils.Mutex
}
// KVStore returns the underlying KVStore.
func (db *Database) KVStore() kvstore.KVStore {
return db.store
}
// Events returns the events of the database.
func (db *Database) Events() *Events {
return db.events
}
// CompactionSupported returns whether the database engine supports compaction.
func (db *Database) CompactionSupported() bool {
return db.compactionSupported
}
// CompactionRunning returns whether a compaction is running.
func (db *Database) CompactionRunning() bool {
return db.compactionRunningFunc()
}
func (db *Database) DatabaseSupportsCleanup() bool {
// ToDo: add this to the db initialization of the different database engines in the core module
return false
}
func (db *Database) CleanupDatabases() error {
// ToDo: add this to the db initialization of the different database engines in the core module
return ErrNothingToCleanUp
}
func (db *Database) RunGarbageCollection() {
if !db.DatabaseSupportsCleanup() {
return
}
db.garbageCollectionLock.Lock()
defer db.garbageCollectionLock.Unlock()
db.log.Info("running full database garbage collection. This can take a while...")
start := time.Now()
db.events.DatabaseCleanup.Trigger(&DatabaseCleanup{
Start: start,
})
err := db.CleanupDatabases()
end := time.Now()
db.events.DatabaseCleanup.Trigger(&DatabaseCleanup{
Start: start,
End: end,
})
if err != nil {
if !errors.Is(err, ErrNothingToCleanUp) {
db.log.Warnf("full database garbage collection failed with error: %s. took: %v", err, end.Sub(start).Truncate(time.Millisecond))
return
}
}
db.log.Infof("full database garbage collection finished. took %v", end.Sub(start).Truncate(time.Millisecond))
}
<file_sep>package node
import (
"strings"
"sync"
flag "github.com/spf13/pflag"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
)
type PluginStatus int
const (
StatusDisabled PluginStatus = iota
StatusEnabled
)
// PluginParams defines the parameters configuration of a plugin.
type PluginParams struct {
// The parameters of the plugin under for the defined configuration.
Params map[string]*flag.FlagSet
// The configuration values to mask.
Masked []string
}
// Pluggable is something which extends the Node's capabilities.
type Pluggable struct {
// A reference to the Node instance.
Node *Node
// The name of the plugin.
Name string
// The config parameters for this plugin.
Params *PluginParams
// The function to call to initialize the plugin dependencies.
DepsFunc interface{}
// InitConfigPars gets called in the init stage of node initialization.
// This can be used to provide config parameters even if the pluggable is disabled.
InitConfigPars InitConfigParsFunc
// PreProvide gets called before the provide stage of node initialization.
// This can be used to force disable other pluggables before they get initialized.
PreProvide PreProvideFunc
// Provide gets called in the provide stage of node initialization (enabled pluggables only).
Provide ProvideFunc
// Configure gets called in the configure stage of node initialization (enabled pluggables only).
Configure Callback
// Run gets called in the run stage of node initialization (enabled pluggables only).
Run Callback
// The logger instance used in this plugin.
log *logger.Logger
logOnce sync.Once
}
// Logger instantiates and returns a logger with the name of the plugin.
func (p *Pluggable) Logger() *logger.Logger {
p.logOnce.Do(func() {
p.log = logger.NewLogger(p.Name)
})
return p.log
}
func (p *Pluggable) Daemon() daemon.Daemon {
return p.Node.Daemon()
}
func (p *Pluggable) Identifier() string {
return strings.ToLower(strings.Replace(p.Name, " ", "", -1))
}
// LogDebug uses fmt.Sprint to construct and log a message.
func (p *Pluggable) LogDebug(args ...interface{}) {
p.Logger().Debug(args...)
}
// LogDebugf uses fmt.Sprintf to log a templated message.
func (p *Pluggable) LogDebugf(template string, args ...interface{}) {
p.Logger().Debugf(template, args...)
}
// LogError uses fmt.Sprint to construct and log a message.
func (p *Pluggable) LogError(args ...interface{}) {
p.Logger().Error(args...)
}
// LogErrorf uses fmt.Sprintf to log a templated message.
func (p *Pluggable) LogErrorf(template string, args ...interface{}) {
p.Logger().Errorf(template, args...)
}
// LogFatal uses fmt.Sprint to construct and log a message, then calls os.Exit.
func (p *Pluggable) LogFatal(args ...interface{}) {
p.Logger().Fatal(args...)
}
// LogFatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.
func (p *Pluggable) LogFatalf(template string, args ...interface{}) {
p.Logger().Fatalf(template, args...)
}
// LogInfo uses fmt.Sprint to construct and log a message.
func (p *Pluggable) LogInfo(args ...interface{}) {
p.Logger().Info(args...)
}
// LogInfof uses fmt.Sprintf to log a templated message.
func (p *Pluggable) LogInfof(template string, args ...interface{}) {
p.Logger().Infof(template, args...)
}
// LogWarn uses fmt.Sprint to construct and log a message.
func (p *Pluggable) LogWarn(args ...interface{}) {
p.Logger().Warn(args...)
}
// LogWarnf uses fmt.Sprintf to log a templated message.
func (p *Pluggable) LogWarnf(template string, args ...interface{}) {
p.Logger().Warnf(template, args...)
}
// Panic uses fmt.Sprint to construct and log a message, then panics.
func (p *Pluggable) Panic(args ...interface{}) {
p.Logger().Panic(args...)
}
// Panicf uses fmt.Sprintf to log a templated message, then panics.
func (p *Pluggable) Panicf(template string, args ...interface{}) {
p.Logger().Panicf(template, args...)
}
// InitPlugin is the module initializing configuration of the node.
// A Node can only have one of such modules.
type InitPlugin struct {
Pluggable
// Init gets called in the initialization stage of the node.
Init InitFunc
// The configs this InitPlugin brings to the node.
Configs map[string]*configuration.Configuration
}
// CorePlugin is a plugin essential for node operation.
// It can not be disabled.
type CorePlugin struct {
Pluggable
}
type Plugin struct {
Pluggable
// The status of the plugin.
Status PluginStatus
}
<file_sep>package toolset
import (
"encoding/hex"
"fmt"
"os"
"path/filepath"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/mr-tron/base58"
"github.com/iotaledger/hive.go/configuration"
p2pCore "github.com/gohornet/hornet/core/p2p"
"github.com/gohornet/hornet/pkg/p2p"
)
func extractP2PIdentity(nodeConfig *configuration.Configuration, args []string) error {
printUsage := func() {
println("Usage:")
println(fmt.Sprintf(" %s [P2P_DATABASE_PATH]", ToolP2PExtractIdentity))
println()
println(" [P2P_DATABASE_PATH] - the path to the p2p database folder (optional)")
println()
println(fmt.Sprintf("example: %s %s", ToolP2PExtractIdentity, "p2pstore"))
}
if len(args) > 1 {
printUsage()
return fmt.Errorf("too many arguments for '%s'", ToolP2PExtractIdentity)
}
p2pDatabasePath := nodeConfig.String(p2pCore.CfgP2PDatabasePath)
if len(args) > 0 {
p2pDatabasePath = args[0]
}
privKeyFilePath := filepath.Join(p2pDatabasePath, p2p.PrivKeyFileName)
_, err := os.Stat(privKeyFilePath)
switch {
case os.IsNotExist(err):
// private key does not exist
return fmt.Errorf("private key file (%s) does not exist", privKeyFilePath)
case err == nil || os.IsExist(err):
// private key file exists
default:
return fmt.Errorf("unable to check private key file (%s): %w", privKeyFilePath, err)
}
privKey, err := p2p.ReadEd25519PrivateKeyFromPEMFile(privKeyFilePath)
if err != nil {
return fmt.Errorf("reading private key file for peer identity failed: %w", err)
}
peerID, err := peer.IDFromPublicKey(privKey.GetPublic())
if err != nil {
return fmt.Errorf("unable to get peer identity from public key: %w", err)
}
privKeyBytes, err := privKey.Raw()
if err != nil {
return fmt.Errorf("unable to get raw private key bytes: %w", err)
}
pubKeyBytes, err := privKey.GetPublic().Raw()
if err != nil {
return fmt.Errorf("unable to get raw public key bytes: %w", err)
}
fmt.Println("Your p2p private key (hex): ", hex.EncodeToString(privKeyBytes))
fmt.Println("Your p2p public key (hex): ", hex.EncodeToString(pubKeyBytes))
fmt.Println("Your p2p public key (base58): ", base58.Encode(pubKeyBytes))
fmt.Println("Your p2p PeerID: ", peerID.String())
return nil
}
<file_sep>package faucet
import (
"fmt"
"net"
"net/http"
"net/url"
"strings"
"github.com/gobuffalo/packr/v2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
var (
// holds faucet website assets
appBox = packr.New("Faucet_App", "./frontend/public")
)
func appBoxMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
contentType := calculateMimeType(c)
path := strings.TrimPrefix(c.Request().URL.Path, "/")
if len(path) == 0 {
path = "index.html"
contentType = echo.MIMETextHTMLCharsetUTF8
}
staticBlob, err := appBox.Find(path)
if err != nil {
// If the asset cannot be found, fall back to the index.html for routing
path = "index.html"
contentType = echo.MIMETextHTMLCharsetUTF8
staticBlob, err = appBox.Find(path)
if err != nil {
return next(c)
}
}
return c.Blob(http.StatusOK, contentType, staticBlob)
}
}
}
func apiMiddlewares() []echo.MiddlewareFunc {
proxySkipper := func(context echo.Context) bool {
// Only proxy allowed routes, skip all others
return !deps.FaucetAllowedAPIRoute(context)
}
apiBindAddr := deps.RestAPIBindAddress
_, apiBindPort, err := net.SplitHostPort(apiBindAddr)
if err != nil {
Plugin.LogFatalf("wrong REST API bind address: %s", err)
}
apiURL, err := url.Parse(fmt.Sprintf("http://localhost:%s", apiBindPort))
if err != nil {
Plugin.LogFatalf("wrong faucet website API url: %s", err)
}
balancer := middleware.NewRoundRobinBalancer([]*middleware.ProxyTarget{
{
URL: apiURL,
},
})
config := middleware.ProxyConfig{
Skipper: proxySkipper,
Balancer: balancer,
}
return []echo.MiddlewareFunc{
middleware.ProxyWithConfig(config),
}
}
func calculateMimeType(e echo.Context) string {
url := e.Request().URL.String()
switch {
case strings.HasSuffix(url, ".html"):
return echo.MIMETextHTMLCharsetUTF8
case strings.HasSuffix(url, ".css"):
return "text/css"
case strings.HasSuffix(url, ".js"):
return echo.MIMEApplicationJavaScript
case strings.HasSuffix(url, ".json"):
return echo.MIMEApplicationJSONCharsetUTF8
case strings.HasSuffix(url, ".png"):
return "image/png"
case strings.HasSuffix(url, ".svg"):
return "image/svg+xml"
default:
return echo.MIMETextHTMLCharsetUTF8
}
}
func enforceMaxOneDotPerURL(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if strings.Count(c.Request().URL.Path, "..") != 0 {
return c.String(http.StatusForbidden, "path not allowed")
}
return next(c)
}
}
func setupRoutes(e *echo.Echo) {
e.Pre(enforceMaxOneDotPerURL)
//e.Use(middleware.CSRF())
e.Group("/*").Use(appBoxMiddleware())
// Pass all the requests through to the local rest API
e.Group("/api", apiMiddlewares()...)
}
<file_sep>package autopeering
import (
"strings"
"time"
"github.com/libp2p/go-libp2p-core/crypto"
libp2p "github.com/libp2p/go-libp2p-core/peer"
"github.com/pkg/errors"
"go.uber.org/dig"
"github.com/iotaledger/hive.go/crypto/ed25519"
databaseCore "github.com/gohornet/hornet/core/database"
"github.com/gohornet/hornet/core/gossip"
"github.com/gohornet/hornet/core/pow"
"github.com/gohornet/hornet/core/snapshot"
"github.com/gohornet/hornet/core/tangle"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/p2p"
"github.com/gohornet/hornet/pkg/p2p/autopeering"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/plugins/coordinator"
"github.com/gohornet/hornet/plugins/dashboard"
"github.com/gohornet/hornet/plugins/debug"
"github.com/gohornet/hornet/plugins/faucet"
"github.com/gohornet/hornet/plugins/migrator"
"github.com/gohornet/hornet/plugins/mqtt"
"github.com/gohornet/hornet/plugins/prometheus"
"github.com/gohornet/hornet/plugins/receipt"
restapiv1 "github.com/gohornet/hornet/plugins/restapi/v1"
"github.com/gohornet/hornet/plugins/spammer"
"github.com/gohornet/hornet/plugins/urts"
"github.com/gohornet/hornet/plugins/warpsync"
"github.com/iotaledger/hive.go/autopeering/discover"
"github.com/iotaledger/hive.go/autopeering/peer/service"
"github.com/iotaledger/hive.go/autopeering/selection"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/events"
)
func init() {
Plugin = &node.Plugin{
Status: node.StatusDisabled,
Pluggable: node.Pluggable{
Name: "Autopeering",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
PreProvide: preProvide,
Configure: configure,
Run: run,
},
}
}
var (
Plugin *node.Plugin
deps dependencies
localPeerContainer *autopeering.LocalPeerContainer
onDiscoveryPeerDiscovered *events.Closure
onDiscoveryPeerDeleted *events.Closure
onSelectionSaltUpdated *events.Closure
onSelectionOutgoingPeering *events.Closure
onSelectionIncomingPeering *events.Closure
onSelectionDropped *events.Closure
onPeerDisconnected *events.Closure
onAutopeerBecameKnown *events.Closure
)
type dependencies struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
NodePrivateKey crypto.PrivKey `name:"nodePrivateKey"`
P2PDatabasePath string `name:"p2pDatabasePath"`
P2PBindMultiAddresses []string `name:"p2pBindMultiAddresses"`
DatabaseEngine database.Engine `name:"databaseEngine"`
NetworkIDName string `name:"networkIdName"`
AutopeeringRunAsEntryNode bool `name:"autopeeringRunAsEntryNode"`
Manager *p2p.Manager `optional:"true"`
}
func preProvide(c *dig.Container, configs map[string]*configuration.Configuration, initConfig *node.InitConfig) {
pluginEnabled := true
containsPlugin := func(pluginsList []string, pluginIdentifier string) bool {
contains := false
for _, plugin := range pluginsList {
if strings.ToLower(plugin) == pluginIdentifier {
contains = true
break
}
}
return contains
}
if disabled := containsPlugin(initConfig.DisabledPlugins, Plugin.Identifier()); disabled {
// Autopeering is disabled
pluginEnabled = false
}
if enabled := containsPlugin(initConfig.EnabledPlugins, Plugin.Identifier()); !enabled {
// Autopeering was not enabled
pluginEnabled = false
}
runAsEntryNode := pluginEnabled && configs["nodeConfig"].Bool(CfgNetAutopeeringRunAsEntryNode)
if runAsEntryNode {
// the following pluggables stay enabled
// - profile
// - protocfg
// - gracefulshutdown
// - p2p
// - profiling
// - versioncheck
// - autopeering
// disable the other plugins if the node runs as an entry node for autopeering
initConfig.ForceDisablePluggable(databaseCore.CorePlugin.Identifier())
initConfig.ForceDisablePluggable(pow.CorePlugin.Identifier())
initConfig.ForceDisablePluggable(gossip.CorePlugin.Identifier())
initConfig.ForceDisablePluggable(tangle.CorePlugin.Identifier())
initConfig.ForceDisablePluggable(snapshot.CorePlugin.Identifier())
initConfig.ForceDisablePluggable(restapiv1.Plugin.Identifier())
initConfig.ForceDisablePluggable(warpsync.Plugin.Identifier())
initConfig.ForceDisablePluggable(urts.Plugin.Identifier())
initConfig.ForceDisablePluggable(dashboard.Plugin.Identifier())
initConfig.ForceDisablePluggable(spammer.Plugin.Identifier())
initConfig.ForceDisablePluggable(mqtt.Plugin.Identifier())
initConfig.ForceDisablePluggable(coordinator.Plugin.Identifier())
initConfig.ForceDisablePluggable(migrator.Plugin.Identifier())
initConfig.ForceDisablePluggable(receipt.Plugin.Identifier())
initConfig.ForceDisablePluggable(prometheus.Plugin.Identifier())
initConfig.ForceDisablePluggable(debug.Plugin.Identifier())
initConfig.ForceDisablePluggable(faucet.Plugin.Identifier())
}
// the parameter has to be provided in the preProvide stage.
// this is a special case, since it only should be true if the plugin is enabled
type cfgResult struct {
dig.Out
AutopeeringRunAsEntryNode bool `name:"autopeeringRunAsEntryNode"`
}
if err := c.Provide(func() cfgResult {
return cfgResult{
AutopeeringRunAsEntryNode: runAsEntryNode,
}
}); err != nil {
Plugin.Panic(err)
}
}
func configure() {
selection.SetParameters(selection.Parameters{
InboundNeighborSize: deps.NodeConfig.Int(CfgNetAutopeeringInboundPeers),
OutboundNeighborSize: deps.NodeConfig.Int(CfgNetAutopeeringOutboundPeers),
SaltLifetime: deps.NodeConfig.Duration(CfgNetAutopeeringSaltLifetime),
})
if err := autopeering.RegisterAutopeeringProtocolInMultiAddresses(); err != nil {
Plugin.Panicf("unable to register autopeering protocol for multi addresses: %s", err)
}
rawPrvKey, err := deps.NodePrivateKey.Raw()
if err != nil {
Plugin.Panicf("unable to obtain raw private key: %s", err)
}
localPeerContainer, err = autopeering.NewLocalPeerContainer(p2pServiceKey(),
rawPrvKey[:ed25519.SeedSize],
deps.P2PDatabasePath,
deps.DatabaseEngine,
deps.P2PBindMultiAddresses,
deps.NodeConfig.String(CfgNetAutopeeringBindAddr),
deps.AutopeeringRunAsEntryNode)
if err != nil {
Plugin.Panicf("unable to initialize local peer container: %s", err)
}
Plugin.LogInfof("initialized local autopeering: %s@%s", localPeerContainer.Local().PublicKey(), localPeerContainer.Local().Address())
if deps.AutopeeringRunAsEntryNode {
entryNodeMultiAddress, err := autopeering.GetEntryNodeMultiAddress(localPeerContainer.Local())
if err != nil {
Plugin.Panicf("unable to parse entry node multiaddress: %s", err)
}
Plugin.LogInfof("\n\nentry node multiaddress: %s\n", entryNodeMultiAddress.String())
}
configureAutopeering(localPeerContainer)
configureEvents()
}
func run() {
if err := Plugin.Node.Daemon().BackgroundWorker(Plugin.Name, func(shutdownSignal <-chan struct{}) {
attachEvents()
start(localPeerContainer, shutdownSignal)
detachEvents()
}, shutdown.PriorityAutopeering); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
}
// gets the peering service key from the config.
func p2pServiceKey() service.Key {
return service.Key(deps.NetworkIDName)
}
func configureEvents() {
onDiscoveryPeerDiscovered = events.NewClosure(func(ev *discover.DiscoveredEvent) {
if peerID := autopeering.ConvertHivePubKeyToPeerIDOrLog(ev.Peer.PublicKey(), Plugin.LogWarnf); peerID != nil {
Plugin.LogInfof("discovered: %s / %s", ev.Peer.Address(), *peerID)
}
})
onDiscoveryPeerDeleted = events.NewClosure(func(ev *discover.DeletedEvent) {
if peerID := autopeering.ConvertHivePubKeyToPeerIDOrLog(ev.Peer.PublicKey(), Plugin.LogWarnf); peerID != nil {
Plugin.LogInfof("removed offline: %s / %s", ev.Peer.Address(), *peerID)
}
})
onPeerDisconnected = events.NewClosure(func(peerOptErr *p2p.PeerOptError) {
if peerOptErr.Peer.Relation != p2p.PeerRelationAutopeered {
return
}
if id := autopeering.ConvertPeerIDToHiveIdentityOrLog(peerOptErr.Peer, Plugin.LogWarnf); id != nil {
Plugin.LogInfof("removing: %s", peerOptErr.Peer.ID)
selectionProtocol.RemoveNeighbor(id.ID())
}
})
onAutopeerBecameKnown = events.NewClosure(func(p *p2p.Peer, oldRel p2p.PeerRelation) {
if oldRel != p2p.PeerRelationAutopeered {
return
}
if id := autopeering.ConvertPeerIDToHiveIdentityOrLog(p, Plugin.LogWarnf); id != nil {
Plugin.LogInfof("removing %s from autopeering selection protocol", p.ID)
selectionProtocol.RemoveNeighbor(id.ID())
}
})
onSelectionSaltUpdated = events.NewClosure(func(ev *selection.SaltUpdatedEvent) {
Plugin.LogInfof("salt updated; expires=%s", ev.Public.GetExpiration().Format(time.RFC822))
})
onSelectionOutgoingPeering = events.NewClosure(func(ev *selection.PeeringEvent) {
if !ev.Status {
return
}
Plugin.LogInfof("[outgoing peering] adding autopeering peer %s", ev.Peer.ID())
addrInfo, err := autopeering.HivePeerToAddrInfo(ev.Peer, p2pServiceKey())
if err != nil {
Plugin.LogWarnf("unable to convert outgoing selection autopeering peer to addr info: %s", err)
return
}
handleSelection(ev, addrInfo, func() {
Plugin.LogInfof("connecting to %s", addrInfo)
if err := deps.Manager.ConnectPeer(addrInfo, p2p.PeerRelationAutopeered); err != nil {
Plugin.LogWarnf("couldn't add autopeering peer %s", err)
}
})
})
onSelectionIncomingPeering = events.NewClosure(func(ev *selection.PeeringEvent) {
if !ev.Status {
return
}
Plugin.LogInfof("[incoming peering] whitelisting %s", ev.Peer.ID())
addrInfo, err := autopeering.HivePeerToAddrInfo(ev.Peer, p2pServiceKey())
if err != nil {
Plugin.LogWarnf("unable to convert incoming selection autopeering peer to addr info: %s", err)
return
}
handleSelection(ev, addrInfo, func() {
// TODO: maybe do whitelisting instead?
//Plugin.LogInfof("connecting to %s", addrInfo)
//if err := deps.Manager.ConnectPeer(addrInfo, p2p.PeerRelationAutopeered); err != nil {
// Plugin.LogWarnf("couldn't add autopeering peer %s", err)
//}
})
})
onSelectionDropped = events.NewClosure(func(ev *selection.DroppedEvent) {
peerID := autopeering.ConvertHivePubKeyToPeerIDOrLog(ev.Peer.PublicKey(), Plugin.LogWarnf)
if peerID == nil {
return
}
Plugin.LogInfof("[dropped event] disconnecting %s", peerID)
var peerRelation p2p.PeerRelation
deps.Manager.Call(*peerID, func(p *p2p.Peer) {
peerRelation = p.Relation
})
if len(peerRelation) == 0 {
Plugin.LogWarnf("didn't find autopeered peer %s for disconnecting", peerID)
return
}
if peerRelation != p2p.PeerRelationAutopeered {
Plugin.LogWarnf("won't disconnect %s as it its relation is not '%s' but '%s'", peerID, p2p.PeerRelationAutopeered, peerRelation)
return
}
if err := deps.Manager.DisconnectPeer(*peerID, errors.New("removed via autopeering selection")); err != nil {
Plugin.LogWarnf("couldn't disconnect selection dropped autopeer: %s", err)
}
})
}
// handles a peer gotten from the autopeering selection according to its existing relation.
// if the peer is not yet part of the peering manager, the given noRelationFunc is called.
func handleSelection(ev *selection.PeeringEvent, addrInfo *libp2p.AddrInfo, noRelationFunc func()) {
// extract peer relation
var peerRelation p2p.PeerRelation
deps.Manager.Call(addrInfo.ID, func(p *p2p.Peer) {
peerRelation = p.Relation
})
switch peerRelation {
case p2p.PeerRelationKnown:
clearFromAutopeeringSelector(ev)
case p2p.PeerRelationUnknown:
updatePeerRelationToDiscovered(addrInfo)
case p2p.PeerRelationAutopeered:
handleAlreadyAutopeered(addrInfo)
default:
noRelationFunc()
}
}
// logs a warning about a from the selector seen peer which is already autopeered.
func handleAlreadyAutopeered(addrInfo *libp2p.AddrInfo) {
Plugin.LogWarnf("peer is already autopeered %s", addrInfo.ID)
}
// updates the given peers relation to discovered.
func updatePeerRelationToDiscovered(addrInfo *libp2p.AddrInfo) {
if err := deps.Manager.ConnectPeer(addrInfo, p2p.PeerRelationAutopeered); err != nil {
Plugin.LogWarnf("couldn't update unknown peer to 'discovered' %s", err)
}
}
// clears an already statically peered from the autopeering selector.
func clearFromAutopeeringSelector(ev *selection.PeeringEvent) {
Plugin.LogInfof("peer is statically peered already %s, removing from autopeering selection protocol", ev.Peer.ID())
selectionProtocol.RemoveNeighbor(ev.Peer.ID())
}
func attachEvents() {
discoveryProtocol.Events().PeerDiscovered.Attach(onDiscoveryPeerDiscovered)
discoveryProtocol.Events().PeerDeleted.Attach(onDiscoveryPeerDeleted)
if deps.Manager == nil {
return
}
// notify the selection when a connection is closed or failed.
deps.Manager.Events.Disconnected.Attach(onPeerDisconnected)
deps.Manager.Events.RelationUpdated.Attach(onAutopeerBecameKnown)
selectionProtocol.Events().SaltUpdated.Attach(onSelectionSaltUpdated)
selectionProtocol.Events().OutgoingPeering.Attach(onSelectionOutgoingPeering)
selectionProtocol.Events().IncomingPeering.Attach(onSelectionIncomingPeering)
selectionProtocol.Events().Dropped.Attach(onSelectionDropped)
}
func detachEvents() {
discoveryProtocol.Events().PeerDiscovered.Detach(onDiscoveryPeerDiscovered)
discoveryProtocol.Events().PeerDeleted.Detach(onDiscoveryPeerDeleted)
if deps.Manager == nil {
return
}
deps.Manager.Events.Disconnected.Detach(onPeerDisconnected)
deps.Manager.Events.RelationUpdated.Detach(onAutopeerBecameKnown)
selectionProtocol.Events().SaltUpdated.Detach(onSelectionSaltUpdated)
selectionProtocol.Events().OutgoingPeering.Detach(onSelectionOutgoingPeering)
selectionProtocol.Events().IncomingPeering.Detach(onSelectionIncomingPeering)
selectionProtocol.Events().Dropped.Detach(onSelectionDropped)
}
<file_sep>package protocfg
import (
"encoding/json"
flag "github.com/spf13/pflag"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/model/coordinator"
"github.com/gohornet/hornet/pkg/node"
"github.com/iotaledger/hive.go/configuration"
iotago "github.com/iotaledger/iota.go/v2"
)
func init() {
_ = flag.CommandLine.MarkHidden(CfgProtocolPublicKeyRangesJSON)
CorePlugin = &node.CorePlugin{
Pluggable: node.Pluggable{
Name: "ProtoCfg",
Params: params,
InitConfigPars: initConfigPars,
},
}
}
var (
CorePlugin *node.CorePlugin
cooPubKeyRangesFlag = flag.String(CfgProtocolPublicKeyRangesJSON, "", "overwrite public key ranges (JSON)")
)
func initConfigPars(c *dig.Container) {
type cfgDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
}
type cfgResult struct {
dig.Out
PublicKeyRanges coordinator.PublicKeyRanges
NetworkID uint64 `name:"networkId"`
NetworkIDName string `name:"networkIdName"`
Bech32HRP iotago.NetworkPrefix `name:"bech32HRP"`
MinPoWScore float64 `name:"minPoWScore"`
MilestonePublicKeyCount int `name:"milestonePublicKeyCount"`
}
if err := c.Provide(func(deps cfgDeps) cfgResult {
res := cfgResult{
NetworkID: iotago.NetworkIDFromString(deps.NodeConfig.String(CfgProtocolNetworkIDName)),
NetworkIDName: deps.NodeConfig.String(CfgProtocolNetworkIDName),
Bech32HRP: iotago.NetworkPrefix(deps.NodeConfig.String(CfgProtocolBech32HRP)),
MinPoWScore: deps.NodeConfig.Float64(CfgProtocolMinPoWScore),
MilestonePublicKeyCount: deps.NodeConfig.Int(CfgProtocolMilestonePublicKeyCount),
}
if *cooPubKeyRangesFlag != "" {
// load from special CLI flag
if err := json.Unmarshal([]byte(*cooPubKeyRangesFlag), &res.PublicKeyRanges); err != nil {
CorePlugin.Panic(err)
}
return res
}
if err := deps.NodeConfig.SetDefault(CfgProtocolPublicKeyRanges, coordinator.PublicKeyRanges{
{
Key: "<KEY>",
StartIndex: 0,
EndIndex: 777600,
}, {
Key: "365fb85e7568b9b32f7359d6cbafa9814472ad0ecbad32d77beaf5dd9e84c6ba",
StartIndex: 0,
EndIndex: 1555200,
}, {
Key: "<KEY>",
StartIndex: 552960,
EndIndex: 2108160,
}, {
Key: "760d88e112c0fd210cf16a3dce3443ecf7e18c456c2fb9646cabb2e13e367569",
StartIndex: 1333460,
EndIndex: 2888660,
}, {
Key: "7bac2209b576ea2235539358c7df8ca4d2f2fc35a663c760449e65eba9f8a6e7",
StartIndex: 2111060,
EndIndex: 3666260,
}, {
Key: "<KEY>",
StartIndex: 2888660,
EndIndex: 4443860,
},
}); err != nil {
CorePlugin.Panic(err)
}
// load from config
if err := deps.NodeConfig.Unmarshal(CfgProtocolPublicKeyRanges, &res.PublicKeyRanges); err != nil {
CorePlugin.Panic(err)
}
return res
}); err != nil {
CorePlugin.Panic(err)
}
}
<file_sep>package keymanager_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/gohornet/hornet/pkg/keymanager"
iotago "github.com/iotaledger/iota.go/v2"
"github.com/iotaledger/iota.go/v2/ed25519"
)
func TestMilestoneKeyManager(t *testing.T) {
pubKey1, privKey1, err := ed25519.GenerateKey(nil)
assert.NoError(t, err)
pubKey2, privKey2, err := ed25519.GenerateKey(nil)
assert.NoError(t, err)
pubKey3, privKey3, err := ed25519.GenerateKey(nil)
assert.NoError(t, err)
km := keymanager.New()
km.AddKeyRange(pubKey1, 0, 0)
km.AddKeyRange(pubKey2, 3, 10)
km.AddKeyRange(pubKey3, 8, 15)
keysIndex0 := km.PublicKeysForMilestoneIndex(0)
assert.Len(t, keysIndex0, 1)
keysIndex3 := km.PublicKeysForMilestoneIndex(3)
assert.Len(t, keysIndex3, 2)
keysIndex7 := km.PublicKeysForMilestoneIndex(7)
assert.Len(t, keysIndex7, 2)
keysIndex8 := km.PublicKeysForMilestoneIndex(8)
assert.Len(t, keysIndex8, 3)
keysIndex10 := km.PublicKeysForMilestoneIndex(10)
assert.Len(t, keysIndex10, 3)
keysIndex11 := km.PublicKeysForMilestoneIndex(11)
assert.Len(t, keysIndex11, 2)
keysIndex15 := km.PublicKeysForMilestoneIndex(15)
assert.Len(t, keysIndex15, 2)
keysIndex16 := km.PublicKeysForMilestoneIndex(16)
assert.Len(t, keysIndex16, 1)
keysIndex1000 := km.PublicKeysForMilestoneIndex(1000)
assert.Len(t, keysIndex1000, 1)
keysSet8 := km.PublicKeysSetForMilestoneIndex(8)
assert.Len(t, keysSet8, 3)
var msPubKey1 iotago.MilestonePublicKey
copy(msPubKey1[:], pubKey1)
var msPubKey2 iotago.MilestonePublicKey
copy(msPubKey2[:], pubKey2)
var msPubKey3 iotago.MilestonePublicKey
copy(msPubKey3[:], pubKey3)
assert.Contains(t, keysSet8, msPubKey1)
assert.Contains(t, keysSet8, msPubKey2)
assert.Contains(t, keysSet8, msPubKey3)
keyMapping8 := km.MilestonePublicKeyMappingForMilestoneIndex(8, []ed25519.PrivateKey{privKey1, privKey2, privKey3}, 2)
assert.Len(t, keyMapping8, 2)
assert.Equal(t, keyMapping8[msPubKey1], privKey1)
assert.Equal(t, keyMapping8[msPubKey2], privKey2)
}
<file_sep>package database
import (
"runtime"
"github.com/iotaledger/hive.go/kvstore/rocksdb"
)
// NewRocksDB creates a new RocksDB instance.
func NewRocksDB(path string) (*rocksdb.RocksDB, error) {
opts := []rocksdb.Option{
rocksdb.IncreaseParallelism(runtime.NumCPU() - 1),
}
return rocksdb.CreateDB(path, opts...)
}
<file_sep>package faucet
// faucetEnqueueRequest defines the request for a POST RouteFaucetEnqueue REST API call.
type faucetEnqueueRequest struct {
// The bech32 address.
Address string `json:"address"`
}
<file_sep>package faucet
import (
"bytes"
"fmt"
"runtime"
"time"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"github.com/gohornet/hornet/pkg/common"
"github.com/gohornet/hornet/pkg/dag"
"github.com/gohornet/hornet/pkg/model/hornet"
"github.com/gohornet/hornet/pkg/model/milestone"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/gohornet/hornet/pkg/model/utxo"
"github.com/gohornet/hornet/pkg/pow"
"github.com/gohornet/hornet/pkg/restapi"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/syncutils"
iotago "github.com/iotaledger/iota.go/v2"
)
// SendMessageFunc is a function which sends a message to the network.
type SendMessageFunc = func(msg *storage.Message) error
// TipselFunc selects tips for the faucet.
type TipselFunc = func() (tips hornet.MessageIDs, err error)
var (
// ErrNoTipsGiven is returned when no tips were given to issue a message.
ErrNoTipsGiven = errors.New("no tips given")
)
// Events are the events issued by the faucet.
type Events struct {
// Fired when a faucet message is issued.
IssuedMessage *events.Event
// SoftError is triggered when a soft error is encountered.
SoftError *events.Event
}
// queueItem is an item for the faucet requests queue.
type queueItem struct {
Bech32 string
Amount uint64
Ed25519Address *iotago.Ed25519Address
}
// FaucetInfoResponse defines the response of a GET RouteFaucetInfo REST API call.
type FaucetInfoResponse struct {
// The bech32 address of the faucet.
Address string `json:"address"`
// The remaining balance of faucet.
Balance uint64 `json:"balance"`
}
// FaucetEnqueueResponse defines the response of a POST RouteFaucetEnqueue REST API call.
type FaucetEnqueueResponse struct {
// The bech32 address.
Address string `json:"address"`
// The number of waiting requests in the queue.
WaitingRequests int `json:"waitingRequests"`
}
// Faucet is used to issue transaction to users that requested funds via a REST endpoint.
type Faucet struct {
syncutils.Mutex
// used to access the node storage.
storage *storage.Storage
// id of the network the faucet is running in.
networkID uint64
// belowMaxDepth is the maximum allowed delta
// value between OCRI of a given message in relation to the current CMI before it gets lazy.
belowMaxDepth milestone.Index
// used to get the outputs.
utxoManager *utxo.Manager
// the address of the faucet.
address *iotago.Ed25519Address
// used to sign the faucet transactions.
addressSigner iotago.AddressSigner
// used to get valid tips for new faucet messages.
tipselFunc TipselFunc
// used to do the PoW for the faucet messages.
powHandler *pow.Handler
// the function used to send a message.
sendMessageFunc SendMessageFunc
// holds the faucet options.
opts *Options
// events of the faucet.
Events *Events
// the message ID of the last sent faucet message.
lastMessageID hornet.MessageID
// map with all queued requests per address.
queueMap map[string]*queueItem
// queue of new requests.
queue chan *queueItem
}
// the default options applied to the faucet.
var defaultOptions = []Option{
WithHRPNetworkPrefix(iotago.PrefixTestnet),
WithAmount(10000000), // 10 Mi
WithSmallAmount(1000000), // 1 Mi
WithMaxAddressBalance(20000000), // 20 Mi
WithMaxOutputCount(iotago.MaxOutputsCount),
WithIndexationMessage("HORNET FAUCET"),
WithBatchTimeout(2 * time.Second),
WithPowWorkerCount(0),
}
// Options define options for the faucet.
type Options struct {
logger *logger.Logger
hrpNetworkPrefix iotago.NetworkPrefix
amount uint64
smallAmount uint64
maxAddressBalance uint64
maxOutputCount int
indexationMessage []byte
batchTimeout time.Duration
powWorkerCount int
}
// applies the given Option.
func (so *Options) apply(opts ...Option) {
for _, opt := range opts {
opt(so)
}
}
// WithLogger enables logging within the faucet.
func WithLogger(logger *logger.Logger) Option {
return func(opts *Options) {
opts.logger = logger
}
}
// WithHRPNetworkPrefix sets the bech32 HRP network prefix.
func WithHRPNetworkPrefix(networkPrefix iotago.NetworkPrefix) Option {
return func(opts *Options) {
opts.hrpNetworkPrefix = networkPrefix
}
}
// WithAmount defines the amount of funds the requester receives.
func WithAmount(amount uint64) Option {
return func(opts *Options) {
opts.amount = amount
}
}
// WithSmallAmount defines the amount of funds the requester receives
// if the target address has more funds than the faucet amount and less than maximum.
func WithSmallAmount(smallAmount uint64) Option {
return func(opts *Options) {
opts.smallAmount = smallAmount
}
}
// WithMaxAddressBalance defines the maximum allowed amount of funds on the target address.
// If there are more funds already, the faucet request is rejected.
func WithMaxAddressBalance(maxAddressBalance uint64) Option {
return func(opts *Options) {
opts.maxAddressBalance = maxAddressBalance
}
}
// WithMaxOutputCount defines the maximum output count per faucet message.
func WithMaxOutputCount(maxOutputCount int) Option {
return func(opts *Options) {
if maxOutputCount > iotago.MaxOutputsCount {
maxOutputCount = iotago.MaxOutputsCount
}
opts.maxOutputCount = maxOutputCount
}
}
// WithIndexationMessage defines the faucet transaction indexation payload.
func WithIndexationMessage(indexationMessage string) Option {
return func(opts *Options) {
opts.indexationMessage = []byte(indexationMessage)
}
}
// WithBatchTimeout sets the maximum duration for collecting faucet batches.
func WithBatchTimeout(timeout time.Duration) Option {
return func(opts *Options) {
opts.batchTimeout = timeout
}
}
// WithPowWorkerCount defines the amount of workers used for calculating PoW when issuing faucet messages.
func WithPowWorkerCount(powWorkerCount int) Option {
if powWorkerCount == 0 {
powWorkerCount = runtime.NumCPU() - 1
}
if powWorkerCount < 1 {
powWorkerCount = 1
}
return func(opts *Options) {
opts.powWorkerCount = powWorkerCount
}
}
// Option is a function setting a faucet option.
type Option func(opts *Options)
// New creates a new faucet instance.
func New(
storage *storage.Storage,
networkID uint64,
belowMaxDepth int,
utxoManager *utxo.Manager,
address *iotago.Ed25519Address,
addressSigner iotago.AddressSigner,
tipselFunc TipselFunc,
powHandler *pow.Handler,
sendMessageFunc SendMessageFunc,
opts ...Option) *Faucet {
options := &Options{}
options.apply(defaultOptions...)
options.apply(opts...)
faucet := &Faucet{
storage: storage,
networkID: networkID,
belowMaxDepth: milestone.Index(belowMaxDepth),
utxoManager: utxoManager,
address: address,
addressSigner: addressSigner,
tipselFunc: tipselFunc,
powHandler: powHandler,
sendMessageFunc: sendMessageFunc,
opts: options,
Events: &Events{
IssuedMessage: events.NewEvent(events.VoidCaller),
SoftError: events.NewEvent(events.ErrorCaller),
},
}
faucet.init()
return faucet
}
func (f *Faucet) init() {
f.queue = make(chan *queueItem, 5000)
f.queueMap = make(map[string]*queueItem)
f.lastMessageID = hornet.NullMessageID()
}
// NetworkPrefix returns the used network prefix.
func (f *Faucet) NetworkPrefix() iotago.NetworkPrefix {
return f.opts.hrpNetworkPrefix
}
// Info returns the used faucet address and remaining balance.
func (f *Faucet) Info() (*FaucetInfoResponse, error) {
balance, _, err := f.utxoManager.AddressBalanceWithoutLocking(f.address)
if err != nil {
return nil, err
}
return &FaucetInfoResponse{
Address: f.address.Bech32(f.opts.hrpNetworkPrefix),
Balance: balance,
}, nil
}
// Enqueue adds a new faucet request to the queue.
func (f *Faucet) Enqueue(bech32 string, ed25519Addr *iotago.Ed25519Address) (*FaucetEnqueueResponse, error) {
f.Lock()
defer f.Unlock()
if _, exists := f.queueMap[bech32]; exists {
return nil, errors.WithMessage(restapi.ErrInvalidParameter, "Address is already in the queue.")
}
amount := f.opts.amount
balance, _, err := f.utxoManager.AddressBalanceWithoutLocking(ed25519Addr)
if err == nil && balance >= f.opts.amount {
amount = f.opts.smallAmount
if balance >= f.opts.maxAddressBalance {
return nil, errors.WithMessage(restapi.ErrInvalidParameter, "You already have enough coins on your address.")
}
}
request := &queueItem{
Bech32: bech32,
Amount: amount,
Ed25519Address: ed25519Addr,
}
select {
case f.queue <- request:
f.queueMap[bech32] = request
return &FaucetEnqueueResponse{
Address: bech32,
WaitingRequests: len(f.queueMap),
}, nil
default:
// queue is full
return nil, errors.WithMessage(echo.ErrInternalServerError, "Faucet queue is full. Please try again later!")
}
}
// clearRequests clears the old requests from the map.
// this is necessary to be able to send new requests to the same addresses.
func (f *Faucet) clearRequests(batchedRequests []*queueItem) {
f.Lock()
defer f.Unlock()
for _, request := range batchedRequests {
delete(f.queueMap, request.Bech32)
}
}
// createMessage creates a new message and references the last faucet message (also reattaches if below max depth).
func (f *Faucet) createMessage(txPayload iotago.Serializable, shutdownSignal <-chan struct{}) (*storage.Message, error) {
tips, err := f.tipselFunc()
if err != nil {
return nil, err
}
reattachMessage := func(messageID hornet.MessageID) (*storage.Message, error) {
cachedMsg := f.storage.CachedMessageOrNil(f.lastMessageID)
if cachedMsg == nil {
// message unknown
return nil, fmt.Errorf("message not found: %s", messageID.ToHex())
}
defer cachedMsg.Release(true)
tips, err := f.tipselFunc()
if err != nil {
return nil, err
}
iotaMsg := &iotago.Message{
NetworkID: f.networkID,
Parents: tips.ToSliceOfArrays(),
Payload: cachedMsg.Message().Message().Payload,
}
if err := f.powHandler.DoPoW(iotaMsg, shutdownSignal, 1); err != nil {
return nil, err
}
msg, err := storage.NewMessage(iotaMsg, iotago.DeSeriModePerformValidation)
if err != nil {
return nil, err
}
if err := f.sendMessageFunc(msg); err != nil {
return nil, err
}
return msg, nil
}
// check if the last faucet message was already confirmed.
// if not, check if it is already below max depth and reattach in case.
// we need to check for the last faucet message, because we reference the last message as a tip
// to be sure the tangle consumes our UTXOs in the correct order.
if err = func() error {
if bytes.Equal(f.lastMessageID, hornet.NullMessageID()) {
// do not reference NullMessage
return nil
}
cachedMsgMeta := f.storage.CachedMessageMetadataOrNil(f.lastMessageID)
if cachedMsgMeta == nil {
// message unknown
return nil
}
defer cachedMsgMeta.Release(true)
if cachedMsgMeta.Metadata().IsReferenced() {
// message is already confirmed, no need to reference
return nil
}
_, ocri := dag.ConeRootIndexes(f.storage, cachedMsgMeta.Retain(), f.storage.ConfirmedMilestoneIndex()) // meta +
if (f.storage.LatestMilestoneIndex() - ocri) > f.belowMaxDepth {
// the last faucet message is not confirmed yet, but it is already below max depth
// we need to reattach it
msg, err := reattachMessage(f.lastMessageID)
if err != nil {
return common.CriticalError(fmt.Errorf("faucet message was below max depth and couldn't be reattached: %w", err))
}
// update the lastMessasgeID because we reattached the message
f.lastMessageID = msg.MessageID()
}
tips[0] = f.lastMessageID
tips = tips.RemoveDupsAndSortByLexicalOrder()
return nil
}(); err != nil {
return nil, err
}
// create the message
iotaMsg := &iotago.Message{
NetworkID: f.networkID,
Parents: tips.ToSliceOfArrays(),
Payload: txPayload,
}
if err := f.powHandler.DoPoW(iotaMsg, shutdownSignal, 1); err != nil {
return nil, err
}
msg, err := storage.NewMessage(iotaMsg, iotago.DeSeriModePerformValidation)
if err != nil {
return nil, err
}
return msg, nil
}
// buildTransactionPayload creates a signed transaction payload with all UTXO and batched requests.
func (f *Faucet) buildTransactionPayload(unspentOutputs []*utxo.Output, batchedRequests []*queueItem) (*iotago.Transaction, *iotago.UTXOInput, uint64, error) {
txBuilder := iotago.NewTransactionBuilder()
txBuilder.AddIndexationPayload(&iotago.Indexation{Index: f.opts.indexationMessage, Data: nil})
outputCount := 0
var remainderAmount int64 = 0
// collect all unspent output of the faucet address
for _, unspentOutput := range unspentOutputs {
outputCount++
remainderAmount += int64(unspentOutput.Amount())
txBuilder.AddInput(&iotago.ToBeSignedUTXOInput{Address: f.address, Input: unspentOutput.UTXOInput()})
}
// add all requests as outputs
for _, req := range batchedRequests {
outputCount++
if outputCount >= f.opts.maxOutputCount {
// do not collect further requests
// the last slot is for the remainder
break
}
if remainderAmount == 0 {
// do not collect further requests
break
}
amount := req.Amount
if remainderAmount < int64(amount) {
// not enough funds left
amount = uint64(remainderAmount)
}
remainderAmount -= int64(amount)
txBuilder.AddOutput(&iotago.SigLockedSingleOutput{Address: req.Ed25519Address, Amount: uint64(amount)})
}
if remainderAmount > 0 {
txBuilder.AddOutput(&iotago.SigLockedSingleOutput{Address: f.address, Amount: uint64(remainderAmount)})
}
txPayload, err := txBuilder.Build(f.addressSigner)
if err != nil {
return nil, nil, 0, err
}
if remainderAmount == 0 {
// no remainder available
return txPayload, nil, 0, nil
}
transactionID, err := txPayload.ID()
if err != nil {
return nil, nil, 0, fmt.Errorf("can't compute the transaction ID, error: %w", err)
}
remainderOutput := &iotago.UTXOInput{}
copy(remainderOutput.TransactionID[:], transactionID[:iotago.TransactionIDLength])
// search remainder address in the outputs
found := false
var outputIndex uint16 = 0
for _, output := range txPayload.Essence.(*iotago.TransactionEssence).Outputs {
sigLock := output.(*iotago.SigLockedSingleOutput)
ed25519Addr := sigLock.Address.(*iotago.Ed25519Address)
if bytes.Equal(ed25519Addr[:], f.address[:]) {
// found the remainder address in the outputs
found = true
remainderOutput.TransactionOutputIndex = outputIndex
break
}
outputIndex++
}
if !found {
return nil, nil, 0, errors.New("can't find the faucet remainder output")
}
return txPayload, remainderOutput, uint64(remainderAmount), nil
}
// sendFaucetMessage creates a faucet transaction payload and remembers the last sent messageID.
func (f *Faucet) sendFaucetMessage(unspentOutputs []*utxo.Output, batchedRequests []*queueItem, shutdownSignal <-chan struct{}) (*utxo.Output, error) {
txPayload, remainderIotaGoOutput, remainderAmount, err := f.buildTransactionPayload(unspentOutputs, batchedRequests)
if err != nil {
return nil, fmt.Errorf("build transaction payload failed, error: %w", err)
}
msg, err := f.createMessage(txPayload, shutdownSignal)
if err != nil {
return nil, fmt.Errorf("build faucet message failed, error: %w", err)
}
if err := f.sendMessageFunc(msg); err != nil {
return nil, fmt.Errorf("send faucet message failed, error: %w", err)
}
f.lastMessageID = msg.MessageID()
remainderIotaGoOutputID := remainderIotaGoOutput.ID()
remainderOutput := utxo.CreateOutput(&remainderIotaGoOutputID, msg.MessageID(), iotago.OutputSigLockedSingleOutput, f.address, uint64(remainderAmount))
return remainderOutput, nil
}
// logSoftError logs a soft error and triggers the event.
func (f *Faucet) logSoftError(err error) {
if f.opts.logger != nil {
f.opts.logger.Warn(err)
}
f.Events.SoftError.Trigger(err)
}
// RunFaucetLoop collects unspent outputs on the faucet address and batches the requests from the queue.
func (f *Faucet) RunFaucetLoop(shutdownSignal <-chan struct{}) error {
var lastRemainderOutput *utxo.Output
for {
select {
case <-shutdownSignal:
// faucet was stopped
return nil
default:
// only collect unspent outputs if the lastRemainderOutput is not pending
shouldCollectUnspentOutputs := func() bool {
if lastRemainderOutput == nil {
return true
}
if _, err := f.utxoManager.ReadOutputByOutputIDWithoutLocking(lastRemainderOutput.OutputID()); err != nil {
return false
}
return true
}
var err error
unspentOutputs := []*utxo.Output{}
if shouldCollectUnspentOutputs() {
unspentOutputs, err = f.utxoManager.UnspentOutputs(utxo.FilterAddress(f.address), utxo.ReadLockLedger(false), utxo.MaxResultCount(f.opts.maxOutputCount-2), utxo.FilterOutputType(iotago.OutputSigLockedSingleOutput))
if err != nil {
return fmt.Errorf("reading unspent outputs failed: %s, error: %w", f.address.Bech32(f.opts.hrpNetworkPrefix), err)
}
} else {
unspentOutputs = append(unspentOutputs, lastRemainderOutput)
}
var amount uint64 = 0
found := false
for _, unspentOutput := range unspentOutputs {
amount += unspentOutput.Amount()
if lastRemainderOutput != nil && bytes.Equal(unspentOutput.OutputID()[:], lastRemainderOutput.OutputID()[:]) {
found = true
}
}
if lastRemainderOutput != nil && !found {
unspentOutputs = append(unspentOutputs, lastRemainderOutput)
amount += lastRemainderOutput.Amount()
}
collectedRequestsCounter := len(unspentOutputs)
batchWriterTimeoutChan := time.After(f.opts.batchTimeout)
batchedRequests := []*queueItem{}
CollectValues:
for collectedRequestsCounter < f.opts.maxOutputCount-1 && amount > f.opts.amount {
select {
case <-shutdownSignal:
// faucet was stopped
return nil
case <-batchWriterTimeoutChan:
// timeout was reached => stop collecting requests
break CollectValues
case request := <-f.queue:
batchedRequests = append(batchedRequests, request)
collectedRequestsCounter++
amount -= request.Amount
}
}
f.clearRequests(batchedRequests)
if len(unspentOutputs) < 2 && len(batchedRequests) == 0 {
// no need to sweep or send funds
continue
}
remainderOutput, err := f.sendFaucetMessage(unspentOutputs, batchedRequests, shutdownSignal)
if err != nil {
if common.IsCriticalError(err) != nil {
// error is a critical error
// => stop the faucet
return err
}
f.logSoftError(err)
continue
}
lastRemainderOutput = remainderOutput
}
}
}
<file_sep>package storage
import (
"time"
"github.com/gohornet/hornet/pkg/common"
"github.com/gohornet/hornet/pkg/model/hornet"
"github.com/gohornet/hornet/pkg/profile"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/objectstorage"
iotago "github.com/iotaledger/iota.go/v2"
)
// CachedChild represents a cached Child.
type CachedChild struct {
objectstorage.CachedObject
}
type CachedChildren []*CachedChild
// Retain registers a new consumer for the cached children.
func (cachedChildren CachedChildren) Retain() CachedChildren {
cachedResult := make(CachedChildren, len(cachedChildren))
for i, cachedChild := range cachedChildren {
cachedResult[i] = cachedChild.Retain()
}
return cachedResult
}
// Release releases the cached children, to be picked up by the persistence layer (as soon as all consumers are done).
func (cachedChildren CachedChildren) Release(force ...bool) {
for _, cachedChild := range cachedChildren {
cachedChild.Release(force...)
}
}
// Retain registers a new consumer for the cached child.
func (c *CachedChild) Retain() *CachedChild {
return &CachedChild{c.CachedObject.Retain()}
}
// Child retrieves the child, that is cached in this container.
func (c *CachedChild) Child() *Child {
return c.Get().(*Child)
}
func childrenFactory(key []byte, _ []byte) (objectstorage.StorableObject, error) {
child := NewChild(hornet.MessageIDFromSlice(key[:iotago.MessageIDLength]), hornet.MessageIDFromSlice(key[iotago.MessageIDLength:iotago.MessageIDLength+iotago.MessageIDLength]))
return child, nil
}
func (s *Storage) ChildrenStorageSize() int {
return s.childrenStorage.GetSize()
}
func (s *Storage) configureChildrenStorage(store kvstore.KVStore, opts *profile.CacheOpts) error {
cacheTime, err := time.ParseDuration(opts.CacheTime)
if err != nil {
return err
}
leakDetectionMaxConsumerHoldTime, err := time.ParseDuration(opts.LeakDetectionOptions.MaxConsumerHoldTime)
if err != nil {
return err
}
s.childrenStorage = objectstorage.New(
store.WithRealm([]byte{common.StorePrefixChildren}),
childrenFactory,
objectstorage.CacheTime(cacheTime),
objectstorage.PersistenceEnabled(true),
objectstorage.PartitionKey(iotago.MessageIDLength, iotago.MessageIDLength),
objectstorage.KeysOnly(true),
objectstorage.StoreOnCreation(true),
objectstorage.ReleaseExecutorWorkerCount(opts.ReleaseExecutorWorkerCount),
objectstorage.LeakDetectionEnabled(opts.LeakDetectionOptions.Enabled,
objectstorage.LeakDetectionOptions{
MaxConsumersPerObject: opts.LeakDetectionOptions.MaxConsumersPerObject,
MaxConsumerHoldTime: leakDetectionMaxConsumerHoldTime,
}),
)
return nil
}
// ChildrenMessageIDs returns the message IDs of the children of the given message.
// children +-0
func (s *Storage) ChildrenMessageIDs(messageID hornet.MessageID, iteratorOptions ...IteratorOption) hornet.MessageIDs {
var childrenMessageIDs hornet.MessageIDs
s.childrenStorage.ForEachKeyOnly(func(key []byte) bool {
childrenMessageIDs = append(childrenMessageIDs, hornet.MessageIDFromSlice(key[iotago.MessageIDLength:iotago.MessageIDLength+iotago.MessageIDLength]))
return true
}, append(iteratorOptions, objectstorage.WithIteratorPrefix(messageID))...)
return childrenMessageIDs
}
// ContainsChild returns if the given child exists in the cache/persistence layer.
func (s *Storage) ContainsChild(messageID hornet.MessageID, childMessageID hornet.MessageID, readOptions ...ReadOption) bool {
return s.childrenStorage.Contains(append(messageID, childMessageID...), readOptions...)
}
// CachedChildrenOfMessageID returns the cached children of a message.
// children +1
func (s *Storage) CachedChildrenOfMessageID(messageID hornet.MessageID, iteratorOptions ...IteratorOption) CachedChildren {
cachedChildren := make(CachedChildren, 0)
s.childrenStorage.ForEach(func(_ []byte, cachedObject objectstorage.CachedObject) bool {
cachedChildren = append(cachedChildren, &CachedChild{CachedObject: cachedObject})
return true
}, append(iteratorOptions, objectstorage.WithIteratorPrefix(messageID))...)
return cachedChildren
}
// ChildConsumer consumes the given child during looping through all children.
type ChildConsumer func(messageID hornet.MessageID, childMessageID hornet.MessageID) bool
// ForEachChild loops over all children.
func (s *Storage) ForEachChild(consumer ChildConsumer, iteratorOptions ...IteratorOption) {
s.childrenStorage.ForEachKeyOnly(func(key []byte) bool {
return consumer(hornet.MessageIDFromSlice(key[:iotago.MessageIDLength]), hornet.MessageIDFromSlice(key[iotago.MessageIDLength:iotago.MessageIDLength+iotago.MessageIDLength]))
}, iteratorOptions...)
}
// StoreChild stores the child in the persistence layer and returns a cached object.
// child +1
func (s *Storage) StoreChild(parentMessageID hornet.MessageID, childMessageID hornet.MessageID) *CachedChild {
child := NewChild(parentMessageID, childMessageID)
return &CachedChild{CachedObject: s.childrenStorage.Store(child)}
}
// DeleteChild deletes the child in the cache/persistence layer.
// child +-0
func (s *Storage) DeleteChild(messageID hornet.MessageID, childMessageID hornet.MessageID) {
child := NewChild(messageID, childMessageID)
s.childrenStorage.Delete(child.ObjectStorageKey())
}
// DeleteChildren deletes the children of the given message in the cache/persistence layer.
// child +-0
func (s *Storage) DeleteChildren(messageID hornet.MessageID, iteratorOptions ...IteratorOption) {
var keysToDelete [][]byte
s.childrenStorage.ForEachKeyOnly(func(key []byte) bool {
keysToDelete = append(keysToDelete, key)
return true
}, append(iteratorOptions, objectstorage.WithIteratorPrefix(messageID))...)
for _, key := range keysToDelete {
s.childrenStorage.Delete(key)
}
}
// ShutdownChildrenStorage shuts down the children storage.
func (s *Storage) ShutdownChildrenStorage() {
s.childrenStorage.Shutdown()
}
// FlushChildrenStorage flushes the children storage.
func (s *Storage) FlushChildrenStorage() {
s.childrenStorage.Flush()
}
<file_sep>package p2p
import (
"bytes"
"context"
stded25519 "crypto/ed25519"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"github.com/ipfs/go-datastore/query"
badger "github.com/ipfs/go-ds-badger"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/libp2p/go-libp2p-peerstore/pstoreds"
"github.com/pkg/errors"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/utils"
kvstoreds "github.com/iotaledger/go-ds-kvstore"
"github.com/iotaledger/hive.go/kvstore"
)
const (
DeprecatedPubKeyFileName = "key.pub"
PrivKeyFileName = "identity.key"
)
var (
ErrPrivKeyInvalid = errors.New("invalid private key")
ErrNoPrivKeyFound = errors.New("no private key found")
)
// PeerStoreContainer is a container for a libp2p peer store.
type PeerStoreContainer struct {
store kvstore.KVStore
peerStore peerstore.Peerstore
}
// Peerstore returns the libp2p peer store from the container.
func (psc *PeerStoreContainer) Peerstore() peerstore.Peerstore {
return psc.peerStore
}
// Flush persists all outstanding write operations to disc.
func (psc *PeerStoreContainer) Flush() error {
return psc.store.Flush()
}
// Close flushes all outstanding write operations and closes the store.
func (psc *PeerStoreContainer) Close() error {
psc.peerStore.Close()
if err := psc.store.Flush(); err != nil {
return err
}
return psc.store.Close()
}
// NewPeerStoreContainer creates a peerstore using kvstore.
func NewPeerStoreContainer(peerStorePath string, dbEngine database.Engine, createDatabaseIfNotExists bool) (*PeerStoreContainer, error) {
dirPath := filepath.Dir(peerStorePath)
if createDatabaseIfNotExists {
if err := os.MkdirAll(dirPath, 0700); err != nil {
return nil, fmt.Errorf("could not create peer store database dir '%s': %w", dirPath, err)
}
}
store, err := database.StoreWithDefaultSettings(peerStorePath, createDatabaseIfNotExists, dbEngine)
if err != nil {
return nil, fmt.Errorf("unable to initialize peer store database: %w", err)
}
peerStore, err := pstoreds.NewPeerstore(context.Background(), kvstoreds.NewDatastore(store), pstoreds.DefaultOpts())
if err != nil {
return nil, fmt.Errorf("unable to initialize peer store: %w", err)
}
return &PeerStoreContainer{
store: store,
peerStore: peerStore,
}, nil
}
// parseEd25519PrivateKeyFromString parses an Ed25519 private key from a hex encoded string.
func parseEd25519PrivateKeyFromString(identityPrivKey string) (crypto.PrivKey, error) {
if identityPrivKey == "" {
return nil, ErrNoPrivKeyFound
}
hivePrivKey, err := utils.ParseEd25519PrivateKeyFromString(identityPrivKey)
if err != nil {
return nil, fmt.Errorf("unable to parse private key: %w", ErrPrivKeyInvalid)
}
stdPrvKey := stded25519.PrivateKey(hivePrivKey)
p2pPrvKey, _, err := crypto.KeyPairFromStdKey(&stdPrvKey)
if err != nil {
return nil, fmt.Errorf("unable to convert private key: %w", err)
}
return p2pPrvKey, nil
}
// ReadEd25519PrivateKeyFromPEMFile reads an Ed25519 private key from a file with PEM format.
func ReadEd25519PrivateKeyFromPEMFile(filepath string) (crypto.PrivKey, error) {
pemPrivateBlockBytes, err := os.ReadFile(filepath)
if err != nil {
return nil, fmt.Errorf("unable to read private key: %w", err)
}
pemPrivateBlock, _ := pem.Decode(pemPrivateBlockBytes)
if pemPrivateBlock == nil {
return nil, fmt.Errorf("unable to decode private key: %w", err)
}
stdCryptoPrvKey, err := x509.ParsePKCS8PrivateKey(pemPrivateBlock.Bytes)
if err != nil {
return nil, fmt.Errorf("unable to parse private key: %w", err)
}
stdPrvKey, ok := stdCryptoPrvKey.(stded25519.PrivateKey)
if !ok {
return nil, fmt.Errorf("unable to type assert private key: %w", err)
}
privKey, err := crypto.UnmarshalEd25519PrivateKey((stdPrvKey)[:])
if err != nil {
return nil, fmt.Errorf("unable to unmarshal private key: %w", err)
}
return privKey, nil
}
// WriteEd25519PrivateKeyToPEMFile stores an Ed25519 private key to a file with PEM format.
func WriteEd25519PrivateKeyToPEMFile(filepath string, privateKey crypto.PrivKey) error {
stdCryptoPrvKey, err := crypto.PrivKeyToStdKey(privateKey)
if err != nil {
return fmt.Errorf("unable to convert private key: %w", err)
}
stdPrvKey, ok := stdCryptoPrvKey.(*stded25519.PrivateKey)
if !ok {
return fmt.Errorf("unable to type assert private key: %w", err)
}
pkcs8Bytes, err := x509.MarshalPKCS8PrivateKey(*stdPrvKey)
if err != nil {
return fmt.Errorf("unable to mashal private key: %w", err)
}
pemPrivateBlock := &pem.Block{
Type: "PRIVATE KEY",
Bytes: pkcs8Bytes,
}
var pemBuffer bytes.Buffer
if err := pem.Encode(&pemBuffer, pemPrivateBlock); err != nil {
return fmt.Errorf("unable to encode private key: %w", err)
}
if err := utils.WriteToFile(filepath, pemBuffer.Bytes(), 0660); err != nil {
return fmt.Errorf("unable to write private key: %w", err)
}
return nil
}
// LoadOrCreateIdentityPrivateKey loads an existing Ed25519 based identity private key
// or creates a new one and stores it as a PEM file in the p2p store folder.
func LoadOrCreateIdentityPrivateKey(p2pStorePath string, identityPrivKey string) (crypto.PrivKey, bool, error) {
privKeyFromConfig, err := parseEd25519PrivateKeyFromString(identityPrivKey)
if err != nil {
if errors.Is(err, ErrPrivKeyInvalid) {
return nil, false, errors.New("configuration contains an invalid private key")
}
if !errors.Is(err, ErrNoPrivKeyFound) {
return nil, false, fmt.Errorf("unable to parse private key from config: %w", err)
}
}
privKeyFilePath := filepath.Join(p2pStorePath, PrivKeyFileName)
_, err = os.Stat(privKeyFilePath)
switch {
case err == nil || os.IsExist(err):
// private key already exists, load and return it
privKey, err := ReadEd25519PrivateKeyFromPEMFile(privKeyFilePath)
if err != nil {
return nil, false, fmt.Errorf("unable to load Ed25519 private key for peer identity: %w", err)
}
if privKeyFromConfig != nil && !privKeyFromConfig.Equals(privKey) {
storedPrivKeyBytes, err := crypto.MarshalPrivateKey(privKey)
if err != nil {
return nil, false, fmt.Errorf("unable to marshal stored Ed25519 private key for peer identity: %w", err)
}
configPrivKeyBytes, err := crypto.MarshalPrivateKey(privKeyFromConfig)
if err != nil {
return nil, false, fmt.Errorf("unable to marshal configured Ed25519 private key for peer identity: %w", err)
}
return nil, false, fmt.Errorf("stored Ed25519 private key (%s) for peer identity doesn't match private key in config (%s)", hex.EncodeToString(storedPrivKeyBytes[:]), hex.EncodeToString(configPrivKeyBytes[:]))
}
return privKey, false, nil
case os.IsNotExist(err):
var privKey crypto.PrivKey
if privKeyFromConfig != nil {
privKey = privKeyFromConfig
} else {
// private key does not exist, create a new one
privKey, _, err = crypto.GenerateKeyPair(crypto.Ed25519, -1)
if err != nil {
return nil, false, fmt.Errorf("unable to generate Ed25519 private key for peer identity: %w", err)
}
}
if err := WriteEd25519PrivateKeyToPEMFile(privKeyFilePath, privKey); err != nil {
return nil, false, fmt.Errorf("unable to store private key file for peer identity: %w", err)
}
return privKey, true, nil
default:
return nil, false, fmt.Errorf("unable to check private key file for peer identity (%s): %w", privKeyFilePath, err)
}
}
// MigrateDeprecatedPeerStore extracts the old peer identity private key from the configuration or peer store,
// migrates the old database and stores the private key in a new file with PEM format.
func MigrateDeprecatedPeerStore(p2pStorePath string, identityPrivKey string, newPeerStoreContainer *PeerStoreContainer) (bool, error) {
privKeyFilePath := filepath.Join(p2pStorePath, PrivKeyFileName)
_, err := os.Stat(privKeyFilePath)
switch {
case err == nil || os.IsExist(err):
// migration not necessary since the private key file already exists
return false, nil
case os.IsNotExist(err):
// migration maybe necessary
default:
return false, fmt.Errorf("unable to check private key file for peer identity (%s): %w", privKeyFilePath, err)
}
deprecatedPubKeyFilePath := filepath.Join(p2pStorePath, DeprecatedPubKeyFileName)
if _, err := os.Stat(deprecatedPubKeyFilePath); err != nil {
if os.IsNotExist(err) {
// migration not necessary since no old public key file exists
return false, nil
}
return false, fmt.Errorf("unable to check deprecated public key file for peer identity (%s): %w", deprecatedPubKeyFilePath, err)
}
// migrates the deprecated badger DB peerstore to the new kvstore based peerstore.
migrateDeprecatedPeerStore := func(deprecatedPeerStorePath string, newStore kvstore.KVStore) error {
defaultOpts := badger.DefaultOptions
// needed under Windows otherwise peer store is 'corrupted' after a restart
defaultOpts.Truncate = runtime.GOOS == "windows"
badgerStore, err := badger.NewDatastore(deprecatedPeerStorePath, &defaultOpts)
if err != nil {
return fmt.Errorf("unable to initialize data store for deprecated peer store: %w", err)
}
defer func() { _ = badgerStore.Close() }()
results, err := badgerStore.Query(query.Query{})
if err != nil {
return fmt.Errorf("unable to query deprecated peer store: %w", err)
}
for res := range results.Next() {
if err := newStore.Set([]byte(res.Key), res.Value); err != nil {
return fmt.Errorf("unable to migrate data to new peer store: %w", err)
}
}
if err := newStore.Flush(); err != nil {
return fmt.Errorf("unable to flush new peer store: %w", err)
}
return nil
}
if err := migrateDeprecatedPeerStore(p2pStorePath, newPeerStoreContainer.store); err != nil {
return false, err
}
privKey, err := parseEd25519PrivateKeyFromString(identityPrivKey)
if err != nil {
if errors.Is(err, ErrPrivKeyInvalid) {
return false, errors.New("configuration contains an invalid private key")
}
if !errors.Is(err, ErrNoPrivKeyFound) {
return false, fmt.Errorf("unable to parse private key from config: %w", err)
}
// there was no private key specified, retrieve it from the peer store with the public key from the deprecated file
existingPubKeyBytes, err := ioutil.ReadFile(deprecatedPubKeyFilePath)
if err != nil {
return false, fmt.Errorf("unable to read deprecated public key file for peer identity: %w", err)
}
pubKey, err := crypto.UnmarshalPublicKey(existingPubKeyBytes)
if err != nil {
return false, fmt.Errorf("unable to unmarshal deprecated public key for peer identity: %w", err)
}
peerID, err := peer.IDFromPublicKey(pubKey)
if err != nil {
return false, fmt.Errorf("unable to get peer identity from deprecated public key: %w", err)
}
// retrieve this node's private key from the new peer store
privKey = newPeerStoreContainer.peerStore.PrivKey(peerID)
if privKey == nil {
return false, errors.New("error while fetching private key for peer identity from peer store")
}
}
if err := WriteEd25519PrivateKeyToPEMFile(privKeyFilePath, privKey); err != nil {
return false, err
}
// delete the deprecated public key file
if err := os.Remove(deprecatedPubKeyFilePath); err != nil {
return false, fmt.Errorf("unable to remove deprecated public key file for peer identity: %w", err)
}
return true, nil
}
<file_sep># HORNET Changelog
All notable changes to this project will be documented in this file.
## [1.0.5] - 02.09.2021
### Added
- Add faucet plugin
- Add faucet website
- Add database migration tool
- Add io utils to read/write a TOML file
- Add private tangle scripts to deb/rpm files
- New public keys applicable for milestone ranges between 1333460-4443860
### Changed
- Move p2p identity private key to PEM file
- Run autopeering entry node in standalone mode
- Merge peerstore and autopeering db path in config
- Expose autopeering port in dockerfile
- Add detailed reason for snapshot download failure
- Print bech32 address in toolset
- Use kvstore for libp2p peerstore and autopeering database
- Use internal bech32 HRP instead of additional config parameter
- Update go version in workflows and dockerfile
- Update github workflow actions
- Update go modules
- Update libp2p
- Autopeering entry nodes for mainnet
- Snapshot download sources for mainnet/comnet
### Fixed
- Fix data size units according to SI units and IEC 60027
- Fix possible jwt token vulnerabilities
- Fix nil pointer exception in optimalSnapshotType
- Set missing config default values for mainnet
- Do not disable plugins for the entry nodes in the integration tests
- Fix dependency injection of global config pars if pluggables are disabled by adding a InitConfigPars stage
- Do not panic in MilestoneRetrieverFromStorage
- Fix logger init in test cases
### Removed
- Remove support for boltdb
### Cleanups
- Refactor node/pluggable logger interface
- Check returned error at the initialization of new background workers
- Fixed return values order of StreamSnapshotDataTo
- Do not use unbuffered channels for signal.Notify
- Change some variable names according to linter suggestions
- Remove duplicate imports
- Remove dead code
- Cleanup toolset listTools func
- Replace deprecated prometheus functions
- Fix comments
- Remove 'Get' from getter function names
- Add error return value to SetConfirmedMilestoneIndex
- Add error return value to SetSnapshotMilestone
- Add error return value to database health functions
- Add error return value to loadSnaphotInfo
- Replace http.Get with client.Do and a context
- Add missing checks for returned errors
- Add linter ignore rules
- Cleanup unused parameters and return values
- Fix some printouts and move hornet logo to startup
- Return error if database init fails
- Reduce dependencies between plugins/core modules
- Replace deprecated libp2p crypto Bytes function
- Add error return value to loadSolidEntryPoints
- Rename util files to utils
- Move database events to package
- Move graceful shutdown logic to package
- Move autopeering local to pkg
- Add error return value to authorization init functions
### Config file changes
`config.json`
```diff
"snapshots": {
"downloadURLs": [
{
- "full": "https://mainnet.tanglebay.com/ls/full_snapshot.bin",
+ "full": "https://cdn.tanglebay.com/snapshots/mainnet/full_snapshot.bin",
- "delta": "https://mainnet.tanglebay.com/ls/delta_snapshot.bin"
+ "delta": "https://cdn.tanglebay.com/snapshots/mainnet/delta_snapshot.bin"
}
]
},
"protocol": {
"publicKeyRanges": [
{
"key": "<KEY>",
"start": 552960,
"end": 2108160
- }
+ },
+ {
+ "key": "760d88e112c0fd210cf16a3dce3443ecf7e18c456c2fb9646cabb2e13e367569",
+ "start": 1333460,
+ "end": 2888660
+ },
+ {
+ "key": "<KEY>76ea2235539358c7df8ca4d2f2fc35a663c760449e65eba9f8a6e7",
+ "start": 2111060,
+ "end": 3666260
+ },
+ {
+ "key": "<KEY>",
+ "start": 2888660,
+ "end": 4443860
+ }
]
},
"p2p": {
- "identityPrivateKey": "",
- "peerStore": {
- "path": "./p2pstore"
- }
+ "db": {
+ "path": "p2pstore"
+ },
"autopeering": {
- "db": {
- "path": "./p2pstore"
- },
"entryNodes": [
- "/dns/lucamoser.ch/udp/14926/autopeering/4H6WV54tB29u8xCcEaMGQMn37LFvM1ynNpp27TTXaqNM",
+ "/dns/lucamoser.ch/udp/14826/autopeering/4H6WV54tB29u8xCcEaMGQMn37LFvM1ynNpp27TTXaqNM",
+ "/dns/entry-hornet-0.h.chrysalis-mainnet.iotaledger.net/udp/14626/autopeering/iotaPHdAn7eueBnXtikZMwhfPXaeGJGXDt4RBuLuGgb",
+ "/dns/entry-hornet-1.h.chrysalis-mainnet.iotaledger.net/udp/14626/autopeering/iotaJJqMd5CQvv1A61coSQCYW9PNT1QKPs7xh2Qg5K2",
"/dns/entry-mainnet.tanglebay.com/udp/14626/autopeering/iot4By1FD4pFLrGJ6AAe7YEeSu9RbW9xnPUmxMdQenC"
],
}
},
+ "faucet": {
+ "amount": 10000000,
+ "smallAmount": 1000000,
+ "maxAddressBalance": 20000000,
+ "maxOutputCount": 127,
+ "indexationMessage": "HORNET FAUCET",
+ "batchTimeout": "2s",
+ "powWorkerCount": 0,
+ "website": {
+ "bindAddress": "localhost:8091",
+ "enabled": true
+ },
}
```
## [1.0.4] - 04.08.2021
### Added
- Autopeering with two default entry nodes (disabled by default)
- Default config for community network
### Changed
- Reduces the default WarpSync advancement range back to 150 as the previous value was only a workaround.
- Cleaned up parameter names and values in all config files
- Rate limit for dashboard login changed from 1 request every 5 minutes to 5 requests every minute
### Config file changes
`config.json`
```diff
"receipts": {
"backup": {
- "folder": "receipts"
+ "path": "receipts"
},
}
"p2p": {
"bindMultiAddresses": [
"/ip4/0.0.0.0/tcp/15600",
+ "/ip6/::/tcp/15600"
],
- "gossipUnknownPeersLimit": 4,
+ "gossip": {
+ "unknownPeersLimit": 4,
+ "streamReadTimeout": "1m0s",
+ "streamWriteTimeout": "10s"
+ },
"autopeering": {
- "dirPath": "./p2pstore"
+ "db": {
+ "path": "./p2pstore"
+ },
}
"warpsync": {
- "advancementRange": 10000
+ "advancementRange": 150
},
"spammer": {
- "mpsRateLimit": 5.0,
+ "mpsRateLimit": 0.0,
},
```
## [1.0.3] - 02.06.2021
### Added
- A new public key applicable for milestone ranges between 552960-2108160
### Changed
- Increases the WarpSync advancement range to 10k which allows nodes to resync even if
they already stored the milestone for which they lacked the applicable public key beforehand.
## [1.0.2] - 28.05.2021
### Added
- p2pidentity-extract tool (#1090)
- tool to generate JWT token for REST API (#1085)
- Add database pruning based on database size (#1115)
### Changed
- Improved documentation (#1060 + #1083 + #1087 + #1090)
- Build Dockerfile with rocksdb (#1077)
- Default DB engine changed to rocksdb (#1078)
- Renamed alphanet scripts to private_tangle (#1078)
- Updated rocksdb (#1080)
- Updated go modules, containers and dashboard (#1103)
- Check if files exist in the p2pstore directory (needed for docker) (#1084)
- Disabled MQTT http port (#1094)
- Download the latest snapshots from the given targets (#1097)
- Adds "ledgerIndex" field to some REST HTTP and MQTT API responses (#1106)
- Add delta snapshots to control endpoint (#1039)
- Changed node control endpoints to use POST (#1039)
- Expose MQTT port. Remove no longer needed ports (#1105)
- Re-add private Tangle doc (#1113)
### Fixed
- Added workdir to docker/Dockerfile. (#1068)
- JWT subject verification (#1076)
- Send on closed channel in coo quorum (#1082)
- Database revalidation (#1096)
- Mask sensitive config parameters in log (#1100)
- Fix ulimits and dependencies at node startup (#1107)
- Do not print API JWT auth tokens to the log (unsafe) (#1039)
- Check if node is busy before accepting snapshot commands via API (#1039)
### Config file changes
`config.json`
```diff
"pruning": {
- "enabled": true,
- "delay": 60480,
+ "milestones": {
+ "enabled": false,
+ "maxMilestonesToKeep": 60480
+ },
+ "size": {
+ "enabled": true,
+ "targetSize": "30GB",
+ "thresholdPercentage": 10.0,
+ "cooldownTime": "5m"
+ },
"pruneReceipts": false
},
```
## [1.0.1] - 28.04.2021
### Fixed
- Receipt validation deadlock
- Docker Image Build Tags for RocksDB
## [1.0.0] - 28.04.2021
### Changed
- IOTA: A new dawn.<file_sep>package utils
import (
"os"
"path/filepath"
)
// FolderSize returns the size of a folder.
func FolderSize(target string) (int64, error) {
var size int64
err := filepath.Walk(target, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
<file_sep>package database
import (
flag "github.com/spf13/pflag"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/node"
)
const (
// the used database engine (pebble/rocksdb).
CfgDatabaseEngine = "db.engine"
// the path to the database folder.
CfgDatabasePath = "db.path"
// whether to automatically start revalidation on startup if the database is corrupted.
CfgDatabaseAutoRevalidation = "db.autoRevalidation"
// ignore the check for corrupted databases (should only be used for debug reasons).
CfgDatabaseDebug = "db.debug"
)
var params = &node.PluginParams{
Params: map[string]*flag.FlagSet{
"nodeConfig": func() *flag.FlagSet {
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.String(CfgDatabaseEngine, database.EngineRocksDB, "the used database engine (pebble/rocksdb)")
fs.String(CfgDatabasePath, "mainnetdb", "the path to the database folder")
fs.Bool(CfgDatabaseAutoRevalidation, false, "whether to automatically start revalidation on startup if the database is corrupted")
fs.Bool(CfgDatabaseDebug, false, "ignore the check for corrupted databases (should only be used for debug reasons)")
return fs
}(),
},
Masked: nil,
}
<file_sep>package storage
import (
"sync"
"github.com/gohornet/hornet/pkg/keymanager"
"github.com/gohornet/hornet/pkg/model/milestone"
"github.com/gohornet/hornet/pkg/model/utxo"
"github.com/gohornet/hornet/pkg/profile"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/objectstorage"
"github.com/iotaledger/hive.go/syncutils"
)
type packageEvents struct {
ReceivedValidMilestone *events.Event
PruningStateChanged *events.Event
}
type ReadOption = objectstorage.ReadOption
type IteratorOption = objectstorage.IteratorOption
type Storage struct {
log *logger.Logger
// database
databaseDir string
store kvstore.KVStore
belowMaxDepth milestone.Index
// kv storages
healthStore kvstore.KVStore
snapshotStore kvstore.KVStore
// object storages
childrenStorage *objectstorage.ObjectStorage
indexationStorage *objectstorage.ObjectStorage
messagesStorage *objectstorage.ObjectStorage
metadataStorage *objectstorage.ObjectStorage
milestoneStorage *objectstorage.ObjectStorage
unreferencedMessagesStorage *objectstorage.ObjectStorage
// solid entry points
solidEntryPoints *SolidEntryPoints
solidEntryPointsLock sync.RWMutex
// snapshot info
snapshot *SnapshotInfo
snapshotMutex syncutils.RWMutex
// milestones
confirmedMilestoneIndex milestone.Index
confirmedMilestoneLock syncutils.RWMutex
latestMilestoneIndex milestone.Index
latestMilestoneLock syncutils.RWMutex
// node synced
isNodeSynced bool
isNodeAlmostSynced bool
isNodeSyncedWithinBelowMaxDepth bool
waitForNodeSyncedChannelsLock syncutils.Mutex
waitForNodeSyncedChannels []chan struct{}
// milestones
keyManager *keymanager.KeyManager
milestonePublicKeyCount int
// utxo
utxoManager *utxo.Manager
// events
Events *packageEvents
}
func New(log *logger.Logger, databaseDirectory string, store kvstore.KVStore, cachesProfile *profile.Caches, belowMaxDepth int, keyManager *keymanager.KeyManager, milestonePublicKeyCount int) (*Storage, error) {
utxoManager := utxo.New(store)
s := &Storage{
log: log,
databaseDir: databaseDirectory,
store: store,
keyManager: keyManager,
milestonePublicKeyCount: milestonePublicKeyCount,
utxoManager: utxoManager,
belowMaxDepth: milestone.Index(belowMaxDepth),
Events: &packageEvents{
ReceivedValidMilestone: events.NewEvent(MilestoneWithRequestedCaller),
PruningStateChanged: events.NewEvent(events.BoolCaller),
},
}
if err := s.configureStorages(s.store, cachesProfile); err != nil {
return nil, err
}
if err := s.loadConfirmedMilestoneFromDatabase(); err != nil {
return nil, err
}
if err := s.loadSnapshotInfo(); err != nil {
return nil, err
}
if err := s.loadSolidEntryPoints(); err != nil {
return nil, err
}
return s, nil
}
func (s *Storage) KVStore() kvstore.KVStore {
return s.store
}
func (s *Storage) UTXO() *utxo.Manager {
return s.utxoManager
}
func (s *Storage) configureStorages(store kvstore.KVStore, caches *profile.Caches) error {
if err := s.configureHealthStore(store); err != nil {
return err
}
if err := s.configureMessageStorage(store, caches.Messages); err != nil {
return err
}
if err := s.configureChildrenStorage(store, caches.Children); err != nil {
return err
}
if err := s.configureMilestoneStorage(store, caches.Milestones); err != nil {
return err
}
if err := s.configureUnreferencedMessageStorage(store, caches.UnreferencedMessages); err != nil {
return err
}
if err := s.configureIndexationStorage(store, caches.Indexations); err != nil {
return err
}
s.configureSnapshotStore(store)
return nil
}
// FlushStorages flushes all storages.
func (s *Storage) FlushStorages() {
s.FlushMilestoneStorage()
s.FlushMessagesStorage()
s.FlushChildrenStorage()
s.FlushIndexationStorage()
s.FlushUnreferencedMessagesStorage()
}
// ShutdownStorages shuts down all storages.
func (s *Storage) ShutdownStorages() {
s.ShutdownMilestoneStorage()
s.ShutdownMessagesStorage()
s.ShutdownChildrenStorage()
s.ShutdownIndexationStorage()
s.ShutdownUnreferencedMessagesStorage()
}
func (s *Storage) loadConfirmedMilestoneFromDatabase() error {
ledgerMilestoneIndex, err := s.UTXO().ReadLedgerIndex()
if err != nil {
return err
}
// set the confirmed milestone index based on the ledger milestone
return s.SetConfirmedMilestoneIndex(ledgerMilestoneIndex, false)
}
// DatabaseSize returns the size of the database.
func (s *Storage) DatabaseSize() (int64, error) {
return utils.FolderSize(s.databaseDir)
}
<file_sep>package toolset
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/kvstore"
)
func databaseMigration(_ *configuration.Configuration, args []string) error {
printUsage := func() {
println("Usage:")
println(fmt.Sprintf(" %s [SOURCE_DATABASE_PATH] [TARGET_DATABASE_PATH] [TARGET_DATABASE_ENGINE]", ToolDatabaseMigration))
println()
println(" [SOURCE_DATABASE_PATH] - the path to the source database")
println(" [TARGET_DATABASE_PATH] - the path to the target database")
println(" [TARGET_DATABASE_ENGINE] - the engine of the target database (values: pebble, rocksdb)")
println()
println(fmt.Sprintf("example: %s %s %s %s", ToolDatabaseMigration, "mainnetdb", "mainnetdb_new", "rocksdb"))
}
// check arguments
if len(args) != 3 {
printUsage()
return fmt.Errorf("wrong argument count for '%s'", ToolDatabaseMigration)
}
sourcePath := args[0]
if _, err := os.Stat(sourcePath); err != nil || os.IsNotExist(err) {
return fmt.Errorf("SOURCE_DATABASE_PATH (%s) does not exist", sourcePath)
}
targetPath := args[1]
if _, err := os.Stat(targetPath); err == nil || !os.IsNotExist(err) {
return fmt.Errorf("TARGET_DATABASE_PATH (%s) already exist", targetPath)
}
dbEngineTarget := strings.ToLower(args[2])
engineTarget, err := database.DatabaseEngine(dbEngineTarget)
if err != nil {
return err
}
storeSource, err := database.StoreWithDefaultSettings(sourcePath, false)
if err != nil {
return fmt.Errorf("source database initialization failed: %w", err)
}
defer func() { _ = storeSource.Close() }()
storeTarget, err := database.StoreWithDefaultSettings(targetPath, true, engineTarget)
if err != nil {
return fmt.Errorf("target database initialization failed: %w", err)
}
defer func() { _ = storeTarget.Close() }()
copyBytes := func(source []byte) []byte {
cpy := make([]byte, len(source))
copy(cpy, source)
return cpy
}
ts := time.Now()
lastStatusTime := time.Now()
sourcePathAbs, err := filepath.Abs(sourcePath)
if err != nil {
sourcePathAbs = sourcePath
}
targetPathAbs, err := filepath.Abs(targetPath)
if err != nil {
targetPathAbs = targetPath
}
fmt.Printf("Migrating database... (source: \"%s\", target: \"%s\")\n", sourcePathAbs, targetPathAbs)
var errDB error
if err := storeSource.Iterate(kvstore.EmptyPrefix, func(key []byte, value kvstore.Value) bool {
dstKey := copyBytes(key)
dstValue := copyBytes(value)
if errDB = storeTarget.Set(dstKey, dstValue); errDB != nil {
return false
}
if time.Since(lastStatusTime) >= printStatusInterval {
lastStatusTime = time.Now()
sourceSizeBytes, _ := utils.FolderSize(sourcePath)
targetSizeBytes, _ := utils.FolderSize(targetPath)
percentage, remaining := utils.EstimateRemainingTime(ts, targetSizeBytes, sourceSizeBytes)
fmt.Printf("Source database size: %s, target database size: %s, estimated percentage: %0.2f%%. %v elapsed, %v left...)\n", humanize.Bytes(uint64(sourceSizeBytes)), humanize.Bytes(uint64(targetSizeBytes)), percentage, time.Since(ts).Truncate(time.Second), remaining.Truncate(time.Second))
}
return true
}); err != nil {
return fmt.Errorf("source database iteration failed: %w", err)
}
if errDB != nil {
return fmt.Errorf("target database set failed: %w", err)
}
if err := storeTarget.Flush(); err != nil {
return fmt.Errorf("target database flush failed: %w", err)
}
fmt.Printf("Migration successful! took: %v\n", time.Since(ts).Truncate(time.Second))
return nil
}
<file_sep>package node
import (
"fmt"
"strings"
flag "github.com/spf13/pflag"
"go.uber.org/dig"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
)
type Node struct {
enabledPlugins map[string]struct{}
disabledPlugins map[string]struct{}
forceDisabledPluggables map[string]struct{}
corePluginsMap map[string]*CorePlugin
corePlugins []*CorePlugin
pluginsMap map[string]*Plugin
plugins []*Plugin
container *dig.Container
log *logger.Logger
options *NodeOptions
}
func New(optionalOptions ...NodeOption) *Node {
nodeOpts := &NodeOptions{}
nodeOpts.apply(defaultNodeOptions...)
nodeOpts.apply(optionalOptions...)
node := &Node{
enabledPlugins: make(map[string]struct{}),
disabledPlugins: make(map[string]struct{}),
forceDisabledPluggables: make(map[string]struct{}),
corePluginsMap: make(map[string]*CorePlugin),
corePlugins: make([]*CorePlugin, 0),
pluginsMap: make(map[string]*Plugin),
plugins: make([]*Plugin, 0),
container: dig.New(dig.DeferAcyclicVerification()),
options: nodeOpts,
}
// initialize the core plugins and plugins
node.init()
// initialize logger after init phase because plugins could modify it
node.log = logger.NewLogger("Node")
// configure the core plugins and enabled plugins
node.configure()
return node
}
// LogDebug uses fmt.Sprint to construct and log a message.
func (n *Node) LogDebug(args ...interface{}) {
n.log.Debug(args...)
}
// LogDebugf uses fmt.Sprintf to log a templated message.
func (n *Node) LogDebugf(template string, args ...interface{}) {
n.log.Debugf(template, args...)
}
// LogError uses fmt.Sprint to construct and log a message.
func (n *Node) LogError(args ...interface{}) {
n.log.Error(args...)
}
// LogErrorf uses fmt.Sprintf to log a templated message.
func (n *Node) LogErrorf(template string, args ...interface{}) {
n.log.Errorf(template, args...)
}
// LogFatal uses fmt.Sprint to construct and log a message, then calls os.Exit.
func (n *Node) LogFatal(args ...interface{}) {
n.log.Fatal(args...)
}
// LogFatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.
func (n *Node) LogFatalf(template string, args ...interface{}) {
n.log.Fatalf(template, args...)
}
// LogInfo uses fmt.Sprint to construct and log a message.
func (n *Node) LogInfo(args ...interface{}) {
n.log.Info(args...)
}
// LogInfof uses fmt.Sprintf to log a templated message.
func (n *Node) LogInfof(template string, args ...interface{}) {
n.log.Infof(template, args...)
}
// LogWarn uses fmt.Sprint to construct and log a message.
func (n *Node) LogWarn(args ...interface{}) {
n.log.Warn(args...)
}
// LogWarnf uses fmt.Sprintf to log a templated message.
func (n *Node) LogWarnf(template string, args ...interface{}) {
n.log.Warnf(template, args...)
}
// Panic uses fmt.Sprint to construct and log a message, then panics.
func (n *Node) Panic(args ...interface{}) {
n.log.Panic(args...)
}
// Panicf uses fmt.Sprintf to log a templated message, then panics.
func (n *Node) Panicf(template string, args ...interface{}) {
n.log.Panicf(template, args...)
}
func Start(optionalOptions ...NodeOption) *Node {
node := New(optionalOptions...)
node.Start()
return node
}
func Run(optionalOptions ...NodeOption) *Node {
node := New(optionalOptions...)
node.Run()
return node
}
func (n *Node) isEnabled(identifier string) bool {
_, exists := n.enabledPlugins[identifier]
return exists
}
func (n *Node) isDisabled(identifier string) bool {
_, exists := n.disabledPlugins[identifier]
return exists
}
func (n *Node) isForceDisabled(identifier string) bool {
_, exists := n.forceDisabledPluggables[identifier]
return exists
}
// IsSkipped returns whether the plugin is loaded or skipped.
func (n *Node) IsSkipped(plugin *Plugin) bool {
// list of disabled plugins has the highest priority
if n.isDisabled(plugin.Identifier()) || n.isForceDisabled(plugin.Identifier()) {
return true
}
// if the plugin was not in the list of disabled plugins, it is only skipped if
// the plugin was not enabled and not in the list of enabled plugins.
return plugin.Status != StatusEnabled && !n.isEnabled(plugin.Identifier())
}
func (n *Node) init() {
if n.options.initPlugin == nil {
panic("you must configure the node with an InitPlugin")
}
params := map[string][]*flag.FlagSet{}
masked := []string{}
//
// Collect parameters
//
n.options.initPlugin.Node = n
if n.options.initPlugin.Params != nil {
for k, v := range n.options.initPlugin.Params.Params {
params[k] = append(params[k], v)
}
}
if n.options.initPlugin.Params.Masked != nil {
masked = append(masked, n.options.initPlugin.Params.Masked...)
}
forEachCorePlugin(n.options.corePlugins, func(corePlugin *CorePlugin) bool {
corePlugin.Node = n
if corePlugin.Params == nil {
return true
}
for k, v := range corePlugin.Params.Params {
params[k] = append(params[k], v)
}
if corePlugin.Params.Masked != nil {
masked = append(masked, corePlugin.Params.Masked...)
}
return true
})
forEachPlugin(n.options.plugins, func(plugin *Plugin) bool {
plugin.Node = n
if plugin.Params == nil {
return true
}
for k, v := range plugin.Params.Params {
params[k] = append(params[k], v)
}
if plugin.Params.Masked != nil {
masked = append(masked, plugin.Params.Masked...)
}
return true
})
//
// Init Stage
//
// the init plugin parses the config files and initializes the global logger
initCfg, err := n.options.initPlugin.Init(params, masked)
if err != nil {
panic(fmt.Errorf("unable to initialize node: %w", err))
}
//
// InitConfig Stage
//
if n.options.initPlugin.InitConfigPars == nil {
panic(fmt.Errorf("the init plugin must have an InitConfigPars func"))
}
n.options.initPlugin.InitConfigPars(n.container)
forEachCorePlugin(n.options.corePlugins, func(corePlugin *CorePlugin) bool {
if corePlugin.InitConfigPars != nil {
corePlugin.InitConfigPars(n.container)
}
return true
})
forEachPlugin(n.options.plugins, func(plugin *Plugin) bool {
if plugin.InitConfigPars != nil {
plugin.InitConfigPars(n.container)
}
return true
})
//
// Pre-Provide Stage
//
if n.options.initPlugin.PreProvide != nil {
n.options.initPlugin.PreProvide(n.container, n.options.initPlugin.Configs, initCfg)
}
forEachCorePlugin(n.options.corePlugins, func(corePlugin *CorePlugin) bool {
if corePlugin.PreProvide != nil {
corePlugin.PreProvide(n.container, n.options.initPlugin.Configs, initCfg)
}
return true
})
forEachPlugin(n.options.plugins, func(plugin *Plugin) bool {
if plugin.PreProvide != nil {
plugin.PreProvide(n.container, n.options.initPlugin.Configs, initCfg)
}
return true
})
//
// Enable / (Force-) disable Pluggables
//
for _, name := range initCfg.EnabledPlugins {
n.enabledPlugins[strings.ToLower(name)] = struct{}{}
}
for _, name := range initCfg.DisabledPlugins {
n.disabledPlugins[strings.ToLower(name)] = struct{}{}
}
for _, name := range initCfg.forceDisabledPluggables {
n.forceDisabledPluggables[strings.ToLower(name)] = struct{}{}
}
forEachCorePlugin(n.options.corePlugins, func(corePlugin *CorePlugin) bool {
if n.isForceDisabled(corePlugin.Identifier()) {
return true
}
n.addCorePlugin(corePlugin)
return true
})
forEachPlugin(n.options.plugins, func(plugin *Plugin) bool {
if n.IsSkipped(plugin) {
return true
}
n.addPlugin(plugin)
return true
})
//
// Provide Stage
//
if n.options.initPlugin.Provide != nil {
n.options.initPlugin.Provide(n.container)
}
n.ForEachCorePlugin(func(corePlugin *CorePlugin) bool {
if corePlugin.Provide != nil {
corePlugin.Provide(n.container)
}
return true
})
n.ForEachPlugin(func(plugin *Plugin) bool {
if plugin.Provide != nil {
plugin.Provide(n.container)
}
return true
})
//
// Invoke Stage
//
if n.options.initPlugin.DepsFunc != nil {
if err := n.container.Invoke(n.options.initPlugin.DepsFunc); err != nil {
panic(err)
}
}
n.ForEachCorePlugin(func(corePlugin *CorePlugin) bool {
if corePlugin.DepsFunc != nil {
if err := n.container.Invoke(corePlugin.DepsFunc); err != nil {
panic(err)
}
}
return true
})
n.ForEachPlugin(func(plugin *Plugin) bool {
if plugin.DepsFunc != nil {
if err := n.container.Invoke(plugin.DepsFunc); err != nil {
panic(err)
}
}
return true
})
}
func (n *Node) configure() {
if n.options.initPlugin.Configure != nil {
n.options.initPlugin.Configure()
}
n.ForEachCorePlugin(func(corePlugin *CorePlugin) bool {
if corePlugin.Configure != nil {
corePlugin.Configure()
}
n.LogInfof("Loading core plugin: %s ... done", corePlugin.Name)
return true
})
n.ForEachPlugin(func(plugin *Plugin) bool {
if plugin.Configure != nil {
plugin.Configure()
}
n.LogInfof("Loading plugin: %s ... done", plugin.Name)
return true
})
}
func (n *Node) execute() {
n.LogInfo("Executing core plugin ...")
if n.options.initPlugin.Run != nil {
n.options.initPlugin.Run()
}
n.ForEachCorePlugin(func(corePlugin *CorePlugin) bool {
if corePlugin.Run != nil {
corePlugin.Run()
}
n.LogInfof("Starting core plugin: %s ... done", corePlugin.Name)
return true
})
n.LogInfo("Executing plugins ...")
n.ForEachPlugin(func(plugin *Plugin) bool {
if plugin.Run != nil {
plugin.Run()
}
n.LogInfof("Starting plugin: %s ... done", plugin.Name)
return true
})
}
func (n *Node) Start() {
n.execute()
n.LogInfo("Starting background workers ...")
n.Daemon().Start()
}
func (n *Node) Run() {
n.execute()
n.LogInfo("Starting background workers ...")
n.Daemon().Run()
n.LogInfo("Shutdown complete!")
}
func (n *Node) Shutdown() {
n.Daemon().ShutdownAndWait()
}
func (n *Node) Daemon() daemon.Daemon {
return n.options.daemon
}
func (n *Node) addCorePlugin(corePlugin *CorePlugin) {
name := corePlugin.Name
if _, exists := n.corePluginsMap[name]; exists {
panic("duplicate core plugin - \"" + name + "\" was defined already")
}
n.corePluginsMap[name] = corePlugin
n.corePlugins = append(n.corePlugins, corePlugin)
}
func (n *Node) addPlugin(plugin *Plugin) {
name := plugin.Name
if _, exists := n.pluginsMap[name]; exists {
panic("duplicate plugin - \"" + name + "\" was defined already")
}
n.pluginsMap[name] = plugin
n.plugins = append(n.plugins, plugin)
}
// InitConfigParsFunc gets called with a dig.Container.
type InitConfigParsFunc func(c *dig.Container)
// PreProvideFunc gets called with a dig.Container, the configs the InitPlugin brings to the node and the InitConfig.
type PreProvideFunc func(c *dig.Container, configs map[string]*configuration.Configuration, initConf *InitConfig)
// ProvideFunc gets called with a dig.Container.
type ProvideFunc func(c *dig.Container)
// InitConfig describes the result of a node initialization.
type InitConfig struct {
EnabledPlugins []string
DisabledPlugins []string
forceDisabledPluggables []string
}
// ForceDisablePluggable is used to force disable pluggables before the provide stage.
func (ic *InitConfig) ForceDisablePluggable(identifier string) {
exists := false
for _, entry := range ic.forceDisabledPluggables {
if entry == identifier {
exists = true
break
}
}
if !exists {
ic.forceDisabledPluggables = append(ic.forceDisabledPluggables, identifier)
}
}
// InitFunc gets called as the initialization function of the node.
type InitFunc func(params map[string][]*flag.FlagSet, maskedKeys []string) (*InitConfig, error)
// Callback is a function called without any arguments.
type Callback func()
// CorePluginForEachFunc is used in ForEachCorePlugin.
// Returning false indicates to stop looping.
type CorePluginForEachFunc func(corePlugin *CorePlugin) bool
func forEachCorePlugin(corePlugins []*CorePlugin, f CorePluginForEachFunc) {
for _, corePlugin := range corePlugins {
if !f(corePlugin) {
break
}
}
}
// ForEachCorePlugin calls the given CorePluginForEachFunc on each loaded core plugins.
func (n *Node) ForEachCorePlugin(f CorePluginForEachFunc) {
forEachCorePlugin(n.corePlugins, f)
}
// PluginForEachFunc is used in ForEachPlugin.
// Returning false indicates to stop looping.
type PluginForEachFunc func(plugin *Plugin) bool
func forEachPlugin(plugins []*Plugin, f PluginForEachFunc) {
for _, plugin := range plugins {
if !f(plugin) {
break
}
}
}
// ForEachPlugin calls the given PluginForEachFunc on each loaded plugin.
func (n *Node) ForEachPlugin(f PluginForEachFunc) {
forEachPlugin(n.plugins, f)
}
<file_sep>package mqtt
import (
"fmt"
"net/url"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/model/milestone"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/gohornet/hornet/pkg/model/utxo"
mqttpkg "github.com/gohornet/hornet/pkg/mqtt"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/pkg/tangle"
"github.com/gohornet/hornet/plugins/restapi"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/workerpool"
iotago "github.com/iotaledger/iota.go/v2"
)
func init() {
Plugin = &node.Plugin{
Status: node.StatusEnabled,
Pluggable: node.Pluggable{
Name: "MQTT",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
Configure: configure,
Run: run,
},
}
}
const (
// RouteMQTT is the route for accessing the MQTT over WebSockets.
RouteMQTT = "/mqtt"
workerCount = 1
workerQueueSize = 10000
)
var (
Plugin *node.Plugin
deps dependencies
newLatestMilestoneWorkerPool *workerpool.WorkerPool
newConfirmedMilestoneWorkerPool *workerpool.WorkerPool
messagesWorkerPool *workerpool.WorkerPool
messageMetadataWorkerPool *workerpool.WorkerPool
utxoOutputWorkerPool *workerpool.WorkerPool
receiptWorkerPool *workerpool.WorkerPool
topicSubscriptionWorkerPool *workerpool.WorkerPool
wasSyncBefore = false
mqttBroker *mqttpkg.Broker
)
type dependencies struct {
dig.In
Storage *storage.Storage
Tangle *tangle.Tangle
NodeConfig *configuration.Configuration `name:"nodeConfig"`
MaxDeltaMsgYoungestConeRootIndexToCMI int `name:"maxDeltaMsgYoungestConeRootIndexToCMI"`
MaxDeltaMsgOldestConeRootIndexToCMI int `name:"maxDeltaMsgOldestConeRootIndexToCMI"`
BelowMaxDepth int `name:"belowMaxDepth"`
Bech32HRP iotago.NetworkPrefix `name:"bech32HRP"`
Echo *echo.Echo `optional:"true"`
}
func configure() {
// check if RestAPI plugin is disabled
if Plugin.Node.IsSkipped(restapi.Plugin) {
Plugin.Panic("RestAPI plugin needs to be enabled to use the MQTT plugin")
}
newLatestMilestoneWorkerPool = workerpool.New(func(task workerpool.Task) {
publishLatestMilestone(task.Param(0).(*storage.CachedMilestone)) // milestone pass +1
task.Return(nil)
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize), workerpool.FlushTasksAtShutdown(true))
newConfirmedMilestoneWorkerPool = workerpool.New(func(task workerpool.Task) {
publishConfirmedMilestone(task.Param(0).(*storage.CachedMilestone)) // milestone pass +1
task.Return(nil)
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize), workerpool.FlushTasksAtShutdown(true))
messagesWorkerPool = workerpool.New(func(task workerpool.Task) {
publishMessage(task.Param(0).(*storage.CachedMessage)) // metadata pass +1
task.Return(nil)
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize), workerpool.FlushTasksAtShutdown(true))
messageMetadataWorkerPool = workerpool.New(func(task workerpool.Task) {
publishMessageMetadata(task.Param(0).(*storage.CachedMetadata)) // metadata pass +1
task.Return(nil)
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize), workerpool.FlushTasksAtShutdown(true))
utxoOutputWorkerPool = workerpool.New(func(task workerpool.Task) {
publishOutput(task.Param(0).(milestone.Index), task.Param(1).(*utxo.Output), task.Param(2).(bool))
task.Return(nil)
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize))
receiptWorkerPool = workerpool.New(func(task workerpool.Task) {
publishReceipt(task.Param(0).(*iotago.Receipt))
task.Return(nil)
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize))
topicSubscriptionWorkerPool = workerpool.New(func(task workerpool.Task) {
defer task.Return(nil)
topic := task.Param(0).([]byte)
topicName := string(topic)
if messageID := messageIDFromTopic(topicName); messageID != nil {
if cachedMsgMeta := deps.Storage.CachedMessageMetadataOrNil(messageID); cachedMsgMeta != nil {
if _, added := messageMetadataWorkerPool.TrySubmit(cachedMsgMeta); added {
return // Avoid Release (done inside workerpool task)
}
cachedMsgMeta.Release(true)
}
return
}
if transactionID := transactionIDFromTopic(topicName); transactionID != nil {
// Find the first output of the transaction
outputID := &iotago.UTXOInputID{}
copy(outputID[:], transactionID[:])
output, err := deps.Storage.UTXO().ReadOutputByOutputIDWithoutLocking(outputID)
if err != nil {
return
}
publishTransactionIncludedMessage(transactionID, output.MessageID())
return
}
if outputID := outputIDFromTopic(topicName); outputID != nil {
// we need to lock the ledger here to have the correct index for unspent info of the output.
deps.Storage.UTXO().ReadLockLedger()
defer deps.Storage.UTXO().ReadUnlockLedger()
ledgerIndex, err := deps.Storage.UTXO().ReadLedgerIndexWithoutLocking()
if err != nil {
return
}
output, err := deps.Storage.UTXO().ReadOutputByOutputIDWithoutLocking(outputID)
if err != nil {
return
}
unspent, err := deps.Storage.UTXO().IsOutputUnspentWithoutLocking(output)
if err != nil {
return
}
utxoOutputWorkerPool.TrySubmit(ledgerIndex, output, !unspent)
return
}
if topicName == topicMilestonesLatest {
index := deps.Storage.LatestMilestoneIndex()
if milestone := deps.Storage.CachedMilestoneOrNil(index); milestone != nil {
publishLatestMilestone(milestone) // milestone pass +1
}
return
}
if topicName == topicMilestonesConfirmed {
index := deps.Storage.ConfirmedMilestoneIndex()
if milestone := deps.Storage.CachedMilestoneOrNil(index); milestone != nil {
publishConfirmedMilestone(milestone) // milestone pass +1
}
return
}
}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(workerQueueSize), workerpool.FlushTasksAtShutdown(true))
var err error
mqttBroker, err = mqttpkg.NewBroker(deps.NodeConfig.String(CfgMQTTBindAddress), deps.NodeConfig.Int(CfgMQTTWSPort), "/ws", deps.NodeConfig.Int(CfgMQTTWorkerCount), func(topic []byte) {
Plugin.LogInfof("Subscribe to topic: %s", string(topic))
topicSubscriptionWorkerPool.TrySubmit(topic)
}, func(topic []byte) {
Plugin.LogInfof("Unsubscribe from topic: %s", string(topic))
})
if err != nil {
Plugin.LogFatalf("MQTT broker init failed! %s", err)
}
setupWebSocketRoute()
}
func setupWebSocketRoute() {
// Configure MQTT WebSocket route
mqttWSUrl, err := url.Parse(fmt.Sprintf("http://%s:%s", mqttBroker.Config().Host, mqttBroker.Config().WsPort))
if err != nil {
Plugin.LogFatalf("MQTT WebSocket init failed! %s", err)
}
wsGroup := deps.Echo.Group(RouteMQTT)
proxyConfig := middleware.ProxyConfig{
Skipper: middleware.DefaultSkipper,
Balancer: middleware.NewRoundRobinBalancer([]*middleware.ProxyTarget{
{
URL: mqttWSUrl,
},
}),
// We need to forward any calls to the MQTT route to the ws endpoint of our broker
Rewrite: map[string]string{
RouteMQTT: mqttBroker.Config().WsPath,
},
}
wsGroup.Use(middleware.ProxyWithConfig(proxyConfig))
}
func run() {
Plugin.LogInfof("Starting MQTT Broker (port %s) ...", mqttBroker.Config().Port)
onLatestMilestoneChanged := events.NewClosure(func(cachedMs *storage.CachedMilestone) {
if !wasSyncBefore {
// Not sync
cachedMs.Release(true)
return
}
if _, added := newLatestMilestoneWorkerPool.TrySubmit(cachedMs); added {
return // Avoid Release (done inside workerpool task)
}
cachedMs.Release(true)
})
onConfirmedMilestoneChanged := events.NewClosure(func(cachedMs *storage.CachedMilestone) {
if !wasSyncBefore {
if !deps.Storage.IsNodeAlmostSynced() {
cachedMs.Release(true)
return
}
wasSyncBefore = true
}
if _, added := newConfirmedMilestoneWorkerPool.TrySubmit(cachedMs); added {
return // Avoid Release (done inside workerpool task)
}
cachedMs.Release(true)
})
onReceivedNewMessage := events.NewClosure(func(cachedMsg *storage.CachedMessage, _ milestone.Index, _ milestone.Index) {
if !wasSyncBefore {
// Not sync
cachedMsg.Release(true)
return
}
if _, added := messagesWorkerPool.TrySubmit(cachedMsg); added {
return // Avoid Release (done inside workerpool task)
}
cachedMsg.Release(true)
})
onMessageSolid := events.NewClosure(func(cachedMetadata *storage.CachedMetadata) {
if _, added := messageMetadataWorkerPool.TrySubmit(cachedMetadata); added {
return // Avoid Release (done inside workerpool task)
}
cachedMetadata.Release(true)
})
onMessageReferenced := events.NewClosure(func(cachedMetadata *storage.CachedMetadata, _ milestone.Index, _ uint64) {
if _, added := messageMetadataWorkerPool.TrySubmit(cachedMetadata); added {
return // Avoid Release (done inside workerpool task)
}
cachedMetadata.Release(true)
})
onUTXOOutput := events.NewClosure(func(index milestone.Index, output *utxo.Output) {
utxoOutputWorkerPool.TrySubmit(index, output, false)
})
onUTXOSpent := events.NewClosure(func(index milestone.Index, spent *utxo.Spent) {
utxoOutputWorkerPool.TrySubmit(index, spent.Output(), true)
})
onReceipt := events.NewClosure(func(receipt *iotago.Receipt) {
receiptWorkerPool.TrySubmit(receipt)
})
if err := Plugin.Daemon().BackgroundWorker("MQTT Broker", func(shutdownSignal <-chan struct{}) {
go func() {
mqttBroker.Start()
Plugin.LogInfof("Starting MQTT Broker (port %s) ... done", mqttBroker.Config().Port)
}()
if mqttBroker.Config().Port != "" {
Plugin.LogInfof("You can now listen to MQTT via: http://%s:%s", mqttBroker.Config().Host, mqttBroker.Config().Port)
}
if mqttBroker.Config().TlsPort != "" {
Plugin.LogInfof("You can now listen to MQTT via: https://%s:%s", mqttBroker.Config().TlsHost, mqttBroker.Config().TlsPort)
}
<-shutdownSignal
Plugin.LogInfo("Stopping MQTT Broker ...")
Plugin.LogInfo("Stopping MQTT Broker ... done")
}, shutdown.PriorityMetricsPublishers); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
if err := Plugin.Daemon().BackgroundWorker("MQTT Events", func(shutdownSignal <-chan struct{}) {
Plugin.LogInfo("Starting MQTT Events ... done")
deps.Tangle.Events.LatestMilestoneChanged.Attach(onLatestMilestoneChanged)
deps.Tangle.Events.ConfirmedMilestoneChanged.Attach(onConfirmedMilestoneChanged)
deps.Tangle.Events.ReceivedNewMessage.Attach(onReceivedNewMessage)
deps.Tangle.Events.MessageSolid.Attach(onMessageSolid)
deps.Tangle.Events.MessageReferenced.Attach(onMessageReferenced)
deps.Tangle.Events.NewUTXOOutput.Attach(onUTXOOutput)
deps.Tangle.Events.NewUTXOSpent.Attach(onUTXOSpent)
deps.Tangle.Events.NewReceipt.Attach(onReceipt)
messagesWorkerPool.Start()
newLatestMilestoneWorkerPool.Start()
newConfirmedMilestoneWorkerPool.Start()
messageMetadataWorkerPool.Start()
topicSubscriptionWorkerPool.Start()
utxoOutputWorkerPool.Start()
receiptWorkerPool.Start()
<-shutdownSignal
deps.Tangle.Events.LatestMilestoneChanged.Detach(onLatestMilestoneChanged)
deps.Tangle.Events.ConfirmedMilestoneChanged.Detach(onConfirmedMilestoneChanged)
deps.Tangle.Events.ReceivedNewMessage.Detach(onReceivedNewMessage)
deps.Tangle.Events.MessageSolid.Detach(onMessageSolid)
deps.Tangle.Events.MessageReferenced.Detach(onMessageReferenced)
deps.Tangle.Events.NewUTXOOutput.Detach(onUTXOOutput)
deps.Tangle.Events.NewUTXOSpent.Detach(onUTXOSpent)
deps.Tangle.Events.NewReceipt.Detach(onReceipt)
messagesWorkerPool.StopAndWait()
newLatestMilestoneWorkerPool.StopAndWait()
newConfirmedMilestoneWorkerPool.StopAndWait()
messageMetadataWorkerPool.StopAndWait()
topicSubscriptionWorkerPool.StopAndWait()
utxoOutputWorkerPool.StopAndWait()
receiptWorkerPool.StopAndWait()
Plugin.LogInfo("Stopping MQTT Events ... done")
}, shutdown.PriorityMetricsPublishers); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
}
<file_sep>---
keywords:
- IOTA Node
- Hornet Node
- Troubleshooting
- Problems
- Discord
- FAQ
- Difficulties
description: Resources to troubleshoot your node.
image: /img/logo/HornetLogo.png
---
# Troubleshooting
Check our [Frequently asked questions](faq.md).
If you can't find your question in the FAQ, feel free to ask in the `#hornet` channel in the ([official iota discord server](https://discord.iota.org/)).
## Something went wrong?
Please open a [new issue](https://github.com/gohornet/hornet/issues/new) if you detect an error or crash. You can also submit a PR if you have already fixed it.
<file_sep>package urts
import (
"time"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/metrics"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/pkg/tangle"
"github.com/gohornet/hornet/pkg/tipselect"
"github.com/gohornet/hornet/pkg/whiteflag"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/events"
)
func init() {
Plugin = &node.Plugin{
Status: node.StatusEnabled,
Pluggable: node.Pluggable{
Name: "URTS",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
InitConfigPars: initConfigPars,
Provide: provide,
Configure: configure,
Run: run,
},
}
}
var (
Plugin *node.Plugin
deps dependencies
// Closures
onMessageSolid *events.Closure
onMilestoneConfirmed *events.Closure
)
type dependencies struct {
dig.In
TipSelector *tipselect.TipSelector
Storage *storage.Storage
Tangle *tangle.Tangle
}
func initConfigPars(c *dig.Container) {
type cfgDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
}
type cfgResult struct {
dig.Out
MaxDeltaMsgYoungestConeRootIndexToCMI int `name:"maxDeltaMsgYoungestConeRootIndexToCMI"`
MaxDeltaMsgOldestConeRootIndexToCMI int `name:"maxDeltaMsgOldestConeRootIndexToCMI"`
BelowMaxDepth int `name:"belowMaxDepth"`
}
if err := c.Provide(func(deps cfgDeps) cfgResult {
return cfgResult{
MaxDeltaMsgYoungestConeRootIndexToCMI: deps.NodeConfig.Int(CfgTipSelMaxDeltaMsgYoungestConeRootIndexToCMI),
MaxDeltaMsgOldestConeRootIndexToCMI: deps.NodeConfig.Int(CfgTipSelMaxDeltaMsgOldestConeRootIndexToCMI),
BelowMaxDepth: deps.NodeConfig.Int(CfgTipSelBelowMaxDepth),
}
}); err != nil {
Plugin.Panic(err)
}
}
func provide(c *dig.Container) {
type tipselDeps struct {
dig.In
Storage *storage.Storage
ServerMetrics *metrics.ServerMetrics
NodeConfig *configuration.Configuration `name:"nodeConfig"`
MaxDeltaMsgYoungestConeRootIndexToCMI int `name:"maxDeltaMsgYoungestConeRootIndexToCMI"`
MaxDeltaMsgOldestConeRootIndexToCMI int `name:"maxDeltaMsgOldestConeRootIndexToCMI"`
BelowMaxDepth int `name:"belowMaxDepth"`
}
if err := c.Provide(func(deps tipselDeps) *tipselect.TipSelector {
return tipselect.New(
deps.Storage,
deps.ServerMetrics,
deps.MaxDeltaMsgYoungestConeRootIndexToCMI,
deps.MaxDeltaMsgOldestConeRootIndexToCMI,
deps.BelowMaxDepth,
deps.NodeConfig.Int(CfgTipSelNonLazy+CfgTipSelRetentionRulesTipsLimit),
deps.NodeConfig.Duration(CfgTipSelNonLazy+CfgTipSelMaxReferencedTipAge),
uint32(deps.NodeConfig.Int64(CfgTipSelNonLazy+CfgTipSelMaxChildren)),
deps.NodeConfig.Int(CfgTipSelNonLazy+CfgTipSelSpammerTipsThreshold),
deps.NodeConfig.Int(CfgTipSelSemiLazy+CfgTipSelRetentionRulesTipsLimit),
deps.NodeConfig.Duration(CfgTipSelSemiLazy+CfgTipSelMaxReferencedTipAge),
uint32(deps.NodeConfig.Int64(CfgTipSelSemiLazy+CfgTipSelMaxChildren)),
deps.NodeConfig.Int(CfgTipSelSemiLazy+CfgTipSelSpammerTipsThreshold),
)
}); err != nil {
Plugin.Panic(err)
}
}
func configure() {
configureEvents()
}
func run() {
if err := Plugin.Daemon().BackgroundWorker("Tipselection[Events]", func(shutdownSignal <-chan struct{}) {
attachEvents()
<-shutdownSignal
detachEvents()
}, shutdown.PriorityTipselection); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
if err := Plugin.Daemon().BackgroundWorker("Tipselection[Cleanup]", func(shutdownSignal <-chan struct{}) {
for {
select {
case <-shutdownSignal:
return
case <-time.After(time.Second):
ts := time.Now()
removedTipCount := deps.TipSelector.CleanUpReferencedTips()
Plugin.LogDebugf("CleanUpReferencedTips finished, removed: %d, took: %v", removedTipCount, time.Since(ts).Truncate(time.Millisecond))
}
}
}, shutdown.PriorityTipselection); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
}
func configureEvents() {
onMessageSolid = events.NewClosure(func(cachedMsgMeta *storage.CachedMetadata) {
cachedMsgMeta.ConsumeMetadata(func(metadata *storage.MessageMetadata) { // metadata -1
// do not add tips during syncing, because it is not needed at all
if !deps.Storage.IsNodeAlmostSynced() {
return
}
deps.TipSelector.AddTip(metadata)
})
})
onMilestoneConfirmed = events.NewClosure(func(_ *whiteflag.Confirmation) {
// do not update tip scores during syncing, because it is not needed at all
if !deps.Storage.IsNodeAlmostSynced() {
return
}
ts := time.Now()
removedTipCount := deps.TipSelector.UpdateScores()
Plugin.LogDebugf("UpdateScores finished, removed: %d, took: %v", removedTipCount, time.Since(ts).Truncate(time.Millisecond))
})
}
func attachEvents() {
deps.Tangle.Events.MessageSolid.Attach(onMessageSolid)
deps.Tangle.Events.MilestoneConfirmed.Attach(onMilestoneConfirmed)
}
func detachEvents() {
deps.Tangle.Events.MessageSolid.Detach(onMessageSolid)
deps.Tangle.Events.MilestoneConfirmed.Detach(onMilestoneConfirmed)
}
<file_sep>package database
import (
"os"
flag "github.com/spf13/pflag"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/keymanager"
"github.com/gohornet/hornet/pkg/metrics"
"github.com/gohornet/hornet/pkg/model/coordinator"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/gohornet/hornet/pkg/model/utxo"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/profile"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/configuration"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/kvstore/pebble"
"github.com/iotaledger/hive.go/kvstore/rocksdb"
"github.com/iotaledger/hive.go/logger"
)
const (
// whether to delete the database at startup
CfgTangleDeleteDatabase = "deleteDatabase"
// whether to delete the database and snapshots at startup
CfgTangleDeleteAll = "deleteAll"
)
func init() {
CorePlugin = &node.CorePlugin{
Pluggable: node.Pluggable{
Name: "Database",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
InitConfigPars: initConfigPars,
Provide: provide,
Configure: configure,
Run: run,
},
}
}
var (
CorePlugin *node.CorePlugin
deps dependencies
deleteDatabase = flag.Bool(CfgTangleDeleteDatabase, false, "whether to delete the database at startup")
deleteAll = flag.Bool(CfgTangleDeleteAll, false, "whether to delete the database and snapshots at startup")
// Closures
onPruningStateChanged *events.Closure
)
type dependencies struct {
dig.In
Database *database.Database
Storage *storage.Storage
StorageMetrics *metrics.StorageMetrics
}
func initConfigPars(c *dig.Container) {
type cfgDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
}
type cfgResult struct {
dig.Out
DatabaseEngine database.Engine `name:"databaseEngine"`
DatabasePath string `name:"databasePath"`
DeleteDatabaseFlag bool `name:"deleteDatabase"`
DeleteAllFlag bool `name:"deleteAll"`
DatabaseDebug bool `name:"databaseDebug"`
DatabaseAutoRevalidation bool `name:"databaseAutoRevalidation"`
}
if err := c.Provide(func(deps cfgDeps) cfgResult {
dbEngine, err := database.DatabaseEngine(deps.NodeConfig.String(CfgDatabaseEngine))
if err != nil {
CorePlugin.Panic(err)
}
return cfgResult{
DatabaseEngine: dbEngine,
DatabasePath: deps.NodeConfig.String(CfgDatabasePath),
DeleteDatabaseFlag: *deleteDatabase,
DeleteAllFlag: *deleteAll,
DatabaseDebug: deps.NodeConfig.Bool(CfgDatabaseDebug),
DatabaseAutoRevalidation: deps.NodeConfig.Bool(CfgDatabaseAutoRevalidation),
}
}); err != nil {
CorePlugin.Panic(err)
}
}
func provide(c *dig.Container) {
type dbResult struct {
dig.Out
StorageMetrics *metrics.StorageMetrics
DatabaseMetrics *metrics.DatabaseMetrics
}
if err := c.Provide(func() dbResult {
return dbResult{
StorageMetrics: &metrics.StorageMetrics{},
DatabaseMetrics: &metrics.DatabaseMetrics{},
}
}); err != nil {
CorePlugin.Panic(err)
}
type databaseDeps struct {
dig.In
DeleteDatabaseFlag bool `name:"deleteDatabase"`
DeleteAllFlag bool `name:"deleteAll"`
NodeConfig *configuration.Configuration `name:"nodeConfig"`
DatabaseEngine database.Engine `name:"databaseEngine"`
DatabasePath string `name:"databasePath"`
Metrics *metrics.DatabaseMetrics
}
if err := c.Provide(func(deps databaseDeps) *database.Database {
events := &database.Events{
DatabaseCleanup: events.NewEvent(database.DatabaseCleanupCaller),
DatabaseCompaction: events.NewEvent(events.BoolCaller),
}
if deps.DeleteDatabaseFlag || deps.DeleteAllFlag {
// delete old database folder
if err := os.RemoveAll(deps.DatabasePath); err != nil {
CorePlugin.Panicf("deleting database folder failed: %s", err)
}
}
targetEngine, err := database.CheckDatabaseEngine(deps.DatabasePath, true, deps.DatabaseEngine)
if err != nil {
CorePlugin.Panic(err)
}
switch targetEngine {
case database.EnginePebble:
reportCompactionRunning := func(running bool) {
deps.Metrics.CompactionRunning.Store(running)
if running {
deps.Metrics.CompactionCount.Inc()
}
events.DatabaseCompaction.Trigger(running)
}
db, err := database.NewPebbleDB(deps.DatabasePath, reportCompactionRunning, true)
if err != nil {
CorePlugin.Panicf("database initialization failed: %s", err)
}
return database.New(
CorePlugin.Logger(),
pebble.New(db),
events,
true,
func() bool { return deps.Metrics.CompactionRunning.Load() },
)
case database.EngineRocksDB:
db, err := database.NewRocksDB(deps.DatabasePath)
if err != nil {
CorePlugin.Panicf("database initialization failed: %s", err)
}
return database.New(
CorePlugin.Logger(),
rocksdb.New(db),
events,
true,
func() bool {
if numCompactions, success := db.GetIntProperty("rocksdb.num-running-compactions"); success {
runningBefore := deps.Metrics.CompactionRunning.Load()
running := numCompactions != 0
deps.Metrics.CompactionRunning.Store(running)
if running && !runningBefore {
// we may miss some compactions, since this is only calculated if polled.
deps.Metrics.CompactionCount.Inc()
events.DatabaseCompaction.Trigger(running)
}
return running
}
return false
},
)
default:
CorePlugin.Panicf("unknown database engine: %s, supported engines: pebble/rocksdb", targetEngine)
return nil
}
}); err != nil {
CorePlugin.Panic(err)
}
type storageDeps struct {
dig.In
NodeConfig *configuration.Configuration `name:"nodeConfig"`
DatabasePath string `name:"databasePath"`
Database *database.Database
Profile *profile.Profile
BelowMaxDepth int `name:"belowMaxDepth"`
CoordinatorPublicKeyRanges coordinator.PublicKeyRanges
MilestonePublicKeyCount int `name:"milestonePublicKeyCount"`
}
if err := c.Provide(func(deps storageDeps) *storage.Storage {
keyManager := keymanager.New()
for _, keyRange := range deps.CoordinatorPublicKeyRanges {
pubKey, err := utils.ParseEd25519PublicKeyFromString(keyRange.Key)
if err != nil {
CorePlugin.Panicf("can't load public key ranges: %s", err)
}
keyManager.AddKeyRange(pubKey, keyRange.StartIndex, keyRange.EndIndex)
}
store, err := storage.New(logger.NewLogger("Storage"), deps.DatabasePath, deps.Database.KVStore(), deps.Profile.Caches, deps.BelowMaxDepth, keyManager, deps.MilestonePublicKeyCount)
if err != nil {
CorePlugin.Panicf("can't initialize storage: %s", err)
}
return store
}); err != nil {
CorePlugin.Panic(err)
}
if err := c.Provide(func(storage *storage.Storage) *utxo.Manager {
return storage.UTXO()
}); err != nil {
CorePlugin.Panic(err)
}
}
func configure() {
correctDatabaseVersion, err := deps.Storage.IsCorrectDatabaseVersion()
if err != nil {
CorePlugin.Panic(err)
}
if !correctDatabaseVersion {
databaseVersionUpdated, err := deps.Storage.UpdateDatabaseVersion()
if err != nil {
CorePlugin.Panic(err)
}
if !databaseVersionUpdated {
CorePlugin.Panic("HORNET database version mismatch. The database scheme was updated. Please delete the database folder and start with a new snapshot.")
}
}
if err = CorePlugin.Daemon().BackgroundWorker("Close database", func(shutdownSignal <-chan struct{}) {
<-shutdownSignal
if err = deps.Storage.MarkDatabaseHealthy(); err != nil {
CorePlugin.Panic(err)
}
CorePlugin.LogInfo("Syncing databases to disk...")
if err = closeDatabases(); err != nil {
CorePlugin.Panicf("Syncing databases to disk... failed: %s", err)
}
CorePlugin.LogInfo("Syncing databases to disk... done")
}, shutdown.PriorityCloseDatabase); err != nil {
CorePlugin.Panicf("failed to start worker: %s", err)
}
configureEvents()
}
func run() {
if err := CorePlugin.Daemon().BackgroundWorker("Database[Events]", func(shutdownSignal <-chan struct{}) {
attachEvents()
<-shutdownSignal
detachEvents()
}, shutdown.PriorityMetricsUpdater); err != nil {
CorePlugin.Panicf("failed to start worker: %s", err)
}
}
func closeDatabases() error {
if err := deps.Database.KVStore().Flush(); err != nil {
return err
}
if err := deps.Database.KVStore().Close(); err != nil {
return err
}
return nil
}
func configureEvents() {
onPruningStateChanged = events.NewClosure(func(running bool) {
deps.StorageMetrics.PruningRunning.Store(running)
if running {
deps.StorageMetrics.Prunings.Inc()
}
})
}
func attachEvents() {
deps.Storage.Events.PruningStateChanged.Attach(onPruningStateChanged)
}
func detachEvents() {
deps.Storage.Events.PruningStateChanged.Detach(onPruningStateChanged)
}
<file_sep>package faucet
import (
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"github.com/gohornet/hornet/pkg/model/faucet"
"github.com/gohornet/hornet/pkg/restapi"
iotago "github.com/iotaledger/iota.go/v2"
)
func parseBech32Address(addressParam string) (*iotago.Ed25519Address, error) {
hrp, bech32Address, err := iotago.ParseBech32(addressParam)
if err != nil {
return nil, errors.WithMessage(restapi.ErrInvalidParameter, "Invalid bech32 address provided!")
}
if hrp != deps.Faucet.NetworkPrefix() {
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "Invalid bech32 address provided! Address does not start with \"%s\".", deps.Faucet.NetworkPrefix())
}
switch address := bech32Address.(type) {
case *iotago.Ed25519Address:
return address, nil
default:
return nil, errors.WithMessage(restapi.ErrInvalidParameter, "Invalid bech32 address provided! Unknown address type.")
}
}
func getFaucetInfo(_ echo.Context) (*faucet.FaucetInfoResponse, error) {
return deps.Faucet.Info()
}
func addFaucetOutputToQueue(c echo.Context) (*faucet.FaucetEnqueueResponse, error) {
request := &faucetEnqueueRequest{}
if err := c.Bind(request); err != nil {
return nil, errors.WithMessagef(restapi.ErrInvalidParameter, "Invalid Request! Error: %s", err)
}
bech32Addr := request.Address
ed25519Addr, err := parseBech32Address(bech32Addr)
if err != nil {
return nil, err
}
response, err := deps.Faucet.Enqueue(bech32Addr, ed25519Addr)
if err != nil {
return nil, err
}
return response, nil
}
<file_sep>package storage
import (
"time"
"github.com/gohornet/hornet/pkg/common"
"github.com/gohornet/hornet/pkg/model/hornet"
"github.com/gohornet/hornet/pkg/profile"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/objectstorage"
iotago "github.com/iotaledger/iota.go/v2"
)
// CachedIndexation represents a cached indexation.
type CachedIndexation struct {
objectstorage.CachedObject
}
// Indexation retrieves the indexation, that is cached in this container.
func (c *CachedIndexation) Indexation() *Indexation {
return c.Get().(*Indexation)
}
func indexationFactory(key []byte, data []byte) (objectstorage.StorableObject, error) {
return &Indexation{
index: key[:IndexationIndexLength],
messageID: hornet.MessageIDFromSlice(key[IndexationIndexLength : IndexationIndexLength+iotago.MessageIDLength]),
}, nil
}
func (s *Storage) IndexationStorageSize() int {
return s.indexationStorage.GetSize()
}
func (s *Storage) configureIndexationStorage(store kvstore.KVStore, opts *profile.CacheOpts) error {
cacheTime, err := time.ParseDuration(opts.CacheTime)
if err != nil {
return err
}
leakDetectionMaxConsumerHoldTime, err := time.ParseDuration(opts.LeakDetectionOptions.MaxConsumerHoldTime)
if err != nil {
return err
}
s.indexationStorage = objectstorage.New(
store.WithRealm([]byte{common.StorePrefixIndexation}),
indexationFactory,
objectstorage.CacheTime(cacheTime),
objectstorage.PersistenceEnabled(true),
objectstorage.PartitionKey(IndexationIndexLength, iotago.MessageIDLength),
objectstorage.KeysOnly(true),
objectstorage.StoreOnCreation(true),
objectstorage.ReleaseExecutorWorkerCount(opts.ReleaseExecutorWorkerCount),
objectstorage.LeakDetectionEnabled(opts.LeakDetectionOptions.Enabled,
objectstorage.LeakDetectionOptions{
MaxConsumersPerObject: opts.LeakDetectionOptions.MaxConsumersPerObject,
MaxConsumerHoldTime: leakDetectionMaxConsumerHoldTime,
}),
)
return nil
}
// IndexMessageIDs returns all known message IDs for the given index.
// indexation +-0
func (s *Storage) IndexMessageIDs(index []byte, iteratorOptions ...IteratorOption) hornet.MessageIDs {
var messageIDs hornet.MessageIDs
indexPadded := PadIndexationIndex(index)
s.indexationStorage.ForEachKeyOnly(func(key []byte) bool {
messageIDs = append(messageIDs, hornet.MessageIDFromSlice(key[IndexationIndexLength:IndexationIndexLength+iotago.MessageIDLength]))
return true
}, append(iteratorOptions, objectstorage.WithIteratorPrefix(indexPadded[:]))...)
return messageIDs
}
// IndexConsumer consumes the messageID during looping through all messages with given index.
type IndexConsumer func(messageID hornet.MessageID) bool
// ForEachMessageIDWithIndex loops over all messages with the given index.
func (s *Storage) ForEachMessageIDWithIndex(index []byte, consumer IndexConsumer, iteratorOptions ...IteratorOption) {
indexPadded := PadIndexationIndex(index)
s.indexationStorage.ForEachKeyOnly(func(key []byte) bool {
return consumer(hornet.MessageIDFromSlice(key[IndexationIndexLength : IndexationIndexLength+iotago.MessageIDLength]))
}, append(iteratorOptions, objectstorage.WithIteratorPrefix(indexPadded[:]))...)
}
// CachedIndexationConsumer consumes the given indexation during looping through all indexations.
type CachedIndexationConsumer func(indexation *CachedIndexation) bool
// ForEachIndexation loops over all indexations.
// indexation +1
func (s *Storage) ForEachIndexation(consumer CachedIndexationConsumer, iteratorOptions ...IteratorOption) {
s.indexationStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool {
return consumer(&CachedIndexation{CachedObject: cachedObject})
}, iteratorOptions...)
}
// StoreIndexation stores the indexation in the persistence layer and returns a cached object.
// indexation +1
func (s *Storage) StoreIndexation(index []byte, messageID hornet.MessageID) *CachedIndexation {
indexation := NewIndexation(index, messageID)
return &CachedIndexation{CachedObject: s.indexationStorage.Store(indexation)}
}
// DeleteIndexation deletes the indexation in the cache/persistence layer.
// indexation +-0
func (s *Storage) DeleteIndexation(index []byte, messageID hornet.MessageID) {
indexation := NewIndexation(index, messageID)
s.indexationStorage.Delete(indexation.ObjectStorageKey())
}
// DeleteIndexationByKey deletes the indexation by key in the cache/persistence layer.
// indexation +-0
func (s *Storage) DeleteIndexationByKey(key []byte) {
s.indexationStorage.Delete(key)
}
// ShutdownIndexationStorage shuts down the indexation storage.
func (s *Storage) ShutdownIndexationStorage() {
s.indexationStorage.Shutdown()
}
// FlushIndexationStorage flushes the indexation storage.
func (s *Storage) FlushIndexationStorage() {
s.indexationStorage.Flush()
}
<file_sep>package toolset
import (
stded25519 "crypto/ed25519"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/mr-tron/base58"
p2pCore "github.com/gohornet/hornet/core/p2p"
"github.com/gohornet/hornet/pkg/p2p"
"github.com/gohornet/hornet/pkg/utils"
"github.com/iotaledger/hive.go/configuration"
)
func generateP2PIdentity(nodeConfig *configuration.Configuration, args []string) error {
printUsage := func() {
println("Usage:")
println(fmt.Sprintf(" %s [P2P_DATABASE_PATH] [P2P_PRIVATE_KEY]", ToolP2PIdentityGen))
println()
println(" [P2P_DATABASE_PATH] - the path to the p2p database folder (optional)")
println(" [P2P_PRIVATE_KEY] - the p2p private key (optional)")
println()
println(fmt.Sprintf("example: %s %s", ToolP2PIdentityGen, "p2pstore"))
}
if len(args) > 2 {
printUsage()
return fmt.Errorf("too many arguments for '%s'", ToolP2PIdentityGen)
}
p2pDatabasePath := nodeConfig.String(p2pCore.CfgP2PDatabasePath)
if len(args) > 0 {
p2pDatabasePath = args[0]
}
privKeyFilePath := filepath.Join(p2pDatabasePath, p2p.PrivKeyFileName)
if err := os.MkdirAll(p2pDatabasePath, 0700); err != nil {
return fmt.Errorf("could not create peer store database dir '%s': %w", p2pDatabasePath, err)
}
_, err := os.Stat(privKeyFilePath)
switch {
case err == nil || os.IsExist(err):
// private key file already exists
return fmt.Errorf("private key file (%s) already exists", privKeyFilePath)
case os.IsNotExist(err):
// private key file does not exist, create a new one
default:
return fmt.Errorf("unable to check private key file (%s): %w", privKeyFilePath, err)
}
var privateKey crypto.PrivKey
var publicKey crypto.PubKey
if len(args) > 1 {
hivePrivKey, err := utils.ParseEd25519PrivateKeyFromString(args[1])
if err != nil {
return fmt.Errorf("invalid private key given '%s': %w", args[1], err)
}
stdPrvKey := stded25519.PrivateKey(hivePrivKey)
privateKey, publicKey, err = crypto.KeyPairFromStdKey(&stdPrvKey)
if err != nil {
return fmt.Errorf("unable to convert given private key '%s': %w", args[1], err)
}
} else {
// create identity
privateKey, publicKey, err = crypto.GenerateKeyPair(crypto.Ed25519, -1)
if err != nil {
return fmt.Errorf("unable to generate Ed25519 private key for peer identity: %w", err)
}
}
// obtain Peer ID from public key
peerID, err := peer.IDFromPublicKey(publicKey)
if err != nil {
return fmt.Errorf("unable to get peer identity from public key: %w", err)
}
privKeyBytes, err := privateKey.Raw()
if err != nil {
return fmt.Errorf("unable to get raw private key bytes: %w", err)
}
pubKeyBytes, err := publicKey.Raw()
if err != nil {
return fmt.Errorf("unable to get raw public key bytes: %w", err)
}
if err := p2p.WriteEd25519PrivateKeyToPEMFile(privKeyFilePath, privateKey); err != nil {
return fmt.Errorf("writing private key file for peer identity failed: %w", err)
}
fmt.Println("Your p2p private key (hex): ", hex.EncodeToString(privKeyBytes))
fmt.Println("Your p2p public key (hex): ", hex.EncodeToString(pubKeyBytes))
fmt.Println("Your p2p public key (base58): ", base58.Encode(pubKeyBytes))
fmt.Println("Your p2p PeerID: ", peerID.String())
return nil
}
<file_sep># Keys for the private tangle
## Coordinator
1. private key: <KEY>
1. public key: ed3c3f1a319ff4e909cf2771d79fece0ac9bd9fd2ee49ea6c0885c9cb3b1248c
2. private key: 0e324c6ff069f31890d496e9004636fd73d8e8b5bea08ec58a4178ca85462325f6752f5f46a53364e2ee9c4d662d762a81efd51010282a75cd6bd03f28ef349c
2. public key: f6752f5f46a53364e2ee9c4d662d762a81efd51010282a75cd6bd03f28ef349c
## Wallet
token mnemonic: giant dynamic museum toddler six deny defense ostrich bomb access mercy blood explain muscle shoot shallow glad autumn author calm heavy hawk abuse rally <br>
token ed25519 private key: 52d23081a626b1eca34b63f1eaeeafcbd66bf545635befc12cd0f19926efefb0 <br>
token ed25519 public key: 31f176dadf38cdec0eadd1d571394be78f0bbee3ed594316678dffc162a095cb <br>
token ed25519 address: 60200bad8137a704216e84f8f9acfe65b972d9f4155becb4815282b03cef99fe <br>
token bech32 address: atoi1qpszqzadsym6wpppd6z037dvlejmjuke7s24hm95s9fg9vpua7vluehe53e
## P2P Identities
### Coordinator node
p2p private key: 1f46fad4f538a031d4f87f490f6bca4319dfd0307636a5759a22b5e8874bd608f9156ba976a12918c16a481c38c88a7b5351b769adc30390e93b6c0a63b09b79 <br>
p2p public key: f9156ba976a12918c16a481c38c88a7b5351b769adc30390e93b6c0a63b09b79 <br>
p2p PeerID: 12D3KooWSagdVaCrS14GeJhM8CbQr41AW2PiYMgptTyAybCbQuEY
### 2nd node
p2p private key: <KEY> <br>
p2p public key: <KEY> <br>
p2p PeerID: 12D3KooWCKwcTWevoRKa2kEBputeGASvEBuDfRDSbe8t1DWugUmL
### 3nd node
p2p private key: <KEY> <br>
p2p public key: <KEY> <br>
p2p PeerID: 12D3KooWGdr8M5KX8KuKaXSiKfHJstdVnRkadYmupF7tFk2HrRoA
### 4th node
p2p private key: <KEY> <br>
p2p public key: <KEY> <br>
p2p PeerID: 12D3KooWC7uE9w3RN4Vh1FJAZa8SbE8yMWR6wCVBajcWpyWguV73
## Dashboard
Username: admin <br>
Password: <PASSWORD>
<file_sep>package shutdown
import (
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
)
const (
// the maximum amount of time to wait for background processes to terminate. After that the process is killed.
waitToKillTimeInSeconds = 300
)
// ShutdownHandler waits until a shutdown signal was received or the node tried to shutdown itself,
// and shuts down all processes gracefully.
type ShutdownHandler struct {
log *logger.Logger
daemon daemon.Daemon
gracefulStop chan os.Signal
nodeSelfShutdown chan string
}
// NewShutdownHandler creates a new shutdown handler.
func NewShutdownHandler(log *logger.Logger, daemon daemon.Daemon) *ShutdownHandler {
gs := &ShutdownHandler{
log: log,
daemon: daemon,
gracefulStop: make(chan os.Signal, 1),
nodeSelfShutdown: make(chan string),
}
signal.Notify(gs.gracefulStop, syscall.SIGTERM)
signal.Notify(gs.gracefulStop, syscall.SIGINT)
return gs
}
// SelfShutdown can be called in order to instruct the node to shutdown cleanly without receiving any interrupt signals.
func (gs *ShutdownHandler) SelfShutdown(msg string) {
select {
case gs.nodeSelfShutdown <- msg:
default:
}
}
// Run starts the ShutdownHandler go routine.
func (gs *ShutdownHandler) Run() {
go func() {
select {
case <-gs.gracefulStop:
gs.log.Warnf("Received shutdown request - waiting (max %d seconds) to finish processing ...", waitToKillTimeInSeconds)
case msg := <-gs.nodeSelfShutdown:
gs.log.Warnf("Node self-shutdown: %s; waiting (max %d seconds) to finish processing ...", msg, waitToKillTimeInSeconds)
}
go func() {
start := time.Now()
for x := range time.Tick(1 * time.Second) {
secondsSinceStart := x.Sub(start).Seconds()
if secondsSinceStart <= waitToKillTimeInSeconds {
processList := ""
runningBackgroundWorkers := gs.daemon.GetRunningBackgroundWorkers()
if len(runningBackgroundWorkers) >= 1 {
processList = "(" + strings.Join(runningBackgroundWorkers, ", ") + ") "
}
gs.log.Warnf("Received shutdown request - waiting (max %d seconds) to finish processing %s...", waitToKillTimeInSeconds-int(secondsSinceStart), processList)
} else {
gs.log.Fatal("Background processes did not terminate in time! Forcing shutdown ...")
}
}
}()
gs.daemon.ShutdownAndWait()
}()
}
<file_sep>package prometheus
import (
"context"
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/dig"
"github.com/gohornet/hornet/pkg/app"
"github.com/gohornet/hornet/pkg/database"
"github.com/gohornet/hornet/pkg/metrics"
"github.com/gohornet/hornet/pkg/model/coordinator"
"github.com/gohornet/hornet/pkg/model/migrator"
"github.com/gohornet/hornet/pkg/model/storage"
"github.com/gohornet/hornet/pkg/node"
"github.com/gohornet/hornet/pkg/p2p"
"github.com/gohornet/hornet/pkg/protocol/gossip"
"github.com/gohornet/hornet/pkg/shutdown"
"github.com/gohornet/hornet/pkg/snapshot"
"github.com/gohornet/hornet/pkg/tangle"
"github.com/gohornet/hornet/pkg/tipselect"
"github.com/iotaledger/hive.go/configuration"
)
// RouteMetrics is the route for getting the prometheus metrics.
// GET returns metrics.
const (
RouteMetrics = "/metrics"
)
func init() {
Plugin = &node.Plugin{
Status: node.StatusDisabled,
Pluggable: node.Pluggable{
Name: "Prometheus",
DepsFunc: func(cDeps dependencies) { deps = cDeps },
Params: params,
Configure: configure,
Run: run,
},
}
}
var (
Plugin *node.Plugin
deps dependencies
server *http.Server
registry = prometheus.NewRegistry()
collects []func()
)
type dependencies struct {
dig.In
AppInfo *app.AppInfo
NodeConfig *configuration.Configuration `name:"nodeConfig"`
Database *database.Database
DatabasePath string `name:"databasePath"`
Storage *storage.Storage
ServerMetrics *metrics.ServerMetrics
DatabaseMetrics *metrics.DatabaseMetrics
StorageMetrics *metrics.StorageMetrics
RestAPIMetrics *metrics.RestAPIMetrics `optional:"true"`
Service *gossip.Service
ReceiptService *migrator.ReceiptService `optional:"true"`
Tangle *tangle.Tangle
MigratorService *migrator.MigratorService `optional:"true"`
Manager *p2p.Manager
RequestQueue gossip.RequestQueue
MessageProcessor *gossip.MessageProcessor
TipSelector *tipselect.TipSelector `optional:"true"`
Snapshot *snapshot.Snapshot
Coordinator *coordinator.Coordinator `optional:"true"`
}
func configure() {
if deps.NodeConfig.Bool(CfgPrometheusDatabase) {
configureDatabase()
}
if deps.NodeConfig.Bool(CfgPrometheusNode) {
configureNode()
}
if deps.NodeConfig.Bool(CfgPrometheusGossip) {
configureGossipPeers()
configureGossipNode()
}
if deps.NodeConfig.Bool(CfgPrometheusCaches) {
configureCaches()
}
if deps.NodeConfig.Bool(CfgPrometheusRestAPI) && deps.RestAPIMetrics != nil {
configureRestAPI()
}
if deps.NodeConfig.Bool(CfgPrometheusMigration) {
if deps.ReceiptService != nil {
configureReceipts()
}
if deps.MigratorService != nil {
configureMigrator()
}
}
if deps.NodeConfig.Bool(CfgPrometheusCoordinator) && deps.Coordinator != nil {
configureCoordinator()
}
if deps.NodeConfig.Bool(CfgPrometheusDebug) {
configureDebug()
}
if deps.NodeConfig.Bool(CfgPrometheusGoMetrics) {
registry.MustRegister(collectors.NewGoCollector())
}
if deps.NodeConfig.Bool(CfgPrometheusProcessMetrics) {
registry.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
}
}
func addCollect(collect func()) {
collects = append(collects, collect)
}
type fileservicediscovery struct {
Targets []string `json:"targets"`
Labels map[string]string `json:"labels"`
}
func writeFileServiceDiscoveryFile() {
path := deps.NodeConfig.String(CfgPrometheusFileServiceDiscoveryPath)
d := []fileservicediscovery{{
Targets: []string{deps.NodeConfig.String(CfgPrometheusFileServiceDiscoveryTarget)},
Labels: make(map[string]string),
}}
j, err := json.MarshalIndent(d, "", " ")
if err != nil {
Plugin.Panic("unable to marshal file service discovery JSON:", err)
return
}
// this truncates an existing file
if err := ioutil.WriteFile(path, j, 0666); err != nil {
Plugin.Panic("unable to write file service discovery file:", err)
}
Plugin.LogInfof("Wrote 'file service discovery' content to %s", path)
}
func run() {
Plugin.LogInfo("Starting Prometheus exporter ...")
if deps.NodeConfig.Bool(CfgPrometheusFileServiceDiscoveryEnabled) {
writeFileServiceDiscoveryFile()
}
if err := Plugin.Daemon().BackgroundWorker("Prometheus exporter", func(shutdownSignal <-chan struct{}) {
Plugin.LogInfo("Starting Prometheus exporter ... done")
e := echo.New()
e.HideBanner = true
e.Use(middleware.Recover())
e.GET(RouteMetrics, func(c echo.Context) error {
for _, collect := range collects {
collect()
}
handler := promhttp.HandlerFor(
registry,
promhttp.HandlerOpts{
EnableOpenMetrics: true,
},
)
if deps.NodeConfig.Bool(CfgPrometheusPromhttpMetrics) {
handler = promhttp.InstrumentMetricHandler(registry, handler)
}
handler.ServeHTTP(c.Response().Writer, c.Request())
return nil
})
bindAddr := deps.NodeConfig.String(CfgPrometheusBindAddress)
server = &http.Server{Addr: bindAddr, Handler: e}
go func() {
Plugin.LogInfof("You can now access the Prometheus exporter using: http://%s/metrics", bindAddr)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
Plugin.LogWarnf("Stopped Prometheus exporter due to an error (%s)", err)
}
}()
<-shutdownSignal
Plugin.LogInfo("Stopping Prometheus exporter ...")
if server != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err := server.Shutdown(ctx)
if err != nil {
Plugin.LogWarn(err)
}
cancel()
}
Plugin.LogInfo("Stopping Prometheus exporter ... done")
}, shutdown.PriorityPrometheus); err != nil {
Plugin.Panicf("failed to start worker: %s", err)
}
}
<file_sep>package storage
import (
"github.com/pkg/errors"
"github.com/gohornet/hornet/pkg/model/hornet"
"github.com/gohornet/hornet/pkg/model/milestone"
)
var (
ErrSolidEntryPointsAlreadyInitialized = errors.New("solidEntryPoints already initialized")
ErrSolidEntryPointsNotInitialized = errors.New("solidEntryPoints not initialized")
)
func (s *Storage) ReadLockSolidEntryPoints() {
s.solidEntryPointsLock.RLock()
}
func (s *Storage) ReadUnlockSolidEntryPoints() {
s.solidEntryPointsLock.RUnlock()
}
func (s *Storage) WriteLockSolidEntryPoints() {
s.solidEntryPointsLock.Lock()
}
func (s *Storage) WriteUnlockSolidEntryPoints() {
s.solidEntryPointsLock.Unlock()
}
func (s *Storage) loadSolidEntryPoints() error {
s.WriteLockSolidEntryPoints()
defer s.WriteUnlockSolidEntryPoints()
if s.solidEntryPoints != nil {
return ErrSolidEntryPointsAlreadyInitialized
}
points, err := s.readSolidEntryPoints()
if err != nil {
return err
}
if points == nil {
s.solidEntryPoints = NewSolidEntryPoints()
return nil
}
s.solidEntryPoints = points
return nil
}
func (s *Storage) SolidEntryPointsContain(messageID hornet.MessageID) bool {
s.ReadLockSolidEntryPoints()
defer s.ReadUnlockSolidEntryPoints()
if s.solidEntryPoints == nil {
// this can only happen at startup of the node, no need to return an unused error all the time
panic(ErrSolidEntryPointsNotInitialized)
}
return s.solidEntryPoints.Contains(messageID)
}
// SolidEntryPointsIndex returns the index of a solid entry point and whether the message is a solid entry point or not.
func (s *Storage) SolidEntryPointsIndex(messageID hornet.MessageID) (milestone.Index, bool) {
s.ReadLockSolidEntryPoints()
defer s.ReadUnlockSolidEntryPoints()
if s.solidEntryPoints == nil {
// this can only happen at startup of the node, no need to return an unused error all the time
panic(ErrSolidEntryPointsNotInitialized)
}
return s.solidEntryPoints.Index(messageID)
}
// SolidEntryPointsAddWithoutLocking adds a message to the solid entry points.
// WriteLockSolidEntryPoints must be held while entering this function.
func (s *Storage) SolidEntryPointsAddWithoutLocking(messageID hornet.MessageID, milestoneIndex milestone.Index) {
if s.solidEntryPoints == nil {
// this can only happen at startup of the node, no need to return an unused error all the time
panic(ErrSolidEntryPointsNotInitialized)
}
s.solidEntryPoints.Add(messageID, milestoneIndex)
}
// ResetSolidEntryPointsWithoutLocking resets the solid entry points.
// WriteLockSolidEntryPoints must be held while entering this function.
func (s *Storage) ResetSolidEntryPointsWithoutLocking() {
if s.solidEntryPoints == nil {
// this can only happen at startup of the node, no need to return an unused error all the time
panic(ErrSolidEntryPointsNotInitialized)
}
s.solidEntryPoints.Clear()
}
// StoreSolidEntryPointsWithoutLocking stores the solid entry points in the persistence layer.
// WriteLockSolidEntryPoints must be held while entering this function.
func (s *Storage) StoreSolidEntryPointsWithoutLocking() error {
if s.solidEntryPoints == nil {
// this can only happen at startup of the node, no need to return an unused error all the time
panic(ErrSolidEntryPointsNotInitialized)
}
return s.storeSolidEntryPoints(s.solidEntryPoints)
}
<file_sep>package protocfg
import (
flag "github.com/spf13/pflag"
"github.com/gohornet/hornet/pkg/node"
iotago "github.com/iotaledger/iota.go/v2"
)
const (
// the network ID on which this node operates on.
CfgProtocolNetworkIDName = "protocol.networkID"
// the HRP which should be used for Bech32 addresses.
CfgProtocolBech32HRP = "protocol.bech32HRP"
// the minimum PoW score required by the network.
CfgProtocolMinPoWScore = "protocol.minPoWScore"
// the amount of public keys in a milestone.
CfgProtocolMilestonePublicKeyCount = "protocol.milestonePublicKeyCount"
// the ed25519 public key of the coordinator in hex representation.
CfgProtocolPublicKeyRanges = "protocol.publicKeyRanges"
// the ed25519 public key of the coordinator in hex representation.
CfgProtocolPublicKeyRangesJSON = "publicKeyRanges"
)
var params = &node.PluginParams{
Params: map[string]*flag.FlagSet{
"nodeConfig": func() *flag.FlagSet {
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.String(CfgProtocolNetworkIDName, "chrysalis-mainnet", "the network ID on which this node operates on.")
fs.String(CfgProtocolBech32HRP, string(iotago.PrefixMainnet), "the HRP which should be used for Bech32 addresses.")
fs.Float64(CfgProtocolMinPoWScore, 4000, "the minimum PoW score required by the network.")
fs.Int(CfgProtocolMilestonePublicKeyCount, 2, "the amount of public keys in a milestone")
return fs
}(),
},
Masked: nil,
}
<file_sep>package prometheus
import (
"github.com/prometheus/client_golang/prometheus"
)
var (
cacheSizes *prometheus.GaugeVec
)
func configureCaches() {
cacheSizes = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: "iota",
Subsystem: "caches",
Name: "size",
Help: "Size of the cache.",
},
[]string{"type"},
)
registry.MustRegister(cacheSizes)
addCollect(collectCaches)
}
func collectCaches() {
cacheSizes.WithLabelValues("children").Set(float64(deps.Storage.ChildrenStorageSize()))
cacheSizes.WithLabelValues("indexations").Set(float64(deps.Storage.IndexationStorageSize()))
cacheSizes.WithLabelValues("messages").Set(float64(deps.Storage.MessageStorageSize()))
cacheSizes.WithLabelValues("messages_metadata").Set(float64(deps.Storage.MessageMetadataStorageSize()))
cacheSizes.WithLabelValues("milestones").Set(float64(deps.Storage.MilestoneStorageSize()))
cacheSizes.WithLabelValues("unreferenced_messages").Set(float64(deps.Storage.UnreferencedMessageStorageSize()))
cacheSizes.WithLabelValues("message_processor_work_units").Set(float64(deps.MessageProcessor.WorkUnitsSize()))
}
| 350ce4ab30ca9c861f164c191024677a8a5b80c4 | [
"Markdown",
"Go Module",
"Go"
] | 42 | Go | sudharya0506/hornet | 85d82d7a543ac67a1ad7259b7322656c665d017c | b4f4ba19a67176aa82a2292fab4f632b82558e0d | |
refs/heads/master | <file_sep>package main
import (
"net"
"fmt"
"sync"
"time"
)
type NetNod struct {
recvCon *net.UDPConn
broadCon *net.UDPConn
recvChan chan []byte
broadChan chan []byte
sync.RWMutex
}
var netNod *NetNod = &NetNod{
recvChan:make(chan []byte,1024),
broadChan:make(chan []byte,1024),
}
func publish(msg[]byte){
netNod.broadChan<-msg
}
func StartBroadNode(port int){
//初始化发送端口
broadAddr := &net.UDPAddr{
IP:net.IPv4(192,168,0,255),
Port:port,
}
broadCon ,err:= net.DialUDP("udp",nil,broadAddr)
defer broadCon.Close()
if err!=nil{
fmt.Println(err)
panic(err)
}
netNod.broadCon = broadCon
for {
select {
case d := <-netNod.broadChan:
broadCon.Write(d)
}
}
}
func StartRecvNode(port int){
recvAddr := &net.UDPAddr{
IP:net.IPv4zero,
Port:port,
}
recvCon ,err := net.ListenUDP("udp",recvAddr)
defer recvCon.Close()
if err!=nil{
fmt.Println(err)
panic(err)
}
netNod.recvCon = recvCon
//初始化变量
for{
var buf [250]byte
n, raddr, err := recvCon.ReadFromUDP(buf[0:])
if err != nil {
fmt.Println(err.Error())
return;
}
if n>1 && raddr!=nil{
}
netNod.recvChan <- buf[0:n]
//判断这个数据是不是自己的,是就处理,不是就抛弃
//fmt.Println("msg from ",raddr," is ", string(buf[0:n]))
}
}
func main() {
go StartRecvNode(3000)
go StartBroadNode(3000)
t1 := time.NewTicker(5*time.Second)
for{
select {
case d := <-netNod.recvChan:
fmt.Println("<=",string(d))
break
case <-t1.C:
publish([]byte(time.Now().String()))
}
}
}
<file_sep>package ctrl
import (
"net/http"
"fmt"
"math/rand"
"../util"
"../service"
"../model"
)
func UserLogin(writer http.ResponseWriter,
request *http.Request) {
//数据库操作
//逻辑处理
//restapi json/xml返回
//1.获取前端传递的参数
//mobile,passwd
//解析参数
//如何获得参数
//解析参数
request.ParseForm()
mobile := request.PostForm.Get("mobile")
passwd := request.PostForm.Get("passwd")
loginok := false
if(mobile=="18600000000" && passwd=="<PASSWORD>"){
loginok = true
}
if(loginok){
//{"id":1,"token":"xx"}
data := make(map[string]interface{})
data["id"]=1
data["token"]="test"
util.RespOk(writer,data,"")
}else{
util.RespFail(writer,"密码不正确")
}
//go get github.com/go-xorm/xorm
//go get github.com/go-sql-driver/mysql
//返回json ok
//如何返回JSON
//io.WriteString(writer,request.PostForm.Get("mobile"))
}
var userService service.UserService
func UserRegister(writer http.ResponseWriter,
request *http.Request) {
request.ParseForm()
//
mobile := request.PostForm.Get("mobile")
//
plainpwd := request.PostForm.Get("passwd")
nickname := fmt.Sprintf("user%06d",rand.Int31())
avatar :=""
sex := model.SEX_UNKNOW
user,err := userService.Register(mobile, plainpwd,nickname,avatar,sex)
if err!=nil{
util.RespFail(writer,err.Error())
}else{
util.RespOk(writer,user,"")
}
}
<file_sep>package util
import (
"net/http"
"encoding/json"
"log"
)
type H struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
}
//
func RespFail(w http.ResponseWriter,msg string){
Resp(w,-1,nil,msg)
}
func RespOk(w http.ResponseWriter,data interface{},msg string){
Resp(w,0,data,msg)
}
func Resp(w http.ResponseWriter,code int,data interface{},msg string) {
w.Header().Set("Content-Type","application/json")
//设置200状态
w.WriteHeader(http.StatusOK)
//输出
//定义一个结构体
h := H{
Code:code,
Msg:msg,
Data:data,
}
//将结构体转化成JSOn字符串
ret,err := json.Marshal(h)
if err!=nil{
log.Println(err.Error())
}
//输出
w.Write(ret)
}
| 1bc9f8f8f8b0ca88c779070da2ab2777387ca1d8 | [
"Go"
] | 3 | Go | leiwenxuan/Go-im | a4c90f82565ed4692219448f8af03c35dcb6b9a2 | 85f4f55c28cb84511bf128690cc2b12794f807d7 | |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import {requestHomeOrder} from 'actions/homeActions';
class MyMonitor extends Component {
constructor(props) {
super(props);
this.state = {
orders: props.orders || []
}
this.renderCharts = this.renderCharts.bind(this);
this.renderOrders = this.renderOrders.bind(this);
}
componentWillReceiveProps(props) {
this.setState({orders: props.orders}, this.renderOrders)
}
componentDidMount() {
this.renderOrders();
}
render() {
return(
<div className='pb-10'>
<div id='monitor'></div>
</div>
)
}
renderOrders() {
let {orders} = this.state, data1 = [], data2 = [];
orders.length > 0 && orders.map((item, idx) => {
let time = item[4] + (8 * 60 * 60 * 1000);
if(item[3]== 0) {
// data1.push([time, Math.log(item[1])])
data1.push({
x: time,
y: Math.log(item[1]),
val: item[1]
})
} else if (item[3] == 1) {
// data2.push([time, Math.log(item[1])])
data2.push({
x: time,
y: Math.log(item[1]),
val: item[1]
})
}
})
this.renderCharts(data1, data2)
}
renderCharts(data1, data2, data3, data4) {
let formats='%H:%M';
Highcharts.chart('monitor', {
chart: {
type: 'scatter',
zoomType: 'xy'
},
title: {
text: '24小时转入转出',
style: {
fontSize: '14px'
}
},
subtitle: {
// text: 'Source: Heinz 2003'
},
xAxis: {
title: {
enabled: true,
text: 'time (hour)'
},
labels: {
formatter: function() {
return Highcharts.dateFormat(formats,this.value);
}
},
type: 'datetime',
startOnTick: true,
endOnTick: true,
showLastLabel: true,
},
yAxis: {
title: {
text: ''
},
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
}
}
},
tooltip: {
formatter: function() {
return `${this.series.name}<br> 数量:${this.point.val}`
}
},
series: [{
name: '转出',
color: 'rgba(252, 5, 46, 1)',
data: data1
}, {
name: '转入',
color: '#28a745',
// color: '#007bff',
data: data2
},
]
});
}
}
function mapState(state) {
return {
orders: state.homeOrder.orders
}
}
function mapDispatch(dispatch) {
return {
getOrders: () => dispatch(requestHomeOrder())
}
}
export default connect(mapState, mapDispatch)(MyMonitor);
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import Flask,jsonify,request
from api.order import *
from api.address import *
from api.ut_price import *
from api.transaction import *
app = Flask(__name__)
###大单监控
@app.route("/api/v1/monitor/order")
def order():
order_list = query_big_order()
return jsonify(order_list)
####地址监控
@app.route("/api/v1/monitor/address")
def address():
address_list = query_address()
return jsonify(address_list)
###ut价格
@app.route("/api/v1/monitor/price")
def price():
period = request.values.get('period')
price = ut_price(period)
return jsonify(price)
###交易数度
@app.route("/api/v1/monitor/transaction")
def transaction():
f = request.values.get('f')
speed = trans_speed(f)
return jsonify(speed)
def start():
print("start web server at 5000")
app.run(host='0.0.0.0', port=5000)
if __name__ == '__main__':
start()
<file_sep>/**
* Created by admin on 2017/4/14.
*/
const initState = {isFetching: true, fetched: false, orders: [],};
export default function homeOrder(state = initState, action) {
switch (action.type) {
case 'fetchHomeOrder' :
return Object.assign({}, state, {isFetching: true, fetched: false});
case 'reciveHomeOrder':
return Object.assign({}, state, {isFetching: false, fetched: true, orders: action.orders});
case 'fetchHomehomeOrderErr':
return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
default :
return state;
}
}<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import #如果没有这一行,下一行可能会出错
SQLALCHEMY_DATABASE_URI='mysql://ulord:===passrod===@localhost:3306/tn?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS=True
SQLALCHEMY_POOL_SIZE=10<file_sep>from create_db import *
def query_address():
row_list = []
try:
address_query = "select DATE_FORMAT(create_date,'%Y-%m-%d'),gt10000_address,gt0_address,trans_num,address_num from ud_trans_address where create_date>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -90 DAY),'%Y-%m-%d') and create_date <=DATE_FORMAT(NOW(),'%Y-%m-%d') order by create_date asc"
res = db.session.execute(address_query)
row_list = res.fetchall()
db.session.commit()
except Exception as e:
db.session.rollback()
print e
all_address_list = []
for index in range(len(row_list)):
address_list = []
address_list.append(row_list[index][0])
address_list.append(row_list[index][1])
address_list.append(row_list[index][2])
address_list.append(row_list[index][3])
address_list.append(row_list[index][4])
all_address_list.append(address_list)
return all_address_list<file_sep>/**
* Created by admin on 2017/4/14.
*/
const initState = {isFetching: true, fetched: false, addressList: [],};
export default function addressList(state = initState, action) {
switch (action.type) {
case 'fetchAddressList' :
return Object.assign({}, state, {isFetching: true, fetched: false});
case 'reciveAddressList':
return Object.assign({}, state, {isFetching: false, fetched: true, addressList: action.addressList});
case 'fetchAddressListrErr':
return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
default :
return state;
}
}<file_sep>/**
* Created by admin on 2017/4/14.
*/
const initState = {isFetching: true, fetched: false, list: [],};
export default function priceTrend(state = initState, action) {
switch (action.type) {
case 'fetchPriceTrend' :
return Object.assign({}, state, {isFetching: true, fetched: false});
case 'recivePriceTrend':
return Object.assign({}, state, {isFetching: false, fetched: true, list: action.list});
case 'fetchPriceTrendErr':
return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
default :
return state;
}
}<file_sep>
### python
pip install -r requirements.txt
### UI
npm install yarn -g
yarn install
yarn run build
webpack.dev.config.js //修改server ip
### 数据库脚本
sql/ut.sql
### 第一次运行需要同步历史数据(多线程同步数据时间比较长)
job/config.py //---数据库、守护进程配置文件
nohup python -u thread_run.py >log_thread.txt 2>&1 &
### 同步完历史数据后,使用job_run.py同步数据(单机运行)
nohup python -u job_run.py >log_job.txt 2>&1 &
### app service run
config.py //---数据库配置文件
nohup python -u app.py >log_app.txt 2>&1 &
<file_sep>/**
* Created by admin on 2017/3/3.
*/
import { Router, hashHistory, browserHistory} from 'react-router';
import React from 'react';
// 按需加载
const routers = {
path:'/',
getComponent(nextState,callback){
require.ensure([],require=>{
callback(null,require('containers/main').default); // 按需加载时,require不能使用变量,且之前不能使用import将组件引入。如果你的组件是使用es5的module.exports导出的话,那么只需要require('components/Index')即可。而如果你的组件是使用es6的export default导出的话,那么需要加上default
},'');
},
indexRoute:{
getComponent(nextState,callback){
require.ensure([],require=>{
callback(null,require('containers/home').default);
},'home');
},
},
childRoutes:[
{
path:'home',
getComponent(nextState,callback){
require.ensure([],require=>{
callback(null,require('containers/home').default);
},'home');
},
},
{
path:'management',
getComponent(nextState,callback){
require.ensure([],require=>{
callback(null,require('containers/management').default);
},'management');
},
}
]
};
export default <Router routes={routers} history={hashHistory}/>
// export default <Router routes={routers} history={browserHistory}/> // 使用browserHistory, 当用户直接请求页面的某个子路由会报404的错误<file_sep>CREATE TABLE `ud_address_details` (
`Address` varchar(60) DEFAULT NULL,
`Total_Received` float DEFAULT NULL,
`Total_Sent` float DEFAULT NULL,
`Final_Balance` float DEFAULT NULL,
`id` int(10) NOT NULL AUTO_INCREMENT,
`update_time` timestamp NULL DEFAULT NULL,
`trans_no` int(10) DEFAULT NULL,
`mined_time` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_block_info` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`height` int(10) DEFAULT NULL,
`json_date` varchar(5000) DEFAULT NULL,
`rsync_date` timestamp NULL DEFAULT NULL,
`date_type` varchar(10) DEFAULT NULL,
`block_hash` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `ud_block` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`height` int(10) DEFAULT NULL,
`mined_by` varchar(10) DEFAULT NULL,
`difficulty` float DEFAULT NULL,
`transactions_number` int(10) DEFAULT NULL,
`timestamp` int(11) DEFAULT NULL,
`Size` int(10) DEFAULT NULL,
`Bits` varchar(10) DEFAULT NULL,
`Block_reward` float DEFAULT NULL,
`Previous_Block` varchar(100) DEFAULT NULL,
`Next_Block` varchar(100) DEFAULT NULL,
`BlockHash` varchar(100) DEFAULT NULL,
`total_trans` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `block_height_index` (`height`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_price` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`price` float DEFAULT NULL,
`create_time` timestamp NULL DEFAULT NULL,
`platform` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_trans_address` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`create_date` timestamp NULL DEFAULT NULL,
`gt10000_address` int(10) DEFAULT NULL,
`gt0_address` int(10) DEFAULT NULL,
`trans_num` int(10) DEFAULT NULL,
`address_num` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_transaction_records` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`HEIGHT` int(10) DEFAULT NULL,
`TX_ID` varchar(100) DEFAULT NULL,
`confirmations` int(60) DEFAULT NULL,
`time` int(10) DEFAULT NULL,
`blocktime` int(10) DEFAULT NULL,
`version` int(10) DEFAULT NULL,
`fees` float DEFAULT NULL,
`ud_blockid` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_transaction_recods_vin` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`txid` varchar(100) DEFAULT NULL,
`vout` int(10) DEFAULT NULL,
`vin_txid` varchar(100) DEFAULT NULL,
`ud_transaction_recordsid` int(10) NOT NULL,
`coinbase` varchar(100) DEFAULT NULL,
`height` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `vout_vin_txid_index` (`vin_txid`),
KEY `vout_height_index` (`height`),
KEY `index_vin_txid` (`txid`),
KEY `index_vin_vout` (`vout`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_transaction_recods_vout` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`value` float DEFAULT NULL,
`n` int(10) DEFAULT NULL,
`txid` varchar(100) DEFAULT NULL,
`ud_transaction_recordsid` int(10) NOT NULL,
`type` varchar(50) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`mined_time` timestamp NULL DEFAULT NULL,
`has_vin` int(10) DEFAULT NULL,
`coinbase` varchar(100) DEFAULT NULL,
`height` int(10) DEFAULT NULL,
`has_trans` varchar(10) DEFAULT NULL,
`mined_day` varchar(30) DEFAULT NULL,
`trans_value` double DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `vout_txid_index` (`txid`),
KEY `vout_has_vin_index` (`has_vin`),
KEY `vout_address_index` (`address`),
KEY `idx_vout_vin` (`has_vin`),
KEY `index_vout_mined_day` (`mined_day`),
KEY `index_vout_height` (`height`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `ud_transaction_recods_address` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`address` varchar(100) DEFAULT NULL,
`ud_transaction_recods_voutid` int(10) NOT NULL,
`current_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`mined_time` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `recods_address_index` (`address`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;<file_sep>import datetime,time
import schedule
from rawtransaction_task import *
from addres_count_task import *
from trans_address_task import *
from crawl_ulord_price_task import *
from trans_block_task import *
def block_job():
update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print("run crawl_ulord job:", datetime.datetime.now())
crawl_ulord()
crawl_price_coin()
print("run block_check job:", datetime.datetime.now())
rsync_block()
print("run address_count job:", datetime.datetime.now())
address_count_job()
print("run trans_address_count job:", datetime.datetime.now())
tran_address_job('')
print("run trans_block_update job:", datetime.datetime.now())
trans_block_update()
if __name__ == '__main__':
print('job run...')
schedule.every(10).minutes.do(block_job)
while True:
beginTime = datetime.datetime.now()
print('block_job run...', beginTime)
schedule.run_pending()
time.sleep(60)<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import { isArray } from 'util';
class AreaChart extends Component {
constructor(props) {
super(props);
this.state = {
largeAccount: [],
nonZeroAccount: [],
activityAccount: [],
totalAccount: [],
categories: [],
pointStart: ''
}
this.renderCharts = this.renderCharts.bind(this);
}
render() {
return(
<div className='area-container'>
<div id='large-container'></div>
<div className='white-space'></div>
<div id='account-container'></div>
<div className='white-space'></div>
<div id='activity-container'></div>
</div>
)
}
componentWillReceiveProps(newProps) {
if(newProps.addressList && newProps.addressList instanceof Array) {
let addressList = newProps.addressList, largeAccount = [], totalAccount = [], activityAccount = [], nonZeroAccount = [], categories = [], pointStart = addressList[0][0];
addressList.length > 0 && addressList.map( (item, idx) => {
largeAccount.push(item[1]);
nonZeroAccount.push(item[2])
activityAccount.push(item[3]);
totalAccount.push(item[4]);
categories.push(item[0])
})
this.setState({largeAccount, nonZeroAccount, activityAccount, totalAccount, pointStart, categories}, this.renderCharts)
}
}
componentDidMount() {
this.renderCharts()
}
renderCharts() {
let {largeAccount, nonZeroAccount, activityAccount, totalAccount, categories, pointStart} = this.state;
let chart1 = Highcharts.chart('account-container',{
chart: {
type: 'area'
},
title: {
text: '账户数统计'
},
xAxis: {
allowDecimals: false,
categories: categories
},
yAxis: {
title: {
text: ''
},
},
tooltip: {
// pointFormat: '{series.name} 制造 <b>{point.y:,.0f}</b>枚弹头'
},
series: [{
name: '非零账户数',
color: '#77a2c5',
data: nonZeroAccount
}, {
name: '账户总数',
color: '#a4c1d8',
data: totalAccount
}]
});
let chart2 = Highcharts.chart('activity-container',{
chart: {
type: 'area'
},
title: {
text: '活跃账户数'
},
xAxis: {
allowDecimals: false,
categories: categories
},
yAxis: {
title: {
text: ''
},
},
tooltip: {
// pointFormat: '{series.name} 制造 <b>{point.y:,.0f}</b>枚弹头'
},
series: [{
name: '活跃账户数',
color: '#a4c1d8',
data: activityAccount
}]
});
let chart3 = Highcharts.chart('large-container',{
chart: {
type: 'area'
},
title: {
text: '大户账户'
},
xAxis: {
allowDecimals: false,
categories: categories
},
yAxis: {
title: {
text: ''
},
},
tooltip: {
// pointFormat: '{series.name} 制造 <b>{point.y:,.0f}</b>枚弹头'
},
series: [{
name: '大户账户数',
color: '#a4c1d8',
data: largeAccount
}]
});
}
}
function mapState(state) {
return {
addressList: state.addressList.addressList
// orders: state.homeOrder.orders
}
}
function mapDispatch(dispatch) {
return {
// getOrders: () => dispatch(requestHomeOrder())
}
}
export default connect(mapState, mapDispatch)(AreaChart);<file_sep>/*
webpack将所有的文件当作js文件来处理,主要是通过一个入口文件,查找相应的依赖,遇见不是js的文件借助相应的loader来进行处理,打包输出到统一的js文件中。
webpack基于模块化打包的工具。同时它的核心功能有许多的插件以及loader,来处理我们的文件。
*/
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
vendor: ['react', 'react-dom'],
index: path.resolve(__dirname, "src/index.js")
},
output: {
path: path.resolve(__dirname, "dist/"), // 打包好的文件输出的路径
filename: "js/[name].[hash:8].js",
// publicPath: "/dist", // 指定 HTML 文件中资源文件 (字体、图片、JS文件等) 的文件名的公共 URL 部分的
chunkFilename: 'js/[name].[hash:8].js' // 按需加载时打包的chunk
},
module: {
rules: [
{
test: /.(js|jsx)$/,
use: [{
loader: 'babel-loader',
options: {presets: ["react", ["env", {"modules": false}]]}
}],
exclude: path.resolve(__dirname, "node_modules") // 排除node_modules下的文件
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
"style-loader",
"css-loader",
]
},
{
test: /\.less$/,
exclude: /node_modules/,
use: [
"style-loader",
"css-loader",
"less-loader"
]
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
{
test: /\.(gif|png|jpe?g)$/,
use: [{
loader: "file-loader",
options: {
name: "static/img/[name].[ext]"
}
}]
},
{
test: /\.(ttf|eot|svg|woff)(\?(\w|#)*)?$/,
use: [{
loader: "file-loader",
options: {
name: "static/font/[name].[ext]"
}
}]
}
]
},
resolve: {
modules:[path.resolve(__dirname,'src'),'node_modules'], // 将src添加到搜索目录,且src目录优先'node_modules'搜索。modules: [],告诉 webpack 解析模块时应该搜索的目录.默认为node——modules
extensions: [".js", ".jsx", ".css", ".less", '.scss'], // 自动解析确定的扩展名(js/jsx/json),能够使用户在引入模块时不带扩展
alias: { // 创建 import 或 require 的别名,来确保模块引入变得更简单
"components": path.resolve(__dirname, 'src/components/'),
"containers": path.resolve(__dirname, 'src/containers/'),
"assets": path.resolve(__dirname, "src/assets/"),
"actions": path.resolve(__dirname, 'src/actions/'),
"reducers": path.resolve(__dirname, 'src/reducers/'),
"utils": path.resolve(__dirname, 'src/utils/'),
}
},
plugins: [
require('autoprefixer'), // 自动补全css前缀
new htmlWebpackPlugin({ // 自动创建html
template: 'index.html', // 创建html所引用的模板,默认为根目录下的html
title: "", // 传参,模板中可通过<%= htmlWebpackPlugin.options.title%>来获取
filename: "index.html", // 创建后的html的文件名
// inject: true // 注入打包好的js,默认为true。 可通过 inject: head/body 声明将js注入到模板中的head/body标签中
}),
new webpack.optimize.CommonsChunkPlugin(['vendor']), // 将公用的模块抽取到vendor文件中
new CleanWebpackPlugin('dist/', { verbose: false }), // 每次打包时,将之前打包生成的文件都删除
new webpack.optimize.UglifyJsPlugin({ // 压缩打包的js文件
sourceMap: true, // 当你的js编译压缩后,需要继续读取原始脚本信息的行数,位置,警告等有效调试信息时,手动开启UglifyJsPlugin 的配置项:sourceMap: true
compress: {
warnings: false
}
}),
new webpack.ProvidePlugin({ // 配置全局的jquery
$:"jquery",
jQuery:"jquery",
"window.jQuery":"jquery"
})
],
};<file_sep># -*- coding: utf-8 -*-
"""
@Author: <NAME>(050511)
"""
import requests,os,time,datetime,json
import sys
from lxml import etree
from job_create_db import *
reload(sys)
sys.setdefaultencoding('utf8')
def crawl_price_coin():
try:
sp = time.time()
st = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sp))
etl_time = datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S")
target_url = "https://www.aicoin.net.cn/api/second/global_custom?symbol=kucoinuteth&list_flag=2"
headers = {"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Cookie": "_ga=GA1.3.56640674.1537171331; Hm_lvt_3c606e4c5bc6e9ff490f59ae4106beb4=1537171331,1537171419,1537171773; acw_tc=784c10e115378666792501369ed44e4f9808ab78a3b64d96ac3260bc4abf69; _gid=GA1.3.1697212968.1537866685; Hm_lpvt_3c606e4c5bc6e9ff490f59ae4106beb4=1537868855; _gat_gtag_UA_108140256_2=1; XSRF-TOKEN=<KEY>%3D%3D; aicoin_session=<KEY>",
"Host": "www.aicoin.net.cn",
"Referer": "https://www.aicoin.net.cn/",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
r = requests.get(target_url, headers=headers)
d = r.text
data = json.loads(d)
price_data_list = data["quotes"]
price_info_list = []
for price_data in price_data_list:
price = price_data["last_curr"]
currency_base = price_data["currency_base"]
if currency_base == "lbanketh":
currency_name = "UT/ETH(LBank)"
elif currency_base == "kucoineth":
currency_name = "UT/ETH(Kucoin)"
elif currency_base == "kucoinbtc":
currency_name = "UT/BTC(Kucoin)"
else:
currency_name = "UT/ETH(BBX)"
price_info = (currency_name, price, etl_time)
price_info_list.append(price_info)
sql = "insert into ud_price (create_time,price,platform) VALUES (DATE_FORMAT(NOW(), '%%Y-%%m-%%d %%H:%%i'),'%s','%s')" % \
(price, currency_name)
print sql
res = db.session.execute(sql)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
def crawl_ulord():
try :
#获取当前时间
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
time_now = int(time.time())
#转换成localtime
time_local = time.localtime(time_now)
#转换成新的时间格式(2016-05-09 18:59:20)
etl_time = time.strftime('"%Y-%m-%d %H:%M:%S"',time_local)
url = "http://www.topbtc.one/"
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Cookie": "PHPSESSID=jna61tcaorgat5o41nd08d6i46; _ga=GA1.2.1660271731.1529467228; _gid=GA1.2.1811285768.1529467228; _gat=1; SERVERID=90f486e728e39041f7d76ebd13f977d3|1529467248|1529467225",
"Host": "www.topbtc.one",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"}
r = requests.get(url,headers=headers)
d = r.text
html = etree.HTML(d)
coinname = html.xpath("//div[@id='ETHMarket']/table/tbody/tr/td[2]/text()")
coinname = ["".join(name.split()) for name in coinname]
price_list = html.xpath("//div[@id='ETHMarket']/table/tbody/tr/td[3]/span/text()")
price_list = [price.replace("/¥","")for price in price_list]
info = (etl_time,price_list)
dict_list = dict(zip(coinname,price_list))
for name in coinname:
if "(UT/ETH)" in name:
target_key = name
price = dict_list[target_key]
# 创建连接
sql = "insert into ud_price (create_time,price,platform) VALUES (DATE_FORMAT(NOW(), '%%Y-%%m-%%d %%H:%%i'),'%s','%s')" % \
(price,'topbtc')
print sql
res = db.session.execute(sql)
db.session.commit()
except Exception as e:
db.session.rollback()
print(e)
<file_sep>const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// 读取同一目录下的 base config
const config = require('./webpack.base.config');
config.plugins.push(
// 官方文档推荐使用下面的插件确保 NODE_ENV
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
}),
// 启动 minify
new webpack.LoaderOptionsPlugin({ minimize: true })
// 抽取 CSS 文件
// new ExtractTextPlugin({
// filename: '[name].css',
// allChunks: true,
// ignoreOrder: true
// })
);
module.exports = config;<file_sep>from flask import Flask
from create_db import *
def query_big_order():
row_list = []
try :
# big_order_query = " select address,value,DATE_FORMAT(mined_time, '%Y-%m-%d %H:%i:%S'),has_vin,UNIX_TIMESTAMP(mined_time)*1000 from ud_transaction_recods_vout where CHAR_LENGTH(address)>10 and `value`>500 and mined_time>DATE_FORMAT(Now(),'%Y-%m-%d') order by mined_time desc "
big_order_query = "select * from (select address,value,DATE_FORMAT(mined_time, '%Y-%m-%d %H:%i:%S'),has_vin,UNIX_TIMESTAMP(mined_time)*1000,mined_time from ud_transaction_recods_vout where `value`>500 and `has_trans`=0 and (mined_day=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -24 HOUR), '%Y-%m-%d') or mined_day=DATE_FORMAT(NOW(), '%Y-%m-%d')) order by mined_time desc ) a where a.mined_time>DATE_ADD(NOW(),INTERVAL -24 HOUR)"
res = db.session.execute(big_order_query)
row_list = res.fetchall()
db.session.commit()
except Exception as e:
db.session.rollback()
print e
order_list = []
for index in range(len(row_list)):
list = []
list.append(row_list[index][0])
list.append(row_list[index][1])
list.append(row_list[index][2])
list.append(row_list[index][3])
list.append(row_list[index][4])
order_list.append(list)
return order_list<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import {requestTransList} from 'actions/transAction';
class Transaction extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
period: 'hour',
categories: []
}
this.renderTrend = this.renderTrend.bind(this);
this.changePeriod = this.changePeriod.bind(this);
}
changePeriod(period) {
let {getTransData} = this.props;
this.setState({
period
})
getTransData(period)
}
render() {
let {period} = this.state;
return (
<div>
<p className='change-period-tab'>
<span className={`${period === 'hour'? 'active': '' }`} onClick={() => this.changePeriod('hour')}>每时</span>
<span className={`${period === 'day'? 'active': '' }`} onClick={() => this.changePeriod('day')}>每天</span>
<span className={`${period === 'week'? 'active': '' }`} onClick={() => this.changePeriod('week')}>每周</span>
<span className={`${period === 'month'? 'active': '' }`} onClick={() => this.changePeriod('month')}>每月</span>
</p>
<div id='trans-container'></div>
<p className='trans-label'>交易速度</p>
</div>
)
}
componentWillReceiveProps(newProps) {
let {period} = this.state;
let transData = newProps.transData, categories = [], data = [];
transData.length > 0 && transData.map( (item, idx) => {
if(period === 'month') {
let month = item[1].split('-')[0]+ '-' + item[1].split('-')[1];
categories.push(month)
} else if (period === 'day') {
let day = item[1].split('-')[0] + '-' + item[1].split('-')[1] + '-' + item[1].split('-')[2].split(' ')[0];
categories.push(day);
} else if(period === 'week') {
let temp = ''
switch(item[0]) {
case 'Monday':
temp = '星期一';
break;
case 'Tuesday':
temp = '星期二';
break;
case 'Wednesday':
temp = '星期三';
break;
case 'Thursday':
temp = '星期四';
break;
case 'Friday':
temp = '星期五';
break;
case 'Saturday':
temp = '星期六';
break;
case 'Sunday':
temp = '星期天';
break;
}
categories.push(temp)
} else if(period === 'hour') {
let hour =item[1].split('-')[2].split(' ')[1] + ':00';
categories.push(hour)
}
data.push( { y: Number(item[6]), trans_num: item[2], total_block: item[3], total_block_size: item[5], speed: item[6]});
})
this.setState({categories, data}, this.renderTrend)
}
componentDidMount() {
this.renderTrend();
}
renderTrend() {
let { categories, data, format, tickInterval} = this.state;
Highcharts.chart('trans-container', {
title: {
text: '',
},
xAxis: {
categories: categories,
},
yAxis: {
title: {
text: ''
},
startOnTick: true,
endOnTick: true,
showLastLabel: true,
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Total Transaction: {point.trans_num}<br/>Total block: {point.total_block}<br/>avg blockSize: {point.total_block_size}<br>Transaction Speed: {point.speed}'
},
series: [{
name: '交易速度',
data: data,
}]
});
}
}
function mapState(state) {
return {
transData: state.transListReducer.transList
}
}
function mapDispatch(dispatch) {
return {
getTransData: (period) => dispatch(requestTransList(period)),
}
}
export default connect(mapState, mapDispatch)(Transaction);<file_sep>from job import db
class ud_transaction_recods_addr(db.Model):
__tablename__ = 'ud_transaction_recods_addr'
id = db.Column(db.Integer, primary_key=True)
address = db.Column(db.String(100), nullable=True)
current_date = db.Column(db.TIMESTAMP(True), nullable=True)
ud_transaction_recods_voutid = db.Column(db.Integer, nullable=True)
def __init__(self, address):
self.address = address
def __repr__(self):
return '<ud_transaction_recods_addr %r>'
class ud_transaction_recods_vout(db.Model):
__tablename__ = 'ud_transaction_recods_vout'
id = db.Column(db.Integer, primary_key=True)
height = db.Column(db.Integer, nullable=True)
txid = db.Column(db.String(True), nullable=True)
value = db.Column(db.Float, nullable=True)
n = db.Column(db.Integer, nullable=True)
ud_transaction_recordsid = db.Column(db.Integer, nullable=True)
type = db.Column(db.String(50), nullable=True)
address = db.Column(db.String(100), nullable=True)
mined_time = db.Column(db.TIMESTAMP(True), nullable=True)
has_vin = db.Column(db.String(100), nullable=True)
coinbase = db.Column(db.String(100), nullable=True)
def __init__(self, height):
self.height = height
def __repr__(self):
return '<ud_transaction_recods_vout %r>'
class ud_transaction_recods_vin(db.Model):
__tablename__ = 'ud_transaction_recods_vin'
id = db.Column(db.Integer, primary_key=True)
height = db.Column(db.Integer, nullable=True)
txid = db.Column(db.String(True), nullable=True)
vout = db.Column(db.Integer, nullable=True)
vin_txid = db.Column(db.String(100), nullable=True)
ud_transaction_recordsid = db.Column(db.Integer, nullable=True)
coinbase = db.Column(db.String(100), nullable=True)
def __init__(self, height):
self.height = height
def __repr__(self):
return '<ud_transaction_recods_vin %r>'
class ud_transaction_records(db.Model):
__tablename__ = 'ud_transaction_records'
id = db.Column(db.Integer, primary_key=True)
height = db.Column(db.Integer, nullable=True)
tx_id = db.Column(db.String(True), nullable=True)
confirmations = db.Column(db.Integer, nullable=True)
time = db.Column(db.Integer, nullable=True)
blocktime = db.Column(db.Integer, nullable=True)
version = db.Column(db.Integer, nullable=True)
fees = db.Column(db.Float, nullable=True)
ud_blockid = db.Column(db.Integer, nullable=True)
def __init__(self,height):
self.height = height
def __repr__(self):
return '<ud_transaction_records %r>'
class udBlock(db.Model):
__tablename__ = 'ud_block'
id = db.Column(db.Integer, primary_key=True)
height = db.Column(db.Integer, nullable=True)
mined_by = db.Column(db.TIMESTAMP(True), nullable=False)
difficulty = db.Column(db.Float, nullable=True)
transactions_number = db.Column(db.Integer, nullable=True)
timestamp = db.Column(db.TIMESTAMP(True), nullable=True)
Size = db.Column(db.Integer, nullable=True)
Bits = db.Column(db.String(10), nullable=True)
Block_reward = db.Column(db.Float, nullable=True)
Previous_Block = db.Column(db.String(100), nullable=True)
Next_Block = db.Column(db.String(100), nullable=True)
BlockHash = db.Column(db.String(100), nullable=True)
def __init__(self,height, mined_by, difficulty, transactions_number, timestamp, size, bits, block_reward, previous_block, next_block, blockHash):
self.height = height
self. mined_by=mined_by
self.difficulty=difficulty
self.transactions_number=transactions_number
self.timestamp=timestamp
self.size=size
self.bits=bits
self.block_reward=bits
self.previous_block=previous_block
self.next_block=next_block
self.blockHash=blockHash
def __repr__(self):
return '<ud_block %r>'
class ud_trans_address(db.Model):
__tablename__ ='ud_trans_address'
id = db.Column(db.Integer, primary_key=True)
ut_num = db.Column(db.Integer, nullable=True)
ut_balance_num = db.Column(db.Integer,nullable=True)
trans_num = db.Column(db.Integer,nullable=True)
address_num = db.Column(db.Integer,nullable=True)
create_date = db.Column(db.TIMESTAMP(True),nullable=False)
def __repr__(self):
return '<ud_trans_address %r>'
def __init__(self,ut_num,ut_balance_num,trans_num,address_num,create_date):
self.ut_num = ut_num
self.ut_balance_num = ut_balance_num
self.trans_num = trans_num
self.address_num = address_num
self.create_date = create_date<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from job_create_db import *
import traceback
###账户数量统计
def trans_block_count(height):
try:
trans_query_sql = "select count(1) from ud_transaction_recods_vout where height=%s and `has_trans`=0" % \
(height)
res = db.session.execute(trans_query_sql)
trans_count = res.fetchone()
trans_address_update_sql = "update ud_block set total_trans=%s where height=%s" % \
(trans_count[0],height)
db.session.execute(trans_address_update_sql)
db.session.commit()
except Exception as e:
db.session.rollback()
traceback.print_exc()
def trans_block_update():
try:
trans_query_sql = "select height from ud_block where total_trans is null"
res = db.session.execute(trans_query_sql)
height_list = res.fetchall()
db.session.commit()
for index in range(len(height_list)):
trans_block_count(height_list[index][0])
except Exception as e:
db.session.rollback()
traceback.print_exc()
<file_sep>/**
* Created by admin on 2017/4/14.
*/
import {get} from 'utils/fetch';
export function fetchHomeOrder() {
return {
type: 'fetchHomeOrder',
}
}
export function reciveHomeOrder(orders) {
return {
type: 'reciveHomeOrder',
orders,
}
}
export function fetchHomeOrderErr(err) {
return {
type: 'fetchHomeOrderErr',
err,
}
}
export function requestHomeOrder() {
return dispatch => {
dispatch(fetchHomeOrder());
get(`/api/v1/monitor/order`).then(res => {
dispatch(reciveHomeOrder(res.data));
})
.catch(err => {
console.log(err);
dispatch(fetchHomeOrderErr(err))
})
}
}<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from job_create_db import *
###
def address_count(address):
try:
update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
vout_query_sql ="select sum(value) as Total_Received, count(*) as trans_no, address, (select sum(value) from ud_transaction_recods_vout where address =vout.address and has_vin=0) as Final_Balance, (select sum(value) from ud_transaction_recods_vout where address =vout.address and has_vin=1 ) as Total_Sent, max(vout.mined_time) from ud_transaction_recods_vout vout where address='%s' group by address" % \
(address)
print vout_query_sql
res = db.session.execute(vout_query_sql)
address_value = res.fetchall()
Total_Received=address_value[0][0]
if Total_Received == None:
Total_Received = 0
trans_no = address_value[0][1]
if trans_no == None:
trans_no = 0
Final_Balance = address_value[0][3]
if Final_Balance == None:
Final_Balance = 0
Total_Sent=address_value[0][4]
if Total_Sent == None:
Total_Sent=0
address_detail_query_sql = "select * from ud_address_details where address='%s'" % \
(address)
res = db.session.execute(address_detail_query_sql)
addr = res.fetchone()
if addr == None:
address_detail_insert_sql = "insert into ud_address_details(Address , Total_Received, Total_Sent, Final_Balance, update_time, trans_no) VALUES('%s','%s','%s','%s',DATE_FORMAT('%s','%%Y-%%m-%%d'),'%s')" % \
(address , Total_Received, Total_Sent, Final_Balance, update_time, trans_no)
db.session.execute(address_detail_insert_sql)
else :
address_detail_update_sql = "update ud_address_details set Total_Received='%s', Total_Sent='%s', Final_Balance='%s', update_time=DATE_FORMAT('%s','%%Y-%%m-%%d'), trans_no='%s' where address='%s'" % \
(Total_Received, Total_Sent, Final_Balance, update_time, trans_no,address)
db.session.execute(address_detail_update_sql)
address_delete_sql = "delete from ud_transaction_recods_address where address='%s'" % \
(address)
db.session.execute(address_delete_sql)
db.session.commit()
except Exception as e:
db.session.rollback()
print str(e)
finally:
print('finally count_address',address,update_time)
def query_address():
address_query_sql = "select address from ud_transaction_recods_address group by address"
res = db.session.execute(address_query_sql)
addressList = res.fetchall()
return addressList
def address_count_job():
try:
addressList = query_address()
for index in range(len(addressList)):
address=addressList[index][0]
address_count(address)
except Exception as e:
db.rollback()
print str(e)
finally:
print('finally count_address')
<file_sep>测试环境部署方式
## 安装yarn
npm install yarn -g
## 本地启动
yarn install
yarn start
## 项目打包方法
项目初始化(只需执行一次)
yarn install
之后每次重新打包只需执行
1. yarn run build
build完之后网站所有文件都会生成在dist文件夹,直接访问 index.html<file_sep>import React, { Component } from 'react';
import {Table} from 'react-bootstrap';
import { connect } from 'react-redux';
class AddressTable extends Component {
constructor(props) {
super(props);
}
render() {
let {addressList} = this.props, lastAddressData = addressList && addressList[addressList.length -1] || [];
return(
<div className='monitor-table-container pd-5'>
<Table responsive>
{/* <thead> */}
{/* <tr>
<th colSpan="2">地址监控</th>
</tr> */}
{/* </thead> */}
<tbody className='monitor-table-body'>
<tr>
<th>项目</th>
<th>数量</th>
</tr>
<tr>
<td>
<p>大账户地址</p>
<p className='small-size'>大于10000UT的账户数量</p>
</td>
<td>{lastAddressData[1]}</td>
</tr>
<tr>
<td>
<p>账户数量统计</p>
<p className='small-size'>有余额账户数量</p>
</td>
<td>{lastAddressData[2]}</td>
</tr>
<tr>
<td>
<p>活跃地址</p>
<p className='small-size'>近7天有交易的账户数量</p>
</td>
<td>{lastAddressData[3]}</td>
</tr>
</tbody>
</Table>
</div>
)
}
}
function mapState(state) {
return {
addressList: state.addressList.addressList
}
}
export default connect(mapState, null)(AddressTable);
<file_sep>/**
* Created by admin on 2017/4/14.
*/
import {get} from 'utils/fetch';
export function fetchPriceTrend() {
return {
type: 'fetchPriceTrend',
}
}
export function recivePriceTrend(list) {
return {
type: 'recivePriceTrend',
list,
}
}
export function fetchPriceTrendErr(err) {
return {
type: 'fetchPriceTrendErr',
err,
}
}
export function requestPriceTrend(period) {
return dispatch => {
dispatch(fetchPriceTrend());
get(`/api/v1/monitor/price?period=${period}`).then(res => {
dispatch(recivePriceTrend(res.data));
})
.catch(err => {
console.log(err);
dispatch(fetchPriceTrendErr(err))
})
}
}<file_sep>from flask import Flask
from create_db import *
def ut_price(period):
row_list = []
try:
ud_price_query = ''
if period == 'day':
ud_price_query = " select UNIX_TIMESTAMP(create_time)*1000,sum(price)/count(*),DATE_FORMAT(create_time,'%Y-%m-%d %h:00:00') from ud_price where create_time>DATE_ADD(NOW(),INTERVAL -1 DAY) group by DATE_FORMAT(create_time,'%Y-%m-%d %h') order by create_time asc"
elif period == 'week':
ud_price_query = " select UNIX_TIMESTAMP(create_time)*1000,sum(price)/count(*),DATE_FORMAT(create_time,'%Y-%m-%d %h:00:00') from ud_price where create_time>DATE_ADD(NOW(),INTERVAL -7 DAY) group by DATE_FORMAT(create_time,'%Y-%m-%d %h') order by create_time asc"
elif period == 'month':
ud_price_query = " select UNIX_TIMESTAMP(create_time)*1000,sum(price)/count(*),DATE_FORMAT(create_time,'%Y-%m-%d 00:00:00') from ud_price where create_time>DATE_ADD(NOW(),INTERVAL -30 DAY) group by DATE_FORMAT(create_time,'%Y-%m-%d') order by create_time asc"
res = db.session.execute(ud_price_query)
row_list = res.fetchall()
db.session.commit()
except Exception as e:
db.session.rollback()
print e
price_list = []
if row_list != None:
for index in range(len(row_list)):
list = []
list.append(row_list[index][0])
list.append(row_list[index][1])
price_list.append(list)
return price_list<file_sep>alabaster==0.7.11
amqp==2.3.2
Babel==2.6.0
billiard==3.5.0.4
celery==4.2.1
certifi==2018.4.16
chardet==3.0.4
click==6.7
docutils==0.14
Flask==1.0.2
Flask-SQLAlchemy==2.1
Foundations==2.1.0
futures==3.2.0
idna==2.7
imagesize==1.0.0
itsdangerous==0.24
Jinja2==2.10
kombu==4.2.1
linecache2==1.0.0
Manager==2.0.5
MarkupSafe==1.0
mysql==0.0.1
mysql-connector-python==8.0.11
Oncilla==0.1.0
order==0.1.17
packaging==17.1
protobuf==3.6.0
py-mysql==1.0
Pygments==2.2.0
pyparsing==2.2.0
pytz==2018.5
requests==2.19.1
schedule==0.5.0
scinum==0.2.3
six==1.11.0
snowballstemmer==1.2.1
Sphinx==1.7.6
sphinx-rtd-theme==0.4.1
sphinxcontrib-websupport==1.1.0
SQLAlchemy==1.2.10
traceback2==1.4.0
typing==3.6.4
unittest2==1.1.0
urllib3==1.23
vine==1.1.4
Werkzeug==0.14.1
lxml==4.2.4
<file_sep># !/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime,time
import concurrent.futures,threading
from rawtransaction_task import *
from addres_count_task import *
from trans_address_task import *
from job_create_db import *
from trans_block_task import *
def rsync_block(height) :
print('====rsync_block############################====',threading.current_thread().getName(), height)
block_load(height)
def rsync_address(address):
print('====rsync_address############################====', threading.current_thread().getName(), address)
address_count(address)
def update_vin_trans():
address_query_sql = "select height from ud_block"
res = db.session.execute(address_query_sql)
heightList = res.fetchall()
for d in range(len(heightList)):
height = heightList[d][0]
update_sql = "UPDATE ud_transaction_recods_vout AS a1 INNER JOIN (SELECT * FROM ud_transaction_recods_vin WHERE vin_txid is not null and height is not null and height='%s') AS a2 SET a1.has_vin = 1 where a1.txid = a2.vin_txid and a1.n=a2.vout" % \
(height)
db.session.execute(update_sql)
# has_trans 0交易;1挖矿奖励;2找零;
update_vout_trans_sql = "UPDATE ud_transaction_recods_vout AS a1 INNER JOIN (select distinct vout.txid,vout.address from ud_transaction_recods_vout vout left join ud_transaction_recods_vin vin on vout.txid=vin.txid left join ud_transaction_recods_vout vout2 on vout2.txid=vin.vin_txid and vin.vout=vout2.n where vout.height='%s' and vout.address=vout2.address ) AS a2 SET a1.`has_trans`=2 where a1.txid=a2.TXID and a1.address=a2.address" % \
(height)
db.session.execute(update_vout_trans_sql)
if d % 1000 == 0 or (d + 1) == len(heightList):
print("height", d, len(heightList))
db.session.commit()
def block_thread():
endHeight = load_height()
# 线程池执行
start_time_1 = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
futures = [executor.submit(rsync_block, item) for item in range(endHeight)]
for future in concurrent.futures.as_completed(futures):
print('====block==========', future.result())
print ("block Thread pool execution in " + str(time.time() - start_time_1), "seconds")
def address_thread():
addressList = query_day_address()
if len(addressList)>0:
start_time_1 = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
futures = [executor.submit(rsync_address, addressList[item][0]) for item in range(len(addressList))]
for future in concurrent.futures.as_completed(futures):
print('====address==========', future.result())
print ("address Thread pool execution in " + str(time.time() - start_time_1), "seconds")
def query_day_address():
address_query_sql = "select address from ud_transaction_recods_vout vout group by address"
res = db.session.execute(address_query_sql)
addressList = res.fetchall()
return addressList
def days(str1,str2):
date1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d")
date2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d")
num=(date1-date2).days
return num
def day_run():
block_begin_time = "2018-05-22 23:59:59"
curr_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#两个日期相隔天数
day_num = days(curr_time,block_begin_time)
#
d1 = datetime.datetime.strptime(block_begin_time, '%Y-%m-%d %H:%M:%S')
for d in range(0, day_num):
curr_d = d1 + datetime.timedelta(d)
tran_address_job(curr_d)
if __name__ == "__main__":
block_thread()
update_vin_trans()
trans_block_update()
address_thread()
day_run()
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
from json import dumps, loads
from requests import request
import time
from job_create_db import *
from config import *
url = ULORD_IP
auth=(ULORD_USER, ULORD_PASSWORD)
def rsync_block():
endHeight = load_height()
max_height_query = "select max(HEIGHT) from ud_block"
result = db.session.execute(max_height_query)
max_height = result.fetchone()
if max_height[0] != None :
max_height=max_height[0]+1
else:
max_height = 1
count = 0
try:
while True:
height =max_height+count
print('=================',height)
block_load(height)
update_sql = "UPDATE ud_transaction_recods_vout AS a1 INNER JOIN (SELECT * FROM ud_transaction_recods_vin WHERE vin_txid is not null and height='%s') AS a2 SET a1.has_vin = 1 where a1.txid = a2.vin_txid and a1.n=a2.vout" % \
(height)
db.session.execute(update_sql)
#has_trans 0交易;1挖矿奖励;2找零;
update_vout_trans_sql = "UPDATE ud_transaction_recods_vout AS a1 INNER JOIN (select distinct vout.txid,vout.address from ud_transaction_recods_vout vout left join ud_transaction_recods_vin vin on vout.txid=vin.txid left join ud_transaction_recods_vout vout2 on vout2.txid=vin.vin_txid and vin.vout=vout2.n where vout.height='%s' and vout.address=vout2.address ) AS a2 SET a1.`has_trans`=2 where a1.txid=a2.TXID and a1.address=a2.address" % \
(height)
db.session.execute(update_vout_trans_sql)
db.session.commit()
#找零地址实际交易金额
# trans_2_query = ""
if height == endHeight:
break;
else:
count = count+1
except Exception as e:
print('error',e)
def save_transaction(txList,ud_blockid):
for index in range(len(txList)):
tx = txList[index]
payload = dumps({"method": 'getrawtransaction', "params": [tx, 1]})
response = request("POST", url, data=payload, auth=auth)
res = loads(response.text)
HEIGHT = res['result']['height']
TX_ID = res['result']['txid']
confirmations = res['result']['confirmations']
time = res['result']['time']
blocktime = res['result']['blocktime']
version = res['result']['version']
fees = 0
insert_ud_transaction_records_sql = "INSERT INTO ud_transaction_records(HEIGHT, TX_ID , confirmations , time , blocktime , version , fees , ud_blockid ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
(HEIGHT,TX_ID, confirmations, time, blocktime, version, fees, ud_blockid)
result = db.session.execute(insert_ud_transaction_records_sql)
ud_transaction_recordsid = result.lastrowid
mined_time = timestamp_to_date(time)
###vout
vout = res['result']['vout']
##挖矿奖励
coinbase = ""
has_trans = 0
try:
coinbase = res['result']['vin'][0]['coinbase']
has_trans = 1
except Exception as e:
coinbase = ""
for index in range(len(vout)):
value = vout[index]['value']
n = vout[index]['n']
vout_type = vout[index]['scriptPubKey']['type']
address = vout[index]['scriptPubKey']['addresses'][0]
insert_ud_transaction_recods_vout_sql = "INSERT INTO ud_transaction_recods_vout(value, n , txid , ud_transaction_recordsid,type,address,mined_time,coinbase,height,has_trans,has_vin,mined_day,trans_value) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s',DATE_FORMAT('%s','%%Y-%%m-%%d'),'%s')" % \
(value, n, TX_ID, ud_transaction_recordsid,vout_type,address,mined_time,coinbase,HEIGHT,has_trans,0,mined_time,value)
result = db.session.execute(insert_ud_transaction_recods_vout_sql)
vout_id = result.lastrowid
try:
#####vout address
if vout_type == 'pubkeyhash':
addresses = vout[index]['scriptPubKey']['addresses']
for index in range(len(addresses)):
addr = addresses[index]
insert_ud_transaction_recods_address_sql = "INSERT INTO ud_transaction_recods_address(address,ud_transaction_recods_voutid,mined_time) VALUES ('%s', '%s','%s')" % \
(addr, vout_id,mined_time)
db.session.execute(insert_ud_transaction_recods_address_sql)
else :
print('nonstandard',TX_ID)
except Exception as e:
print("",e)
#####vin
vin = res['result']['vin']
if len(vin[0]) > 2 :
for index in range(len(vin)):
vin_txid = vin[index]['txid']
vout_index = vin[index]['vout']
insert_ud_transaction_recods_vin_sql = "INSERT INTO ud_transaction_recods_vin(txid, vout , vin_txid , ud_transaction_recordsid,height) VALUES ('%s', '%s', '%s', '%s', '%s')" % \
(TX_ID, vout_index, vin_txid, ud_transaction_recordsid,HEIGHT)
db.session.execute(insert_ud_transaction_recods_vin_sql)
else :
coinbase = vin[0]['coinbase']
insert_ud_transaction_recods_vin_sql = "INSERT INTO ud_transaction_recods_vin(txid , coinbase , ud_transaction_recordsid,height) VALUES ('%s', '%s', '%s', '%s')" % \
(TX_ID, coinbase, ud_transaction_recordsid,HEIGHT)
db.session.execute(insert_ud_transaction_recods_vin_sql)
def block_load(height):
try:
ub_block_query_sql = "select height from ud_block where height = %s" % \
(height)
result = db.session.execute(ub_block_query_sql)
block = result.fetchone()
txList = []
if block == None:
payload = dumps({"method": 'getblockhash', "params": [height]})
response = request("POST", url, data=payload, auth=auth)
res = loads(response.text)
blockHash = res['result']
#
payload = dumps({"method": 'getblock', "params": [blockHash]})
response = request("POST", url, data=payload, auth=auth)
res = loads(response.text)
####
height = res['result']['height']
size = res['result']['size']
bits = res['result']['bits']
difficulty = res['result']['difficulty']
previous_block =res['result']['previousblockhash']
next_block =res['result']['nextblockhash']
timestamp =res['result']['time']
transactions_number = len(res['result']['tx'])
block_reward = 112.96602502
if height > 57599:
block_reward=165.377
insert_sql = "INSERT INTO ud_block(height,mined_by,difficulty,transactions_number,timestamp,Size,Bits, Block_reward , Previous_Block , Next_Block , BlockHash) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
(height, '', difficulty, transactions_number, timestamp, size, bits, block_reward,previous_block, next_block, blockHash)
result = db.session.execute(insert_sql)
ud_blockid = result.lastrowid
for index in range(len(res['result']['tx'])):
txList.append(res['result']['tx'][index])
save_transaction(txList,ud_blockid)
else:
print('已存在',height)
db.session.commit()
except Exception as e:
db.session.rollback()
print str(e)
finally:
print('finally')
def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
time_array = time.localtime(time_stamp)
str_date = time.strftime(format_string, time_array)
return str_date
def load_height():
payload = dumps({"method": 'getblockcount', "params": []})
response = request("POST", url, data=payload, auth=auth)
res = loads(response.text)
endHeight = res['result']
return endHeight
<file_sep>/**
* Created by admin on 2017/4/14.
*/
import axios from 'axios';
const baseURL = 'http://172.16.31.10:5000/';
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, PUT',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With'
};
const http = axios.create({
// baseURL,
// timeout: 1000,
// headers
});
export const get = function (url, params) {
// let URL = baseUrl + url;
// console.log('URL:', URL)
// return Promise.resolve(function () {
return http.get(url, {params})
// }())
};
export const post = (url, params) => {
// return Promise.resolve(function () {
return http.post(url, params)
// }())
};<file_sep>import React, { Component } from 'react';
import Highcharts from 'highcharts';
import { connect } from 'react-redux';
import {requestPriceTrend} from 'actions/pricetrend';
class PriceTrend extends Component {
constructor(props) {
super(props);
this.state = {
period: 'day',
format: '{value: %H:%M}',
tickInterval: 3600 * 1000
}
this.renderTrend = this.renderTrend.bind(this);
this.changePeriod = this.changePeriod.bind(this);
}
render() {
let {period} = this.state;
return (
<div>
<p className='change-period-tab'>
<span className={`${period === 'day'? 'active': '' }`} onClick={() => this.changePeriod('day')}>一天</span>
<span className={`${period === 'week'? 'active': '' }`} onClick={() => this.changePeriod('week')}>一周</span>
</p>
<div id='price-trend-container'></div>
</div>
)
}
changePeriod(period) {
let {getPriceTrend} = this.props;
this.setState({period})
if(period === 'day') {
this.setState({
format: '{value: %H:%M}',
tickInterval: 3600 * 1000
})
getPriceTrend(period)
} else if(period === 'week') {
this.setState({
format: '{value: %m-%d}',
tickInterval: 24 * 3600 * 1000
})
getPriceTrend(period)
}
}
componentWillReceiveProps(props) {
let data = props.data, total = [];
data.length > 0 && data.map((item, idx) => {
let time = item[0] + (8 * 60 * 60 * 1000);
item[0] = time;
})
this.setState({data}, this.renderTrend)
}
componentDidMount() {
this.renderTrend();
}
renderTrend() {
let {format, tickInterval} = this.state;
let {data} = this.state;
// let formats='%m-%d';
Highcharts.chart('price-trend-container', {
chart: {
zoomType: 'x'
},
title: {
text: '',
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
labels: {
format: format
},
tickInterval: tickInterval,
// startOnTick: true,
// endOnTick: true,
showLastLabel: true,
},
yAxis: {
title: {
text: ''
},
startOnTick: true,
endOnTick: true,
showLastLabel: true,
tickPositions: [0, 1, 2, 3, 4, 5, 6]
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'price',
data: data,
}]
});
}
}
function mapState(state) {
return {
data: state.priceTrend.list
}
}
function mapDispatch(dispatch) {
return {
getPriceTrend: (period) => dispatch(requestPriceTrend(period)),
}
}
export default connect(mapState, mapDispatch)(PriceTrend);<file_sep>
const initState = {isFetching: true, fetched: false, transList: [],};
export default function transListReducer(state = initState, action) {
switch (action.type) {
case 'fetchTransList' :
return Object.assign({}, state, {isFetching: true, fetched: false});
case 'reciveTransList':
return Object.assign({}, state, {isFetching: false, fetched: true, transList: action.transList});
case 'fetchTransListrErr':
return Object.assign({}, state, {isFetching: false, fetched: true, err: action.err});
default :
return state;
}
}<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
from job_create_db import *
import traceback
###账户数量统计
def trans_address_count(curr_time):
try:
address_query_sql = "";
if curr_time == '':
address_query_sql = "select (select count(distinct address) from ud_address_details where `Final_Balance`>=10000) as gt10000,(select count(distinct address) from ud_address_details where `Final_Balance`>0) as gt0,(select count(distinct address) from ud_address_details) as address_num"
curr_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
else:
address_query_sql = "select count(CASE WHEN a.`Final_Balance`>=10000 THEN 1 end) as gt10000,count(CASE WHEN a.`Final_Balance`>0 THEN 1 end) as gt0,count(distinct a.address) as address_num from (select address, sum(CASE WHEN has_vin=0 THEN value end) as Final_Balance from ud_transaction_recods_vout vout where vout.`mined_day`<=DATE_FORMAT('%s','%%Y-%%m-%%d') group by address) a" % \
(curr_time)
print address_query_sql
res = db.session.execute(address_query_sql)
address_count = res.fetchone()
gt10000_address = address_count[0]
gt0_address = address_count[1]
address_num = address_count[2]
trans_address_query_sql = "select count(distinct address) from ud_transaction_recods_vout where mined_time>=DATE_ADD('%s',INTERVAL -7 DAY) and mined_time<DATE_ADD('%s',INTERVAL 0 DAY) and has_vin =1" % \
(curr_time,curr_time)
res = db.session.execute(trans_address_query_sql)
trans_address_num = res.fetchone()
trans_num = trans_address_num[0]
trans_address_query = "select * FROM ud_trans_address where create_date=DATE_FORMAT('%s','%%Y-%%m-%%d') " % \
(curr_time)
res = db.session.execute(trans_address_query)
trans_address = res.fetchone()
if trans_address == None:
trans_address_insert_sql = "insert into ud_trans_address(create_date , gt10000_address, gt0_address, trans_num, address_num ) VALUES(DATE_FORMAT('%s','%%Y-%%m-%%d'),'%s','%s','%s','%s')" % \
(curr_time, gt10000_address, gt0_address, trans_num,address_num)
db.session.execute(trans_address_insert_sql)
else :
trans_address_update_sql = "update ud_trans_address set gt10000_address='%s', gt0_address='%s', trans_num='%s', address_num='%s' where create_date=DATE_FORMAT('%s','%%Y-%%m-%%d')" % \
(gt10000_address, gt0_address, trans_num, address_num,curr_time)
db.session.execute(trans_address_update_sql)
db.session.commit()
except Exception as e:
db.session.rollback()
traceback.print_exc()
def tran_address_job(update_time):
#update_time = datetime.datetime.now().strftime('%Y-%m-%d')
trans_address_count(update_time)
<file_sep>/**
* Created by admin on 2017/3/3.
*/
import React, {Component} from 'react'
import {connect} from 'react-redux';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import MyTabContainer from 'components/myTabContainer';
import {requestHomeOrder} from 'actions/homeActions';
import {requestAddressList} from 'actions/addressAction';
import {requestPriceTrend} from 'actions/pricetrend';
import {requestTransList} from 'actions/transAction';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
let {getOrders, getAddressList, getPriceTrend, getTransData} = this.props;
getOrders();
getAddressList();
getPriceTrend();
getTransData();
}
render() {
return (
<div className="home-container">
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a href="#"><img src={require('assets/icons/logo.png')} /></a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="http://explorer.ulord.one/">
Blocks
</NavItem>
<NavItem eventKey={2} href="http://ulord.one/">
Ulord
</NavItem>
<NavItem eventKey={3} href="#">
Monitor
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<div className='main-container'>
<MyTabContainer />
</div>
</div>
);
}
shouldComponentUpdate(nextProps, nextState) {
return this.props.router.location.action === 'PUSH'; //防止页面二次渲染
}
}
function mapStateToProps(state) {
return {orders: state.homeOrder.orders}
}
function mapDispatchToProps(dispatch) {
return {
getOrders: () => dispatch(requestHomeOrder()),
getAddressList: () => dispatch(requestAddressList()),
getPriceTrend: () => dispatch(requestPriceTrend('day')),
getTransData: () => dispatch(requestTransList()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home)<file_sep>/**
* Created by admin on 2017/3/3.
*/
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Provider } from'react-redux';
import { createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import AppRoute from './routes.js';
import reducers from 'reducers/index.js';
import './assets/style.scss';
const store = createStore(reducers,applyMiddleware(thunkMiddleware));
function App() {
return(
<Provider store={store}>
{AppRoute}
</Provider>
)
}
ReactDOM.render(<App/>,document.getElementById('app'));<file_sep>from flask import Flask
from create_db import *
def trans_speed(f):
trans_query = ""
if f=="hour":
trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') group by FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') ) a"
elif f=="day":
trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -30 DAY),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') group by FROM_UNIXTIME(timestamp,'%Y-%m-%d') ) a"
elif f=="week":
trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed,FROM_UNIXTIME(a.timestamp,'%W') w from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') group by FROM_UNIXTIME(timestamp,'%Y-%m-%d') ) a "
elif f=="month":
trans_query = "select a.timestamp,a.day_time,a.trans_num,a.total_block,a.m_min,(a.total_block_size/a.total_block) avg_block_size,(a.m_min*a.trans_num) speed from (select timestamp, FROM_UNIXTIME(timestamp,'%Y-%m-%d %H') day_time, sum(total_trans) trans_num, count(1) total_block, 0.4 m_min, sum(size) total_block_size from ud_block where FROM_UNIXTIME(timestamp,'%Y-%m-%d')>=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -12 month),'%Y-%m-%d') and FROM_UNIXTIME(timestamp,'%Y-%m-%d') <=DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -1 DAY),'%Y-%m-%d') group by FROM_UNIXTIME(timestamp,'%Y-%m') ) a"
row_list = []
try :
res = db.session.execute( trans_query)
row_list = res.fetchall()
db.session.commit()
except Exception as e:
db.session.rollback()
print e
trans_list = []
for index in range(len(row_list)):
list = []
if f=="week":
list.append(row_list[index][7])
else:
list.append(row_list[index][0])
list.append(str(row_list[index][1]))
list.append(str(row_list[index][2]))
list.append(str(row_list[index][3]))
list.append(str(row_list[index][4]))
list.append(str(row_list[index][5]))
list.append(str(row_list[index][6]))
trans_list.append(list)
return trans_list<file_sep>import React, { Component } from 'react';
import {Table} from 'react-bootstrap';
import { connect } from 'react-redux';
class MonitorTable extends Component {
constructor(props) {
super(props);
this.renderTable = this.renderTable.bind(this);
this._onClick = this._onClick.bind(this);
}
render() {
return(
<div className='monitor-table-container bg-white'>
<Table responsive>
{/* <thead> */}
{/* </thead> */}
<tbody className='monitor-table-body'>
<tr className='table-header'>
<th>交易对</th>
<th>UT</th>
</tr>
{ this.renderTable()}
</tbody>
</Table>
</div>
)
}
renderTable(){
let {data} = this.props;
return data.length > 0 && data.map( (item, idx) => {
return (
<tr key={idx}>
<td className='table-left-td'>
<p>{item[3]==1? <span className='moni-label'>入</span> : <span className='red moni-label'>出</span>} <span>{item[2]}</span></p>
<p style={{cursor:'pointer'}} onClick={() => this._onClick(item[0])}>{item[0]}</p>
</td>
<td className='num'>{item[1]}</td>
</tr>
)
})
}
_onClick(hash) {
location.href = `http://explorer.ulord.one/address/${hash}`;
}
}
function mapState(state) {
return {
data: state.homeOrder.orders
}
}
export default connect(mapState, null)(MonitorTable);
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import #如果没有这一行,下一行可能会出错
SQLALCHEMY_DATABASE_URI='mysql://ulord:===password==@localhost:3306/tn?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS=True
SQLALCHEMY_POOL_SIZE=1000
ULORD_IP='http://127.0.0.1:9889/'
ULORD_USER ='ulordpool'
ULORD_PASSWORD='<PASSWORD>'<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import {Navbar, Nav, NavItem, Table} from 'react-bootstrap'
class Management extends Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<div className="home-container">
<Navbar collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<a href="#/"><img src={require('assets/icons/logo.png')} /></a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">
用户数据管理
</NavItem>
{/* <NavItem eventKey={2} href="#">
Ulord
</NavItem>
<NavItem eventKey={2} href="#">
趋势
</NavItem> */}
</Nav>
</Navbar.Collapse>
</Navbar>
<div className='main-container'>
<div className='txt-title'>用户数据管理</div>
<Table responsive bordered>
<thead>
<tr>
<th>交易对</th>
<th>UT</th>
</tr>
</thead>
<tbody>
<tr>
<td>卖出</td>
<td>5000</td>
</tr>
<tr>
<td>买入</td>
<td>2000</td>
</tr>
</tbody>
</Table>
</div>
</div>
);
}
}
function mapState(state) {
return {}
}
export default connect(mapState, null)(Management);
| 72c03141862ff45cc28a961de8a991984e027fa7 | [
"SQL",
"JavaScript",
"Markdown",
"Python",
"Text"
] | 38 | JavaScript | yuzhibing/browsers | 3f9d6a4d97b893278bc01d141e1b655c89a851cb | 5659d299e794bb01a555b608c87d6670379aa702 | |
refs/heads/master | <file_sep>import math
import numpy as np
from itertools import combinations
from random import randrange
# Klasa przedstawiająca punkty
# Każdy punkt zawiera kategorię oraz zbiór cech
class Pkt:
def __init__(self, klasa, cechy):
self.cecha = {}
self.klasa = klasa
for i in range(len(cechy)):
self.cecha[i + 1] = float(cechy[i])
# # Listy zawierające punkty klasy
# klasaA = []
# klasaB = []
# klasaTest = []
# czytanie pliku i dodawanie do klas punktów
def odczyt_pliku(sciezka):
try:
plik = open(sciezka)
for linia in plik:
x = randrange(5)
kategoria = linia[0:linia.index(" ")]
if kategoria == "A" or kategoria == "Acer":
if x == 0 and len(klasaTest)<156:
klasaTest.append(Pkt('acer', linia[linia.index(",") + 1:].split(',')))
else:
klasaA.append(Pkt('acer', linia[linia.index(",") + 1:].split(',')))
else:
if x == 0 and len(klasaTest)<156:
klasaTest.append(Pkt('quercus', linia[linia.index(",") + 1:].split(',')))
else:
klasaB.append(Pkt('quercus', linia[linia.index(",") + 1:].split(',')))
# print(linia)
print("Ilośc elementów w klasie A: ", len(klasaA))
print("Ilośc elementów w klasie B: ", len(klasaB))
print("Ilośc elementów w klasie test: ", len(klasaTest))
finally:
plik.close()
# funkcja zwracająca odległość euklidesową pomiędzy 2 punktami
def odleglosc(pkt1, pkt2):
odleglosc = 0
# print(pkt1.cecha)
for i in range(len(pkt1.cecha)):
odleglosc += (list(pkt1.cecha.values())[i] - list(pkt2.cecha.values())[i]) ** 2
return math.sqrt(odleglosc)
def odleglosc2(pkt1, pkt2):
odleglosc = 0
for keys in pkt1.cecha:
odleglosc += (pkt1.cecha[keys] - pkt2.cecha[keys]) ** 2
return math.sqrt(odleglosc)
# NN-algorytm, Przyjmuje sprawdzany punkt i ilość k. Zwracqa klasę do której należy punkt
def k_nn_algorytm(k, test, *klasy):
dobry_wynik = 0
zly_wynik = 0
for pkt in test:
odleglosci = []
for klasa in klasy:
for punkcik in klasa:
odleglosci.append({'klasa': punkcik.klasa, 'odleglosc': odleglosc(punkcik, pkt)})
# print(punkcik.klasa, odleglosc(punkcik,pkt))
# for i in odleglosci:
# if i['klasa'] == "acer":
# print("YEP")
najblizsze_pkt = []
for i in range(k):
najblizsze_pkt.append(sorted(odleglosci, key=lambda i: i['odleglosc'], reverse=False)[i]['klasa'])
# print(najblizsze_pkt)
if najblizsze_pkt.count(klasaA[0].klasa) > najblizsze_pkt.count(klasaB[0].klasa):
klasyfikacja = klasaA[0].klasa
else:
klasyfikacja = klasaB[0].klasa
if klasyfikacja == pkt.klasa:
dobry_wynik += 1
else:
# print("Not OK")
zly_wynik += 1
print("liczba zlych klasyfikacji: ", zly_wynik)
print("Liczba dobrych klasyfikacji ", dobry_wynik)
print("policzyłem dobrze na poziomie: ", round((dobry_wynik / (dobry_wynik + zly_wynik)) * 100, 2), "%")
# funkcja zwracająca punkt który jest środkiem danej listy punktów
def srednie(lista_pkt):
same_cechy = []
for punkt in lista_pkt:
same_cechy.append(punkt.cecha)
wynik = []
# print(len(same_cechy))
for key in same_cechy[0].keys():
wynik.append((sum(item[key] for item in same_cechy)) / len(same_cechy))
# print(wynik)
return Pkt(lista_pkt[0].klasa, wynik)
def nm_algorytm(test):
dobry_wynik = 0
zly_wynik = 0
for punkt in test:
odlegloscA = odleglosc(punkt, srednie(klasaA))
odlegloscB = odleglosc(punkt, srednie(klasaB))
if odlegloscA < odlegloscB:
klasyfikacja = klasaA[0].klasa
else:
klasyfikacja = klasaB[0].klasa
if klasyfikacja == punkt.klasa:
# print("OK")
dobry_wynik += 1
else:
# print("Not OK")
zly_wynik += 1
print("liczba zlych klasyfikacji: ", zly_wynik)
print("Liczba dobrych klasyfikacji ", dobry_wynik)
print("policzyłem dobrze na poziomie: ", round((dobry_wynik / (dobry_wynik + zly_wynik)) * 100,2), "%")
def podzialNaPodklasy(k, listaPkt):
srodki = []
listaPodKlas = []
for i in range(k):
nowaPodKlasa = []
listaPodKlas.append(nowaPodKlasa)
# listaPkt[i].klasa += " " +str(i)
srodki.append(listaPkt[i])
listaPodKlas[i].append(listaPkt[i])
# print(listaPodKlas[1][0].klasa)
for z in range(20):
for i in range(len(listaPkt)):
odlegloscOdSrodka = []
# print("licze odległosć dla :", listaPkt[i].klasa, listaPkt[i].cecha)
for j in range(k):
odlegloscOdSrodka.append(odleglosc(srodki[j], listaPkt[i]))
listaPodKlas[odlegloscOdSrodka.index(min(odlegloscOdSrodka))].append(listaPkt[i])
# for i in range(k):
# print("Klasa: ", i)
# for punkcik in listaPodKlas[i]:
# print(punkcik.klasa, punkcik.cecha)
noweSrodki = []
checkpoint = True
for i in range(k):
noweSrodki.append(srednie(listaPodKlas[i]))
# print('Nowy srodek: ', noweSrodki[i].cecha)
# print('Srodek: ', srodki[i].cecha)
# print('Srodek: ', srodki[i].klasa)
if odleglosc(noweSrodki[i], srodki[i]) != 0:
checkpoint = False
listaPodKlas[i].clear()
if checkpoint:
print("Wykonałem tyle powtórzeń: ", z)
break
else:
srodki.clear()
srodki = noweSrodki[:]
# print("srodki: ", srodki)
# print(srodki[0].klasa, srodki[0].cecha)
return srodki
def podzialNaPodklasy2(k, listaPkt):
srodki = []
listaPodKlas = []
for i in range(k):
nowaPodKlasa = []
listaPodKlas.append(nowaPodKlasa)
srodki.append(listaPkt[i])
listaPodKlas[i].append(listaPkt[i])
for z in range(20):
for i in range(len(listaPkt)):
odlegloscOdSrodka = []
for j in range(k):
odlegloscOdSrodka.append(odleglosc(srodki[j], listaPkt[i]))
listaPodKlas[odlegloscOdSrodka.index(min(odlegloscOdSrodka))].append(listaPkt[i])
noweSrodki = []
checkpoint = True
for i in range(k):
noweSrodki.append(srednie(listaPodKlas[i]))
if odleglosc(noweSrodki[i], srodki[i]) != 0:
checkpoint = False
listaPodKlas[i].clear()
if checkpoint:
print("Wykonałem tyle powtórzeń: ", z)
break
else:
srodki.clear()
srodki = noweSrodki[:]
return srodki
def k_nm_algorytm(k, test, *klasy):
nowe_srodki = []
for klasa in klasy:
nowe_srodki.extend(podzialNaPodklasy(k, klasa))
# print("to są środki :", nowe_srodki)
k_nn_algorytm(1, test, nowe_srodki)
def wybor_cech(k):
sredniaA = srednie(klasaA)
sredniaB = srednie(klasaB)
najlepsze_cechy = []
ilosc_cech = list(range(1, len(klasaA[0].cecha) + 1))
# print(ilosc_cech)
comb = combinations(ilosc_cech, k)
for i in list(comb):
macierzA = np.zeros(shape=(k, len(klasaA)))
macierzB = np.zeros(shape=(k, len(klasaB)))
licznik = 0.0
# print(i)
for j in range(k):
# licznik[j]=[sredniaA.cecha[j+1],sredniaB.cecha[j+1]]
licznik = licznik + (sredniaA.cecha[i[j]] - sredniaB.cecha[i[j]]) ** 2
wierszA = []
wierszB = []
for punkcikA in klasaA:
wierszA.append(punkcikA.cecha[i[j]] - sredniaA.cecha[i[j]])
for punkcikB in klasaB:
wierszB.append(punkcikB.cecha[i[j]] - sredniaB.cecha[i[j]])
macierzA[j] = wierszA
macierzB[j] = wierszB
licznik = math.sqrt(licznik)
macierzA = np.dot(macierzA, macierzA.T)
macierzB = np.dot(macierzB, macierzB.T)
if k == 1:
mianownik = math.sqrt(macierzA) + math.sqrt(macierzB)
else:
mianownik = np.linalg.det(macierzA) + np.linalg.det(macierzB)
fisher = math.fabs(licznik) / mianownik
najlepsze_cechy.append({'cechy': i, 'wartosc': fisher})
# print(fisher)
print("Oto najlepsze cechy: ", sorted(najlepsze_cechy, key=lambda i: i['wartosc'], reverse=True)[0]['cechy'], "\n")
zapisz_nowe_cechy(sorted(najlepsze_cechy, key=lambda i: i['wartosc'], reverse=True)[0]['cechy'], klasaA, klasaB,
klasaTest)
def sfs_algorytm(k):
sredniaA = srednie(klasaA)
sredniaB = srednie(klasaB)
ilosc_cech = list(range(1, len(klasaA[0].cecha) + 1))
najlepsze_cechy = []
for iteracja in range(k):
# comb = combinations(ilosc_cech, iteracja + 1)
cechy = []
for thing in najlepsze_cechy:
if thing in ilosc_cech: ilosc_cech.remove(thing)
for i in combinations(ilosc_cech, 1):
kombinacje = najlepsze_cechy[:]
for element in i:
if element not in kombinacje:
kombinacje.append(element)
# print(kombinacje)
macierzA = np.zeros(shape=(iteracja + 1, len(klasaA)))
macierzB = np.zeros(shape=(iteracja + 1, len(klasaB)))
licznik = 0.0
# print(i)
for j in range(len(kombinacje)):
# licznik[j]=[sredniaA.cecha[j+1],sredniaB.cecha[j+1]]
licznik = licznik + (sredniaA.cecha[kombinacje[j]] - sredniaB.cecha[kombinacje[j]]) ** 2
wierszA = []
wierszB = []
# print(kombinacje[j])
for punkcikA in klasaA:
wierszA.append(punkcikA.cecha[kombinacje[j]] - sredniaA.cecha[kombinacje[j]])
for punkcikB in klasaB:
wierszB.append(punkcikB.cecha[kombinacje[j]] - sredniaB.cecha[kombinacje[j]])
macierzA[j] = wierszA
macierzB[j] = wierszB
licznik = math.sqrt(licznik)
macierzA = np.dot(macierzA, macierzA.T)
macierzB = np.dot(macierzB, macierzB.T)
if iteracja + 1 == 1:
mianownik = math.sqrt(macierzA) + math.sqrt(macierzB)
else:
mianownik = np.linalg.det(macierzA) + np.linalg.det(macierzB)
fisher = math.fabs(licznik) / mianownik
# print("elo: ", kombinacje)
cechy.append({'cechy': kombinacje[-1], 'wartosc': fisher})
# print(fisher)
najlepsze_cechy.append(sorted(cechy, key=lambda i: i['wartosc'], reverse=True)[0]['cechy'])
print("Oto najlepsze cechy: ", sorted(najlepsze_cechy), "\n")
zapisz_nowe_cechy(sorted(najlepsze_cechy), klasaA, klasaB, klasaTest)
def zapisz_nowe_cechy(nowe_cechy, *klasy):
for klasa in klasy:
for punkt in klasa:
ceszki = {}
for cecha in nowe_cechy:
ceszki[cecha] = punkt.cecha[cecha]
punkt.cecha = ceszki
def main():
global klasaA
global klasaB
global klasaTest
klasaA = []
klasaB = []
klasaTest = []
mniej_cech = False
# odczyt_pliku("k-NM.txt")
# podzialNaPodklasy(3, klasaA)
odczyt_pliku("Maple_Oak.txt")
switcher = {
1: wybor_cech,
2: sfs_algorytm,
3: k_nn_algorytm,
4: k_nn_algorytm,
5: nm_algorytm,
6: k_nm_algorytm}
wybor = 0
while True:
wybor = int(input("Co chcesz zrobić?\n"
"1. Policz najlepsze cechy - Fisher\n"
"2. Policz najlepsze cechy - SFS\n"
"3. Policz przynależność do klasy - NN\n"
"4. Policz przynależność do klasy - k-NN\n"
"5. Policz przynależność do klasy - NM\n"
"6. Policz przynależność do klasy - k-NM\n"
"7. Losuj raz jescze\n"
"8. Rzucić to wszystko i wyjechać w Bieszczady\n\n"
"WYBÓR: "))
if wybor == 1:
k = int(input("Podaj dla ilu cech mam policzyć: "))
wybor_cech(k)
mniej_cech=True
if wybor == 2:
k = int(input("Podaj dla ilu cech mam policzyć: "))
sfs_algorytm(k)
mniej_cech = True
if wybor == 3:
k_nn_algorytm(1, klasaTest, klasaA, klasaB)
if wybor == 4:
k = int(input("Podaj dla jakiego K mam policzyć: "))
k_nn_algorytm(k, klasaTest, klasaA, klasaB)
if wybor == 5:
nm_algorytm(klasaTest)
if wybor == 6:
k = int(input("Podaj dla jakiego K mam policzyć: "))
# podzialNaPodklasy(k,klasaA)
k_nm_algorytm(k, klasaTest, klasaA, klasaB)
if wybor == 7:
klasaA.clear()
klasaB.clear()
klasaTest.clear()
odczyt_pliku("Maple_Oak.txt")
if wybor not in range(1, 8):
print(""
" /\\ /\\ /\\ \n"
" /\\/\\/\\/\\/\\/\\ /\ /\ \n"
" / \\ \\ \\ /__\\ /__\\\n"
" / \\ \\ \\ || ||")
print("Rzucam studia, jadę w Bieszczady")
break
#
#
# # print(odleglosc(klasaA[0], nowyPunkt))
# # print(odleglosc(klasaB[0], nowyPunkt))
# # print(nowyPunkt.cecha)
# # print(odleglosc(klasaB[0], klasaA[0]))
# # print(k_nn_algorytm(3, nowyPunkt, klasaA, klasaB))
# # print(k_nn_algorytm(1, nowyPunkt, klasaA, klasaB))
# # podzialNaPodklasy(4, klasaB)
# # k_nm_algorytm(2,nowyPunkt, klasaA, klasaB)
# # wybor_cech(3)
# sfs_algorytm(6)
# print(kl5
#asaA[0].cecha)
if __name__ == "__main__":
main()
0
| fbbd33953a6fa595a47f6ffba81ee4409d8e2e6c | [
"Python"
] | 1 | Python | 233130/SMPD | 8c0b33f72b4def4025da3a40185fd0e01dd5ac6c | dd1457c020ee6be1c8bd82f62557049ba63067a4 | |
refs/heads/master | <repo_name>josiahdavis/base_python<file_sep>/base_python.py
"""
Introduction to Base Python
Author: <NAME>
"""
# ==================================================================
# D A T A T Y P E S
# ==================================================================
# Integer
type(2)
# Float (with the decimal)
type(2.7)
type(2.7e+2)
# Long (more than 10 digits, or L)
type(27L)
# String (either single ('') or double ("") quotes may be used)
type("Data Science")
type('Data Science')
# Boolean
type(False)
# You can check datatypes
isinstance(1, float)
isinstance(1.0, int)
isinstance(2L, long)
isinstance("Data Science", str)
isinstance(False, bool)
# You can convert between datatypes
int(1.0)
float(1)
int("1")
int(54L)
# ==================================================================
# O P E R A T I O N S
# ==================================================================
var1 = 3
var2 = 10
# Boolean Operators
var1 == var2 # EQUAL TO
var1 < var2 # LESS THAN
var1 <= var2 # LESS THAN OR EQUAL TO
(var1 == 1) | (var2 == 10) # OR
(var1 == 1) or (var2 == 10) # OR (alternative)
(var1 == 1) & (var2 == 10) # AND
(var1 == 1) and (var2 == 10) # AND (alternative)
# Addition
10 + 3
# Subtraction
10 - 3
# Multiplication
10 * 3
# Division
10 / 3 # returns 3 in Python 2.x
10 / 3.0 # returns 3.333...
10 / float(3) # returns 3.333...
# Powers
10**3
# Remainders
10 % 3
# ==================================================================
# L I S T S : Mutable, Ordered Data Structures
# ==================================================================
# Lists are denoted by []
lis = [0, 1, 2, 3, 4, 5, 6, 7]
type(lis)
# Specific elemnents can be accessed using [] as well
lis[4] # Returns the 5th element
# Multiple elements can be accessed using the ':' operator
# Returns the 1st number through one shy of the 2nd number
lis[0:4]
# Returns the 5th element through the last element
lis[4:]
# Returns the first through the 4th element
lis[:4]
# Returns the last element
lis[-1]
# Returns the last n elements
lis[-3:]
# List elements are mutable
lis[4] = 100
lis[4:6] = [500, 600]
# The type of list elements is also mutable
lis[0:3] = ["Guido", "Van", "Rossum"]
lis[3:7] = ["created", "python,", "programming", "language,"]
# Check if an element is in a list
"Van" in lis # returns True
# Elements can be removed with the .remove method
lis.remove(7)
# Elements can be added to the end of a list using the .append method
lis.append("in 1991")
# Elements can be inserted into the middle of a list
lis.insert(5,"a")
# Lists can be nested within each other
# List of three lists
lis = [[1,2,3],[4,5,6],[7,8,9]]
# Lets try to access a particular number, say 6
lis[1][2]
# A list within a list within a list within a list within a list
lis = [1,2,[3,4,[5,6,[7,8]]]]
# ==================================================================
# D I C T: Unordered data structures with key-value pairs
# Keys must be unique
# ==================================================================
dct = {"Name": "<NAME>",
"Description": "British Comedy Group",
"Known for": ["Irreverant Comedy", "Monty Python and the Holy Grail"],
"Years Active" : 17,
"# Members": 6}
# Access an element within the list
dct["Years Active"]
# Add a new item to a list within the dictionary
dct["Known for"].append("Influencing SNL")
# Returns the keys
dct.keys()
# Returns the values
dct.values()
# Create a dictionary within the 'dct' dictionary
dct["Influence"] = { "Asteroids": [13681, 9618, 9619, 9620, 9621, 9622],
"Technology": ["Spam", "Python", "IDLE (for Eric Idle)"],
"Food": ["Monty Python's Holy Ale", "Vermonty Python"]}
# Accessing a nested dictionary item
dct["Influence"]["Technology"]
# A dictionary can be turned into a list
# Each key/value pair is an element in the list
dct.items()
# What do the ( ) that enclose each element of the list mean? --> Tuple.
# ==================================================================
# T U P L E S: Immutable data structures
# ==================================================================
# Tuples are denoted by ()
tup = ("Monty Python and the Flying Circus", 1969, "British Comedy Group")
type(tup)
# Elements can be accessed in the same way as lists
tup[0]
# You can't change an element within a tuple
tup[0] = "Monty Python"
# Tuples can be "unpacked" by the following
name, year, description = tup
# Tuples can be nested within one another
tup = ("Monty Python and the Flying Circus", (1969, "British Comedy Group"))
# ==================================================================
# S T R I N G S
# ==================================================================
# Example strings
s1 = "What is the air-speed velocity"
s2 = "of an unladen swallow?"
# Concatenate two strings
s = s1 + " " + s2
# Also, equivalently
s = " ".join([s1, s2])
# Replace an item within a string
s = s.replace("unladen", "unladen African")
# Return the index of the first instance of a string
s.find("swallow")
# Slice the string
s[-8:]
s[s.find("swallow"):]
# Change to upper and lower case
"swallow".upper()
"SWALLOW".lower()
"swallow".capitalize()
# Count the instances of a substring
s.count(" ")
# Split up a string (returns a list)
s.split()
s.split(" ") # Same thing
# ==================================================================
# F U N C T I O N S
# ==================================================================
# <NAME>: Functions are the primary and most important method of code
# organization and reuse in Python. There may not be such a thing as too many
# functions. In fact, I would argue that most programmers doing data analysis
# don't write enough functions! (p. 420 of Python for Data Analysis)
# Range returns a list with a defined start/stop point (default start is 0)
range(1, 10, 2)
range(5, 10)
range(10)
# Type identifies the object type you pass it
type(3)
# Isinstance checks for the variable type
isinstance(4, str)
# Len returns the length of an object
len("Holy Grail")
len([3, 4, 5, 1])
# User-defined functions start with the 'def' keyword
# They may take inputs as arguments, and may return an output
def my_function(x, y):
return x - y
# These are equivalent
my_function(100, 10)
my_function(x=100, y=10)
my_function(y=10, x=100)
# This is not equivalent
my_function(10, 100)
# What if we want to make one of our arguments optional?
def my_function_optional(x, y = 10):
return x - y
# These are equivalent
my_function_optional(100, 10)
my_function_optional(100)
# ==================================================================
# I F - S T A T E M E N T S & L O O P I N G
# ==================================================================
var1 = 10
# If elif else statement
# Whitespace is important
if var1 > 5:
print "More than 5"
elif var1 < 5:
print "Less than 5"
else:
print "5"
# While statement
while var1 < 10:
print var1
var1 += 1 # This is commonly used shorthand for var1 = var1 + 1
# For loop
for i in range(0,10,2):
print i**2
# For loop in the list
fruits = ['apple', 'banana', 'cherry', 'plum']
for i in range(len(fruits)):
print fruits[i].upper()
# Better way
for fruit in fruits:
print fruit.upper()
# Dictionaries are also iterable
for first in dct.items():
print first[0]
for first, second in dct.items():
print second
# ==================================================================
# I M P O R T
# ==================================================================
# Import a package (collection of (sub)modules)
import sklearn
clf = sklearn.tree.DecisionTreeClassifier()
# Import a specific (sub)module within the sklearn package
from sklearn import tree
clf = tree.DecisionTreeClassifier()
# Import the DecisionTreeClassifer class within the sklearn.tree submodule
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
# ==================================================================
# L I S T C O M P R E H E N S I O N
# ==================================================================
# List comprehension is a popular construct in the python programming language:
# Takes an iterable as the input, performs a function on each element of that
# input, and returns a list
# Say you have a list and you want to do something to every element,
# or a subset of this list
numbers = [100, 45, 132.0, 1, 0, 0.3, 0.5, 1, 3]
# Long form using a for loop
lis1 = []
for x in numbers:
if isinstance(x,int):
lis1.append(5*x)
# Short form using list comprehension
lis2 = [x * 5 for x in numbers if isinstance(x, int)]
# ==================================================================
# T H E W O R K I N G D I R E C T O R Y
# ==================================================================
# Using the Spyder GUI:
# 1) Select the options buttom in the upper right hand cornder of the editor
# 2) Select "Set console working directory"
# 3) From now on, any read/write operations will executive relative to
# the working directory of the script.
import os
# Check the current working directory
os.getcwd()
# Change the current directory
os.chdir('C:\\Python27')
# Change from the current directory
os.chdir('Scripts')
# List out the files in the current directory
for i in os.listdir(os.getcwd()):
print i<file_sep>/README.md
# Introduction to Base Python
| 79b5d64347f0a0159536639d14a7b37d257ccf07 | [
"Markdown",
"Python"
] | 2 | Python | josiahdavis/base_python | ce55f4ff10d71ca81afd8116da362cd225a2ea33 | d3b87848846526cdb0185b0128c6bffb8eff0957 | |
refs/heads/master | <repo_name>TuhinSah/Hindi-Dialect-Recognition-and-Generation<file_sep>/Code/f_one_score_calc.py
import sys
predictions = []
answers = []
with open(sys.argv[1], "r") as prediction_file:
for line in prediction_file:
(_, dialect) = line.strip().split(" | ")
predictions.append(dialect)
with open(sys.argv[2], "r") as answer_file:
for line in answer_file:
(_, dialect) = line.strip().split(" | ")
answers.append(dialect)
total_lines = len(predictions)
std_true_positive = 0
std_false_positive = 0
std_false_negative = 0
hum_true_positive = 0
hum_false_positive = 0
hum_false_negative = 0
bom_true_positive = 0
bom_false_positive = 0
bom_false_negative = 0
wup_true_positive = 0
wup_false_positive = 0
wup_false_negative = 0
eup_true_positive = 0
eup_false_positive = 0
eup_false_negative = 0
del_true_positive = 0
del_false_positive = 0
del_false_negative = 0
for i in range(total_lines):
if(predictions[i] == "STD" and answers[i] == "STD"):
std_true_positive += 1
elif(predictions[i] == "STD" and answers[i] != "STD"):
std_false_positive += 1
elif(predictions[i] != "STD" and answers[i] == "STD"):
std_false_negative += 1
elif(predictions[i] == "HUM" and answers[i] == "HUM"):
hum_true_positive += 1
elif(predictions[i] == "HUM" and answers[i] != "HUM"):
hum_false_positive += 1
elif(predictions[i] != "HUM" and answers[i] == "HUM"):
hum_false_negative += 1
elif(predictions[i] == "BOM" and answers[i] == "BOM"):
bom_true_positive += 1
elif(predictions[i] == "BOM" and answers[i] != "BOM"):
bom_false_positive += 1
elif(predictions[i] != "BOM" and answers[i] == "BOM"):
bom_false_negative += 1
elif(predictions[i] == "WUP" and answers[i] == "WUP"):
wup_true_positive +=1
elif(predictions[i] == "WUP" and answers[i] != "WUP"):
wup_false_positive += 1
elif(predictions[i] != "WUP" and answers[i] == "WUP"):
wup_false_negative += 1
elif(predictions[i] == "EUP" and answers[i] == "EUP"):
eup_true_positive += 1
elif(predictions[i] == "EUP" and answers[i] != "EUP"):
eup_false_positive += 1
elif(predictions[i] != "EUP" and answers[i] == "EUP"):
eup_false_negative += 1
elif(predictions[i] == "DEL" and answers[i] == "DEL"):
del_true_positive +=1
elif(predictions[i] == "DEL" and answers[i] != "DEL"):
del_false_positive +=1
elif(predictions[i] != "DEL" and answers[i] == "DEL"):
del_false_negative += 1
print "STD True Positive: " + str(std_true_positive)
print "STD False Positive: " + str(std_false_positive)
print "STD False Negative: " + str(std_false_negative)
std_precision = std_true_positive / float(std_true_positive + std_false_positive)
std_recall = std_true_positive / float(std_true_positive + std_false_negative)
std_f1 = 2 * std_precision * std_recall / (std_precision + std_recall)
print "STD Precision: " + str(std_precision)
print "STD Precision: " + str(std_recall)
print "STD F1: " + str(std_f1)
print "HUM True Positive: " + str(hum_true_positive)
print "HUM False Positive: " + str(hum_false_positive)
print "HUM False Negative: " + str(hum_false_negative)
hum_precision = hum_true_positive / float(hum_true_positive + hum_false_positive)
hum_recall = hum_true_positive / float(hum_true_positive + hum_false_negative)
hum_f1 = 2 * hum_precision * hum_recall / (hum_precision + hum_recall)
print "HUM Precision: " + str(hum_precision)
print "HUM Precision: " + str(hum_recall)
print "HUM F1: " + str(hum_f1)
print "BOM True Positive: " + str(bom_true_positive)
print "BOM False Positive: " + str(bom_false_positive)
print "BOM False Negative: " + str(bom_false_negative)
bom_precision = bom_true_positive / float(bom_true_positive + bom_false_positive)
bom_recall = bom_true_positive / float(bom_true_positive + bom_false_negative)
bom_f1 = 2 * bom_precision * bom_recall / (bom_precision + bom_recall)
print "BOM Precision: " + str(bom_precision)
print "BOM Precision: " + str(bom_recall)
print "BOM F1: " + str(bom_f1)
print "WUP True Positive: " + str(wup_true_positive)
print "WUP False Positive: " + str(wup_false_positive)
print "WUP False Negative: " + str(wup_false_negative)
wup_precision = wup_true_positive / float(wup_true_positive + wup_false_positive)
wup_recall = wup_true_positive / float(wup_true_positive + wup_false_negative)
wup_f1 = 2 * wup_precision * wup_recall / (wup_precision + wup_recall)
print "WUP Precision: " + str(wup_precision)
print "WUP Precision: " + str(wup_recall)
print "WUP F1: " + str(wup_f1)
print "EUP True Positive: " + str(eup_true_positive)
print "EUP False Positive: " + str(eup_false_positive)
print "EUP False Negative: " + str(eup_false_negative)
eup_precision = eup_true_positive / float(eup_true_positive + eup_false_positive)
eup_recall = eup_true_positive / float(eup_true_positive + eup_false_negative)
eup_f1 = 2 * eup_precision * eup_recall / (eup_precision + eup_recall)
print "EUP Precision: " + str(eup_precision)
print "EUP Precision: " + str(eup_recall)
print "EUP F1: " + str(eup_f1)
print "DEL True Positive: " + str(del_true_positive)
print "DEL False Positive: " + str(del_false_positive)
print "DEL False Negative: " + str(del_false_negative)
del_precision = del_true_positive / float(del_false_positive + del_true_positive)
del_recall = del_true_positive / float(del_true_positive + del_false_negative)
del_f1 = 2 * del_precision * del_recall / (del_precision + del_recall)
print "DEL Precision: " + str(del_precision)
print "DEL Precision: " + str(del_recall)
print "DEL F1: " + str(del_f1)
<file_sep>/README.md
# Hindi-Dialect-Recognition-and-Generation
This project aims to distinguish between different dialects of Hindi, based on data collected from scripts of Hindi Movies.
There are 2 major components:
1. The dialect recognizer, which tags each line of dialogue with the dialect it is in
2. The part of speech tagger, which tags the parts of speech for each word, in all the dialects
<file_sep>/Code/calculateposaccuracy.py
import sys
predictions = []
answers = []
total_words = 0
correct_words = 0
with open(sys.argv[1], "r") as prediction_file:
for line in prediction_file:
predictions.extend(line.strip().split(" "))
with open(sys.argv[2], "r") as answer_file:
for line in answer_file:
answers.extend(line.strip().split(" "))
for prediction in predictions:
total_words += (len(prediction))
print len(predictions)
print len(answers)
for i in xrange(len(predictions)):
print i, predictions[i], answers[i]
if predictions[i].split("/")[1] == answers[i].split("/")[1]:
correct_words += 1
accuracy = float(correct_words) / float(total_words) * 100.0
print "Accuracy = " + str(accuracy)
| c2e90c6877762425f6b44de1890c5e7dd1b7d35f | [
"Markdown",
"Python"
] | 3 | Python | TuhinSah/Hindi-Dialect-Recognition-and-Generation | 65690e8b1bcaa0b5c12fed0bd00cf067cdf7301e | 40789ba665aa1b42670ea052eb0741ff611e4920 | |
refs/heads/master | <repo_name>mohsinalimat/AACameraView<file_sep>/AACameraView/Classes/AACameraView.swift
//
// AACameraView.swift
// AACameraView
//
// Created by <NAME> on 07/02/2017.
// Copyright © 2017 AA-Creations. All rights reserved.
//
import UIKit
import AVFoundation
/// MARK:- AACameraView
@IBDesignable open class AACameraView: UIView {
/// AACameraView Zoom Gesture Enabled
@IBInspectable open var zoomEnabled: Bool = true {
didSet {
setPinchGesture()
}
}
/// AACameraView Focus Gesture Enabled
@IBInspectable open var focusEnabled: Bool = true {
didSet {
setFocusGesture()
}
}
/// AACameraViewGlobal object for one time initialization in AACameraView
lazy var global: AACameraViewGlobal = {
return AACameraViewGlobal()
}()
/// Gesture for zoom in/out in AACameraView
lazy var pinchGesture: UIPinchGestureRecognizer = {
return UIPinchGestureRecognizer(target: self,
action: #selector(AACameraView.pinchToZoom(_:)))
}()
/// Gesture to focus in AACameraView
lazy var focusGesture: UITapGestureRecognizer = {
let instance = UITapGestureRecognizer(target: self,
action: #selector(AACameraView.tapToFocus(_:)))
instance.cancelsTouchesInView = false
return instance
}()
/// Callback closure for getting the AACameraView response
open var response: ((_ response: Any?) -> ())?
/// Preview layrer for AACameraView
var previewLayer: AVCaptureVideoPreviewLayer?
/// Zoom factor for AACameraView
var zoomFactor: CGFloat = 1
/// Capture Session for AACameraView
var session: AVCaptureSession! {
didSet {
setSession()
}
}
/// Current output for capture session
var output: AVCaptureOutput = AVCaptureStillImageOutput() {
didSet {
session.removeOutput(oldValue)
session.setOutput(output)
}
}
/// Video Output
var outputVideo: AVCaptureMovieFileOutput? {
return self.output as? AVCaptureMovieFileOutput
}
/// Image Output
var outputImage: AVCaptureStillImageOutput? {
return self.output as? AVCaptureStillImageOutput
}
/// Getter for current camera device
var currentDevice: AVCaptureDevice? {
switch cameraPosition {
case .back:
return global.cameraBack
case .front:
return global.cameraFront
default:
return nil
}
}
/// Current output mode for AACameraView
open var outputMode: OUTPUT_MODE = .image {
didSet {
guard outputMode != oldValue else {
return
}
if oldValue == .videoAudio {
session.removeMicInput(global.deviceAudio)
}
setOutputMode()
}
}
/// Current camera position for AACameraView
open var cameraPosition: AVCaptureDevicePosition = .back {
didSet {
guard cameraPosition != oldValue else {
return
}
setDevice()
}
}
/// Current flash mode for AACameraView
open var flashMode: AVCaptureFlashMode = .auto {
didSet {
guard flashMode != oldValue else {
return
}
setFlash()
}
}
/// Current camera quality for AACameraView
open var quality: OUTPUT_QUALITY = .high {
didSet {
guard quality != oldValue else {
return
}
session.setQuality(quality, mode: outputMode)
}
}
/// AACameraView - Interface Builder View
open override func prepareForInterfaceBuilder() {
let label = UILabel(frame: self.bounds)
label.text = "AACameraView"
label.textColor = UIColor.white.withAlphaComponent(0.7)
label.textAlignment = .center
label.font = UIFont(name: "Gill Sans", size: bounds.width/10)
label.sizeThatFits(intrinsicContentSize)
self.addSubview(label)
self.backgroundColor = UIColor(rgb: 0x2891B1)
}
/// Capture session starts/resumes for AACameraView
open func startSession() {
if let session = self.session {
if !session.isRunning {
session.startRunning()
}
} else {
setSession()
}
}
/// Capture session stops for AACameraView
open func stopSession() {
if session.isRunning {
session.stopRunning()
}
}
/// Start Video Recording for AACameraView
open func startVideoRecording() {
guard
let output = outputVideo,
!output.isRecording
else { return }
output.startRecording(toOutputFileURL: global.tempMoviePath, recordingDelegate: self)
}
/// Stop Video Recording for AACameraView
open func stopVideoRecording() {
guard
let output = outputVideo,
output.isRecording
else { return }
output.stopRecording()
}
/// Capture image for AACameraView
open func captureImage() {
guard let output = outputImage else { return }
global.queue.async(execute: {
let connection = output.connection(withMediaType: AVMediaTypeVideo)
output.captureStillImageAsynchronously(from: connection, completionHandler: { [unowned self] response, error in
guard
error == nil,
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(response),
let image = UIImage(data: data)
else {
self.response?(error)
return
}
self.response?(image)
})
})
}
}
// MARK: - UIGestureRecognizer Selectors
extension AACameraView {
/// Zoom in/out selector if allowd
///
/// - Parameter gesture: UIPinchGestureRecognizer
func pinchToZoom(_ gesture: UIPinchGestureRecognizer) {
guard let device = currentDevice else {
return
}
zoomFactor = device.setZoom(zoomFactor, gesture: gesture)
}
/// Focus selector if allowd
///
/// - Parameter gesture: UITapGestureRecognizer
func tapToFocus(_ gesture: UITapGestureRecognizer) {
guard
let previewLayer = previewLayer,
let device = currentDevice
else {
return
}
device.setFocus(self, previewLayer: previewLayer, gesture: gesture)
}
}
// MARK: - AVCaptureFileOutputRecordingDelegate
extension AACameraView: AVCaptureFileOutputRecordingDelegate {
/// Recording did start
///
/// - Parameters:
/// - captureOutput: AVCaptureFileOutput
/// - fileURL: URL
/// - connections: [Any]
open func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
session.beginConfiguration()
if flashMode != .off {
setFlash()
}
session.commitConfiguration()
}
/// Recording did end
///
/// - Parameters:
/// - captureOutput: AVCaptureFileOutput
/// - outputFileURL: URL
/// - connections: [Any]
/// - error: Error
open func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
self.flashMode = .off
let response: Any = error == nil ? outputFileURL : error
self.response?(response)
}
}
// MARK: - Setters for AACameraView
extension AACameraView {
/// Set capture session for AACameraView
func setSession() {
guard let session = self.session else {
if self.global.status == .authorized || self.global.status == .notDetermined {
self.session = AVCaptureSession()
}
return
}
global.queue.async(execute: {
session.beginConfiguration()
session.sessionPreset = AVCaptureSessionPresetHigh
self.setDevice()
self.setOutputMode()
self.previewLayer = session.setPreviewLayer(self)
session.commitConfiguration()
self.setFlash()
self.setPinchGesture()
self.setFocusGesture()
session.startRunning()
})
}
/// Set Output mode for AACameraView
func setOutputMode() {
session.beginConfiguration()
if outputMode == .image {
output = AVCaptureStillImageOutput()
}
else {
if outputMode == .videoAudio {
session.addMicInput(global.deviceAudio)
}
output = AVCaptureMovieFileOutput()
outputVideo!.movieFragmentInterval = kCMTimeInvalid
}
session.commitConfiguration()
session.setQuality(quality, mode: outputMode)
}
/// Set camera device for AACameraView
func setDevice() {
session.setCameraDevice(self.cameraPosition, cameraBack: global.cameraBack, cameraFront: global.cameraFront)
}
/// Set Flash mode for AACameraView
func setFlash() {
session.setFlashMode(global.devicesVideo, flashMode: flashMode)
}
/// Set Zoom in/out gesture for AACameraView
func setPinchGesture() {
toggleGestureRecognizer(zoomEnabled, gesture: pinchGesture)
}
/// Set Focus gesture for AACameraView
func setFocusGesture() {
toggleGestureRecognizer(focusEnabled, gesture: focusGesture)
}
}
| dc7ca5fa5fb506bf52b0902acd1770b9abcf45dd | [
"Swift"
] | 1 | Swift | mohsinalimat/AACameraView | c0285b829289e983fa6555046deefb81ab632316 | 0bd96c5fe37379d32ade78084680d14349da711e | |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
var db = require('../db/db')
/* GET home page. */
router.post('/eliminar', function (req, res, next) {
db.eliminar({id:req.body.id}, function (success, cb) {
console.log(cb)
res.json({success: success, result: cb})
})
});
router.post('/editar', function (req, res, next) {
db.editar({id: req.body.id, texto: req.body.texto}, function (success, cb) {
console.log(cb)
res.json({success: success, result: cb})
})
});
router.get('/todos', function (req, res, next) {
db.todos({}, function (success, cb) {
console.log(cb)
res.json({success: success, result: cb})
})
});
router.post('/crear', function (req, res, next) {
db.crear({texto: req.body.texto}, function (success, cb) {
console.log(cb)
res.json({success: success, result: cb})
})
});
module.exports = router;
<file_sep>var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/API');
var os = require('os');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/API', apiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(app.get('port'), function () {
console.log('Node app is running on port', app.get('port'));
var ifaces = os.networkInterfaces();
// console Server ip address
Object.keys(ifaces).forEach(function (ifname) {
var alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
console.log(ifname + ':' + alias + ' ' + iface.address);
} else {
// this interface has only one ipv4 adress
console.log(ifname + ' ' + iface.address);
}
});
});
})
module.exports = app;
| 560facdfc062872a03d651270e687566f91fd5e2 | [
"JavaScript"
] | 2 | JavaScript | carlosen14/todo-api | efd65c928839e59d822d2da918ca4dfd56741369 | b42d14fb1c4423903dbb28742d6bb40eb4fe217e | |
refs/heads/master | <file_sep>"use strict";
// Load plugins
const browsersync = require("browser-sync").create();
const gulp = require("gulp");
const sass = require("gulp-sass");
const plumber = require("gulp-plumber");
const imagemin = require("gulp-imagemin");
const newer = require("gulp-newer");
const pug = require('gulp-pug');
const del = require("del");
// BrowserSync
function browserSync(done) {
browsersync.init({
server: {
baseDir: "./dist"
},
port: 3000
});
done();
}
// BrowserSync Reload
function browserSyncReload(done) {
browsersync.reload();
done();
}
// Clean assets
function clean() {
return del(["./dist/"]);
}
// CSS task
function css() {
return gulp
.src("./src/scss/**/*.scss")
.pipe(plumber())
.pipe(sass({ outputStyle: "expanded" }))
.pipe(gulp.dest("./dist/css/"))
//.pipe(rename({ suffix: ".min" }))
//.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(browsersync.stream());
}
// Optimize Images
function images() {
return gulp
.src("./src/imgs/**/*")
.pipe(newer("./dist/imgs"))
.pipe(
imagemin([
imagemin.gifsicle({ interlaced: true }),
imagemin.jpegtran({ progressive: true }),
imagemin.optipng({ optimizationLevel: 5 }),
imagemin.svgo({
plugins: [
{
removeViewBox: false,
collapseGroups: true
}
]
})
])
)
.pipe(gulp.dest("./dist/imgs"));
}
// Copy Asscets/ Fonts
function copyFonts() {
return gulp
.src('./src/fonts/**/*')
.pipe(gulp.dest('./dist/fonts'));
}
// Copy Asscets/ Vendors
function copyVendors() {
return gulp
.src('./src/vendors/**/*')
.pipe(gulp.dest('./dist/vendors'));
}
// HTML Generator
function htmlTemplates() {
return gulp
.src('./src/templates/*.pug')
.pipe(pug(
{
pretty: true
}
))
// tell gulp our output folder
.pipe(gulp.dest('./dist'));
}
// Transpile, concatenate and minify scripts
function scripts() {
return (
gulp
.src(["./src/js/**/*"])
.pipe(plumber())
.pipe(webpackstream(webpackconfig, webpack))
// folder only, filename is specified in webpack config
.pipe(gulp.dest("./dist/js/"))
.pipe(browsersync.stream())
);
}
// Watch files
function watchFiles() {
gulp.watch("./src/scss/**/*", css);
//gulp.watch("./src/js/**/*", gulp.series(scripts));
gulp.watch(
[
"./src/templates/_includes/**/*",
"./src/templates/_layouts/**/*",
"./src/templates/_partials/**/*",
"./src/templates/*"
],
gulp.series(htmlTemplates, browserSyncReload)
);
gulp.watch("./src/img/**/*", images);
}
// define complex tasks
//const js = gulp.series(scriptsLint, scripts);
const build = gulp.series(clean, gulp.parallel(css, images, copyVendors, copyFonts, htmlTemplates));
const serve = gulp.parallel(watchFiles, browserSync, copyVendors, copyFonts);
// export tasks
exports.images = images;
exports.css = css;
exports.copyFonts = copyFonts;
exports.copyVendors = copyVendors;
//exports.js = js;
exports.htmlTemplates = htmlTemplates;
exports.clean = clean;
exports.build = build;
exports.serve = serve;
exports.default = build;<file_sep># GAPS--(Gulp app with Pug and Sass)
Custom Gulp App with Pug Templates and Sass
## What is gaps?
* Custom Gulp app with gulp 4.0 and Pug templates
| bff8c2a55d3ef376aa3c29038d26edb6835360d2 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | fahimshani/gaps | d526fa56c87aa4738f3194c1ca0c832ed3f05b6a | 0eb08e0c0821b04881842cca7b2a6527d9975676 | |
refs/heads/main | <file_sep>import User from '../models/Usuarios'
import Role from '../models/Rol'
import jwt from 'jsonwebtoken'
import config from '../config'
export const signup = async (req, res) => {
//obteniendo req body
const {username, email,password,nombre,apellido,numero,poblacion,address,codigo,roles} = req.body
//Creando nuevo usuario
const nuevousuario = new User ({
username,
email,
password: await User.encryptPassword(password),
nombre,
apellido,
numero,
poblacion,address,
codigo
})
//Comprobando si tiene roles si no asigna usuario
if(roles){
const foundRoles = await Role.find({name: {$in : roles}})
nuevousuario.roles = foundRoles.map((role) => role._id)
}else{
const role = await Role.findOne({name : "user"});
nuevousuario.roles = [role._id];
}
//Guardamos usuario en mongo
const saveUser = await nuevousuario.save();
console.log(saveUser)
//Creamos token
const token = jwt.sign({id:saveUser._id}, config.SECRET,{
expiresIn: 1800 // 30 min
})
return res.json(token)
}
export const signin = async (req, res) => {
const userFound = await User.findOne({email: req.body.email}).populate("roles")
if(!userFound) return res.status(400).json({message: "Usuario no encontrado"})
const matchpass = await User.compararPassword(req.body.password , userFound.password)
if (!matchpass) return res.status(401).json({token: null , message : "Contraseña fallida "})
const token = jwt.sign({id: userFound._id}, config.SECRET,{
expiresIn : 1800
})
res.json(token)
}
export const dataProfile = async (req,res) => {
const userFound = await User.findOne({email: req.body.email}).populate("roles")
if(!userFound) return res.status(400).json({message: "Usuario no encontrado"})
const datos = {
"username" : userFound.username,
"email" : userFound.email,
"nombre" : userFound.nombre,
"apellido" : userFound.apellido,
"numero" : userFound.numero,
"poblacion" : userFound.poblacion,
"address" : userFound.address,
"codigo" : userFound.codigo
}
res.json(datos)
}<file_sep>const state = {
topRated: [
{
id: 1,
name: "Tele",
price: 500,
url: "https://m.media-amazon.com/images/I/81tn5ZRtx7L._AC_SX425_.jpg",
desc: "Buena tele",
rate: 4.3,
quantity: 1,
},
{
id: 2,
name: "Cascos",
price: 50,
url: "aqui va el enlace a la foto",
desc: "Buen casco",
rate: 4.0,
},
{
id: 3,
name: "PC",
price: 900,
url: "aqui va el enlace a la foto",
desc: "Buena pc",
rate: 3.9,
},
],
contador_productos: 0,
products: [],
};
const mutations = {
addToCart(state, payload) {
let item = payload;
item = { ...item, quantity: 1 };
if (state.products.length > 0) {
var z = 0;
for (var j = 0; j < state.products.length; j++) {
let bool = state.products[j]._id === item._id;
if (bool) {
let itemIndex = state.products.findIndex((el) => el._id === item._id);
state.products[itemIndex]["quantity"] += 1;
z = 1;
}
}
if (z == 0) {
state.products.push(item);
}
} else {
// state.products.push(state.topRated[0])
state.products.push(item);
}
state.contador_productos++;
//console.log(state.products)
},
removeItem(state, payload) {
if (state.products.length > 0) {
for (var j = 0; j < state.products.length; j++) {
let bool = state.products[j]._id === payload._id;
if (bool) {
let index = state.products.findIndex((el) => el._id === payload._id);
if (state.products[index]["quantity"] !== 0) {
state.products[index]["quantity"] -= 1;
state.contador_productos--;
}
if (state.products[index]["quantity"] === 0) {
state.products.splice(index, 1);
}
}
}
}
},
/*
addToCart(state, payload){
let item = payload;
item = { ...item, quantity: 1 }
if(state.products > 0){
let bool = state.products.some(i => i._id === item._id)
if (bool){
let itemIndex = state.products.findIndex(el => el._id === item._id)
state.products[itemIndex]["quantity"] +=1;
} else {
state.products.push(item)
}
} else{
state.products.push(item)
}
state.contador_productos++
console.log(state.contador_productos)
},
removeItem(state, payload){
if(state.products.length > 0){
let bool = state.products.some (i => i._id === payload._id)
if (bool) {
let index = state.products.findIndex(el => el._id === payload._id)
if (state.products[index]["quantity"] !== 0){
state.products[index]["quantity"] -= 1
state.contador_productos--
}
if (state.products[index]["quantity"] === 0){
state.products.splice(index, 1)
}
}
}
}
*/
};
const actions = {
addToCart: (context, payload) => {
context.commit("addToCart", payload);
},
removeItem: (context, payload) => {
context.commit("removeItem", payload);
},
};
const getters = {
contador: (state) => state.contador_productos,
array_productos: (state) => state.products,
};
/* Esto hay que añadirlo al los methods de Detalles productos
addToCart() {
// this.$store.commit("addToCart")
this.$store.dispatch("addToCart", this.details);
}
removeItem() {
// this.$store.commit("removeItem")
this.$store.dispatch("removeItem", this.details);
}
*/
export default { state, getters, actions, mutations };
/*
addToCart(state, payload){
let item = payload;
item = { ...item, quantity: 1 }
console.log('tetonsito si soy uy')
console.log(item)
console.log('el state products')
console.log(state.products)
if(state.products.length > 0){
var j = 0
while (j < state.products.length || state.products[j]._id === item._id){
let bool = (state.products[j]._id === item._id)
if (bool){
console.log('TETONER FUNCIONA')
let itemIndex = state.products.findIndex(el => el._id === item._id)
state.products[itemIndex]["quantity"] +=1;
}
j++
}
if (j == state.products.length){
state.products.push(item)
console.log('tetoncito')
}
} else{
// state.products.push(state.topRated[0])
state.products.push(item)
}
state.contador_productos++
//console.log(state.products)
},
*/
<file_sep>import mongoose from 'mongoose'
mongoose.connect("mongodb+srv://grupo08:[email protected]/myFirstDatabase?retryWrites=true&w=majority",
{
useNewUrlParser : true,
useUnifiedTopology:true,
useFindAndModify: true,
useCreateIndex: true
})
.then(db => console.log("DB is connect"))
.catch(error => console.log(error))<file_sep>const supertest = require('supertest');
const app = require('../../../front/index');
const api = supertest(app);
test('Pruebas Servidor', async () => {
await api
.get('/')
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8')
})
const validaToken = require("../../../front/src/router/validate-tokens");
const admin = require("../../../front/src/router/admin");
test('Pruebas Servidor', async () => {
await api
.get('/admin', validaToken, admin)
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8')
})<file_sep>import {Schema, model} from 'mongoose'
const ProducSchema = new Schema({
name: String,
categoria: String,
precio: Number,
stock : Number,
descripcion: String,
imgUrl : String
},
{
timestamps : true,
versionKwy : false
})
export default model('Procust',ProducSchema);<file_sep>import axios from "axios";
const url = "https://elective-backend.herokuapp.com/products";
const state = {
products: [],
detalles: {},
};
const getters = {
allProducts: (state) => state.products,
detallesProductos: (state) => state.detalles,
};
const actions = {
async obtenerProductos({ commit }) {
const res = await axios.get(url);
commit("setProducts", res.data);
},
async obtenerDataProducto({ commit }, producto) {
console.log(producto);
const res = await axios.get(`${url}/${producto}`);
console.log(res);
commit("getProduct", res.data);
},
};
const mutations = {
setProducts: (state, products) => (state.products = products),
getProduct: (state, producto) => (state.detalles = producto),
};
export default { state, getters, actions, mutations };
<file_sep>import { shallowMount, mount } from "@vue/test-utils";
import Login from "@/components/Login_component";
import Register from "@/components/Register_component";
describe("Prueba 2", () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(Register, {
methods: { signup: () => {} },
data() {
return {
registro_datos: {
username: "",
nombre: "",
apellido: "",
email: "",
password: "",
address: "",
numero: null,
poblacio: "",
codigo: null,
},
};
},
});
});
it("should create", () => {
expect(wrapper.exists()).toBe(true);
});
});
describe("Prueba 3", () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(Login, {
methods: { login: () => {} },
data() {
return {
usuario: {
email: "<EMAIL>",
password: "<PASSWORD>",
},
};
},
});
});
it("should create", () => {
expect(wrapper.exists()).toBe(true);
});
});
<file_sep>export default{
SECRET : 'grupo08'
}<file_sep># E08 - Elective
## Autores:
- <NAME>
- [<EMAIL>](mailto:<EMAIL>)
- <NAME>
- [<EMAIL>](mailto:<EMAIL>)
- <NAME>
- [<EMAIL>](mailto:<EMAIL>)
- <NAME>
- [<EMAIL>](mailto:<EMAIL>)
### Informe
[Documentación](https://drive.google.com/file/d/1iJOJrPNKa5rGqI1puPLPP8PNZfdpmxjm/view?usp=sharing) detallada de la aplicación web
### Aplicación
[Web](https://string-sergio.github.io/La_Web/#/) desplegada
---
## Introducción
Proyecto web de [Vue](https://vuejs.org) basado en una tienda online con registro y login de usuarios, apoyada en una base de datos en [MongoDB](https://www.mongodb.com/es) desplegada con [Heroku](https://www.heroku.com).
## Ejecución de la aplicación en local
### Clonar el repositorio
```bash
mi-workspace> git clone https://github.com/SyTW2020/E08.git
```
### Desplegar la web en local
Hay que ejecutar dos comando, uno en cada carpeta del proyecto *front* y *backend.*
Primero para abrir el servidor:
```bash
mi-workspace/E08/backend> npm run dev
```
Para ejecutar el frontend de la web
```bash
mi-workspace/E08/front> npm run serve
```
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _mongoose = require("mongoose");
var ProducSchema = new _mongoose.Schema({
name: String,
categoria: String,
precio: Number,
stock: Number,
descripcion: String,
imgUrl: String
}, {
timestamps: true,
versionKwy: false
});
var _default = (0, _mongoose.model)('Procust', ProducSchema);
exports["default"] = _default;<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.dataProfile = exports.signin = exports.signup = void 0;
var _Usuarios = _interopRequireDefault(require("../models/Usuarios"));
var _Rol = _interopRequireDefault(require("../models/Rol"));
var _jsonwebtoken = _interopRequireDefault(require("jsonwebtoken"));
var _config = _interopRequireDefault(require("../config"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var signup = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(req, res) {
var _req$body, username, email, password, nombre, apellido, numero, poblacion, address, codigo, roles, nuevousuario, foundRoles, role, saveUser, token;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
//obteniendo req body
_req$body = req.body, username = _req$body.username, email = _req$body.email, password = _req$body.password, nombre = _req$body.nombre, apellido = _req$body.apellido, numero = _req$body.numero, poblacion = _req$body.poblacion, address = _req$body.address, codigo = _req$body.codigo, roles = _req$body.roles; //Creando nuevo usuario
_context.t0 = _Usuarios["default"];
_context.t1 = username;
_context.t2 = email;
_context.next = 6;
return _Usuarios["default"].encryptPassword(password);
case 6:
_context.t3 = _context.sent;
_context.t4 = nombre;
_context.t5 = apellido;
_context.t6 = numero;
_context.t7 = poblacion;
_context.t8 = address;
_context.t9 = codigo;
_context.t10 = {
username: _context.t1,
email: _context.t2,
password: <PASSWORD>,
nombre: _context.t4,
apellido: _context.t5,
numero: _context.t6,
poblacion: _context.t7,
address: _context.t8,
codigo: _context.t9
};
nuevousuario = new _context.t0(_context.t10);
if (!roles) {
_context.next = 22;
break;
}
_context.next = 18;
return _Rol["default"].find({
name: {
$in: roles
}
});
case 18:
foundRoles = _context.sent;
nuevousuario.roles = foundRoles.map(function (role) {
return role._id;
});
_context.next = 26;
break;
case 22:
_context.next = 24;
return _Rol["default"].findOne({
name: "user"
});
case 24:
role = _context.sent;
nuevousuario.roles = [role._id];
case 26:
_context.next = 28;
return nuevousuario.save();
case 28:
saveUser = _context.sent;
console.log(saveUser); //Creamos token
token = _jsonwebtoken["default"].sign({
id: saveUser._id
}, _config["default"].SECRET, {
expiresIn: 1800 // 30 min
});
return _context.abrupt("return", res.json(token));
case 32:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function signup(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
exports.signup = signup;
var signin = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(req, res) {
var userFound, matchpass, token;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _Usuarios["default"].findOne({
email: req.body.email
}).populate("roles");
case 2:
userFound = _context2.sent;
if (userFound) {
_context2.next = 5;
break;
}
return _context2.abrupt("return", res.status(400).json({
message: "Usuario no encontrado"
}));
case 5:
_context2.next = 7;
return _Usuarios["default"].compararPassword(req.body.password, userFound.password);
case 7:
matchpass = _context2.sent;
if (matchpass) {
_context2.next = 10;
break;
}
return _context2.abrupt("return", res.status(401).json({
token: null,
message: "Contraseña fallida "
}));
case 10:
token = _jsonwebtoken["default"].sign({
id: userFound._id
}, _config["default"].SECRET, {
expiresIn: 1800
});
res.json(token);
case 12:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function signin(_x3, _x4) {
return _ref2.apply(this, arguments);
};
}();
exports.signin = signin;
var dataProfile = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(req, res) {
var userFound, datos;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return _Usuarios["default"].findOne({
email: req.body.email
}).populate("roles");
case 2:
userFound = _context3.sent;
if (userFound) {
_context3.next = 5;
break;
}
return _context3.abrupt("return", res.status(400).json({
message: "Usuario no encontrado"
}));
case 5:
datos = {
"username": userFound.username,
"email": userFound.email,
"nombre": userFound.nombre,
"apellido": userFound.apellido,
"numero": userFound.numero,
"poblacion": userFound.poblacion,
"address": userFound.address,
"codigo": userFound.codigo
};
res.json(datos);
case 7:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function dataProfile(_x5, _x6) {
return _ref3.apply(this, arguments);
};
}();
exports.dataProfile = dataProfile;<file_sep>import {Router} from 'express'
import * as productcontroller from '../controllers/products.controller'
import {verify} from '../middlewares'
const router = Router()
router.post('/',[verify.verifytoken, verify.isModerador ],productcontroller.createProduct)
router.get('/',productcontroller.getProducts)
router.get('/:productId',productcontroller.getProductById)
router.put('/:productId',verify.verifytoken,productcontroller.updateProductById)
router.delete('/:productId',[verify.verifytoken, verify.isModerador ],productcontroller.deleteProductById)
export default router;
<file_sep>import Login_component from "@/components/Login_component";
describe("Prueba 1", () => {
it("should create", () => {
// usuario:{
// email: 'test';
// password: '<PASSWORD>'
// }
expect(Login_component.data()).toStrictEqual({
usuario: {
email: "<EMAIL>",
password: "<PASSWORD>",
},
});
});
});
| a6a004e88faec745fbc3fdc0bb7fcf33b50d306a | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | SyTW2020/E08 | e9ad61fe63927428f3bbb94a595bce1c65454681 | f82d7059b2317db56e9a638967f2b23924f9cc1e | |
refs/heads/master | <repo_name>ctl43/sarlacc_prototype<file_sep>/sam2ranges/split_sam.R
sam <- sam2ranges("/Users/law02/Dropbox (Cambridge University)/Univeristy of Cambridge/Academic/Internship/NanoporeProject/test_20180612/analysis/2h-RNA-unbl/data/genome_pass-both-chopped_sarlacc_2h-RNA-unbl_full-oligo-dT_TSO-with-TruSeq.sam.gz", minq = 0)
undebug(sam2ranges)
library(GenomicAlignments)
cigar <- "6S39M2D9M5D7M1D12M2D5M1D30M8710N3I50M2D18M1I4M2D9M1D1M1D7M2I27M1D20M1D14M1D9M2I3M2D2M1D3M7D3M2I7M1752N2M3D10M1D3M1D22M1D47M1D17M1I14M4D85945N17M1I17M1D22M1D22M1D4M2D87M2D4M1I8M6I10M1D6M123692N1M2D8M2D15M1I5M1D11M83869N19M1I22M1I17M1D10M59493N64M1D15M1D5M1D1M3D16M5462N8M2D32M2I7M2D7M1I20M2D1M1D23M4D4M4D5M3D6M2D16M594N1M1D37M1D49M2D14M1I34M3D22M1I9M2D22M2D8M1D2M1D3M2D13M4D48M2I14M1D3M1D37M21S"
load("internship/NanoporeProject/sarlacc_prototype/sam2ranges/sam2ranges.RData")
mapping <- mapping[1:1000,]
mapping$cigar.groups <- cumsum(!duplicated(mapping$QNAME))
cigar.rle <- cigarToRleList(mapping$CIGAR)
run.val <- runValue(cigar.rle)
run.len <- runLength(cigar.rle)
is.skip <- run.val=="N"
is.skip <- lapply(is.skip, function(x){x[which(x)+1] <- 1; x})
group <- lapply(is.skip, cumsum)
split.len <- mapply(function(x,y)sum(IntegerList(split(x,f=y))), x=run.len, y=group, SIMPLIFY = FALSE)
start <- mapply(function(x,y)cumsum(c(x,y)),x = mapping$POS,y = split.len)
end <- lapply(start, function(x)(x[-1]-1)[seq(1,length(x)-1,2)])
start <- lapply(start, function(x)x[-length(x)][seq(1,length(x)-1,2)])
split.granges <- mapply(function(x,y,z,s)GRanges(x, IRanges(y, end=z), strand=ifelse(bitwAnd(s, 0x10), "-", "+")),
x=mapping$RNAME,y=start,z=end,s=mapping$FLAG)
GRangesList(split.granges)<file_sep>/homopolymerFixer/homopolymerFixer.R
homopolymerTrainer <- function(grouped.reads, ref, each.set=10, rep=30, min.cov,BPPARAM=SerialParam()){
grouped.reads <- grouped.reads[lengths(grouped.reads)>(each.set)]
max.times <- pmin(rep,floor(lengths(grouped.reads)/each.set))
sampled.reads <- mapply(function(x,y)replicate(y,sample(x,each.set)),
x=grouped.reads, y=max.times, SIMPLIFY = FALSE)
sampled.reads <- unlist(sampled.reads, recursive = FALSE, use.names = FALSE)
ercc.label <- rep(names(grouped.reads),max.times)
msa <- bplapply(sampled.reads, multiReadAlign, BPPARAM = BPPARAM)
train <- bplapply(seq_along(ercc.label), function(x){
homopolymerCounter(msa[[x]], ref[ercc.label[x]], min.cov=min.cov)},BPPARAM=BPPARAM)
train <- do.call(rbind, unlist(train))
base.len <- tapply(train$observed, list(train$base,train$len), unlist, use.names = FALSE)
debase.len <- apply(base.len, 2, function(x)unlist(x))
debase.learned.distr <- sapply(debase.len, .proportion_calculator)
debase.learned.distr <- rep(debase.learned.distr, nrow(base.len))
debase.learned.distr <- matrix(debase.learned.distr, nrow(base.len), byrow = TRUE)
learned.distr <- sapply(base.len, .proportion_calculator)
learned.distr <- matrix(learned.distr, nrow(base.len), byrow = FALSE)
dimnames(debase.learned.distr) <- dimnames(learned.distr) <- dimnames(base.len)
learned.len.distr <- mapply(function(x,y)learned.distr[x,y],
x=train$base, y=as.character(train$len))
len.distr <- lapply(train$observed, function(x)table(x)/each.set)
msd <- .msd_calculator(len.distr, learned.len.distr)
msd.distr <- tapply(msd, list(train$base,train$len),unlist, use.names = FALSE)
debase.msd.distr <- apply(msd.distr, 2, unlist)
debase.msd.distr <- matrix(rep(NumericList(debase.msd.distr), nrow(base.len)),nrow(base.len), byrow=TRUE)
is.empty <- sapply(learned.distr, is.null)
is.empty[c(lengths(base.len)<each.set*rep)] <- TRUE
learned.distr[is.empty] <- debase.learned.distr[is.empty]
msd.distr[is.empty] <- debase.msd.distr[is.empty]
dimnames(debase.msd.distr) <- dimnames(msd.distr) <- dimnames(base.len)
list(base=list(len.distr=learned.distr, msd.distr=msd.distr),
debase=list(len.distr=debase.learned.distr, msd.distr=debase.msd.distr))
}
homopolymerCounter <- function(msa, ref.seq, end.dist=10, min.cov){
# Get the alignment matrix
aln.matrix <- unname(do.call(cbind,strsplit(unlist(msa$alignments), split="")))
con.seq <- QUALFUN(msa$alignments[[1]], msa$qualities[[1]], min.cov, gapped = TRUE)
cons.aln <- .get_translation_table(con.seq$seq, ref.seq)
aln.ref <- cons.aln[[2]]
cons.aln <- cons.aln[[1]]
# Get homopolymer matches between consensus and the reference
# Get the corresponding location in alignment matrix
matched <- MATCHCHECK(aln.ref)
pass <- start(matched$ref.pos)>end.dist&end(matched$ref.pos)<((nchar(ref.seq)-end.dist)+1)
matched$aligned.pos <- matched$aligned.pos[pass]
matched$ref.pos <- matched$ref.pos[pass]
aliged.start <- start(matched$aligned.pos)
aligned.end <- end(matched$aligned.pos)
aligned.loc <- mapply(":",(aliged.start-1), (aligned.end+1))
trigger <- as.numeric(elementMetadata(matched$ref.pos)$observed)
# Get the position in alignment matrix
# aln.mat.pos <- lapply(aligned.loc, function(x)range(cons.aln$aln.pos[x], na.rm = TRUE))
aln.mat.pos <- mapply(function(x,y)if(x==0) c(-1,1)else range(cons.aln$aln.pos[y], na.rm = TRUE),
x=trigger,y=aligned.loc, SIMPLIFY = FALSE)
# aln.mat.pos <- mapply(function(x,y)if(x==0)y<-c(-1,1)else y, x=trigger, y=aln.mat.pos, SIMPLIFY=FALSE)
stopifnot(all(unlist(lapply(aln.mat.pos, function(x)all(is.finite(x))))))
# Get the corresponding seq from alignment matrix
aln.seq <- lapply(aln.mat.pos, function(x)DNAStringSet(substr(msa$alignments[[1]], start=x[1]+1,stop=x[2]-1)))
# Find homopolymer in aligned seqeunces
seq.num <- length(msa$alignments[[1]])
aln.seq <- do.call(c, aln.seq)
specific.bases <- rep(elementMetadata(matched$ref.pos)$base,each=seq.num)
obs.homo.len <- .max_homo_length(aln.seq, specific.bases)
obs.homo.len <- split(obs.homo.len, f=rep(seq_len(length(obs.homo.len)/seq.num),each=seq.num))
# Count the number of reads with corresponding base and the observed length of the homopolymer
out <- DataFrame(len=width(matched$ref.pos), base=elementMetadata(matched$ref.pos)$base)
out$observed <- obs.homo.len
out
}
homopolymerFixer <- function(learned, msa, min.cov=0.6, threshold.p=0.2){
learned.len.distr <- learned$len.distr
learned.msd.distr <- learned$msd.distr
aln.matrix <- unname(do.call(cbind,strsplit(unlist(msa$alignments), split="")))
con.seq <- QUALFUN(msa$alignments[[1]], msa$qualities[[1]], min.cov)
con.seq$aln.pos <- .get_aln_pos(con.seq$seq)
cons.rle <- homopolymerFinder(DNAStringSet(con.seq$seq), min.homo = 1)[[1]]
cons.homo <- cons.rle[width(cons.rle)>1]
L <- length(cons.homo)
cons.start <- start(cons.homo)-1
cons.end <- end(cons.homo)+1
aln.loc <- mapply(function(x,y,z)con.seq$aln.pos[x:y],x=cons.start, y=cons.end)
search.range <- lapply(aln.loc, range, na.rm=TRUE)
check.seq <- lapply(search.range, function(x)DNAStringSet(substr(msa$alignments[[1]], start=x[1]+1,stop=x[2]-1)))
check.seq <- do.call(c, check.seq)
seq.num <- length(msa$alignments[[1]])
specific.bases <- rep(elementMetadata(cons.homo)$base,each=seq.num)
check.count <- .max_homo_length(check.seq, specific.bases)
check.count <- split(check.count, f=rep(seq_len(length(check.count)/seq.num),each=seq.num))
len.distr <- lapply(check.count, .proportion_calculator)
msd <- mapply(function(x,y).msd_calculator(x, learned.len.distr[y,]),
x= len.distr, y=elementMetadata(cons.homo)$base,
SIMPLIFY = FALSE)
p <- mapply(function(x,y)sum(x<NumericList(learned.msd.distr[y,]))/lengths(learned.msd.distr[y,]),
x= msd, y=elementMetadata(cons.homo)$base,
SIMPLIFY = FALSE)
corrected.homo <- as.numeric(sapply(p, function(x)names(which.max(x))))
# Safeguard1: if all p<threshold, then it will not be corrected
dunno <- sapply(p,function(x)all(x<threshold.p))
corrected.homo[dunno] <- width(cons.homo)[dunno]
# Safeguard2: Only lengthen the homopolymer regions
shortern <- corrected.homo<width(cons.homo)
corrected.homo[shortern] <- width(cons.homo)[shortern]
# Safeguard3: If the search region is exactly the same as the intitial homopolymer length, do nothing
search.length <- sapply(search.range, function(x)diff(x)+1)
no.change <- search.length == width(cons.homo)
corrected.homo[no.change] <- width(cons.homo)[no.change]
width(cons.rle)[width(cons.rle)>1] <- as.integer(corrected.homo)
fixed.cons <- rep(elementMetadata(cons.rle)$base, times = width(cons.rle))
fixed.cons <- paste(fixed.cons, collapse = "")
result <- list(degapped = gsub("-","",con.seq$seq) ,fixed = fixed.cons)
result
}
.get_aln_pos <- function(gapped){
vec <- strsplit(gapped, split="")[[1]]
aln.pos <- which(!grepl("-",vec))
aln.pos
}
.max_homo_length <- function(seq, base){
obs.homo.len <- homopolymerFinder(seq, base, report0 = TRUE, min.homo = 1)
max.len <- lapply(obs.homo.len, function(x)max(width(x)))
unlist(max.len)
}
.get_translation_table <- function(gapped.con, ref.seq){
no.gap.seq <- gsub("-","",gapped.con)
# Align the consensus sequence to the reference sequence
aln.ref <- pairwiseAlignment(DNAStringSet(no.gap.seq), ref.seq, gapOpening=5, gapExtension=1)
cons.aln <- strsplit(as.character(c(alignedSubject(aln.ref), alignedPattern(aln.ref))), split="")
cons.aln <- do.call(cbind.data.frame, cons.aln)
names(cons.aln) <- c("ref", "cons")
# Create a table for indexing the reference positino and the position in alignment matrix
cons.aln <- cbind.data.frame(cons.aln, ref.pos = NA, aln.pos=NA)
cons.aln$ref.pos[cons.aln$ref!="-"] <- 1:nchar(ref.seq)
cons.aln$aln.pos[cons.aln$cons!="-"] <- .get_aln_pos(gapped.con)
list(cons.aln,aln.ref)
}
.msd_calculator <- function(check, learned){
if(!is.list(check)){
check <- list(check)
}
df1 <- lapply(learned, data.frame)
df2 <- lapply(check, data.frame)
merged <- mapply(merge, x=df1, y=df2, all=TRUE, by.x=names(df1[[1]])[1],
by.y=names(df2[[1]])[1], SIMPLIFY = FALSE)
merged <- lapply(merged, function(x){x[is.na(x)]<-0; x})
msd <- sapply(merged, function(x)mean((x[,2]-x[,3])^2))
msd
}
.proportion_calculator <- function(vec){
table(vec)/length(vec)
}
<file_sep>/demultiplexer/ad_hoc_demultiplexer.R
library(stringr)
library(sarlacc)
demultiplex <- function(adap.stat, barcode, position=NULL){
search_region <- umiExtract(adap.stat, position=position)
aln.pid <- mclapply(barcode, internal_align, search_region=search_region, mc.cores=6L)
aln.pid <- do.call(cbind, aln.pid)
# replace all gapped alignment
aln.pid[is.nan(aln.pid)] <- 0
# Ambigurous alignment
sorted.pid <- t(apply(aln.pid, 1, sort, decreasing = TRUE, na.last=TRUE))
vague <- (sorted.pid[,1]-sorted.pid[,2])<0.05
# sufficient match
good.match <- sorted.pid[,1]>=0.7
# Choose final barcode
chosen.bc <- unlist(apply(aln.pid, 1, which.max))
chosen.bc[c(vague|!good.match)] <- NA
return(chosen.bc)
}
# Store parameter for alignment
internal_align <- function(search_region, x){
aln <- pairwiseAlignment(search_region, x, type="local-global", gapOpening=5, gapExtension=1)
nmatch(aln)/(str_count(subject(aln), "-")+nchar(x))
}
<file_sep>/homopolymerFixer/temp_consensus.R
nucleotides <- c("A","C","G","T")
QUALFUN <- function(alignments, qualities, min.coverage, gapped=TRUE) {
aln.mat <- do.call(rbind, strsplit(as.character(alignments), ""))
# Forming a quality matrix.
qual.mat <- matrix(NA_integer_, nrow(aln.mat), ncol(aln.mat))
for (i in seq_len(nrow(aln.mat))) {
current <- aln.mat[i,]
chosen <- which(current!="-")
qual.mat[i,chosen] <- qualities[[i]]
}
# Subsetting based on the minimum coverage.
keep1 <- colSums(aln.mat!="-")/nrow(aln.mat) >= min.coverage
aln.pos <- which(keep1)
aln.mat <- aln.mat[,keep1,drop=FALSE]
qual.mat <- qual.mat[,keep1,drop=FALSE]
# Running through the alignment matrix.
consensus <- character(ncol(aln.mat))
out.err <- numeric(ncol(aln.mat))
for (i in seq_len(ncol(aln.mat))) {
curcol <- aln.mat[,i]
keep2 <- curcol %in% nucleotides
curcol <- curcol[keep2]
curqual <- qual.mat[keep2,i]
correct <- log(1 - curqual)
incorrect <- log(curqual/3)
# Computing the probability of the current position being a particular base.
all.probs <- c(A=sum(correct[curcol=="A"]) + sum(incorrect[curcol!="A"]),
C=sum(correct[curcol=="C"]) + sum(incorrect[curcol!="C"]),
G=sum(correct[curcol=="G"]) + sum(incorrect[curcol!="G"]),
T=sum(correct[curcol=="T"]) + sum(incorrect[curcol!="T"]))
all.probs <- exp(all.probs)
all.probs <- all.probs/sum(all.probs)
chosen <- which.max(all.probs)
consensus[i] <- names(all.probs)[chosen]
out.err[i] <- log(sum(all.probs[-chosen])) # not using 1-chosen for numerical precision purposes.
}
if(gapped){
gapped.consensus <- rep("-",length(keep1))
gapped.consensus[keep1] <- consensus
consensus <- gapped.consensus
}
return(list(seq=paste(consensus, collapse=""), qual=out.err))
}
<file_sep>/homopolymerFixer/homopolymerFixer_test.R
library(ShortRead)
library(sarlacc)
#ERCC sequence
ERCC_fasta <- readFasta("ERCC92.fa")
names(ERCC_fasta@sread) <- ERCC_fasta@id
ERCC_fasta <- ERCC_fasta@sread
ref <- ERCC_fasta
# Remove polyA tail
vec <- strsplit(as.character(ref),split="")
polyA.len <- sapply(vec, function(x)tail(rle(x)$lengths,1))
ref <- subseq(ref, start=1, end=(lengths(ref)-polyA.len))
reads <- readRDS("no.polyA.ercc.rds")
# Separate reads into train and test set
set.seed(100)
train.set <- sample(seq_along(reads), floor(length(reads)/2))
test.set <- seq_along(reads)[-train.set]
train.reads <- reads[train.set]
test.reads <- reads[test.set]
train.reads <- lapply(names(ref),function(x)train.reads[grep(x, names(train.reads))])
test.reads <- lapply(names(ref),function(x)test.reads[grep(x, names(test.reads))])
names(test.reads) <- names(train.reads) <- names(ref)
homo.correction.check <- function(test){
test.match <- lapply(test, function(x)lapply(seq_along(x), function(y){
homopolymerMatcher(x[y])
}))
original.homo <- unlist(IRangesList(lapply(test.match,function(x)x[[1]])))
fixed.homo <- unlist(IRangesList(lapply(test.match,function(x)x[[2]])))
fixed.obs.len <- as.numeric(unlist(elementMetadata(fixed.homo)$observed))
original.obs.len <- as.numeric(unlist(elementMetadata(original.homo)$observed))
true.len <- width(original.homo)
fixed.tb <- aggregate(fixed.obs.len, list(true.len), table)
original.tb <- aggregate(original.obs.len, list(true.len), table)
fixed.mean <- aggregate(fixed.obs.len, list(true.len), mean)
original.mean <- aggregate(original.obs.len, list(true.len), mean)
fixed.diff <- aggregate((true.len-fixed.obs.len), list(true.len), table)
original.diff <- aggregate((true.len-original.obs.len), list(true.len), table)
fixed.mean.diff <- aggregate(abs(true.len-fixed.obs.len), list(true.len), mean)
original.mean.diff <- aggregate(abs(true.len-original.obs.len), list(true.len), mean)
mean.length <- cbind(original=original.mean, fixed=fixed.mean[,2, drop=FALSE])
diff.length <- cbind(original=original.diff, fixed=fixed.diff[,2, drop=FALSE],
original.mean=original.mean.diff[,2, drop=FALSE], fixed.mean=fixed.mean.diff[,2, drop=FALSE])
colnames(mean.length) <- c("homo", "original.length", "fixed.length")
colnames(diff.length) <- c("homo","original","fixed","original.mean.diff","fixed.mean.diff")
list(mean=mean.length,diff=diff.length)
}
# Validate in the test set
test.reads <- test.reads[lengths(test.reads)>50]
validate.test <- function(learned.distr , sample.size){
sample.size <- as.integer(sample.size)
rep.time <- 20
max.rep <- pmin(rep.time, floor(lengths(test.reads)/sample.size))
sampled.reads <- mapply(function(x,y,z)replicate(z,sample(x,y)),
x=test.reads, y=sample.size, z=max.rep, SIMPLIFY = FALSE)
ref.names <- rep(names(sampled.reads),lengths(sampled.reads))
sampled.reads <- unlist(sampled.reads, recursive = FALSE)
test.msa <- bplapply(sampled.reads, multiReadAlign, BPPARAM = MulticoreParam(30L))
base.test <- bpmapply(function(x,y){
fixed <- homopolymerFixer(learned.distr$base, x, threshold.p=0.5)
aln <- pairwiseAlignment(c(fixed$degapped, fixed$fixed),
ref[y],gapOpening=5, gapExtension=1)
}, x=test.msa, y=ref.names, BPPARAM=MulticoreParam(30L))
debase.test <- bpmapply(function(x,y){
fixed <- homopolymerFixer(learned.distr$debase, x, threshold.p=0.5)
aln <- pairwiseAlignment(c(fixed$degapped, fixed$fixed),
ref[y],gapOpening=5, gapExtension=1)
}, x=test.msa, y=ref.names, BPPARAM=MulticoreParam(30L))
list(base=base.test, debase=debase.test)
}
all.learned.distr <- readRDS("combined.learned.distr.rds")
all.size <- names(all.learned.distr)
system.time(all.validate <- lapply(all.size, function(x)validate.test(all.learned.distr[[x]], x)))<file_sep>/demultiplexer/demultiplex.R
# If the barcodes are on the adaptor2, the input barcode need to be reverse complmeneted.
reads <- readQualityScaledDNAStringSet("fastq/testset.fastq")
source("ad_hoc_demultiplexer.R")
set.seed(119)
reads <- sample(reads,50000)
adaptor1 <- "GTCTCGTGGGCTCGGAGATGTGTATAAGAGACAGNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNACTGGCCGTCGTTTTACATGGCGTAGCGGGTTCGAGCGCACCGCAGGGTATCCGGCTATTTTTTTTTTTTTTT"
adaptor2 <- "TCGTCGGCAGCGTCAGATGTGTATAAGAGACAGGG"
barcode <- read.csv("barcode.csv",header = TRUE,stringsAsFactors = FALSE)
barcode <- DNAStringSet(barcode$seq)
adap.aln <- adaptorAlign(reads, adaptor1 = adaptor1, adaptor2 = adaptor2, tolerance=300,BPPARAM = MulticoreParam(4L))
demulti <- demultiplex(adap.aln$adaptor1, barcode) | aac4a0dead504a1bcb4550dc3fa56bfaa73a5461 | [
"R"
] | 6 | R | ctl43/sarlacc_prototype | 8615088c9a9f07be87f54a949534c96adb193e8c | 3413785bdbf8722c19eb55fd4f5b1e18a5d4561a | |
refs/heads/master | <file_sep>#gdbus monitor -y -d org.freedesktop.login1 | grep LockedHint
#echo 'ready'
sleep 30
#echo 'done'
gdbus monitor -y -d org.freedesktop.login1 |\
grep --line-buffered -i "LockedHint" |\
sed -uE 's/.*LockedHint.*<(.*)>.*/\1/g' |\
(
while true; do
read X
# if echo $X | grep "true" &> /dev/null; then
if [ "$X" = "true" ]; then
echo "is anyone there?---"
#------------PUT A COMMAND TO RUN YOUR SCRIPT IN THE NEXT LINE (LEAVE THE "&" AT THE END)---------
HERE & #the "&" is for it to run in a different process so the program can Continue!
# elif echo $X | grep "false" &> /dev/null; then
elif [ "$X" = "false" ]; then
echo "hi!"
# sleep 1
#------------PUT THE SAME COMMAND YOU PLACED BEFORE BETWEEN THE QUOTES (to kill it when system ceases to be idle)----------
pkill -f "HERE"
# echo "x é $X"
else
echo "error"
fi
done
)
#from https://unix.stackexchange.com/questions/28181/run-script-on-screen-lock-unlock
#gdbus monitor -y -d org.freedesktop.login1 |\
# grep --line-buffered -i "LockedHint" |\
#dbus-monitor --session "type='signal',interface='com.ubuntu.Upstart0_6'" | \
#(
# while true; do
# read X
# if echo $X | grep "desktop-lock" &> /dev/null; then
# SCREEN_LOCKED;
# elif echo $X | grep "desktop-unlock" &> /dev/null; then
# SCREEN_UNLOCKED;
# fi
# done
#)
#gdbus monitor -y -d org.freedesktop.login1 | grep LockedHint
#(
# while true; do
# echo "hello?"
# done
#)
<file_sep># Run-program-while-idle-Linux
------
DESCRIPTION:
.sh super simple script to run a command when Lock Screen is activated (aka system's idle/ I'm afk) because I'm a programming noob. Only tested with a desktop environment (gnome) in Pop!_OS. It detects when the lock screen activates and runs the script, then when the lock screen is deactivated and the user is back, it "pkills" the script. Has a annoying bug that makes the script run when the computer starts which I don't know how to resolve... I'm a noob, so if anyone sees this and wants to give me some advice on how to make this work better, I'm all ears!
Made this according to this discussion:
https://unix.stackexchange.com/questions/28181/run-script-on-screen-lock-unlock
------
-----
USAGE:
Edit the "RunProgram_WhileIdle-linux" so it runs your script, just add the bash command that would run your script in the two places on the .sh file that say "HERE"
-----
| 4bf9d57d47ce7af517d36499ded05fe842f2c2d5 | [
"Markdown",
"Shell"
] | 2 | Shell | Yeshey/Run-program-while-idle-Linux | 7ac51e4f3e0fa63ea0fa659020908ed6010c4311 | c3101f9aec495bf2eeb08721cd5259bdef7cf458 | |
refs/heads/master | <repo_name>zhengzhirun/Finite-Element-Methods<file_sep>/Possion方程--C++(CVT自适应)/Possion.h
/*************************************************************************
> File Name: Possion.h
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年08月19日 星期日 22时04分12秒
************************************************************************/
#ifndef _POSSION_H
#define _POSSION_H
#include "Matrix.h"
double Possion(const std::string, const std::string, std::vector<double>& ,int); // 求解Possion方程
void nodesf2dat(const std::string, std::vector<Point>&, std::vector<int>&); // 读取nodes.dat文档
void trigsf2dat(const std::string, std::vector<std::vector<int>>&); // 读取trigs.dat文档
void writeTriangle(std::vector<Point>&, std::vector<std::vector<int>>&, std::vector<int>&,
const std::string);
#endif
<file_sep>/Possion方程--C++(CVT自适应)/Matrix.h
// 设置类的保护符
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <fstream>
#include <Eigen/Dense> // 线性代数库
#include <Eigen/Sparse> // 稀疏存储矩阵库,以及稀疏存储的线性方程组求解库
#include <Eigen/IterativeLinearSolvers> // 迭代法求解线性方程组的求解库
#include <unsupported/Eigen/IterativeSolvers>
class Point
{
friend std::ostream& operator<< (std::ostream&, const Point&);
friend std::istream& operator>> (std::istream&, Point&);
friend Point operator+ (const Point&, const Point&);
friend Point operator- (const Point&, const Point&);
friend Point midpoint(const Point&, const Point&);
friend double distance(const Point&, const Point&);
// 求三角形的质心,可以求加权质心
friend Point barycenter(const std::vector<Point>&, const double *);
friend double AREA(const Point&, const Point&, const Point&);
private:
double x[2];
public:
Point();
Point(const double*);
Point(const Point&);
Point(const double&, const double&);
Point& operator= (const Point&);
double& operator[] (int);
const double& operator[] (int) const;
double length() const;
Point& operator+= (const Point&);
Point& operator-= (const Point&);
Point& operator*= (const double&);
Point& operator/= (const double&);
};
class TmpEle
{
friend std::ostream& operator<< (std::ostream&, const TmpEle&);
private:
std::vector<Point> Pnt;
std::vector<Point> GaussPnt;
std::vector<double> GaussWeight;
public:
// 构造函数
TmpEle();
TmpEle(int);
void buildTE(int);
Point getPnt(int);
double getArea();
std::vector<Point> getGaussPnt();
std::vector<double> getGaussWeight();
// 标准单元到普通单元
Point Local_to_Global(const Point&, const std::vector<Point> &) const;
// 普通单元到标准单元
Point Global_to_Local(const Point&, const std::vector<Point> &) const;
// 标准单元到普通单元
std::vector<Point> Local_to_Global(const std::vector<Point> &,const std::vector<Point> & ) const;
// 普通单元到标准单元
std::vector<Point> Global_to_Local(const std::vector<Point>&, const std::vector<Point>&) const;
// 从标准单元到普通单元的雅克比矩阵
double Local_to_Global_jacobian(const Point&, const std::vector<Point>&) const;
// 从普通单元到标准单元的雅克比矩阵
double Global_to_Local_jacobian(const Point&, const std::vector<Point>&) const;
// 从标准单元到普通单元的雅克比矩阵
std::vector<double> Local_to_Global_jacobian(const std::vector<Point>&, const std::vector<Point>&) const;
// 从普通单元到标准单元的雅克比矩阵
std::vector<double> Global_to_Local_jacobian(const std::vector<Point>&, const std::vector<Point>&) const;
};
class Mesh
{
friend std::ostream& operator<< (std::ostream&, const Mesh&);
private:
std::vector<Point> Pnt; // 三角单元的点
std::vector<int> BndPnt; // 三角单元的边界点
std::vector<std::vector<int>> Ele; // 三角单元的边
public:
Mesh() = default; // 默认构造函数
void readData(const std::string&);
int getEleVtx(int , int);
std::vector<int> getEleVtx(int);
Point getPnt(int);
std::vector<Point> getPnt(std::vector<int>&);
std::vector<int> getBndPnt();
int n_element(); // 得到三角单元的数量
int n_point(); // 得到点的个数
int n_boundaryPoint(); // 得到边界点的个数
void neighbor(std::vector<std::vector<int>>&); // 单元邻居索引
};
class PDE
{
public:
// 偏微分方程的边界条件
double u_boundary(const Point&);
// 偏微分方程的右端项
double f(const Point&);
// 偏微分方程解析解
double u_exact(const Point&);
};
class Matrix
{
public:
// 数据结构
PDE pde;
Mesh mesh;
TmpEle tmpEle;
std::vector<double> u_h;
Matrix() = default;
Matrix(const std::string&, int);
// gauss-seidel迭代
void GaussSeidel(const std::vector<std::vector<double>>&,std::vector<double>&,
const std::vector<double>&);
// 利用Eigen库求解稀疏代数方程组
void SolveLinearASparse(const Eigen::SparseMatrix<double>&,std::vector<double>&,
const std::vector<double>&, int);
// 基函数的构造
void basisValue(const Point&, const std::vector<Point>&, std::vector<double>&);
void basisValue(const std::vector<Point>&, const std::vector<Point>&, std::vector<std::vector<double>>&);
// 梯度算子的计算
void basisGrad(const Point&, const std::vector<Point>&, std::vector<std::vector<double>>&);
void basisGrad(const std::vector<Point>&, const std::vector<Point>&,
std::vector<std::vector<std::vector<double>>>&);
// 单元刚度矩阵
void buildEleMatrix_RHS(int, std::vector<std::vector<double>>&, std::vector<double>&);
// 总刚度矩阵(稀疏存储)
void buildMatrix_RHS_Sparse(Eigen::SparseMatrix<double>&, std::vector<double>&);
// 稀疏矩阵的边界条件的处理
void DealBoundary_Sparse(Eigen::SparseMatrix<double>&, const std::vector<double>&, std::vector<double>&);
// 计算L2误差
double ComputerL2Error(const std::vector<double> &);
// 计算剖分上每一个单元上的梯度
void GradBasis(std::vector<std::vector<std::vector<double>>>&);
// 计算u_h的梯度
void Gradu(const std::vector<std::vector<std::vector<double>>>&,
const std::vector<double>&, std::vector<std::vector<double>>&);
// 三角单元上每一条边的向量
void eleVector(std::vector<std::vector<std::vector<double>>>&);
// 三角单元上每一条边的法向量
void normalVector(const std::vector<std::vector<std::vector<double>>>&,
std::vector<std::vector<std::vector<double>>>&);
// 三角单元的直径
double diameter(const std::vector<Point>&);
// residual type(误差指示子)
void Estimateresidual(std::vector<double>&,std::vector<double>&);
};
#endif
<file_sep>/Possion方程--C++(CVT自适应)/density.h
/*************************************************************************
> File Name: density.h
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年08月20日 星期一 22时37分18秒
************************************************************************/
#ifndef _DENSITY_H
#define _DENSITY_H
#include<fstream>
#include<vector>
#include<string>
#include "Matrix.h"
void density(const std::vector<Point>&, const std::vector<std::vector<int>>&, const std::vector<double>&);
#endif
<file_sep>/CVT网格控制-绘制误差/CVT_Error.cpp
/*************************************************************************
> File Name: CVT_Error.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年08月23日 星期四 17时13分50秒
************************************************************************/
#include "Possion.h"
int main()
{
// 网格初始化
system("./mesh_init -f square.poly -q 1 -a 0.01");
// 把初始网格信息写入文档中
std::vector<Point> node;
std::vector<std::vector<int>> ele;
std::vector<int> boundary_node;
writeTriangle(node,ele,boundary_node,"Trimesh_0.txt"); // 初始网格信息
std::vector<double> Error; // Error[0]为L2范误差,Error[1]为H1范误差
std::vector<std::vector<double>> Errors; // 存储每一次的误差
std::vector<double> eta;
Error = Possion("Trimesh_0.txt","Results.txt",eta,7);
// 记录点的个数
std::vector<int> nodes;
system("./dens_info");
Errors.push_back(Error);
nodes.push_back(node.size());
system("./mesh_opti -b 1");
// 文件处理
for (int i = 0; i != 200; ++i){
std::string filename = "Trimesh_";
filename = filename + std::to_string(i+1) + ".txt";
writeTriangle(node,ele,boundary_node,filename,i);
nodes.push_back(node.size());
std::cout << "i = " << i << std::endl;
Error = Possion(filename,"Results.txt",eta,7);
Errors.push_back(Error);
}
// 输出文档
std::ofstream out("Error.txt",std::ofstream::out);
for (decltype(Errors.size()) i = 0; i != Errors.size(); ++i)
out << i+1 << "\t" << Errors[i][0] << "\t\t" << Errors[i][1] << "\t\t" << nodes[i] << "\n";
out.close();
return 0;
}
<file_sep>/CVT网格控制-绘制误差/Makefile
all: CVT_Error
CVT_Error: CVT_Error.o Matrix.o Possion.o
g++ -std=c++0x -o CVT_Error CVT_Error.o Possion.o Matrix.o
CVT_Error.o: CVT_Error.cpp Possion.h
g++ -std=c++0x -c CVT_Error.cpp
Possion.o: Possion.cpp Possion.h
g++ -std=c++0x -c Possion.cpp
Matrix.o: Matrix.cpp Matrix.h
g++ -std=c++0x -c Matrix.cpp
<file_sep>/Heat方程-C++隐格式-非零边界/Mesh.h
/*************************************************************************
> File Name: Mesh.h
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时35分13秒
************************************************************************/
#ifndef MESH_H
#define MESH_H
#include "Point.h"
#include <fstream>
class Mesh
{
friend std::ostream& operator<< (std::ostream&, const Mesh&);
private:
std::vector<Point> Pnt; // 三角单元的点
std::vector<int> BndPnt; // 三角单元的边界点
std::vector<std::vector<int>> Ele; // 三角单元的边
public:
Mesh() = default; // 默认构造函数
void readData(const std::string&);
int getEleVtx(int , int);
std::vector<int> getEleVtx(int);
Point getPnt(int);
std::vector<Point> getPnt(std::vector<int>&);
std::vector<int> getBndPnt();
int n_element(); // 得到三角单元的数量
int n_point(); // 得到点的个数
int n_boundaryPoint(); // 得到边界点的个数
};
#endif
<file_sep>/Heat方程-C++隐格式/TmpEle.cpp
/*************************************************************************
> File Name: TmpEle.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时10分27秒
************************************************************************/
#include "TmpEle.h"
// 非成员函数
std::ostream& operator<< (std::ostream& os, const TmpEle& te)
{
for (auto i : te.Pnt)
os << i << '\n';
for (auto i : te.GaussPnt)
os << i << '\n';
for (auto i : te.GaussWeight)
os << i << '\n';
return os;
}
// 构造函数
TmpEle::TmpEle()
{
Pnt.resize(3);
Pnt[0][0]=0.0;
Pnt[0][1]=0.0;
Pnt[1][0]=1.0;
Pnt[1][1]=0.0;
Pnt[2][0]=0.0;
Pnt[2][1]=1.0;
GaussPnt.resize(7);
GaussWeight.resize(7);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.470142064105;
GaussPnt[2][0]=0.470142064105;
GaussPnt[3][0]=0.059715871790;
GaussPnt[4][0]=0.101286507323;
GaussPnt[5][0]=0.101286507323;
GaussPnt[6][0]=0.797426985353;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.470142064105;
GaussPnt[2][1]=0.059715871790;
GaussPnt[3][1]=0.470142064105;
GaussPnt[4][1]=0.101286507323;
GaussPnt[5][1]=0.797426985353;
GaussPnt[6][1]=0.101286507323;
GaussWeight[0]=0.225000000000;
GaussWeight[1]=0.132394152788;
GaussWeight[2]=0.132394152789;
GaussWeight[3]=0.132394152788;
GaussWeight[4]=0.125939180545;
GaussWeight[5]=0.125939180545;
GaussWeight[6]=0.125939180545;
}
TmpEle::TmpEle(int i)
{
Pnt.resize(3);
Pnt[0][0]=0.0;
Pnt[0][1]=0.0;
Pnt[1][0]=1.0;
Pnt[1][1]=0.0;
Pnt[2][0]=0.0;
Pnt[2][1]=1.0;
switch(i){
case 1:
GaussPnt.resize(1);
GaussWeight.resize(1);
GaussPnt[0][0]=0.3333333333333333;
GaussPnt[0][1]=0.3333333333333333;
GaussWeight[0]=1.0;
break;
case 2:
GaussPnt.resize(3);
GaussWeight.resize(3);
GaussPnt[0][0]=0.166666666667;
GaussPnt[1][0]=0.166666666667;
GaussPnt[2][0]=0.666666666667;
GaussPnt[0][1]=0.166666666667;
GaussPnt[1][1]=0.666666666667;
GaussPnt[2][1]=0.166666666667;
GaussWeight[0]=0.333333333333;
GaussWeight[1]=0.333333333334;
GaussWeight[2]=0.333333333333;
break;
case 3:
GaussPnt.resize(4);
GaussWeight.resize(4);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.200000000000;
GaussPnt[2][0]=0.200000000000;
GaussPnt[3][0]=0.600000000000;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.200000000000;
GaussPnt[2][1]=0.600000000000;
GaussPnt[3][1]=0.200000000000;
GaussWeight[0]=-0.562500000000;
GaussWeight[1]=0.520833333333;
GaussWeight[2]=0.520833333334;
GaussWeight[3]=0.520833333333;
break;
case 4:
GaussPnt.resize(6);
GaussWeight.resize(6);
GaussPnt[0][0]=0.445948490916;
GaussPnt[1][0]=0.445948490916;
GaussPnt[2][0]=0.108103018168;
GaussPnt[3][0]=0.091576213510;
GaussPnt[4][0]=0.091576213510;
GaussPnt[5][0]=0.816847572980;
GaussPnt[0][1]=0.445948490916;
GaussPnt[1][1]=0.108103018168;
GaussPnt[2][1]=0.445948490916;
GaussPnt[3][1]=0.091576213510;
GaussPnt[4][1]=0.816847572980;
GaussPnt[5][1]=0.091576213510;
GaussWeight[0]=0.223381589678;
GaussWeight[1]=0.223381589678;
GaussWeight[2]=0.223381589678;
GaussWeight[3]=0.109951743655;
GaussWeight[4]=0.109951743656;
GaussWeight[5]=0.109951743655;
break;
case 5:
GaussPnt.resize(7);
GaussWeight.resize(7);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.470142064105;
GaussPnt[2][0]=0.470142064105;
GaussPnt[3][0]=0.059715871790;
GaussPnt[4][0]=0.101286507323;
GaussPnt[5][0]=0.101286507323;
GaussPnt[6][0]=0.797426985353;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.470142064105;
GaussPnt[2][1]=0.059715871790;
GaussPnt[3][1]=0.470142064105;
GaussPnt[4][1]=0.101286507323;
GaussPnt[5][1]=0.797426985353;
GaussPnt[6][1]=0.101286507323;
GaussWeight[0]=0.225000000000;
GaussWeight[1]=0.132394152788;
GaussWeight[2]=0.132394152789;
GaussWeight[3]=0.132394152788;
GaussWeight[4]=0.125939180545;
GaussWeight[5]=0.125939180545;
GaussWeight[6]=0.125939180545;
break;
case 6:
GaussPnt.resize(12);
GaussWeight.resize(12);
GaussPnt[0][0]=0.249286745171;
GaussPnt[1][0]=0.249286745171;
GaussPnt[2][0]=0.501426509658;
GaussPnt[3][0]=0.063089014492;
GaussPnt[4][0]=0.063089014492;
GaussPnt[5][0]=0.873821971017;
GaussPnt[6][0]=0.310352451034;
GaussPnt[7][0]=0.636502499121;
GaussPnt[8][0]=0.053145049845;
GaussPnt[9][0]=0.636502499121;
GaussPnt[10][0]=0.310352451034;
GaussPnt[11][0]=0.053145049845;
GaussPnt[0][1]=0.249286745171;
GaussPnt[1][1]=0.501426509658;
GaussPnt[2][1]=0.249286745171;
GaussPnt[3][1]=0.063089014492;
GaussPnt[4][1]=0.873821971017;
GaussPnt[5][1]=0.063089014492;
GaussPnt[6][1]=0.636502499121;
GaussPnt[7][1]=0.053145049845;
GaussPnt[8][1]=0.310352451034;
GaussPnt[9][1]=0.310352451034;
GaussPnt[10][1]=0.053145049845;
GaussPnt[11][1]=0.636502499121;
GaussWeight[0]=0.116786275726;
GaussWeight[1]=0.116786275726;
GaussWeight[2]=0.116786275726;
GaussWeight[3]=0.050844906370;
GaussWeight[4]=0.050844906370;
GaussWeight[5]=0.050844906370;
GaussWeight[6]=0.082851075618;
GaussWeight[7]=0.082851075618;
GaussWeight[8]=0.082851075618;
GaussWeight[9]=0.082851075618;
GaussWeight[10]=0.082851075618;
GaussWeight[11]=0.082851075618;
break;
case 7:
GaussPnt.resize(13);
GaussWeight.resize(13);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.260345966079;
GaussPnt[2][0]=0.260345966079;
GaussPnt[3][0]=0.479308067842;
GaussPnt[4][0]=0.065130102902;
GaussPnt[5][0]=0.065130102902;
GaussPnt[6][0]=0.869739794196;
GaussPnt[7][0]=0.312865496005;
GaussPnt[8][0]=0.638444188570;
GaussPnt[9][0]=0.048690315425;
GaussPnt[10][0]=0.638444188570;
GaussPnt[11][0]=0.312865496005;
GaussPnt[12][0]=0.048690315425;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.260345966079;
GaussPnt[2][1]=0.479308067842;
GaussPnt[3][1]=0.260345966079;
GaussPnt[4][1]=0.065130102902;
GaussPnt[5][1]=0.869739794196;
GaussPnt[6][1]=0.065130102902;
GaussPnt[7][1]=0.638444188570;
GaussPnt[8][1]=0.048690315425;
GaussPnt[9][1]=0.312865496005;
GaussPnt[10][1]=0.312865496005;
GaussPnt[11][1]=0.048690315425;
GaussPnt[12][1]=0.638444188570;
GaussWeight[0]=-0.149570044468;
GaussWeight[1]=0.175615257433;
GaussWeight[2]=0.175615257433;
GaussWeight[3]=0.175615257433;
GaussWeight[4]=0.053347235609;
GaussWeight[5]=0.053347235609;
GaussWeight[6]=0.053347235609;
GaussWeight[7]=0.077113760890;
GaussWeight[8]=0.077113760890;
GaussWeight[9]=0.077113760890;
GaussWeight[10]=0.077113760890;
GaussWeight[11]=0.077113760890;
GaussWeight[12]=0.077113760890;
break;
case 10:
GaussPnt.resize(25);
GaussWeight.resize(25);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.485577633384;
GaussPnt[2][0]=0.485577633384;
GaussPnt[3][0]=0.028844733233;
GaussPnt[4][0]=0.109481575485;
GaussPnt[5][0]=0.109481575485;
GaussPnt[6][0]=0.781036849030;
GaussPnt[7][0]=0.307939838764;
GaussPnt[8][0]=0.550352941821;
GaussPnt[9][0]=0.141707219415;
GaussPnt[10][0]=0.550352941821;
GaussPnt[11][0]=0.307939838764;
GaussPnt[12][0]=0.141707219415;
GaussPnt[13][0]=0.246672560640;
GaussPnt[14][0]=0.728323904597;
GaussPnt[15][0]=0.025003534763;
GaussPnt[16][0]=0.728323904597;
GaussPnt[17][0]=0.246672560640;
GaussPnt[18][0]=0.025003534763;
GaussPnt[19][0]=0.066803251012;
GaussPnt[20][0]=0.923655933587;
GaussPnt[21][0]=0.009540815400;
GaussPnt[22][0]=0.923655933587;
GaussPnt[23][0]=0.066803251012;
GaussPnt[24][0]=0.009540815400;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.485577633384;
GaussPnt[2][1]=0.028844733233;
GaussPnt[3][1]=0.485577633384;
GaussPnt[4][1]=0.109481575485;
GaussPnt[5][1]=0.781036849030;
GaussPnt[6][1]=0.109481575485;
GaussPnt[7][1]=0.550352941821;
GaussPnt[8][1]=0.141707219415;
GaussPnt[9][1]=0.307939838764;
GaussPnt[10][1]=0.307939838764;
GaussPnt[11][1]=0.141707219415;
GaussPnt[12][1]=0.550352941821;
GaussPnt[13][1]=0.728323904597;
GaussPnt[14][1]=0.025003534763;
GaussPnt[15][1]=0.246672560640;
GaussPnt[16][1]=0.246672560640;
GaussPnt[17][1]=0.025003534763;
GaussPnt[18][1]=0.728323904597;
GaussPnt[19][1]=0.923655933587;
GaussPnt[20][1]=0.009540815400;
GaussPnt[21][1]=0.066803251012;
GaussPnt[22][1]=0.066803251012;
GaussPnt[23][1]=0.009540815400;
GaussPnt[24][1]=0.923655933587;
GaussWeight[0]=0.090817990383;
GaussWeight[1]=0.036725957756;
GaussWeight[2]=0.036725957756;
GaussWeight[3]=0.036725957756;
GaussWeight[4]=0.045321059436;
GaussWeight[5]=0.045321059436;
GaussWeight[6]=0.045321059436;
GaussWeight[7]=0.072757916845;
GaussWeight[8]=0.072757916845;
GaussWeight[9]=0.072757916845;
GaussWeight[10]=0.072757916845;
GaussWeight[11]=0.072757916845;
GaussWeight[12]=0.072757916845;
GaussWeight[13]=0.028327242531;
GaussWeight[14]=0.028327242531;
GaussWeight[15]=0.028327242531;
GaussWeight[16]=0.028327242531;
GaussWeight[17]=0.028327242531;
GaussWeight[18]=0.028327242531;
GaussWeight[19]=0.009421666964;
GaussWeight[20]=0.009421666964;
GaussWeight[21]=0.009421666964;
GaussWeight[22]=0.009421666964;
GaussWeight[23]=0.009421666964;
GaussWeight[24]=0.009421666964;
break;
case 12:
GaussPnt.resize(33);
GaussWeight.resize(33);
GaussPnt[0][0]=0.488217389774;
GaussPnt[1][0]=0.488217389774;
GaussPnt[2][0]=0.023565220452;
GaussPnt[3][0]=0.439724392294;
GaussPnt[4][0]=0.439724392294;
GaussPnt[5][0]=0.120551215411;
GaussPnt[6][0]=0.271210385012;
GaussPnt[7][0]=0.271210385012;
GaussPnt[8][0]=0.457579229976;
GaussPnt[9][0]=0.127576145542;
GaussPnt[10][0]=0.127576145542;
GaussPnt[11][0]=0.744847708917;
GaussPnt[12][0]=0.021317350453;
GaussPnt[13][0]=0.021317350453;
GaussPnt[14][0]=0.957365299094;
GaussPnt[15][0]=0.275713269686;
GaussPnt[16][0]=0.608943235780;
GaussPnt[17][0]=0.115343494535;
GaussPnt[18][0]=0.608943235780;
GaussPnt[19][0]=0.275713269686;
GaussPnt[20][0]=0.115343494535;
GaussPnt[21][0]=0.281325580990;
GaussPnt[22][0]=0.695836086788;
GaussPnt[23][0]=0.022838332222;
GaussPnt[24][0]=0.695836086788;
GaussPnt[25][0]=0.281325580990;
GaussPnt[26][0]=0.022838332222;
GaussPnt[27][0]=0.116251915908;
GaussPnt[28][0]=0.858014033544;
GaussPnt[29][0]=0.025734050548;
GaussPnt[30][0]=0.858014033544;
GaussPnt[31][0]=0.116251915908;
GaussPnt[32][0]=0.025734050548;
GaussPnt[0][1]=0.488217389774;
GaussPnt[1][1]=0.023565220452;
GaussPnt[2][1]=0.488217389774;
GaussPnt[3][1]=0.439724392294;
GaussPnt[4][1]=0.120551215411;
GaussPnt[5][1]=0.439724392294;
GaussPnt[6][1]=0.271210385012;
GaussPnt[7][1]=0.457579229976;
GaussPnt[8][1]=0.271210385012;
GaussPnt[9][1]=0.127576145542;
GaussPnt[10][1]=0.744847708917;
GaussPnt[11][1]=0.127576145542;
GaussPnt[12][1]=0.021317350453;
GaussPnt[13][1]=0.957365299094;
GaussPnt[14][1]=0.021317350453;
GaussPnt[15][1]=0.608943235780;
GaussPnt[16][1]=0.115343494535;
GaussPnt[17][1]=0.275713269686;
GaussPnt[18][1]=0.275713269686;
GaussPnt[19][1]=0.115343494535;
GaussPnt[20][1]=0.608943235780;
GaussPnt[21][1]=0.695836086788;
GaussPnt[22][1]=0.022838332222;
GaussPnt[23][1]=0.281325580990;
GaussPnt[24][1]=0.281325580990;
GaussPnt[25][1]=0.022838332222;
GaussPnt[26][1]=0.695836086788;
GaussPnt[27][1]=0.858014033544;
GaussPnt[28][1]=0.025734050548;
GaussPnt[29][1]=0.116251915908;
GaussPnt[30][1]=0.116251915908;
GaussPnt[31][1]=0.025734050548;
GaussPnt[32][1]=0.858014033544;
GaussWeight[0]=0.025731066440;
GaussWeight[1]=0.025731066440;
GaussWeight[2]=0.025731066440;
GaussWeight[3]=0.043692544538;
GaussWeight[4]=0.043692544538;
GaussWeight[5]=0.043692544538;
GaussWeight[6]=0.062858224218;
GaussWeight[7]=0.062858224218;
GaussWeight[8]=0.062858224218;
GaussWeight[9]=0.034796112931;
GaussWeight[10]=0.034796112931;
GaussWeight[11]=0.034796112931;
GaussWeight[12]=0.006166261052;
GaussWeight[13]=0.006166261052;
GaussWeight[14]=0.006166261052;
GaussWeight[15]=0.040371557766;
GaussWeight[16]=0.040371557766;
GaussWeight[17]=0.040371557766;
GaussWeight[18]=0.040371557766;
GaussWeight[19]=0.040371557766;
GaussWeight[20]=0.040371557766;
GaussWeight[21]=0.022356773202;
GaussWeight[22]=0.022356773202;
GaussWeight[23]=0.022356773202;
GaussWeight[24]=0.022356773202;
GaussWeight[25]=0.022356773202;
GaussWeight[26]=0.022356773202;
GaussWeight[27]=0.017316231109;
GaussWeight[28]=0.017316231109;
GaussWeight[29]=0.017316231109;
GaussWeight[30]=0.017316231109;
GaussWeight[31]=0.017316231109;
GaussWeight[32]=0.017316231109;
break;
default:
std::cout<<"There are no Gauss quadrature points with accuracy of "<<i<<"-th order"<<std::endl;
}
}
// 成员函数
void TmpEle::buildTE(int i)
{
TmpEle tmpEle(i);
for (auto x : tmpEle.Pnt)
Pnt.push_back(x);
for (auto x : tmpEle.GaussPnt)
GaussPnt.push_back(x);
for (auto x : tmpEle.GaussWeight)
GaussWeight.push_back(x);
}
Point TmpEle::getPnt(int i)
{
return Pnt[i];
}
std::vector<Point> TmpEle::getGaussPnt()
{
return GaussPnt;
}
std::vector<double> TmpEle::getGaussWeight()
{
return GaussWeight;
}
double TmpEle::getArea()
{
return 0.5*((Pnt[1][0] - Pnt[0][0]) * (Pnt[2][1] - Pnt[0][1])
- (Pnt[1][1] - Pnt[0][1]) * (Pnt[2][0] - Pnt[0][0]));
}
// 标准单元到普通单元
Point TmpEle::Local_to_Global(const Point & lp, const std::vector<Point> & gv) const
{
Point gp;
double lambda[3];
double area = AREA(Pnt[0], Pnt[1], Pnt[2]);
lambda[0] = AREA(lp, Pnt[1], Pnt[2]) / area;
lambda[1] = AREA(lp, Pnt[2], Pnt[0]) / area;
lambda[2] = AREA(lp, Pnt[0], Pnt[1]) / area;
gp[0] = lambda[0] * gv[0][0] + lambda[1] * gv[1][0] + lambda[2] * gv[2][0];
gp[1] = lambda[0] * gv[0][1] + lambda[1] * gv[1][1] + lambda[2] * gv[2][1];
return gp;
}
// 普通单元到标准单元
Point TmpEle::Global_to_Local(const Point& gp, const std::vector<Point>& gv) const
{
Point lp;
double area = AREA(gv[0],gv[1],gv[2]);
lp[0] = ((gv[2][1] - gv[0][1]) * (gp[0] - gv[0][0]) -
(gv[2][0] - gv[0][0]) * (gp[1] - gv[0][1])) / (2 * area);
lp[1] = (-(gv[1][1] - gv[0][1]) * (gp[0] - gv[0][0]) +
(gv[1][0] - gv[0][0]) * (gp[1] - gv[0][1])) / (2 * area);
return lp;
}
// 标准单元到普通单元
std::vector<Point> TmpEle::Local_to_Global(const std::vector<Point>& lp, const std::vector<Point> & gv) const
{
std::vector<Point> gp(lp.size());
double area = AREA(Pnt[0], Pnt[1], Pnt[2]);
for(int i=0; i<gp.size(); i++){
double lambda[3];
lambda[0] = AREA(lp[i], Pnt[1], Pnt[2]) / area;
lambda[1] = AREA(lp[i], Pnt[2], Pnt[0]) / area;
lambda[2] = AREA(lp[i], Pnt[0], Pnt[1]) / area;
gp[i][0] = lambda[0] * gv[0][0] + lambda[1] * gv[1][0] + lambda[2] * gv[2][0];
gp[i][1] = lambda[0] * gv[0][1] + lambda[1] * gv[1][1] + lambda[2] * gv[2][1];
}
return gp;
}
// 普通单元到标准单元
std::vector<Point> TmpEle::Global_to_Local(const std::vector<Point>& gp,
const std::vector<Point>& gv) const
{
std::vector<Point> lp;
double area = AREA(gv[0],gv[1],gv[2]);
for (auto point : gp){
Point p;
p[0] = ((gv[2][1] - gv[0][1]) * (point[0] - gv[0][0]) -
(gv[2][0] - gv[0][0]) * (point[1] - gv[0][1])) / (2 * area);
p[1] = (-(gv[1][1] - gv[0][1]) * (point[0] - gv[0][0]) +
(gv[1][0] - gv[0][0]) * (point[1] - gv[0][1])) / (2 * area);
lp.push_back(p);
}
return lp;
}
// 从标准单元到普通单元的雅克比矩阵
double TmpEle::Local_to_Global_jacobian(const Point& lp, const std::vector<Point>& gv) const
{
// lp只是提供维度
double jacobian = AREA(gv[0],gv[1],gv[2]) / AREA(Pnt[0], Pnt[1], Pnt[2]);
return jacobian;
}
// 从普通单元到标准单元的雅克比矩阵
double TmpEle::Global_to_Local_jacobian(const Point& lp, const std::vector<Point>& gv) const
{
// lp只是提供维度
double jacobian = AREA(Pnt[0],Pnt[1],Pnt[2]) / AREA(gv[0],gv[1],gv[2]);
return jacobian;
}
// 从标准单元到普通单元的雅克比矩阵
std::vector<double> TmpEle::Local_to_Global_jacobian(const std::vector<Point>& lp, const std::vector<Point>& gv) const
{
std::vector<double> gj(lp.size());
double larea = AREA(Pnt[0], Pnt[1], Pnt[2]);
double garea = AREA(gv[0], gv[1], gv[2]);
for (int i = 0; i < gj.size(); i++){
gj[i] = garea / larea;
}
return gj;
}
// 从普通单元到标准单元的雅克比矩阵
std::vector<double> TmpEle::Global_to_Local_jacobian(const std::vector<Point>& lp, const std::vector<Point>& gv) const
{
std::vector<double> gj(lp.size());
double larea = AREA(Pnt[0], Pnt[1], Pnt[2]);
double garea = AREA(gv[0], gv[1], gv[2]);
for (int i = 0; i < gj.size(); i++){
gj[i] = larea / garea;
}
return gj;
}
<file_sep>/Heat方程-C++显格式/TmpEle.h
/*************************************************************************
> File Name: TmpEle.h
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时06分26秒
************************************************************************/
#ifndef TMPELE_H
#define TMPELE_H
#include "Point.h"
class TmpEle
{
friend std::ostream& operator<< (std::ostream&, const TmpEle&);
private:
std::vector<Point> Pnt;
std::vector<Point> GaussPnt;
std::vector<double> GaussWeight;
public:
// 构造函数
TmpEle();
TmpEle(int);
void buildTE(int);
Point getPnt(int);
double getArea();
std::vector<Point> getGaussPnt();
std::vector<double> getGaussWeight();
// 标准单元到普通单元
Point Local_to_Global(const Point&, const std::vector<Point> &) const;
// 普通单元到标准单元
Point Global_to_Local(const Point&, const std::vector<Point> &) const;
// 标准单元到普通单元
std::vector<Point> Local_to_Global(const std::vector<Point> &,const std::vector<Point> & ) const;
// 普通单元到标准单元
std::vector<Point> Global_to_Local(const std::vector<Point>&, const std::vector<Point>&) const;
// 从标准单元到普通单元的雅克比矩阵
double Local_to_Global_jacobian(const Point&, const std::vector<Point>&) const;
// 从普通单元到标准单元的雅克比矩阵
double Global_to_Local_jacobian(const Point&, const std::vector<Point>&) const;
// 从标准单元到普通单元的雅克比矩阵
std::vector<double> Local_to_Global_jacobian(const std::vector<Point>&, const std::vector<Point>&) const;
// 从普通单元到标准单元的雅克比矩阵
std::vector<double> Global_to_Local_jacobian(const std::vector<Point>&, const std::vector<Point>&) const;
};
#endif
<file_sep>/Heat方程-C++显格式/Point.cpp
/*************************************************************************
> File Name: Point.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时01分06秒
************************************************************************/
#include "Point.h"
//非成员接口函数
std::ostream& operator<< (std::ostream& os, const Point& p)
{
for (auto i : p.x)
os << i << '\t';
return os;
}
std::istream& operator>> (std::istream& is, Point& p)
{
for (auto &i : p.x)
is >> i;
return is;
}
Point operator+ (const Point& p1, const Point& p2)
{
Point p;
for (int i = 0; i != 2; ++i)
p.x[i] = p1.x[i] + p2.x[i];
return p;
}
Point operator- (const Point& p1, const Point& p2)
{
Point p;
for (int i = 0; i != 2; ++i)
p.x[i] = p1.x[i] - p2.x[i];
return p;
}
Point midpoint(const Point& p1, const Point& p2)
{
Point p;
for (int i = 0; i != 2; ++i)
p.x[i] = (p1.x[i] + p2.x[i]) / 2.0;
return p;
}
double distance(const Point& p1, const Point& p2)
{
double p = 0.;
for (int i = 0; i != 2; ++i)
p += (p1.x[i] - p2.x[i]) * (p1.x[i] - p2.x[i]);
return sqrt(p);
}
Point barycenter(const std::vector<Point>& p, const double * w)
{
double bc[2] = {0,0};
int k = p.size();
if (w == NULL){
for (int i = 0; i < k; i++){
bc[0] += p[i][0];
bc[1] += p[i][1];
}
bc[0] /= k;
bc[1] /= k;
}
else{
double sw = 0;
for (int i = 0; i < k; i++) sw += w[i];
for (int i = 0; i < k; i++){
bc[0] += w[i] * p[i][0];
bc[1] += w[i] * p[i][1];
}
bc[0] /= sw;
bc[1] /= sw;
}
return bc;
}
double AREA(const Point& p1, const Point& p2, const Point& p3)
{
double area = ((p2.x[0] - p1.x[0]) * (p3.x[1] - p1.x[1]) -
(p3.x[0] - p1.x[0]) * (p2.x[1] - p1.x[1])) * 0.5;
if (area < 0)
area = -area;
return area;
}
// 构造函数
Point::Point()
{
for (int i = 0; i != 2; ++i)
x[i] = 0;
}
Point::Point(const double* data)
{
for (int i = 0; i != 2; ++i)
x[i] = data[i];
}
Point::Point(const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] = p.x[i];
}
Point::Point(const double& v1, const double& v2)
{
x[0] = v1;
x[1] = v2;
}
// 成员函数
Point& Point::operator= (const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] = p.x[i];
return *this;
}
double& Point::operator[] (int i)
{
return x[i];
}
const double& Point::operator[] (int i) const
{
return x[i];
}
double Point::length() const
{
double v = 0.0;
for (auto i : x)
v += i * i;
return sqrt(v);
}
Point& Point::operator+= (const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] += p.x[i];
return *this;
}
Point& Point::operator-= (const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] -= p.x[i];
return *this;
}
Point& Point::operator*= (const double& s)
{
for (auto &i : x)
i *= s;
return *this;
}
Point& Point::operator/= (const double& s)
{
for (auto &i : x)
i /= s;
return *this;
}
<file_sep>/README.md
# Finite element algorithm
Matlab;C++
<file_sep>/Heat方程-C++隐格式-非零边界/PDE.h
/*************************************************************************
> File Name: PDE.h
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时42分05秒
************************************************************************/
#ifndef PDE_H
#define PDE_H
#include "Point.h"
const double Pi = 4.0 * atan(1.0);
class PDE
{
public:
// 偏微分方程的边界条件(第一类边界条件)
double u_boundary(const Point &, double);
// 偏微分方程的右端项
double f(const Point &, double);
// 偏微分方程解析解
double u_exact(const Point&, double);
// 偏微分方程解析解的梯度
std::vector<double> u_exact_grad(const Point &, double);
};
#endif
<file_sep>/Possion方程--C++(CVT自适应)/Matrix.cpp
#include "Matrix.h"
#define PI (4.0*atan(1.0))
////////////////////////////////////////////////////////////////////////////////
// 类Point
////////////////////////////////////////////////////////////////////////////////
//非成员接口函数
std::ostream& operator<< (std::ostream& os, const Point& p)
{
for (auto i : p.x)
os << i << '\t';
return os;
}
std::istream& operator>> (std::istream& is, Point& p)
{
for (auto &i : p.x)
is >> i;
return is;
}
Point operator+ (const Point& p1, const Point& p2)
{
Point p;
for (int i = 0; i != 2; ++i)
p.x[i] = p1.x[i] + p2.x[i];
return p;
}
Point operator- (const Point& p1, const Point& p2)
{
Point p;
for (int i = 0; i != 2; ++i)
p.x[i] = p1.x[i] - p2.x[i];
return p;
}
Point midpoint(const Point& p1, const Point& p2)
{
Point p;
for (int i = 0; i != 2; ++i)
p.x[i] = (p1.x[i] + p2.x[i]) / 2.0;
return p;
}
double distance(const Point& p1, const Point& p2)
{
double p = 0.;
for (int i = 0; i != 2; ++i)
p += (p1.x[i] - p2.x[i]) * (p1.x[i] - p2.x[i]);
return sqrt(p);
}
Point barycenter(const std::vector<Point>& p, const double * w)
{
double bc[2] = {0,0};
int k = p.size();
if (w == NULL){
for (int i = 0; i < k; i++){
bc[0] += p[i][0];
bc[1] += p[i][1];
}
bc[0] /= k;
bc[1] /= k;
}
else{
double sw = 0;
for (int i = 0; i < k; i++) sw += w[i];
for (int i = 0; i < k; i++){
bc[0] += w[i] * p[i][0];
bc[1] += w[i] * p[i][1];
}
bc[0] /= sw;
bc[1] /= sw;
}
return bc;
}
double AREA(const Point& p1, const Point& p2, const Point& p3)
{
double area = ((p2.x[0] - p1.x[0]) * (p3.x[1] - p1.x[1]) -
(p3.x[0] - p1.x[0]) * (p2.x[1] - p1.x[1])) * 0.5;
if (area < 0)
area = -area;
return area;
}
// 构造函数
Point::Point()
{
for (int i = 0; i != 2; ++i)
x[i] = 0;
}
Point::Point(const double* data)
{
for (int i = 0; i != 2; ++i)
x[i] = data[i];
}
Point::Point(const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] = p.x[i];
}
Point::Point(const double& v1, const double& v2)
{
x[0] = v1;
x[1] = v2;
}
// 成员函数
Point& Point::operator= (const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] = p.x[i];
return *this;
}
double& Point::operator[] (int i)
{
return x[i];
}
const double& Point::operator[] (int i) const
{
return x[i];
}
double Point::length() const
{
double v = 0.0;
for (auto i : x)
v += i * i;
return sqrt(v);
}
Point& Point::operator+= (const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] += p.x[i];
return *this;
}
Point& Point::operator-= (const Point& p)
{
for (int i = 0; i != 2; ++i)
x[i] -= p.x[i];
return *this;
}
Point& Point::operator*= (const double& s)
{
for (auto &i : x)
i *= s;
return *this;
}
Point& Point::operator/= (const double& s)
{
for (auto &i : x)
i /= s;
return *this;
}
////////////////////////////////////////////////////////////////////////////////
//类TmpEle
////////////////////////////////////////////////////////////////////////////////
// 非成员函数
std::ostream& operator<< (std::ostream& os, const TmpEle& te)
{
for (auto i : te.Pnt)
os << i << '\n';
for (auto i : te.GaussPnt)
os << i << '\n';
for (auto i : te.GaussWeight)
os << i << '\n';
return os;
}
// 构造函数
TmpEle::TmpEle()
{
Pnt.resize(3);
Pnt[0][0]=0.0;
Pnt[0][1]=0.0;
Pnt[1][0]=1.0;
Pnt[1][1]=0.0;
Pnt[2][0]=0.0;
Pnt[2][1]=1.0;
GaussPnt.resize(7);
GaussWeight.resize(7);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.470142064105;
GaussPnt[2][0]=0.470142064105;
GaussPnt[3][0]=0.059715871790;
GaussPnt[4][0]=0.101286507323;
GaussPnt[5][0]=0.101286507323;
GaussPnt[6][0]=0.797426985353;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.470142064105;
GaussPnt[2][1]=0.059715871790;
GaussPnt[3][1]=0.470142064105;
GaussPnt[4][1]=0.101286507323;
GaussPnt[5][1]=0.797426985353;
GaussPnt[6][1]=0.101286507323;
GaussWeight[0]=0.225000000000;
GaussWeight[1]=0.132394152788;
GaussWeight[2]=0.132394152789;
GaussWeight[3]=0.132394152788;
GaussWeight[4]=0.125939180545;
GaussWeight[5]=0.125939180545;
GaussWeight[6]=0.125939180545;
}
TmpEle::TmpEle(int i)
{
Pnt.resize(3);
Pnt[0][0]=0.0;
Pnt[0][1]=0.0;
Pnt[1][0]=1.0;
Pnt[1][1]=0.0;
Pnt[2][0]=0.0;
Pnt[2][1]=1.0;
switch(i){
case 1:
GaussPnt.resize(1);
GaussWeight.resize(1);
GaussPnt[0][0]=0.3333333333333333;
GaussPnt[0][1]=0.3333333333333333;
GaussWeight[0]=1.0;
break;
case 2:
GaussPnt.resize(3);
GaussWeight.resize(3);
GaussPnt[0][0]=0.166666666667;
GaussPnt[1][0]=0.166666666667;
GaussPnt[2][0]=0.666666666667;
GaussPnt[0][1]=0.166666666667;
GaussPnt[1][1]=0.666666666667;
GaussPnt[2][1]=0.166666666667;
GaussWeight[0]=0.333333333333;
GaussWeight[1]=0.333333333334;
GaussWeight[2]=0.333333333333;
break;
case 3:
GaussPnt.resize(4);
GaussWeight.resize(4);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.200000000000;
GaussPnt[2][0]=0.200000000000;
GaussPnt[3][0]=0.600000000000;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.200000000000;
GaussPnt[2][1]=0.600000000000;
GaussPnt[3][1]=0.200000000000;
GaussWeight[0]=-0.562500000000;
GaussWeight[1]=0.520833333333;
GaussWeight[2]=0.520833333334;
GaussWeight[3]=0.520833333333;
break;
case 4:
GaussPnt.resize(6);
GaussWeight.resize(6);
GaussPnt[0][0]=0.445948490916;
GaussPnt[1][0]=0.445948490916;
GaussPnt[2][0]=0.108103018168;
GaussPnt[3][0]=0.091576213510;
GaussPnt[4][0]=0.091576213510;
GaussPnt[5][0]=0.816847572980;
GaussPnt[0][1]=0.445948490916;
GaussPnt[1][1]=0.108103018168;
GaussPnt[2][1]=0.445948490916;
GaussPnt[3][1]=0.091576213510;
GaussPnt[4][1]=0.816847572980;
GaussPnt[5][1]=0.091576213510;
GaussWeight[0]=0.223381589678;
GaussWeight[1]=0.223381589678;
GaussWeight[2]=0.223381589678;
GaussWeight[3]=0.109951743655;
GaussWeight[4]=0.109951743656;
GaussWeight[5]=0.109951743655;
break;
case 5:
GaussPnt.resize(7);
GaussWeight.resize(7);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.470142064105;
GaussPnt[2][0]=0.470142064105;
GaussPnt[3][0]=0.059715871790;
GaussPnt[4][0]=0.101286507323;
GaussPnt[5][0]=0.101286507323;
GaussPnt[6][0]=0.797426985353;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.470142064105;
GaussPnt[2][1]=0.059715871790;
GaussPnt[3][1]=0.470142064105;
GaussPnt[4][1]=0.101286507323;
GaussPnt[5][1]=0.797426985353;
GaussPnt[6][1]=0.101286507323;
GaussWeight[0]=0.225000000000;
GaussWeight[1]=0.132394152788;
GaussWeight[2]=0.132394152789;
GaussWeight[3]=0.132394152788;
GaussWeight[4]=0.125939180545;
GaussWeight[5]=0.125939180545;
GaussWeight[6]=0.125939180545;
break;
case 6:
GaussPnt.resize(12);
GaussWeight.resize(12);
GaussPnt[0][0]=0.249286745171;
GaussPnt[1][0]=0.249286745171;
GaussPnt[2][0]=0.501426509658;
GaussPnt[3][0]=0.063089014492;
GaussPnt[4][0]=0.063089014492;
GaussPnt[5][0]=0.873821971017;
GaussPnt[6][0]=0.310352451034;
GaussPnt[7][0]=0.636502499121;
GaussPnt[8][0]=0.053145049845;
GaussPnt[9][0]=0.636502499121;
GaussPnt[10][0]=0.310352451034;
GaussPnt[11][0]=0.053145049845;
GaussPnt[0][1]=0.249286745171;
GaussPnt[1][1]=0.501426509658;
GaussPnt[2][1]=0.249286745171;
GaussPnt[3][1]=0.063089014492;
GaussPnt[4][1]=0.873821971017;
GaussPnt[5][1]=0.063089014492;
GaussPnt[6][1]=0.636502499121;
GaussPnt[7][1]=0.053145049845;
GaussPnt[8][1]=0.310352451034;
GaussPnt[9][1]=0.310352451034;
GaussPnt[10][1]=0.053145049845;
GaussPnt[11][1]=0.636502499121;
GaussWeight[0]=0.116786275726;
GaussWeight[1]=0.116786275726;
GaussWeight[2]=0.116786275726;
GaussWeight[3]=0.050844906370;
GaussWeight[4]=0.050844906370;
GaussWeight[5]=0.050844906370;
GaussWeight[6]=0.082851075618;
GaussWeight[7]=0.082851075618;
GaussWeight[8]=0.082851075618;
GaussWeight[9]=0.082851075618;
GaussWeight[10]=0.082851075618;
GaussWeight[11]=0.082851075618;
break;
case 7:
GaussPnt.resize(13);
GaussWeight.resize(13);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.260345966079;
GaussPnt[2][0]=0.260345966079;
GaussPnt[3][0]=0.479308067842;
GaussPnt[4][0]=0.065130102902;
GaussPnt[5][0]=0.065130102902;
GaussPnt[6][0]=0.869739794196;
GaussPnt[7][0]=0.312865496005;
GaussPnt[8][0]=0.638444188570;
GaussPnt[9][0]=0.048690315425;
GaussPnt[10][0]=0.638444188570;
GaussPnt[11][0]=0.312865496005;
GaussPnt[12][0]=0.048690315425;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.260345966079;
GaussPnt[2][1]=0.479308067842;
GaussPnt[3][1]=0.260345966079;
GaussPnt[4][1]=0.065130102902;
GaussPnt[5][1]=0.869739794196;
GaussPnt[6][1]=0.065130102902;
GaussPnt[7][1]=0.638444188570;
GaussPnt[8][1]=0.048690315425;
GaussPnt[9][1]=0.312865496005;
GaussPnt[10][1]=0.312865496005;
GaussPnt[11][1]=0.048690315425;
GaussPnt[12][1]=0.638444188570;
GaussWeight[0]=-0.149570044468;
GaussWeight[1]=0.175615257433;
GaussWeight[2]=0.175615257433;
GaussWeight[3]=0.175615257433;
GaussWeight[4]=0.053347235609;
GaussWeight[5]=0.053347235609;
GaussWeight[6]=0.053347235609;
GaussWeight[7]=0.077113760890;
GaussWeight[8]=0.077113760890;
GaussWeight[9]=0.077113760890;
GaussWeight[10]=0.077113760890;
GaussWeight[11]=0.077113760890;
GaussWeight[12]=0.077113760890;
break;
case 10:
GaussPnt.resize(25);
GaussWeight.resize(25);
GaussPnt[0][0]=0.333333333333;
GaussPnt[1][0]=0.485577633384;
GaussPnt[2][0]=0.485577633384;
GaussPnt[3][0]=0.028844733233;
GaussPnt[4][0]=0.109481575485;
GaussPnt[5][0]=0.109481575485;
GaussPnt[6][0]=0.781036849030;
GaussPnt[7][0]=0.307939838764;
GaussPnt[8][0]=0.550352941821;
GaussPnt[9][0]=0.141707219415;
GaussPnt[10][0]=0.550352941821;
GaussPnt[11][0]=0.307939838764;
GaussPnt[12][0]=0.141707219415;
GaussPnt[13][0]=0.246672560640;
GaussPnt[14][0]=0.728323904597;
GaussPnt[15][0]=0.025003534763;
GaussPnt[16][0]=0.728323904597;
GaussPnt[17][0]=0.246672560640;
GaussPnt[18][0]=0.025003534763;
GaussPnt[19][0]=0.066803251012;
GaussPnt[20][0]=0.923655933587;
GaussPnt[21][0]=0.009540815400;
GaussPnt[22][0]=0.923655933587;
GaussPnt[23][0]=0.066803251012;
GaussPnt[24][0]=0.009540815400;
GaussPnt[0][1]=0.333333333333;
GaussPnt[1][1]=0.485577633384;
GaussPnt[2][1]=0.028844733233;
GaussPnt[3][1]=0.485577633384;
GaussPnt[4][1]=0.109481575485;
GaussPnt[5][1]=0.781036849030;
GaussPnt[6][1]=0.109481575485;
GaussPnt[7][1]=0.550352941821;
GaussPnt[8][1]=0.141707219415;
GaussPnt[9][1]=0.307939838764;
GaussPnt[10][1]=0.307939838764;
GaussPnt[11][1]=0.141707219415;
GaussPnt[12][1]=0.550352941821;
GaussPnt[13][1]=0.728323904597;
GaussPnt[14][1]=0.025003534763;
GaussPnt[15][1]=0.246672560640;
GaussPnt[16][1]=0.246672560640;
GaussPnt[17][1]=0.025003534763;
GaussPnt[18][1]=0.728323904597;
GaussPnt[19][1]=0.923655933587;
GaussPnt[20][1]=0.009540815400;
GaussPnt[21][1]=0.066803251012;
GaussPnt[22][1]=0.066803251012;
GaussPnt[23][1]=0.009540815400;
GaussPnt[24][1]=0.923655933587;
GaussWeight[0]=0.090817990383;
GaussWeight[1]=0.036725957756;
GaussWeight[2]=0.036725957756;
GaussWeight[3]=0.036725957756;
GaussWeight[4]=0.045321059436;
GaussWeight[5]=0.045321059436;
GaussWeight[6]=0.045321059436;
GaussWeight[7]=0.072757916845;
GaussWeight[8]=0.072757916845;
GaussWeight[9]=0.072757916845;
GaussWeight[10]=0.072757916845;
GaussWeight[11]=0.072757916845;
GaussWeight[12]=0.072757916845;
GaussWeight[13]=0.028327242531;
GaussWeight[14]=0.028327242531;
GaussWeight[15]=0.028327242531;
GaussWeight[16]=0.028327242531;
GaussWeight[17]=0.028327242531;
GaussWeight[18]=0.028327242531;
GaussWeight[19]=0.009421666964;
GaussWeight[20]=0.009421666964;
GaussWeight[21]=0.009421666964;
GaussWeight[22]=0.009421666964;
GaussWeight[23]=0.009421666964;
GaussWeight[24]=0.009421666964;
break;
case 12:
GaussPnt.resize(33);
GaussWeight.resize(33);
GaussPnt[0][0]=0.488217389774;
GaussPnt[1][0]=0.488217389774;
GaussPnt[2][0]=0.023565220452;
GaussPnt[3][0]=0.439724392294;
GaussPnt[4][0]=0.439724392294;
GaussPnt[5][0]=0.120551215411;
GaussPnt[6][0]=0.271210385012;
GaussPnt[7][0]=0.271210385012;
GaussPnt[8][0]=0.457579229976;
GaussPnt[9][0]=0.127576145542;
GaussPnt[10][0]=0.127576145542;
GaussPnt[11][0]=0.744847708917;
GaussPnt[12][0]=0.021317350453;
GaussPnt[13][0]=0.021317350453;
GaussPnt[14][0]=0.957365299094;
GaussPnt[15][0]=0.275713269686;
GaussPnt[16][0]=0.608943235780;
GaussPnt[17][0]=0.115343494535;
GaussPnt[18][0]=0.608943235780;
GaussPnt[19][0]=0.275713269686;
GaussPnt[20][0]=0.115343494535;
GaussPnt[21][0]=0.281325580990;
GaussPnt[22][0]=0.695836086788;
GaussPnt[23][0]=0.022838332222;
GaussPnt[24][0]=0.695836086788;
GaussPnt[25][0]=0.281325580990;
GaussPnt[26][0]=0.022838332222;
GaussPnt[27][0]=0.116251915908;
GaussPnt[28][0]=0.858014033544;
GaussPnt[29][0]=0.025734050548;
GaussPnt[30][0]=0.858014033544;
GaussPnt[31][0]=0.116251915908;
GaussPnt[32][0]=0.025734050548;
GaussPnt[0][1]=0.488217389774;
GaussPnt[1][1]=0.023565220452;
GaussPnt[2][1]=0.488217389774;
GaussPnt[3][1]=0.439724392294;
GaussPnt[4][1]=0.120551215411;
GaussPnt[5][1]=0.439724392294;
GaussPnt[6][1]=0.271210385012;
GaussPnt[7][1]=0.457579229976;
GaussPnt[8][1]=0.271210385012;
GaussPnt[9][1]=0.127576145542;
GaussPnt[10][1]=0.744847708917;
GaussPnt[11][1]=0.127576145542;
GaussPnt[12][1]=0.021317350453;
GaussPnt[13][1]=0.957365299094;
GaussPnt[14][1]=0.021317350453;
GaussPnt[15][1]=0.608943235780;
GaussPnt[16][1]=0.115343494535;
GaussPnt[17][1]=0.275713269686;
GaussPnt[18][1]=0.275713269686;
GaussPnt[19][1]=0.115343494535;
GaussPnt[20][1]=0.608943235780;
GaussPnt[21][1]=0.695836086788;
GaussPnt[22][1]=0.022838332222;
GaussPnt[23][1]=0.281325580990;
GaussPnt[24][1]=0.281325580990;
GaussPnt[25][1]=0.022838332222;
GaussPnt[26][1]=0.695836086788;
GaussPnt[27][1]=0.858014033544;
GaussPnt[28][1]=0.025734050548;
GaussPnt[29][1]=0.116251915908;
GaussPnt[30][1]=0.116251915908;
GaussPnt[31][1]=0.025734050548;
GaussPnt[32][1]=0.858014033544;
GaussWeight[0]=0.025731066440;
GaussWeight[1]=0.025731066440;
GaussWeight[2]=0.025731066440;
GaussWeight[3]=0.043692544538;
GaussWeight[4]=0.043692544538;
GaussWeight[5]=0.043692544538;
GaussWeight[6]=0.062858224218;
GaussWeight[7]=0.062858224218;
GaussWeight[8]=0.062858224218;
GaussWeight[9]=0.034796112931;
GaussWeight[10]=0.034796112931;
GaussWeight[11]=0.034796112931;
GaussWeight[12]=0.006166261052;
GaussWeight[13]=0.006166261052;
GaussWeight[14]=0.006166261052;
GaussWeight[15]=0.040371557766;
GaussWeight[16]=0.040371557766;
GaussWeight[17]=0.040371557766;
GaussWeight[18]=0.040371557766;
GaussWeight[19]=0.040371557766;
GaussWeight[20]=0.040371557766;
GaussWeight[21]=0.022356773202;
GaussWeight[22]=0.022356773202;
GaussWeight[23]=0.022356773202;
GaussWeight[24]=0.022356773202;
GaussWeight[25]=0.022356773202;
GaussWeight[26]=0.022356773202;
GaussWeight[27]=0.017316231109;
GaussWeight[28]=0.017316231109;
GaussWeight[29]=0.017316231109;
GaussWeight[30]=0.017316231109;
GaussWeight[31]=0.017316231109;
GaussWeight[32]=0.017316231109;
break;
default:
std::cout<<"There are no Gauss quadrature points with accuracy of "<<i<<"-th order"<<std::endl;
}
}
// 成员函数
void TmpEle::buildTE(int i)
{
TmpEle tmpEle(i);
for (auto x : tmpEle.Pnt)
Pnt.push_back(x);
for (auto x : tmpEle.GaussPnt)
GaussPnt.push_back(x);
for (auto x : tmpEle.GaussWeight)
GaussWeight.push_back(x);
}
Point TmpEle::getPnt(int i)
{
return Pnt[i];
}
std::vector<Point> TmpEle::getGaussPnt()
{
return GaussPnt;
}
std::vector<double> TmpEle::getGaussWeight()
{
return GaussWeight;
}
double TmpEle::getArea()
{
return 0.5*((Pnt[1][0] - Pnt[0][0]) * (Pnt[2][1] - Pnt[0][1])
- (Pnt[1][1] - Pnt[0][1]) * (Pnt[2][0] - Pnt[0][0]));
}
// 标准单元到普通单元
Point TmpEle::Local_to_Global(const Point & lp, const std::vector<Point> & gv) const
{
Point gp;
double lambda[3];
double area = AREA(Pnt[0], Pnt[1], Pnt[2]);
lambda[0] = AREA(lp, Pnt[1], Pnt[2]) / area;
lambda[1] = AREA(lp, Pnt[2], Pnt[0]) / area;
lambda[2] = AREA(lp, Pnt[0], Pnt[1]) / area;
gp[0] = lambda[0] * gv[0][0] + lambda[1] * gv[1][0] + lambda[2] * gv[2][0];
gp[1] = lambda[0] * gv[0][1] + lambda[1] * gv[1][1] + lambda[2] * gv[2][1];
return gp;
}
// 普通单元到标准单元
Point TmpEle::Global_to_Local(const Point& gp, const std::vector<Point>& gv) const
{
Point lp;
double area = AREA(gv[0],gv[1],gv[2]);
lp[0] = ((gv[2][1] - gv[0][1]) * (gp[0] - gv[0][0]) -
(gv[2][0] - gv[0][0]) * (gp[1] - gv[0][1])) / (2 * area);
lp[1] = (-(gv[1][1] - gv[0][1]) * (gp[0] - gv[0][0]) +
(gv[1][0] - gv[0][0]) * (gp[1] - gv[0][1])) / (2 * area);
return lp;
}
// 标准单元到普通单元
std::vector<Point> TmpEle::Local_to_Global(const std::vector<Point>& lp, const std::vector<Point> & gv) const
{
std::vector<Point> gp(lp.size());
double area = AREA(Pnt[0], Pnt[1], Pnt[2]);
for(int i=0; i<gp.size(); i++){
double lambda[3];
lambda[0] = AREA(lp[i], Pnt[1], Pnt[2]) / area;
lambda[1] = AREA(lp[i], Pnt[2], Pnt[0]) / area;
lambda[2] = AREA(lp[i], Pnt[0], Pnt[1]) / area;
gp[i][0] = lambda[0] * gv[0][0] + lambda[1] * gv[1][0] + lambda[2] * gv[2][0];
gp[i][1] = lambda[0] * gv[0][1] + lambda[1] * gv[1][1] + lambda[2] * gv[2][1];
}
return gp;
}
// 普通单元到标准单元
std::vector<Point> TmpEle::Global_to_Local(const std::vector<Point>& gp,
const std::vector<Point>& gv) const
{
std::vector<Point> lp;
double area = AREA(gv[0],gv[1],gv[2]);
for (auto point : gp){
Point p;
p[0] = ((gv[2][1] - gv[0][1]) * (point[0] - gv[0][0]) -
(gv[2][0] - gv[0][0]) * (point[1] - gv[0][1])) / (2 * area);
p[1] = (-(gv[1][1] - gv[0][1]) * (point[0] - gv[0][0]) +
(gv[1][0] - gv[0][0]) * (point[1] - gv[0][1])) / (2 * area);
lp.push_back(p);
}
return lp;
}
// 从标准单元到普通单元的雅克比矩阵
double TmpEle::Local_to_Global_jacobian(const Point& lp, const std::vector<Point>& gv) const
{
// lp只是提供维度
double jacobian = AREA(gv[0],gv[1],gv[2]) / AREA(Pnt[0], Pnt[1], Pnt[2]);
return jacobian;
}
// 从普通单元到标准单元的雅克比矩阵
double TmpEle::Global_to_Local_jacobian(const Point& lp, const std::vector<Point>& gv) const
{
// lp只是提供维度
double jacobian = AREA(Pnt[0],Pnt[1],Pnt[2]) / AREA(gv[0],gv[1],gv[2]);
return jacobian;
}
// 从标准单元到普通单元的雅克比矩阵
std::vector<double> TmpEle::Local_to_Global_jacobian(const std::vector<Point>& lp, const std::vector<Point>& gv) const
{
std::vector<double> gj(lp.size());
double larea = AREA(Pnt[0], Pnt[1], Pnt[2]);
double garea = AREA(gv[0], gv[1], gv[2]);
for (int i = 0; i < gj.size(); i++){
gj[i] = garea / larea;
}
return gj;
}
// 从普通单元到标准单元的雅克比矩阵
std::vector<double> TmpEle::Global_to_Local_jacobian(const std::vector<Point>& lp, const std::vector<Point>& gv) const
{
std::vector<double> gj(lp.size());
double larea = AREA(Pnt[0], Pnt[1], Pnt[2]);
double garea = AREA(gv[0], gv[1], gv[2]);
for (int i = 0; i < gj.size(); i++){
gj[i] = larea / garea;
}
return gj;
}
////////////////////////////////////////////////////////////////////////////////
//类Mesh
////////////////////////////////////////////////////////////////////////////////
// 非成员函数
std::ostream& operator<< (std::ostream& os, const Mesh& M)
{
for (auto i : M.Pnt)
os << i << '\n';
for (auto &i : M.Ele){
for (auto j : i)
os << j << '\t';
os << '\n';
}
for (auto i : M.BndPnt)
os << i << '\n';
os << '\n';
return os;
}
// 成员函数
void Mesh::readData(const std::string& f)
{
int i;
std::ifstream is(f,std::ifstream::in); // 以只读的模式打开
is >> i;
Pnt.resize(i);
for (int j = 0; j < i; j++)
is >> Pnt[j][0] >> Pnt[j][1];
int n;
is >> n;
Ele.resize(n);
for (int j = 0; j < n; j++){
Ele[j].resize(3);
is >> Ele[j][0] >> Ele[j][1] >> Ele[j][2];
}
int bn;
is >> bn;
BndPnt.resize(bn);
for (int j = 0; j < bn; j++)
is >> BndPnt[j];
is.close();
}
int Mesh::getEleVtx(int i, int j)
{
return Ele[i][j];
}
std::vector<int> Mesh::getEleVtx(int i)
{
return Ele[i];
}
Point Mesh::getPnt(int i)
{
return Pnt[i];
}
std::vector<Point> Mesh::getPnt(std::vector<int>& vt)
{
std::vector<Point> vec;
for (int x : vt){
Point point = Pnt[x];
vec.push_back(point);
}
return vec;
}
std::vector<int> Mesh::getBndPnt()
{
return BndPnt;
}
int Mesh::n_element()
{
return Ele.size();
}
int Mesh::n_point()
{
return Pnt.size();
}
int Mesh::n_boundaryPoint()
{
return BndPnt.size();
}
void Mesh::neighbor(std::vector<std::vector<int>>& neighbor)
{
auto n_ele = n_element(); // 得到剖分小三角形的数量
// 初始化
neighbor.resize(n_ele);
for (decltype(neighbor.size()) i = 0; i != n_ele; ++i){
neighbor[i].resize(3);
}
for (decltype(neighbor.size()) i = 0; i != n_ele; ++i){
// 检测顶点所对应的边是不是边界边
bool boundary_mark_00 = false, boundary_mark_01 = false;
bool boundary_mark_10 = false, boundary_mark_11 = false;
bool boundary_mark_20 = false, boundary_mark_21 = false;
for (auto boundary : BndPnt){
// 第一个顶点所对应的边是不是边界边
if (boundary == Ele[i][1]) boundary_mark_00 = true;
if (boundary == Ele[i][2]) boundary_mark_01 = true;
// 第二个顶点所对应的边是不是边界边
if (boundary == Ele[i][0]) boundary_mark_10 = true;
if (boundary == Ele[i][2]) boundary_mark_11 = true;
// 第三个顶点所对应的边是不是边界边
if (boundary == Ele[i][0]) boundary_mark_20 = true;
if (boundary == Ele[i][1]) boundary_mark_21 = true;
}
// 如果是边界边的话邻居单元就是自己
if (boundary_mark_00 && boundary_mark_01) neighbor[i][0] = i;
if (boundary_mark_10 && boundary_mark_11) neighbor[i][1] = i;
if (boundary_mark_20 && boundary_mark_21) neighbor[i][2] = i;
for (decltype(neighbor.size()) j = 0; j != n_ele; ++j){
if (i == j) continue;
bool mark_00 = false, mark_01 = false;
bool mark_10 = false, mark_11 = false;
bool mark_20 = false, mark_21 = false;
for (decltype(neighbor.size()) k = 0; k != 3; ++k){
// 第一个顶点对应边的邻居单元(如果是边界边的话邻居单元就是自己)
if (Ele[j][k] == Ele[i][1]) mark_00 = true;
if (Ele[j][k] == Ele[i][2]) mark_01 = true;
// 第二个顶点对应边的邻居单元(如果是边界边的话邻居单元就是自己)
if (Ele[j][k] == Ele[i][0]) mark_10 = true;
if (Ele[j][k] == Ele[i][2]) mark_11 = true;
// 第三个顶点对应边的邻居单元(如果是边界边的话邻居单元就是自己)
if (Ele[j][k] == Ele[i][0]) mark_20 = true;
if (Ele[j][k] == Ele[i][1]) mark_21 = true;
}
if (mark_00 && mark_01) neighbor[i][0] = j;
if (mark_10 && mark_11) neighbor[i][1] = j;
if (mark_20 && mark_21) neighbor[i][2] = j;
}
}
}
////////////////////////////////////////////////////////////////////////////////
//偏微分方程,边界条件和初值条件结构体,PDE
//
////////////////////////////////////////////////////////////////////////////////
// 边界条件(第一类边界条件)
double PDE::u_boundary(const Point& p)
{
return 0;
}
double PDE::f(const Point& p)
{
double value;
value = - 2 * PI * PI * exp(PI * (p[0] + p[1])) * (sin(PI * p[0]) * cos(PI * p[1]) + cos(PI * p[0]) * sin(PI * p[1]));
return value;
}
double PDE::u_exact(const Point& p)
{
double value;
value = exp(PI * (p[0] + p[1])) * sin(PI * p[0]) * sin(PI * p[1]);
return value;
}
////////////////////////////////////////////////////////////////////////////////
//类Matrix
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void Matrix::GaussSeidel(const std::vector<std::vector<double>>& A_matrix, std::vector<double>& u,
const std::vector<double>& rhs)
{
std::vector<double> last_u(A_matrix.size());
do{
last_u=u;
double error=0.0;
for(int i=0;i<A_matrix.size();i++){
double temp=rhs[i];
for(int j=0; j<A_matrix[i].size(); j++){
if(j != i){
temp-=A_matrix[i][j]*u[j];
}
}
u[i]=temp/A_matrix[i][i];
}
u_int Vsize=u.size();
for(int k=0;k<Vsize;k++){
error+=(last_u[k]-u[k])*(last_u[k]-u[k]);
}
error=sqrt(error);
if(error<1.0e-10)
break;
}while(1);
}
void Matrix::SolveLinearASparse(const Eigen::SparseMatrix<double>& A_matrix_sparse,std::vector<double>& u,
const std::vector<double>& rhs, int k)
{
auto b_size = rhs.size();
Eigen::VectorXd b;
b.resize(b_size);
for (size_t i = 0; i != b_size; ++i)
b(i) = rhs[i];
Eigen::VectorXd u_h_now;
// 求解器声明
Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg;
Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IdentityPreconditioner> bicg;
Eigen::GMRES<Eigen::SparseMatrix<double>, Eigen::IdentityPreconditioner> gmres;
Eigen::DGMRES<Eigen::SparseMatrix<double>,Eigen::IdentityPreconditioner> dgmres;
Eigen::MINRES<Eigen::SparseMatrix<double>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> minres;
switch (k){
// 迭代法
case 1:
cg.compute(A_matrix_sparse);
u_h_now = cg.solve(b);
std::cout << "CG:\t #iterations: " << cg.iterations() << ", estimated error: " << cg.error()
<< std::endl;
break;
case 2:
bicg.compute(A_matrix_sparse);
u_h_now = bicg.solve(b);
std::cout << "BiCGSTAB:\t #iterations: " << bicg.iterations() << ", estimated error: "
<< bicg.error() << std::endl;
break;
case 3:
gmres.compute(A_matrix_sparse);
u_h_now = gmres.solve(b);
std::cout << "GMRES:\t #iterator: " << gmres.iterations() << ", estimated error: "
<< gmres.error() << std::endl;
break;
case 4:
dgmres.compute(A_matrix_sparse);
u_h_now = dgmres.solve(b);
std::cout << "DGMRES:\t #iterator: " << dgmres.iterations() << ", estimate error: "
<< dgmres.error() << std::endl;
break;
case 5:
minres.compute(A_matrix_sparse);
u_h_now = minres.solve(b);
std::cout << "MINRES:\t #iterator: " << minres.iterations() << ", estimate error: "
<< minres.error() << std::endl;
break;
}
// 将求解结果存储到u中
for (size_t i = 0; i != u.size(); ++i)
u[i] = u_h_now(i);
}
Matrix::Matrix(const std::string& file, int i)
{
mesh.readData(file);
tmpEle.buildTE(i);
}
// 成员函数
// 基函数的构造(面积坐标)
void Matrix::basisValue(const Point& p, const std::vector<Point>& v, std::vector<double>& val)
{
val.resize(3); // 分片线性单元
double area = AREA(v[0], v[1], v[2]);
val[0] = AREA(p,v[1],v[2]);
val[1] = AREA(v[0],p,v[2]);
val[2] = AREA(v[0],v[1],p);
val[0] /= area;
val[1] /= area;
val[2] /= area;
}
void Matrix::basisValue(const std::vector<Point>& p, const std::vector<Point>& v,
std::vector<std::vector<double>>& val)
{
int n = p.size();
val.resize(3);
for(int i = 0; i < 3; i++)
val[i].resize(n);
double area = AREA(v[0],v[1],v[2]);
for (int i=0; i < n; i++){
val[0][i] = AREA(p[i],v[1],v[2]);
val[1][i] = AREA(v[0],p[i],v[2]);
val[2][i] = AREA(v[0],v[1],p[i]);
val[0][i] /= area;
val[1][i] /= area;
val[2][i] /= area;
}
}
void Matrix::basisGrad(const Point&, const std::vector<Point>& v,
std::vector<std::vector<double>>& val)
{
val.resize(3);
val[0].resize(2);
val[1].resize(2);
val[2].resize(2);
double area = AREA(v[0],v[1],v[2]) * 2; // 面积坐标到直角坐标的雅克比为2s
val[0][0] = (v[1][1] - v[2][1]) / area;
val[0][1] = (v[2][0] - v[1][0]) / area;
val[1][0] = (v[2][1] - v[0][1]) / area;
val[1][1] = (v[0][0] - v[2][0]) / area;
val[2][0] = (v[0][1] - v[1][1]) / area;
val[2][1] = (v[1][0] - v[0][0]) / area;
}
void Matrix::basisGrad(const std::vector<Point>& p, const std::vector<Point>& v,
std::vector<std::vector<std::vector<double>>>& val)
{
int n = p.size();
val.resize(3);
for (int i = 0; i < 3; i++){
val[i].resize(n);
}
for (int i = 0; i < 3; i++){
for (int j = 0; j < n; j++){
val[i][j].resize(2);
}
}
double area = AREA(v[0],v[1],v[2]) * 2;
for (int i = 0; i < n; i++){
val[0][i][0] = (v[1][1] - v[2][1]) / area;
val[0][i][1] = (v[2][0] - v[1][0]) / area;
val[1][i][0] = (v[2][1] - v[0][1]) / area;
val[1][i][1] = (v[0][0] - v[2][0]) / area;
val[2][i][0] = (v[0][1] - v[1][1]) / area;
val[2][i][1] = (v[1][0] - v[0][0]) / area;
}
}
void Matrix::buildEleMatrix_RHS(int n, std::vector<std::vector<double>> &Ele_matrix, std::vector<double> &Ele_Rhs)
{
Ele_matrix.resize(3); // 单元刚度矩阵(左端),维度是3*3的
Ele_Rhs.resize(3); // 单元刚度矩阵(右端),维度是3*1的
for(int i=0; i<3; i++){
Ele_matrix[i].resize(3);
}
// 得到第n个单元的边
std::vector<int> EV=mesh.getEleVtx(n);
// 得到单元的三个点
std::vector<Point> EP(3);
EP[0]=mesh.getPnt(EV[0]);
EP[1]=mesh.getPnt(EV[1]);
EP[2]=mesh.getPnt(EV[2]);
// 标准三角单元的面积
double volume = tmpEle.getArea();
// 得到标准三角单元的Gauss点
std::vector<Point> GP=tmpEle.getGaussPnt();
// 得到标准三角单元的Gauss权重
std::vector<double> GW=tmpEle.getGaussWeight();
// 把标准单元的Gauss点投影到普通单元上
std::vector<Point> q_point = tmpEle.Local_to_Global(GP, EP);
// 得到标准单元到普通单元的雅克比矩阵
std::vector<double> jacobian = tmpEle.Local_to_Global_jacobian(GP, EP);
// 得到三角单元上基函数的值
std::vector<std::vector<double>> basis_value;
basisValue(q_point, EP, basis_value);
// 得到三角单元上梯度算子的值
std::vector<std::vector<std::vector<double>>> basis_grad;
basisGrad(q_point, EP, basis_grad);
// 计算右端的单元刚度矩阵
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i] * jacobian[i] * volume;
double f_value = pde.f(q_point[i]);
for(int j = 0; j < basis_value.size(); j++){
Ele_Rhs[j] += Jxw*f_value*basis_value[j][i];
}
}
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i] * jacobian[i] * volume;
for(int k=0; k<basis_grad.size(); k++){
for(int j=0; j<basis_grad.size(); j++){
Ele_matrix[j][k] += Jxw * (basis_grad[j][i][0] * basis_grad[k][i][0] + basis_grad[j][i][1] *
basis_grad[k][i][1]);
}
}
}
}
void Matrix::buildMatrix_RHS_Sparse(Eigen::SparseMatrix<double>& A_matrix_sparse,std::vector<double>& Rhs)
{
auto n_ele = mesh.n_element();
auto n_pnt = mesh.n_point();
A_matrix_sparse.resize(n_pnt,n_pnt);
Rhs.resize(n_pnt);
// 定义一个用于存储稀疏矩阵的三元组
std::vector<Eigen::Triplet<double>> triple;
for (size_t i = 0; i != n_ele; ++i){
std::vector<int> NV = mesh.getEleVtx(i);
std::vector<std::vector<double>> Ele_matrix(3);
for (size_t j = 0; j != 3; ++j){
Ele_matrix[j].resize(3);
}
std::vector<double> Ele_Rhs(3);
buildEleMatrix_RHS(i,Ele_matrix,Ele_Rhs);
// 稀疏矩阵存储技术
// 利用经典的三元组插入方式来存储A_matrix
triple.push_back(Eigen::Triplet<double>(NV[0],NV[0],Ele_matrix[0][0]));
triple.push_back(Eigen::Triplet<double>(NV[0],NV[1],Ele_matrix[0][1]));
triple.push_back(Eigen::Triplet<double>(NV[0],NV[2],Ele_matrix[0][2]));
triple.push_back(Eigen::Triplet<double>(NV[1],NV[0],Ele_matrix[1][0]));
triple.push_back(Eigen::Triplet<double>(NV[1],NV[1],Ele_matrix[1][1]));
triple.push_back(Eigen::Triplet<double>(NV[1],NV[2],Ele_matrix[1][2]));
triple.push_back(Eigen::Triplet<double>(NV[2],NV[0],Ele_matrix[2][0]));
triple.push_back(Eigen::Triplet<double>(NV[2],NV[1],Ele_matrix[2][1]));
triple.push_back(Eigen::Triplet<double>(NV[2],NV[2],Ele_matrix[2][2]));
// 不利用稀疏矩阵存储右端项Rhs
Rhs[NV[0]] += Ele_Rhs[0];
Rhs[NV[1]] += Ele_Rhs[1];
Rhs[NV[2]] += Ele_Rhs[2];
}
// 把三元组转换成稀疏矩阵
A_matrix_sparse.setFromTriplets(triple.begin(),triple.end());
}
// 对于稀疏矩阵A_matrix_sparse的边界条件处理(dirichlet边界条件)
void Matrix::DealBoundary_Sparse(Eigen::SparseMatrix<double>& A_matrix_sparse, const std::vector<double>& uh,
std::vector<double>& Rhs)
{
auto n_pnt = mesh.n_point();
auto n_bp = mesh.n_boundaryPoint();
std::vector<int> BV = mesh.getBndPnt(); // 得到边界点
for (size_t i = 0; i != n_bp; ++i){
Point Pnt_i = mesh.getPnt(BV[i]); // 得到第i个单元的点
double val = pde.u_boundary(Pnt_i);
Rhs[BV[i]] = A_matrix_sparse.coeffRef(BV[i],BV[i]) * val;
for (size_t j = 0; j != n_pnt; ++j){
if (j != BV[i]){
A_matrix_sparse.coeffRef(BV[i],j) = 0.0;
}
}
for (size_t j = 0; j != n_pnt; ++j){
if (j != BV[i]){
Rhs[j] -= A_matrix_sparse.coeffRef(j,BV[i]) * val;
A_matrix_sparse.coeffRef(j,BV[i]) = 0.0;
}
}
}
}
double Matrix::ComputerL2Error(const std::vector<double> &f)
{
double err=0.0;
int n_ele=mesh.n_element();
for(int j=0; j<n_ele; j++){
std::vector<int> NV = mesh.getEleVtx(j);
std::vector<Point> EP(3);
EP[0]=mesh.getPnt(NV[0]);
EP[1]=mesh.getPnt(NV[1]);
EP[2]=mesh.getPnt(NV[2]);
double volume = tmpEle.getArea();
std::vector<Point> GP = tmpEle.getGaussPnt();
std::vector<double> GW = tmpEle.getGaussWeight();
std::vector<Point> q_point = tmpEle.Local_to_Global(GP, EP);
std::vector<double> jacobian = tmpEle.Local_to_Global_jacobian(GP, EP);
std::vector<std::vector<double> > basis_value;
basisValue(q_point, EP, basis_value);
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i]*jacobian[i]*volume;
double f_value = pde.u_exact(q_point[i]);
double u_h_val = f[NV[0]]*basis_value[0][i]+f[NV[1]]*basis_value[1][i]+f[NV[2]]*basis_value[2][i];
double df_val = f_value-u_h_val;
err += Jxw*df_val*df_val;
}
}
err=sqrt(err);
return err;
}
void Matrix::GradBasis(std::vector<std::vector<std::vector<double>>>& gradbasis)
{
auto n_ele = mesh.n_element(); // 三角单元的数量
auto n_point = mesh.n_point(); // 三角单元点的个数
gradbasis.resize(3);
for (decltype(gradbasis.size()) i = 0; i != 3; ++i)
gradbasis[i].resize(n_ele);
for (decltype(gradbasis.size()) i = 0; i != 3; ++i)
for (decltype(gradbasis.size()) j = 0; j != n_ele; ++j)
gradbasis[i][j].resize(2);
std::vector<int> EV; // 存储三角单元的边
std::vector<Point> EP(3); // 存储三角单元的三个顶点
for (decltype(gradbasis.size()) i = 0; i != n_ele; ++i){
// 得到第i个单元的边
EV = mesh.getEleVtx(i);
// 得到单元的三个顶点
EP[0] = mesh.getPnt(EV[0]);
EP[1] = mesh.getPnt(EV[1]);
EP[2] = mesh.getPnt(EV[2]);
gradbasis[0][i][0] = (EP[1][1] - EP[2][1]) / (2 * AREA(EP[0],EP[1],EP[2]));
gradbasis[0][i][1] = (EP[2][0] - EP[1][0]) / (2 * AREA(EP[0],EP[1],EP[2]));
gradbasis[1][i][0] = (EP[2][1] - EP[0][1]) / (2 * AREA(EP[0],EP[1],EP[2]));
gradbasis[1][i][1] = (EP[0][0] - EP[2][0]) / (2 * AREA(EP[0],EP[1],EP[2]));
gradbasis[2][i][0] = (EP[0][1] - EP[1][1]) / (2 * AREA(EP[0],EP[1],EP[2]));
gradbasis[2][i][1] = (EP[1][0] - EP[0][0]) / (2 * AREA(EP[0],EP[1],EP[2]));
}
}
void Matrix::Gradu(const std::vector<std::vector<std::vector<double>>>& gradbasis,
const std::vector<double>& u_h, std::vector<std::vector<double>>& Du)
{
auto n_ele = mesh.n_element(); // 三角形单元的数量
Du.resize(n_ele);
for (decltype(Du.size()) i = 0; i != n_ele; ++i)
Du[i].resize(2);
std::vector<int> EV; // 存储三角单元的边
std::vector<Point> EP(3); // 存储三角单元的三个顶点
for (decltype(Du.size()) i =0; i != n_ele; ++i){
// 得到第i个单元的边
EV = mesh.getEleVtx(i);
// 得到单元的三个顶点
EP[0] = mesh.getPnt(EV[0]);
EP[1] = mesh.getPnt(EV[1]);
EP[2] = mesh.getPnt(EV[2]);
Du[i][0] = u_h[EV[0]] * gradbasis[0][i][0] + u_h[EV[1]] * gradbasis[1][i][0] + u_h[EV[2]] * gradbasis[2][i][0];
Du[i][1] = u_h[EV[0]] * gradbasis[0][i][1] + u_h[EV[1]] * gradbasis[1][i][1] + u_h[EV[2]] * gradbasis[2][i][1];
}
}
void Matrix::eleVector(std::vector<std::vector<std::vector<double>>>& ve)
{
// 初始化
auto n_ele = mesh.n_element();
ve.resize(n_ele);
for (decltype(ve.size()) i = 0; i != n_ele; ++i){
ve[i].resize(2);
for (decltype(ve.size()) j = 0; j != 2; ++j){
ve[i][j].resize(3);
}
}
// 边的向量
for (decltype(ve.size()) i = 0; i != n_ele; ++i){
for (decltype(ve.size()) j = 0; j != 2; ++j){
// 得到第i个单元的边
std::vector<int> EV = mesh.getEleVtx(i);
std::vector<Point> EP(3);
EP[0] = mesh.getPnt(EV[0]);
EP[1] = mesh.getPnt(EV[1]);
EP[2] = mesh.getPnt(EV[2]);
ve[i][j][0] = EP[2][j] - EP[1][j];
ve[i][j][1] = EP[0][j] - EP[2][j];
ve[i][j][2] = EP[1][j] - EP[0][j];
}
}
}
void Matrix::normalVector(const std::vector<std::vector<std::vector<double>>>& ve,
std::vector<std::vector<std::vector<double>>>& ne)
{
// 初始化
auto n_ele = mesh.n_element();
ne.resize(n_ele);
for (decltype(ne.size()) i = 0; i != n_ele; ++i){
ne[i].resize(2);
for (decltype(ne.size()) j = 0; j != 2; ++j){
ne[i][j].resize(3);
}
}
// 把ve旋转90度得到ne
for (decltype(ne.size()) i = 0; i != n_ele; ++i){
ne[i][0][0] = ve[i][1][0]; ne[i][1][0] = -ve[i][0][0];
ne[i][0][1] = ve[i][1][1]; ne[i][1][1] = -ve[i][0][1];
ne[i][0][2] = ve[i][1][2]; ne[i][1][2] = -ve[i][0][2];
}
}
double Matrix::diameter(const std::vector<Point>& EP)
{
// 求出三角单元三条边的边长
auto distance_0 = distance(EP[0],EP[1]);
auto distance_1 = distance(EP[1],EP[2]);
auto distance_2 = distance(EP[0],EP[2]);
double max = distance_0;
if (max < distance_1)
max = distance_1;
if (max < distance_2);
max = distance_2;
return max;
}
void Matrix::Estimateresidual(std::vector<double>& u_h,std::vector<double>& eta)
{
auto n_ele = mesh.n_element(); // 三角形单元的数量
auto n_point = mesh.n_point(); // 三角形点的个数
// 得到剖分上每一个单元的梯度
std::vector<std::vector<std::vector<double>>> gradbasis;
GradBasis(gradbasis);
// 得到u_h的梯度
std::vector<std::vector<double>> Du;
Gradu(gradbasis,u_h,Du);
// 得到邻居单元的索引
std::vector<std::vector<int>> neighbor_index;
mesh.neighbor(neighbor_index);
// 得到剖分单元上每一条边的向量
std::vector<std::vector<std::vector<double>>> ve;
eleVector(ve);
// 得到向量的法向量
std::vector<std::vector<std::vector<double>>> ne;
normalVector(ve,ne);
// 对于边界边的跳量为0
std::vector<double> edgeJump;
edgeJump.resize(n_ele);
for (decltype(edgeJump.size()) i = 0; i != n_ele; ++i){
auto index_0 = neighbor_index[i][0];
auto index_1 = neighbor_index[i][1];
auto index_2 = neighbor_index[i][2];
std::vector<int> EV = mesh.getEleVtx(i);
std::vector<Point> EP(3);
EP[0] = mesh.getPnt(EV[0]);
EP[1] = mesh.getPnt(EV[1]);
EP[2] = mesh.getPnt(EV[2]);
edgeJump[i] = pow(((Du[i][0] - Du[index_0][0]) * ne[i][0][0] + (Du[i][1] - Du[index_0][1]) * ne[i][1][0]),2.0)
+ pow(((Du[i][0] - Du[index_1][0]) * ne[i][0][1] + (Du[i][1] - Du[index_1][1]) * ne[i][1][1]),2.0) +
pow(((Du[i][0] - Du[index_2][0]) * ne[i][0][2] + (Du[i][1] - Du[index_2][1]) * ne[i][1][2]),2.0);
}
// 初始化
eta.resize(n_ele);
// 计算残差||r||_{L^2}^2
for (decltype(eta.size()) i = 0; i != n_ele; ++i ){
std::vector<int> NV = mesh.getEleVtx(i);
std::vector<Point> EP(3);
EP[0] = mesh.getPnt(NV[0]);
EP[1] = mesh.getPnt(NV[1]);
EP[2] = mesh.getPnt(NV[2]);
double volume = tmpEle.getArea();
// 得到高斯点
std::vector<Point> GP = tmpEle.getGaussPnt();
// 得到高斯权重
std::vector<double> GW = tmpEle.getGaussWeight();
// 把高斯点投影到普通单元
std::vector<Point> q_point = tmpEle.Local_to_Global(GP,EP);
std::vector<double> jacobian = tmpEle.Local_to_Global_jacobian(GP,EP);
// 得到改三角单元的直径
double dm = diameter(EP);
for (decltype(eta.size()) j = 0; j != q_point.size(); ++j){
double Jxw = GW[j] * jacobian[j] * volume;
double f_value = pde.f(q_point[j]);
eta[i] += Jxw * f_value * f_value * dm * dm;
}
// 加入跳量
eta[i] += 0.5 * dm * edgeJump[i];
}
}
<file_sep>/Possion方程--C++(CVT自适应)/density.cpp
/*************************************************************************
> File Name: density.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年08月20日 星期一 22时33分51秒
************************************************************************/
#include "density.h"
void density(const std::vector<Point>& node, const std::vector<std::vector<int>>& ele, const std::vector<double>& eta)
{
auto N = node.size(); // 网格节点数目
auto NT = ele.size(); // 单元数目
// 生成文件"dens_nodes.dat"
std::ofstream out("dens_nodes.dat",std::ofstream::out); // 以只读的模式打开
auto radi = 6371000;
std::vector<std::vector<double>> sp_crd;
// 初始化
sp_crd.resize(N);
for (decltype(sp_crd.size()) i = 0; i != N; ++i)
sp_crd[i].resize(3);
for (decltype(sp_crd.size()) i = 0; i != N; ++i){
auto x = 0.5 * node[i][0] / radi;
auto y = 0.5 * node[i][1] / radi;
auto xy2 = x * x + y * y;
sp_crd[i][0] = radi * 2 * x / (1+xy2);
sp_crd[i][1] = radi * 2 * y / (1+xy2);
sp_crd[i][2] = radi * (1-xy2) / (1+xy2);
}
// 输出到文档中
for (decltype(sp_crd.size()) i = 0; i != sp_crd.size(); ++i){
out << sp_crd[i][0] << "\t" << sp_crd[i][1] << "\t" << sp_crd[i][2] << "\n";
}
out.close();
// 生成文件"dens_valus.dat"
// 检查节点i是否在单元j内,是为1,不是为0
std::vector<std::vector<int>> p2t;
p2t.resize(N);
for (decltype(p2t.size()) i = 0; i != N; ++i)
p2t[i].resize(NT);
for (decltype(p2t.size()) i = 0; i != N; ++i){
for (decltype(p2t.size()) j = 0; j != NT; ++j){
bool direction_0 = false;
bool direction_1 = false;
bool direction_2 = false;
if (i == ele[j][0]) direction_0 = true;
if (i == ele[j][1]) direction_1 = true;
if (i == ele[j][2]) direction_2 = true;
if (direction_0 || direction_1 || direction_2)
p2t[i][j] = 1;
else
p2t[i][j] = 0;
}
}
// 生成单元尺寸
std::vector<double> rho; // 点的尺寸N
std::vector<double> area;
area.resize(NT); // 初始化
rho.resize(N); // 初始化
std::vector<double> temporary_rho;
temporary_rho.resize(NT); // 边的尺寸
for (size_t i = 0; i != NT; ++i){
Point point_0 = node[ele[i][0]];
Point point_1 = node[ele[i][1]];
Point point_2 = node[ele[i][2]];
area[i] = AREA(point_0,point_1,point_2);
auto distance_0 = distance(point_0,point_1);
auto distance_1 = distance(point_0,point_2);
auto distance_2 = distance(point_1,point_2);
auto htri = (distance_0 + distance_1 + distance_2) / 3;
// 计算暂时的rho
temporary_rho[i] = pow(eta[i],2.0) / pow(htri,4.0);
}
// 转换为点的(这里有一个尺寸的变化)
for (decltype(p2t.size()) i = 0; i != N; ++i){
double temporary_0 = 0.0;
double temporary_1 = 0.0;
for (decltype(p2t[i].size()) j = 0; j != NT; ++j){
temporary_0 += p2t[i][j] * area[j] * temporary_rho[j];
temporary_1 += p2t[i][j] * area[j];
}
rho[i] = temporary_0 / temporary_1;
}
for (size_t i = 0; i != 5; ++i){
for (size_t j = 0; j != NT; ++j){
double temporary = 0.0;
for (size_t k = 0; k != N; ++k){
temporary += p2t[k][j] * rho[k] / 3.0;
}
temporary_rho[j] = temporary;
}
for (size_t j = 0; j != N; ++j){
double temporary_0 = 0.0;
double temporary_1 = 0.0;
for (size_t k = 0; k != NT; ++k){
temporary_0 += p2t[j][k] * temporary_rho[k] * area[k];
temporary_1 += p2t[j][k] * area[k];
}
rho[j] = temporary_0 / temporary_1;
}
}
// 写入文件
out.open("dens_valus.dat",std::ofstream::out);
for (decltype(rho.size()) i = 0; i != rho.size(); ++i){
out << rho[i] << "\n";
}
out.close();
}
<file_sep>/Heat方程-C++隐格式/Makefile
c++ = g++
VERSION = -std=c++0x
all: Test
Test: Test.o Point.o Mesh.o Parabolic.o TmpEle.o PDE.o
$(c++) $(VERSION) -o Test Test.o Point.o Mesh.o Parabolic.o TmpEle.o PDE.o
Test.o: Test.cpp
$(c++) $(VERSION) -c Test.cpp
Point.o: Point.cpp Point.h
$(c++) $(VERSION) -c Point.cpp
Mesh.o: Mesh.cpp Mesh.h
$(c++) $(VERSION) -c Mesh.cpp
Parabolic.o: Parabolic.cpp Parabolic.h
$(c++) $(VERSION) -c Parabolic.cpp
TmpEle.o: TmpEle.cpp TmpEle.h
$(c++) $(VERSION) -c TmpEle.cpp
PDE.o: PDE.cpp PDE.h
$(c++) $(VERSION) -c PDE.cpp
<file_sep>/Possion方程--C++/Test.cpp
#include "Matrix.h"
using std::cout;
using std::endl;
using std::cin;
void PointTest()
{
////////////////////////////////////////////////////////////////////////////
// 测试Point类
////////////////////////////////////////////////////////////////////////////
// 第一种初始化的方式
cout << "*********************************************************" << endl;
cout << "\n\t\t类Point的测试\n\n\n";
cout << "*********************************************************" << endl;
Point p;
cout << "默认初始化:\n" << p << endl;
//第二种初始化的方式
double a[] = {1,1};
Point p1(a);
cout << "初始化方式p(数组):\n" << p1 << endl;
//第三种初始化的方式
Point p2(p1);
cout << "初始化方式p(Point类型):\n" << p2 << endl;
//第四种初值化方式
Point p3 = p2;
cout << "初始化方式p = Point类型:\n" << p3 << endl;
Point pp1(0.5,0.5);
cout << "初始化方式p(double, double):\n" << pp1 << endl;
cout << "重载运算符[]:\n" << p3[0] << '\t' << p3[1] << endl;
cout << "输出Point类型的长度:\n " << p3.length() << endl;
p3 += p2;
cout << "重载运算符+=:\n" << p3 << endl;
p3 -= p2;
cout << "重载运算符-=:\n" << p3 << endl;
p3 *= 2;
cout << "重载运算符*=:\n" << p3 << endl;
p3 /= 2;
cout << "重载运算符/=:\n" << p3 << endl;
p3 = p2 + p1;
cout << "重载运算符+:\n " << p3 << endl;
p3 = p2 - p1;
cout << "重载运算符-:\n" << p3 << endl;
cout << "输入两个数:" << endl;
cin >> p3;
cout << "重载输入流 >>:\n" <<p3 << endl;
cout << "输出两个点的中点:\n" << midpoint(p1,p3) << endl;
cout << "输出两个点的距离:\n" << distance(p1,p3) << endl;
Point pp2(0,0), pp3(0.5,0), pp4(0,0.5);
cout << "输出三角形的面积:\n" << AREA(pp2,pp3,pp4) << endl;
std::vector<Point> pp{pp2,pp3,pp4};
Point barycenter0 = barycenter(pp, NULL);
cout << "输出三角形的质心:\n" << barycenter0 << endl;
}
void TmpEleTest()
{
////////////////////////////////////////////////////////////////////////////
// 测试TmpEle类
////////////////////////////////////////////////////////////////////////////
cout << "*********************************************************" << endl;
cout << "\n\t\t类TmpEle的测试\n\n\n";
cout << "*********************************************************" << endl;
TmpEle te;
cout << "默认初始化以及输出流重载的测试:\n" << te <<endl;
TmpEle te1(1);
cout << "给私有成员赋予一阶的Gauss点和权重:\n" << te1 << endl;
TmpEle te2(2);
cout << "给私有成员赋予二阶的Gauss点和权重:\n" << te2 << endl;
TmpEle te3(3);
cout << "给私有成员赋予三阶的Gauss点和权重:\n" << te3 << endl;
TmpEle te4(4);
cout << "给私有成员赋予四阶的Gauss点和权重:\n" << te4 << endl;
TmpEle te5(5);
cout << "给私有成员赋予五阶的Gauss点和权重:\n" << te5 << endl;
TmpEle te6(6);
cout << "给私有成员赋予六阶的Gauss点和权重:\n" << te6 << endl;
TmpEle te7(7);
cout << "给私有成员赋予七阶的Gauss点和权重:\n" << te7 << endl;
TmpEle te10(10);
cout << "给私有成员赋予十阶的Gauss点和权重:\n" << te10 << endl;
TmpEle te12(12);
cout << "给私有成员赋予十二阶的Gauss点和权重:\n" << te12 << endl;
Point p4 = te12.getPnt(1);
cout << "成员函数getPnt(int):\n" << p4 << endl;
double Area = te12.getArea();
cout << "成员函数getArea():\n" << Area << endl;
cout << "成员函数getGaussPnt():" << endl;
std::vector<Point> GP = te12.getGaussPnt();
for (auto i : GP)
cout << i << endl;
cout << "成员函数getGaussWeight():" << endl;
std::vector<double> GW = te12.getGaussWeight();
for (auto i : GW)
cout << i << endl;
Point p5(0,0), p6(0.5,0), p7(0,0.5);
std::vector<Point> v1{p5,p6,p7};
Point ppp1(0,0);
Point p8 = te.Local_to_Global(ppp1,v1);
cout << "测试函数Local_to_Global:\n" << "(0,0)->>\t"<< p8 << endl;
Point ppp2(0,1);
p8 = te.Local_to_Global(ppp2,v1);
cout << "(0,1)->>\t" << p8 << endl;
Point ppp3(1,0);
p8 = te.Local_to_Global(ppp3,v1);
cout << "(1,0)->>\t" << p8 << endl;
Point ppp4(0,0);
Point p9 = te.Global_to_Local(ppp4,v1);
cout << "测试函数Global_to_Local:\n" << "(0,0)->> \t" << p9 << endl;
Point ppp5(0,0.5);
p9 = te.Global_to_Local(ppp5,v1);
cout << "(0,0.5)->>\t" << p9 << endl;
Point ppp6(0.5,0);
p9 = te.Global_to_Local(ppp6,v1);
cout << "(0.5,0)->>\t" << p9 << endl;
std::vector<Point> v2{ppp1,ppp2,ppp3};
std::vector<Point> vv = te.Local_to_Global(v2,v1);
cout << "测试函数Local_to_Global:\n";
for (int i = 0; i < v2.size(); i++)
cout << v2[i] << "-->>" <<vv[i] << endl;
std::vector<Point> vv1 = te.Global_to_Local(v1,v1);
cout << "测试函数Global_to_Local:\n";
for (int i = 0; i < v1.size(); i++)
cout << v1[i] << "-->>" << vv1[i] << endl;
double jacobian = te.Local_to_Global_jacobian(ppp1,v1);
cout << "从标准单元到普通单元的雅克比矩阵:\n" << jacobian << endl;
jacobian = te.Global_to_Local_jacobian(ppp1,v1);
cout << "从普通单元到标准单元的雅克比矩阵:\n" << jacobian << endl;
std::vector<double> jacobian1 = te.Local_to_Global_jacobian(v1,v1);
cout << "从标准单元到普通单元的雅克比矩阵:\n";
for (auto i : jacobian1)
cout << i << "\t";
cout << endl;
jacobian1 = te.Global_to_Local_jacobian(v1,v1);
cout << "从普通单元到标准单元的雅克比矩阵:\n";
for (auto i : jacobian1)
cout << i << "\t";
cout << endl;
}
void MeshTest()
{
////////////////////////////////////////////////////////////////////////////
//测试类Mesh
////////////////////////////////////////////////////////////////////////////
cout << "*********************************************************" << endl;
cout << "\n\t\t类Mesh的测试\n\n\n";
cout << "*********************************************************" << endl;
Mesh mesh;
cout << "测试默认构造函数:\n" << mesh << endl;
mesh.readData("Trimesh.txt");
cout << "测试函数readData\n" << mesh << endl;
int ele = mesh.getEleVtx(2,2); // 选取第三行边的第三个边
cout << "测试函数getEleData\n" << ele << endl;
std::vector<int> ele1 = mesh.getEleVtx(2);
cout << "测试函数getEleData:\n";
for (auto i : ele1)
cout << i << "\t";
cout << endl;
Point p = mesh.getPnt(2);
cout << "测试函数getPnt:\n" << p << endl;
int n_ele = mesh.n_element();
cout << "得到三角单元的个数:\n" << n_ele << endl;
int n_point = mesh.n_point();
cout << "得到剖分单元点的个数:\n" << n_point << endl;
int n_boundaryPoint = mesh.n_boundaryPoint();
cout << "得到剖分单元边界点的个数:\n" << n_boundaryPoint << endl;
std::vector<int> num{1,2,3,4,5,6,7,8,9};
std::vector<Point> point = mesh.getPnt(num);
cout << "测试函数getPnt,输入一系列整数:\n";
for (auto i : point)
cout << i << "\n";
cout << endl;
}
void PDETest()
{
cout << "*********************************************************" << endl;
cout << "\n\t\t类PDE的测试\n\n\n";
cout << "*********************************************************" << endl;
PDE pde;
double p[2] = {1,1};
cout << "PDE中成员函数u_boundary的测试:\n" << pde.u_boundary(p) << endl;
Point p1(1,1);
cout << pde.u_boundary(p) << endl;
cout << "PDE中成员函数u_exact的测试:\n" << pde.u_exact(p) << endl;
cout << pde.u_exact(p1) << endl;
cout << "PDE中成员函数f的测试:\n" << pde.f(p) << endl;
cout << pde.f(p1) << endl;
}
void MatrixTest()
{
////////////////////////////////////////////////////////////////////////////
//测试类Possion
////////////////////////////////////////////////////////////////////////////
cout << "*********************************************************" << endl;
cout << "\n\t\t类Matrix的测试\n\n\n";
cout << "*********************************************************" << endl;
Matrix possion;
cout << "****基函数构造测试****" << endl;
Point p0(0,0);
Point p1(1,0);
Point p2(0,1);
std::vector<Point> Te{p0,p1,p2};
Point center = barycenter(Te,NULL);
cout << "输出三角单元的质心:\n" << center << endl;
std::vector<double> basis;
cout << "标准单元上基函数的值:\n" << endl;
possion.basisValue(p0,Te,basis);
for (auto i : basis)
cout << i << "\t";
cout << endl;
possion.basisValue(p1,Te,basis);
for (auto i : basis)
cout << i << "\t";
cout << endl;
possion.basisValue(p2,Te,basis);
for (auto i : basis)
cout << i << "\t";
cout << endl;
cout << "测试标准单元上的基函数的值,(重载basisValue函数):\n";
std::vector<std::vector<double>> basis1;
std::vector<Point> Te1{p0,p1,p2,p0,p1,p2};
possion.basisValue(Te1,Te,basis1);
for (auto& i : basis1){
for (auto j : i)
cout << j << "\t";
cout << "\n";
}
cout << endl;
cout << "****梯度算子计算测试****" << endl;
std::vector<std::vector<double>> basisGrad1;
possion.basisGrad(p0,Te,basisGrad1);
for (auto &i : basisGrad1){
for (auto j : i)
cout << j << "\t";
cout << "\n";
}
cout << endl;
cout << "重载梯度算子的函数测试:\n";
std::vector<std::vector<std::vector<double>>> basisGrad2;
possion.basisGrad(Te,Te,basisGrad2);
for (auto& i : basisGrad2){
for (auto& j : i){
for (auto k : j){
cout << k << "\t";
}
cout << "\n";
}
}
cout <<endl;
////////////////////////////////////////////////////////////////////////////
//左端刚度矩阵和右端矩阵的测试(未经过边界处理)
////////////////////////////////////////////////////////////////////////////
Matrix Possion_matrix("Trimesh.txt",7);
PDE pde;
int n_pnt = Possion_matrix.mesh.n_point();
Possion_matrix.u_h.resize(n_pnt);
std::vector<std::vector<double>> A_matrix;
std::vector<double> Rhs;
Possion_matrix.buildMatrix_RHS(A_matrix, Rhs);
cout << "输出(未经过边界处理)左端刚度矩阵和右端项:\n" << endl;
// 输出左端刚度矩阵和右端项
for (auto &i : A_matrix){
for (auto j : i)
cout << j << "\t";
cout << "\n";
}
cout << endl;
cout << "\n\n\n";
for (auto i : Rhs)
cout << i << "\n";
cout << endl;
Possion_matrix.DealBoundary(A_matrix, Possion_matrix.u_h, Rhs);
cout << "输出(经过边界处理)左端刚度矩阵和右端项:\n" << endl;
// 输出左端刚度矩阵和右端项
for (auto &i : A_matrix){
for (auto j : i)
cout << j << "\t";
cout << "\n";
}
cout << endl;
cout << "\n\n\n";
for (auto i : Rhs)
cout << i << "\n";
cout << endl;
Possion_matrix.GaussSeidel(A_matrix,Possion_matrix.u_h, Rhs);
cout << "数值解:\n" << endl;
for (auto i : Possion_matrix.u_h)
cout << i << "\n";
cout << endl;
double L2Error=Possion_matrix.ComputerL2Error(Possion_matrix.u_h);
std::cout<<"L2Error="<<L2Error<<std::endl;
}
int main()
{
PointTest();
TmpEleTest();
MeshTest();
PDETest();
MatrixTest();
return 0;
}<file_sep>/Heat方程-C++显格式/Parabolic.h
#ifndef PARABOLIC_H
#define PARABOLIC_H
#include "Point.h"
#include "PDE.h"
#include "TmpEle.h"
#include "Mesh.h"
extern double Dt; // 时间剖分的步长
class Parabolic
{
private:
// 数据结构
PDE pde;
Mesh mesh;
TmpEle tmpEle;
std::vector<double> u_h;
// 私有函数
// gauss-seidel迭代
void GaussSeidel(std::vector<std::vector<double>>&,std::vector<double>&, std::vector<double>&);
// 利用Eigen库求解稀疏代数方程组
void SolveLinearASparse(Eigen::SparseMatrix<double>&,std::vector<double>&, std::vector<double>&, int);
// 基函数的构造
void basisValue(Point&, std::vector<Point>&, std::vector<double>&);
void basisValue(std::vector<Point>&, std::vector<Point>&, std::vector<std::vector<double>>&);
// 梯度算子的计算
void basisGrad(Point&, std::vector<Point>&, std::vector<std::vector<double>>&);
void basisGrad(std::vector<Point>&, std::vector<Point>&,
std::vector<std::vector<std::vector<double>>>&);
// 单元刚度矩阵
void buildEleMatrix_RHS(int, std::vector<std::vector<double>>&,
std::vector<std::vector<double>>&, std::vector<double>&, double);
// 总刚度矩阵(稀疏存储)
void buildMatrix_RHS_Sparse(Eigen::SparseMatrix<double>&,
Eigen::SparseMatrix<double>&, std::vector<double>&, double);
// 稀疏矩阵的边界条件的处理
void DealBoundary_Sparse(Eigen::SparseMatrix<double>&,
std::vector<double>&, double);
// 求解抛物方程的全离散显格式
void fullDiscreteFormat(Eigen::SparseMatrix<double> &,
const Eigen::SparseMatrix<double>&,
const std::vector<double> &, std::vector<double> &);
// 求解抛物方程的全离散隐格式
void fullDiscreteImplicitFormat(Eigen::SparseMatrix<double> &,
Eigen::SparseMatrix<double> &,
const std::vector<double> &, std::vector<double> &);
// 计算L2误差
double ComputerL2Error(const std::vector<double> &, double);
// 计算H1误差
double ComputerH1Error(const std::vector<double> &, double);
// 输出边界处的值
void checkBoundary(const std::vector<double> &, double);
// 输出解析解和数值解
void checkValue(const std::vector<double> &, double);
public:
Parabolic() = default;
Parabolic(const std::string&, int);
// 求解方程组(全离散显格式)
void runFullDiscreteFormat(const std::string &);
// 求解方程组(全离散隐格式)
void runFullDiscreteImplicitFormat(const std::string &);
};
#endif
<file_sep>/Possion方程--C++(CVT自适应)/CVT_Adaptive_finite.cpp
/*************************************************************************
> File Name: CVT_Adaptive_finite.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年08月19日 星期日 22时24分34秒
************************************************************************/
#include "Possion.h"
#include "density.h"
int main()
{
// 参数设置
double maxN = 2e3, theta = 0.5;
int maxIt = 50;
// 初始化网格
system("./mesh_init -f square.poly -q 1 -a 0.01");
// 把初始网格信息写入文档中
std::vector<Point> node;
std::vector<std::vector<int>> ele;
std::vector<int> boundary_node;
writeTriangle(node,ele,boundary_node,"Trimesh.txt");
// 定义记录L2误差
std::vector<double> L2Errors;
// 定义记录点的个数
std::vector<int> numbers_node;
numbers_node.push_back(node.size());
// 开始自适应的过程
for (int index = 0; index != maxIt; ++index){
// 求解Possion方程并且得到残量型误差指示子
std::vector<double> eta; // 存放误差指示子
double L2Error = Possion("Trimesh.txt","Results.txt",eta,7);
L2Errors.push_back(L2Error);
if (node.size() > maxN) break; // 当网格点的数量大于maxN时候退出循环
// 优化和细化网格
density(node,ele,eta);
system("./mesh_refi -b 1 -p 0.2");
system("./mesh_opti -b 1");
std::vector<int> boundary_node1;
writeTriangle(node,ele,boundary_node1,"Trimesh.txt");
numbers_node.push_back(node.size());
}
// 将L2范误差输出到文档"L2Error.txt"中
std::ofstream out("L2Error.txt",std::ofstream::out);
for (decltype(L2Errors.size()) i = 0; i != L2Errors.size(); ++i)
out << L2Errors[i] << "\t" << numbers_node[i] << "\n";
out.close();
return 0;
}
<file_sep>/Possion方程--C++(CVT自适应)/Possion.cpp
/*************************************************************************
> File Name: Possion.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年08月19日 星期日 21时23分39秒
************************************************************************/
#include "Possion.h"
double Possion(const std::string filename_input,const std::string filename_output, std::vector<double>& eta,int i)
{
Matrix possion(filename_input,i);
PDE pde;
int n_pnt = possion.mesh.n_point(); // 得到网格点的个数
possion.u_h.resize(n_pnt);
std::vector<std::vector<double>> A_matrix;
std::vector<double> Rhs;
// 定义一个用于存储A_matrix的稀疏矩阵A_matrix_sparse
Eigen::SparseMatrix<double> A_matrix_sparse(A_matrix.size(),A_matrix.size());
possion.buildMatrix_RHS_Sparse(A_matrix_sparse,Rhs);
possion.DealBoundary_Sparse(A_matrix_sparse,possion.u_h,Rhs);
possion.SolveLinearASparse(A_matrix_sparse,possion.u_h,Rhs,3); // k 可以取1-5;这里取的3:gamres方法
double L2Error = possion.ComputerL2Error(possion.u_h);
// 计算eta误差指示子
possion.Estimateresidual(possion.u_h,eta);
// 把数据u_h写入结果文档
std::ofstream out(filename_output);
for (auto i : possion.u_h)
out << i << "\n";
out.close();
return L2Error;
}
void nodesf2dat(const std::string datafile, std::vector<Point>& node, std::vector<int>& boundary_node)
{
std::ifstream is(datafile,std::ifstream::in); // 以只读模式打开
int numbers;
is >> numbers;
is.close();
std::ifstream read(datafile,std::ifstream::in); // 以只读模式打开
std::vector<std::vector<double>> data;
// 初始化
data.resize(numbers + 1);
for (decltype(data.size()) i = 0; i != numbers+1; ++i){
data[i].resize(4);
}
for (decltype(data.size()) i = 0; i != numbers+1; ++i){
read >> data[i][0] >> data[i][1] >> data[i][2] >> data[i][3];
}
read.close();
// 初始化
node.resize(numbers);
for (decltype(node.size()) i = 0; i != numbers; ++i){
node[i][0] = data[i+1][1];
node[i][1] = data[i+1][2];
if (data[i+1][3] != 0)
boundary_node.push_back(data[i+1][0]-1);
}
}
void trigsf2dat(const std::string datafile, std::vector<std::vector<int>>& ele)
{
std::ifstream is(datafile,std::ifstream::in); // 以只读模式打开
int numbers;
is >> numbers;
is.close();
std::ifstream read(datafile,std::ifstream::in); // 以只读模式打开
std::vector<std::vector<double>> infor;
// 初始化
infor.resize(numbers + 1);
for (decltype(infor.size()) i = 0; i != numbers+1; ++i){
infor[i].resize(4);
}
read >> infor[0][0] >> infor[0][1] >> infor[0][2];
for (decltype(infor.size()) i = 0; i != numbers; ++i){
read >> infor[i+1][0] >> infor[i+1][1] >> infor[i+1][2] >> infor[i+1][3];
}
read.close();
// 初始化
ele.resize(numbers);
for (decltype(ele.size()) i = 0; i != numbers; ++i){
ele[i].resize(3);
}
for (decltype(ele.size()) i = 0; i != numbers; ++i){
ele[i][0] = infor[i+1][1] - 1; // triangle 输出边的编号从1开始
ele[i][1] = infor[i+1][2] - 1;
ele[i][2] = infor[i+1][3] - 1;
}
}
void writeTriangle(std::vector<Point>& node, std::vector<std::vector<int>>& ele,
std::vector<int>& boundary_node, const std::string output_file)
{
nodesf2dat("nodes.dat",node,boundary_node);
trigsf2dat("trigs.dat",ele);
// 输出内容
std::ofstream out(output_file,std::ofstream::out);
out << node.size() << "\n";
for(decltype(node.size()) i = 0; i != node.size(); ++i)
out << node[i][0] << "\t" << node[i][1] << "\n";
out << "\n";
out << ele.size() << "\n";
for (decltype(ele.size()) i = 0; i != ele.size(); ++i)
out << ele[i][0] << "\t" << ele[i][1] << "\t" << ele[i][2] << "\n";
out << "\n";
out << boundary_node.size() << "\n";
for (decltype(boundary_node.size()) i = 0; i != boundary_node.size(); ++i)
out << boundary_node[i] << "\n";
out << "\n";
out.close();
}
<file_sep>/Heat方程-C++隐格式-非零边界/Mesh.cpp
/*************************************************************************
> File Name: Mesh.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时39分19秒
************************************************************************/
#include "Mesh.h"
// 非成员函数
std::ostream& operator<< (std::ostream& os, const Mesh& M)
{
for (auto i : M.Pnt)
os << i << '\n';
for (auto &i : M.Ele){
for (auto j : i)
os << j << '\t';
os << '\n';
}
for (auto i : M.BndPnt)
os << i << '\n';
os << '\n';
return os;
}
// 成员函数
void Mesh::readData(const std::string& f)
{
int i;
std::ifstream is(f,std::ifstream::in); // 以只读的模式打开
is >> i;
Pnt.resize(i);
for (int j = 0; j < i; j++)
is >> Pnt[j][0] >> Pnt[j][1];
int n;
is >> n;
Ele.resize(n);
for (int j = 0; j < n; j++){
Ele[j].resize(3);
is >> Ele[j][0] >> Ele[j][1] >> Ele[j][2];
}
int bn;
is >> bn;
BndPnt.resize(bn);
for (int j = 0; j < bn; j++)
is >> BndPnt[j];
is.close();
}
int Mesh::getEleVtx(int i, int j)
{
return Ele[i][j];
}
std::vector<int> Mesh::getEleVtx(int i)
{
return Ele[i];
}
Point Mesh::getPnt(int i)
{
return Pnt[i];
}
std::vector<Point> Mesh::getPnt(std::vector<int>& vt)
{
std::vector<Point> vec;
for (int x : vt){
Point point = Pnt[x];
vec.push_back(point);
}
return vec;
}
std::vector<int> Mesh::getBndPnt()
{
return BndPnt;
}
int Mesh::n_element()
{
return Ele.size();
}
int Mesh::n_point()
{
return Pnt.size();
}
int Mesh::n_boundaryPoint()
{
return BndPnt.size();
}
<file_sep>/Heat方程-C++显格式/Parabolic.cpp
#include "Parabolic.h"
double Dt = 0.01;
void Parabolic::GaussSeidel(std::vector<std::vector<double> > &A_matrix, std::vector<double> &u, std::vector<double> &rhs)
{
std::vector<double> last_u(A_matrix.size());
do{
last_u=u;
double error=0.0;
for(int i=0;i<A_matrix.size();i++){
double temp=rhs[i];
for(int j=0; j<A_matrix[i].size(); j++){
if(j != i){
temp-=A_matrix[i][j]*u[j];
}
}
u[i]=temp/A_matrix[i][i];
}
u_int Vsize=u.size();
for(int k=0;k<Vsize;k++){
error+=(last_u[k]-u[k])*(last_u[k]-u[k]);
}
error=sqrt(error);
if(error<1.0e-10)
break;
}while(1);
}
void Parabolic::SolveLinearASparse(Eigen::SparseMatrix<double>& A_matrix_sparse,std::vector<double>& u,
std::vector<double>& rhs, int k)
{
auto b_size = rhs.size();
Eigen::VectorXd b;
b.resize(b_size);
for (size_t i = 0; i != b_size; ++i)
b(i) = rhs[i];
Eigen::VectorXd u_h_now;
// 求解器声明
Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner> cg;
Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IdentityPreconditioner> bicg;
Eigen::GMRES<Eigen::SparseMatrix<double>, Eigen::IdentityPreconditioner> gmres;
Eigen::DGMRES<Eigen::SparseMatrix<double>,Eigen::IdentityPreconditioner> dgmres;
Eigen::MINRES<Eigen::SparseMatrix<double>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> minres;
switch (k){
// 迭代法
case 1:
cg.compute(A_matrix_sparse);
u_h_now = cg.solve(b);
std::cout << "CG:\t #iterations: " << cg.iterations() << ", estimated error: " << cg.error()
<< std::endl;
break;
case 2:
bicg.compute(A_matrix_sparse);
u_h_now = bicg.solve(b);
std::cout << "BiCGSTAB:\t #iterations: " << bicg.iterations() << ", estimated error: "
<< bicg.error() << std::endl;
break;
case 3:
gmres.compute(A_matrix_sparse);
u_h_now = gmres.solve(b);
std::cout << "GMRES:\t #iterator: " << gmres.iterations() << ", estimated error: "
<< gmres.error() << std::endl;
break;
case 4:
dgmres.compute(A_matrix_sparse);
u_h_now = dgmres.solve(b);
std::cout << "DGMRES:\t #iterator: " << dgmres.iterations() << ", estimate error: "
<< dgmres.error() << std::endl;
break;
case 5:
minres.compute(A_matrix_sparse);
u_h_now = minres.solve(b);
std::cout << "MINRES:\t #iterator: " << minres.iterations() << ", estimate error: "
<< minres.error() << std::endl;
break;
}
// 将求解结果存储到u中
for (size_t i = 0; i != u.size(); ++i)
u[i] = u_h_now(i);
}
Parabolic::Parabolic(const std::string& file, int i)
{
mesh.readData(file);
tmpEle.buildTE(i);
}
// 成员函数
// 基函数的构造(面积坐标)
void Parabolic::basisValue(Point& p, std::vector<Point>& v, std::vector<double>& val)
{
val.resize(3); // 分片线性单元
double area = AREA(v[0], v[1], v[2]);
val[0] = AREA(p,v[1],v[2]);
val[1] = AREA(v[0],p,v[2]);
val[2] = AREA(v[0],v[1],p);
val[0] /= area;
val[1] /= area;
val[2] /= area;
}
void Parabolic::basisValue(std::vector<Point>& p, std::vector<Point>& v,
std::vector<std::vector<double>>& val)
{
int n = p.size();
val.resize(3);
for(int i = 0; i < 3; i++)
val[i].resize(n);
double area = AREA(v[0],v[1],v[2]);
for (int i=0; i < n; i++){
val[0][i] = AREA(p[i],v[1],v[2]);
val[1][i] = AREA(v[0],p[i],v[2]);
val[2][i] = AREA(v[0],v[1],p[i]);
val[0][i] /= area;
val[1][i] /= area;
val[2][i] /= area;
}
}
void Parabolic::basisGrad(Point&, std::vector<Point>& v,
std::vector<std::vector<double>>& val)
{
val.resize(3);
val[0].resize(2);
val[1].resize(2);
val[2].resize(2);
double area = AREA(v[0],v[1],v[2]) * 2; // 面积坐标到直角坐标的雅克比为2s
val[0][0] = (v[1][1] - v[2][1]) / area;
val[0][1] = (v[2][0] - v[1][0]) / area;
val[1][0] = (v[2][1] - v[0][1]) / area;
val[1][1] = (v[0][0] - v[2][0]) / area;
val[2][0] = (v[0][1] - v[1][1]) / area;
val[2][1] = (v[1][0] - v[0][0]) / area;
}
void Parabolic::basisGrad(std::vector<Point>& p, std::vector<Point>& v,
std::vector<std::vector<std::vector<double>>>& val)
{
int n = p.size();
val.resize(3);
for (int i = 0; i < 3; i++){
val[i].resize(n);
}
for (int i = 0; i < 3; i++){
for (int j = 0; j < n; j++){
val[i][j].resize(2);
}
}
double area = AREA(v[0],v[1],v[2]) * 2;
for (int i = 0; i < n; i++){
val[0][i][0] = (v[1][1] - v[2][1]) / area;
val[0][i][1] = (v[2][0] - v[1][0]) / area;
val[1][i][0] = (v[2][1] - v[0][1]) / area;
val[1][i][1] = (v[0][0] - v[2][0]) / area;
val[2][i][0] = (v[0][1] - v[1][1]) / area;
val[2][i][1] = (v[1][0] - v[0][0]) / area;
}
}
void Parabolic::buildEleMatrix_RHS(int n, std::vector<std::vector<double>> &Ele_Amatrix,
std::vector<std::vector<double>> &Ele_Mmatrix,
std::vector<double> &Ele_Rhs, double t)
{
Ele_Amatrix.resize(3); // 单元刚度矩阵(左端a(u,v)),维度是3*3的
Ele_Mmatrix.resize(3); // 单元刚度矩阵(左端(u,v)),维度是3*3的
Ele_Rhs.resize(3, 0.0); // 单元刚度矩阵(右端),维度是3*1的
for(int i=0; i<3; i++){
Ele_Amatrix[i].resize(3, 0.0);
Ele_Mmatrix[i].resize(3, 0.0);
}
// 得到第n个单元的边
std::vector<int> EV = mesh.getEleVtx(n);
// 得到单元的三个点
std::vector<Point> EP(3);
EP[0] = mesh.getPnt(EV[0]);
EP[1] = mesh.getPnt(EV[1]);
EP[2] = mesh.getPnt(EV[2]);
// 标准三角单元的面积
double volume = tmpEle.getArea();
// 得到标准三角单元的Gauss点
std::vector<Point> GP = tmpEle.getGaussPnt();
// 得到标准三角单元的Gauss权重
std::vector<double> GW = tmpEle.getGaussWeight();
// 把标准单元的Gauss点投影到普通单元上
std::vector<Point> q_point = tmpEle.Local_to_Global(GP, EP);
// 得到标准单元到普通单元的雅克比矩阵
std::vector<double> jacobian = tmpEle.Local_to_Global_jacobian(GP, EP);
// 得到三角单元上基函数的值
std::vector<std::vector<double>> basis_value;
basisValue(q_point, EP, basis_value);
// 得到三角单元上梯度算子的值
std::vector<std::vector<std::vector<double>>> basis_grad;
basisGrad(q_point, EP, basis_grad);
// 计算右端的单元刚度矩阵
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i] * jacobian[i] * volume;
double f_value = pde.f(q_point[i],t);
for(int j = 0; j < basis_value.size(); j++){
Ele_Rhs[j] += Jxw * f_value * basis_value[j][i];
}
}
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i] * jacobian[i] * volume;
for(int k = 0; k<basis_grad.size(); k++){
for(int j = 0; j<basis_grad.size(); j++){
// 左端的单元刚度矩阵(a(u,v))
Ele_Amatrix[j][k] += Jxw * (basis_grad[j][i][0] *
basis_grad[k][i][0] + basis_grad[j][i][1] * basis_grad[k][i][1]);
}
}
for (int k = 0; k < basis_value.size(); ++k){
for (int j = 0; j < basis_value.size(); ++j){
// 左端的单元刚度矩阵((u,v))
Ele_Mmatrix[j][k] += Jxw * basis_value[j][i] * basis_value[k][i];
}
}
}
}
void Parabolic::buildMatrix_RHS_Sparse(Eigen::SparseMatrix<double> &A_matrix_sparse,
Eigen::SparseMatrix<double> &M_matrix_sparse,
std::vector<double>& Rhs, double time)
{
auto n_ele = mesh.n_element();
auto n_pnt = mesh.n_point();
A_matrix_sparse.resize(n_pnt,n_pnt);
M_matrix_sparse.resize(n_pnt,n_pnt);
Rhs.resize(n_pnt);
// 定义一个用于存储稀疏矩阵的三元组
std::vector<Eigen::Triplet<double>> Atriple, Mtriple;
for (size_t i = 0; i != n_ele; ++i){
std::vector<int> NV = mesh.getEleVtx(i);
std::vector<std::vector<double>> Ele_Amatrix(3);
std::vector<std::vector<double>> Ele_Mmatrix(3);
for (size_t j = 0; j != 3; ++j){
Ele_Amatrix[j].resize(3,0.0);
Ele_Mmatrix[j].resize(3,0.0);
}
std::vector<double> Ele_Rhs(3,0.0);
buildEleMatrix_RHS(i,Ele_Amatrix,Ele_Mmatrix,Ele_Rhs,time);
// 稀疏矩阵存储技术
// 利用经典的三元组插入方式来存储A_matrix
Atriple.push_back(Eigen::Triplet<double>(NV[0],NV[0],Ele_Amatrix[0][0]));
Atriple.push_back(Eigen::Triplet<double>(NV[0],NV[1],Ele_Amatrix[0][1]));
Atriple.push_back(Eigen::Triplet<double>(NV[0],NV[2],Ele_Amatrix[0][2]));
Atriple.push_back(Eigen::Triplet<double>(NV[1],NV[0],Ele_Amatrix[1][0]));
Atriple.push_back(Eigen::Triplet<double>(NV[1],NV[1],Ele_Amatrix[1][1]));
Atriple.push_back(Eigen::Triplet<double>(NV[1],NV[2],Ele_Amatrix[1][2]));
Atriple.push_back(Eigen::Triplet<double>(NV[2],NV[0],Ele_Amatrix[2][0]));
Atriple.push_back(Eigen::Triplet<double>(NV[2],NV[1],Ele_Amatrix[2][1]));
Atriple.push_back(Eigen::Triplet<double>(NV[2],NV[2],Ele_Amatrix[2][2]));
// 利用经典的三元组插入方式来存储M_matrix
Mtriple.push_back(Eigen::Triplet<double>(NV[0],NV[0],Ele_Mmatrix[0][0]));
Mtriple.push_back(Eigen::Triplet<double>(NV[0],NV[1],Ele_Mmatrix[0][1]));
Mtriple.push_back(Eigen::Triplet<double>(NV[0],NV[2],Ele_Mmatrix[0][2]));
Mtriple.push_back(Eigen::Triplet<double>(NV[1],NV[0],Ele_Mmatrix[1][0]));
Mtriple.push_back(Eigen::Triplet<double>(NV[1],NV[1],Ele_Mmatrix[1][1]));
Mtriple.push_back(Eigen::Triplet<double>(NV[1],NV[2],Ele_Mmatrix[1][2]));
Mtriple.push_back(Eigen::Triplet<double>(NV[2],NV[0],Ele_Mmatrix[2][0]));
Mtriple.push_back(Eigen::Triplet<double>(NV[2],NV[1],Ele_Mmatrix[2][1]));
Mtriple.push_back(Eigen::Triplet<double>(NV[2],NV[2],Ele_Mmatrix[2][2]));
// 不利用稀疏矩阵存储右端项Rhs
Rhs[NV[0]] += Ele_Rhs[0];
Rhs[NV[1]] += Ele_Rhs[1];
Rhs[NV[2]] += Ele_Rhs[2];
}
// 把三元组转换成稀疏矩阵
A_matrix_sparse.setFromTriplets(Atriple.begin(),Atriple.end());
M_matrix_sparse.setFromTriplets(Mtriple.begin(),Mtriple.end());
}
// 对于稀疏矩阵A_matrix_sparse的边界条件处理(dirichlet边界条件)
void Parabolic::DealBoundary_Sparse(Eigen::SparseMatrix<double> &M_matrix_sparse,
std::vector<double>& Rhs, double t)
{
auto n_pnt = mesh.n_point();
auto n_bp = mesh.n_boundaryPoint();
std::vector<int> BV = mesh.getBndPnt(); // 得到边界点
for (size_t i = 0; i != n_bp; ++i){
Point Pnt_i = mesh.getPnt(BV[i]); // 得到第i个单元的点
double val = pde.u_boundary(Pnt_i,t);
Rhs[BV[i]] = M_matrix_sparse.coeffRef(BV[i],BV[i]) * val;
for (size_t j = 0; j != n_pnt; ++j){
if (j != BV[i]){
M_matrix_sparse.coeffRef(BV[i],j) = 0.0;
}
}
for (size_t j = 0; j != n_pnt; ++j){
if (j != BV[i]){
Rhs[j] -= M_matrix_sparse.coeffRef(j, BV[i]) * val;
M_matrix_sparse.coeffRef(j,BV[i]) = 0.0;
}
}
}
// 去除稀疏矩阵中的零元素
M_matrix_sparse = M_matrix_sparse.pruned();
// 压缩剩余空间
M_matrix_sparse.makeCompressed();
}
// 全离散显格式
void Parabolic::fullDiscreteFormat(Eigen::SparseMatrix<double> &A_matrix_sparse,
const Eigen::SparseMatrix<double> &M_matrix_sparse,
const std::vector<double> &u_h, std::vector<double> &Rhs)
{
// 去除矩阵A_matrix_sparse中的零元素
A_matrix_sparse = A_matrix_sparse.pruned();
// 压缩剩余空间
A_matrix_sparse.makeCompressed();
// 利用Eigen中的Matrix存储u_h,Rhs
Eigen::MatrixXd u_h_matrix(u_h.size(),1);
Eigen::MatrixXd Rhs_matrix(Rhs.size(),1);
for (decltype(u_h.size()) i = 0; i != u_h.size(); ++i)
u_h_matrix(i,0) = u_h[i];
for (decltype(Rhs.size()) i = 0; i != Rhs.size(); ++i)
Rhs_matrix(i,0) = Rhs[i];
// Eigen中二元操作符支持稀疏矩阵和密集矩阵的混合操作
// 实现全离散显格式
Rhs_matrix = (M_matrix_sparse - Dt * A_matrix_sparse) * u_h_matrix + Rhs_matrix * Dt;
// 把得到的Eigen密集型矩阵转换为vector类型
for (decltype(Rhs.size()) i = 0; i != Rhs.size(); ++i)
Rhs[i] = Rhs_matrix(i,0);
}
// 全离散隐格式
void Parabolic::fullDiscreteImplicitFormat(Eigen::SparseMatrix<double> &A_matrix_sparse,
Eigen::SparseMatrix<double> &M_matrix_sparse,
const std::vector<double> &u_h, std::vector<double> &Rhs)
{
// 去除矩阵A_matrix_sparse中的零元素
A_matrix_sparse = A_matrix_sparse.pruned();
// 压缩剩余空间
A_matrix_sparse.makeCompressed();
// 利用Eigen中的Matrix存储u_h,Rhs
Eigen::MatrixXd u_h_matrix(u_h.size(),1);
Eigen::MatrixXd Rhs_matrix(Rhs.size(),1);
for (decltype(u_h.size()) i = 0; i != u_h.size(); ++i)
u_h_matrix(i,0) = u_h[i];
for (decltype(Rhs.size()) i = 0; i != Rhs.size(); ++i)
Rhs_matrix(i,0) = Rhs[i];
// 实现全离散隐格式
Rhs_matrix = Dt * Rhs_matrix + M_matrix_sparse * u_h_matrix;
M_matrix_sparse = M_matrix_sparse + Dt * A_matrix_sparse;
// 把得到的Eigen密集型矩阵转换为vector类型
for (decltype(Rhs.size()) i = 0; i != Rhs.size(); ++i)
Rhs[i] = Rhs_matrix(i,0);
}
double Parabolic::ComputerL2Error(const std::vector<double> &f, double time)
{
double err=0.0;
int n_ele=mesh.n_element();
for(int j=0; j<n_ele; j++){
std::vector<int> NV = mesh.getEleVtx(j);
std::vector<Point> EP(3);
EP[0]=mesh.getPnt(NV[0]);
EP[1]=mesh.getPnt(NV[1]);
EP[2]=mesh.getPnt(NV[2]);
double volume = tmpEle.getArea();
std::vector<Point> GP = tmpEle.getGaussPnt();
std::vector<double> GW = tmpEle.getGaussWeight();
std::vector<Point> q_point = tmpEle.Local_to_Global(GP, EP);
std::vector<double> jacobian = tmpEle.Local_to_Global_jacobian(GP, EP);
std::vector<std::vector<double> > basis_value;
basisValue(q_point, EP, basis_value);
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i]*jacobian[i]*volume;
double f_value = pde.u_exact(q_point[i],time);
double u_h_val = f[NV[0]]*basis_value[0][i]+f[NV[1]]*basis_value[1][i]+f[NV[2]]*basis_value[2][i];
double df_val = f_value-u_h_val;
err += Jxw*df_val*df_val;
}
}
err=sqrt(err);
return err;
}
double Parabolic::ComputerH1Error(const std::vector<double> &f, double time)
{
double err=0.0;
int n_ele=mesh.n_element();
for(int j=0; j<n_ele; j++){
std::vector<int> NV=mesh.getEleVtx(j);
std::vector<Point> EP(3);
EP[0]=mesh.getPnt(NV[0]);
EP[1]=mesh.getPnt(NV[1]);
EP[2]=mesh.getPnt(NV[2]);
std::vector<Point> GP=tmpEle.getGaussPnt();
std::vector<double> GW=tmpEle.getGaussWeight();
std::vector<Point> q_point = tmpEle.Local_to_Global(GP, EP);
std::vector<double> jacobian = tmpEle.Local_to_Global_jacobian(GP, EP);
std::vector<std::vector<std::vector<double>>> basis_grad;
basisGrad(q_point, EP, basis_grad);
for(int i = 0; i < q_point.size(); i++){
double Jxw = GW[i]*jacobian[i];
std::vector<double> f_value = pde.u_exact_grad(q_point[i], time);
double u_h_grad1=0.0;
double u_h_grad2=0.0;
u_h_grad1 = f[NV[0]] * basis_grad[0][i][0] + f[NV[1]] * basis_grad[1][i][0] +
f[NV[2]] * basis_grad[2][i][0];
u_h_grad2 = f[NV[0]] * basis_grad[0][i][1] + f[NV[1]] * basis_grad[1][i][1] +
f[NV[2]] * basis_grad[2][i][1];
double df_val1 = f_value[0] - u_h_grad1;
double df_val2 = f_value[1] - u_h_grad2;
err += Jxw * df_val1 * df_val1;
err += Jxw * df_val2 * df_val2;
}
}
err = sqrt(err);
return err;
}
// 输出u_h在边界处的值
void Parabolic::checkBoundary(const std::vector<double> &u_h, double t)
{
std::vector<int> boundaryPointIndex = mesh.getBndPnt();
for (size_t i = 0; i != mesh.n_boundaryPoint(); ++i){
std::cout << u_h[boundaryPointIndex[i]] << "\t" << pde.u_boundary(mesh.getPnt(boundaryPointIndex[i]),t) << "\t"
<< pde.u_boundary(mesh.getPnt(boundaryPointIndex[i]),t) - u_h[boundaryPointIndex[i]] << "\n";
}
std::cout << "\n";
}
void Parabolic::checkValue(const std::vector<double> &u_h, double t)
{
for (size_t i = 0; i != mesh.n_point(); ++i){
std::cout << u_h[i] << "\t" << pde.u_exact(mesh.getPnt(i), t)
<<"\t" << pde.u_exact(mesh.getPnt(i),t) - u_h[i] << "\n";
}
std::cout << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// 类的接口函数
////////////////////////////////////////////////////////////////////////////////////////////////////////
void Parabolic::runFullDiscreteFormat(const std::string &outputFile)
{
int n_pnt = mesh.n_point(); // 得到网格点的个数
u_h.resize(n_pnt);
// 给u_h赋初始值
for (size_t i = 0; i != n_pnt; ++i)
u_h[i] = pde.u_exact(mesh.getPnt(i),0);
double L2Error, H1Error;
std::ofstream out(outputFile);
out << "time\tL2Error\tH1Error" << "\n";
for (double time = Dt; time <= 1.0000009; time = time + Dt){
// 定义一个用于存储A_matrix的稀疏矩阵A_matrix_sparse
Eigen::SparseMatrix<double> A_matrix_sparse, M_matrix_sparse;
std::vector<double> Rhs;
// 求解刚度矩阵A(a(u,v)),M((u,v)),Rhs((f,v))
buildMatrix_RHS_Sparse(A_matrix_sparse, M_matrix_sparse, Rhs, time);
// 求解抛物方程的全离散显格式
fullDiscreteFormat(A_matrix_sparse, M_matrix_sparse, u_h, Rhs);
// 边界条件的处理
DealBoundary_Sparse(M_matrix_sparse, Rhs, time);
// k可以取1-5; gmres:case 3(求解PDE离散后形成的代数系统)
std::cout << time << std::endl;
SolveLinearASparse(M_matrix_sparse, u_h, Rhs, 3);
L2Error = ComputerL2Error(u_h, time); // 求解L2误差
H1Error = ComputerH1Error(u_h, time); // 求解H1误差
out << time << "\t" << L2Error << "\t" << H1Error << "\n";
}
out.close();
}
void Parabolic::runFullDiscreteImplicitFormat(const std::string &outputFile)
{
int n_pnt = mesh.n_point(); // 得到网格点的个数
u_h.resize(n_pnt);
double L2Error, H1Error;
// 给u_h赋初始值
for (size_t i = 0; i != n_pnt; ++i)
u_h[i] = pde.u_exact(mesh.getPnt(i),0);
L2Error = ComputerL2Error(u_h,0);
H1Error = ComputerH1Error(u_h,0);
std::ofstream out(outputFile);
out << "time\tL2Error\tH1Error" << "\n";
for (double time = Dt; time <= 1.00009; time += Dt){
// 定义一个用于存储A_matrix的稀疏矩阵A_matrix_sparse
Eigen::SparseMatrix<double> A_matrix_sparse, M_matrix_sparse;
std::vector<double> Rhs;
// 求解刚度矩阵A(a(u,v)),M((u,v)),Rhs((f,v))
buildMatrix_RHS_Sparse(A_matrix_sparse, M_matrix_sparse, Rhs, time);
// 求解抛物方程的全离散隐格式
fullDiscreteImplicitFormat(A_matrix_sparse, M_matrix_sparse, u_h, Rhs);
// 边界条件的处理
DealBoundary_Sparse(M_matrix_sparse, Rhs, time);
// k可以取1-5; gmres:case 3(求解PDE离散后形成的代数系统)
std::cout << time << std::endl;
SolveLinearASparse(M_matrix_sparse, u_h, Rhs, 3);
L2Error = ComputerL2Error(u_h, time); // 求解L2误差
H1Error = ComputerH1Error(u_h, time); // 求解H1误差
out << time << "\t" << L2Error << "\t" << H1Error << "\n";
//checkBoundary(u_h,time);
//checkValue(u_h,time);
}
out.close();
}
<file_sep>/Possion方程-C++-p1元--Eigen(no sparse)/Matrix.h
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <fstream>
#include <Eigen/Dense> // 线性代数库
#include <Eigen/IterativeLinearSolvers> // 迭代法求解线性方程组的求解库
#include <unsupported/Eigen/IterativeSolvers>
class Point
{
friend std::ostream& operator<< (std::ostream&, const Point&);
friend std::istream& operator>> (std::istream&, Point&);
friend Point operator+ (const Point&, const Point&);
friend Point operator- (const Point&, const Point&);
friend Point midpoint(const Point&, const Point&);
friend double distance(const Point&, const Point&);
// 求三角形的质心,可以求加权质心
friend Point barycenter(const std::vector<Point>&, const double *);
friend double AREA(const Point&, const Point&, const Point&);
private:
double x[2];
public:
Point();
Point(const double*);
Point(const Point&);
Point(const double&, const double&);
Point& operator= (const Point&);
double& operator[] (int);
const double& operator[] (int) const;
double length() const;
Point& operator+= (const Point&);
Point& operator-= (const Point&);
Point& operator*= (const double&);
Point& operator/= (const double&);
};
class TmpEle
{
friend std::ostream& operator<< (std::ostream&, const TmpEle&);
private:
std::vector<Point> Pnt;
std::vector<Point> GaussPnt;
std::vector<double> GaussWeight;
public:
// 构造函数
TmpEle();
TmpEle(int);
void buildTE(int);
Point getPnt(int);
double getArea();
std::vector<Point> getGaussPnt();
std::vector<double> getGaussWeight();
// 标准单元到普通单元
Point Local_to_Global(const Point&, const std::vector<Point> &) const;
// 普通单元到标准单元
Point Global_to_Local(const Point&, const std::vector<Point> &) const;
// 标准单元到普通单元
std::vector<Point> Local_to_Global(const std::vector<Point> &,const std::vector<Point> & ) const;
// 普通单元到标准单元
std::vector<Point> Global_to_Local(const std::vector<Point>&, const std::vector<Point>&) const;
// 从标准单元到普通单元的雅克比矩阵
double Local_to_Global_jacobian(const Point&, const std::vector<Point>&) const;
// 从普通单元到标准单元的雅克比矩阵
double Global_to_Local_jacobian(const Point&, const std::vector<Point>&) const;
// 从标准单元到普通单元的雅克比矩阵
std::vector<double> Local_to_Global_jacobian(const std::vector<Point>&, const std::vector<Point>&) const;
// 从普通单元到标准单元的雅克比矩阵
std::vector<double> Global_to_Local_jacobian(const std::vector<Point>&, const std::vector<Point>&) const;
};
class Mesh
{
friend std::ostream& operator<< (std::ostream&, const Mesh&);
private:
std::vector<Point> Pnt; // 三角单元的点
std::vector<int> BndPnt; // 三角单元的边界点
std::vector<std::vector<int>> Ele; // 三角单元的边
public:
Mesh() = default; // 默认构造函数
void readData(const std::string&);
int getEleVtx(int , int);
std::vector<int> getEleVtx(int);
Point getPnt(int);
std::vector<Point> getPnt(std::vector<int>&);
std::vector<int> getBndPnt();
int n_element(); // 得到三角单元的数量
int n_point(); // 得到点的个数
int n_boundaryPoint(); // 得到边界点的个数
};
class PDE
{
public:
// 偏微分方程的边界条件
double u_boundary(const Point&);
// 偏微分方程的右端项
double f(const Point&);
// 偏微分方程解析解
double u_exact(const Point&);
};
class Matrix
{
public:
// 数据结构
PDE pde;
Mesh mesh;
TmpEle tmpEle;
std::vector<double> u_h;
Matrix() = default;
Matrix(const std::string&, int);
// gauss-seidel迭代
void GaussSeidel(std::vector<std::vector<double>>&, std::vector<double>&, std::vector<double>&);
// 利用Eigen库求解代数方程组
void SolveLinearA(std::vector<std::vector<double>>&, std::vector<double>&, std::vector<double>&, int);
// 基函数的构造
void basisValue(Point&, std::vector<Point>&, std::vector<double>&);
void basisValue(std::vector<Point>&, std::vector<Point>&, std::vector<std::vector<double>>&);
// 梯度算子的计算
void basisGrad(Point&, std::vector<Point>&, std::vector<std::vector<double>>&);
void basisGrad(std::vector<Point>&, std::vector<Point>&, std::vector<std::vector<std::vector<double>>>&);
// 单元刚度矩阵
void buildEleMatrix_RHS(int, std::vector<std::vector<double>>&, std::vector<double>&);
// 总刚度矩阵
void buildMatrix_RHS(std::vector<std::vector<double>>&, std::vector<double>&);
// 边界条件的处理
void DealBoundary(std::vector<std::vector<double>>&, std::vector<double>&, std::vector<double>&);
// 计算L2误差
double ComputerL2Error(std::vector<double> &);
};
<file_sep>/Heat方程-C++显格式/PDE.cpp
/*************************************************************************
> File Name: PDE.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时45分37秒
************************************************************************/
#include "PDE.h"
// 边界条件(第一类边界条件)
double PDE::u_boundary(const Point &p, double t)
{
double value;
value = 0.0;
return value;
}
double PDE::f(const Point &p, double t)
{
double value;
value = exp(t) * ( (p[0] * p[0] - p[0]) * (p[1] * p[1] - p[1]) -
2 * (p[0] * p[0] - p[0] + p[1] * p[1] - p[1]) );
return value;
}
double PDE::u_exact(const Point& p, double t)
{
double value;
value = (p[0] * p[0] - p[0]) * (p[1] * p[1] - p[1]) * exp(t);
return value;
}
std::vector<double> PDE::u_exact_grad(const Point &p, double t)
{
std::vector<double> val(2);
val[0] = -exp(t) * (-p[1] * p[1] + p[1]) * (2 * p[0] - 1);
val[1] = -exp(t) * (-p[0] * p[0] + p[0]) * (2 * p[1] - 1);
return val;
}
<file_sep>/Possion方程--C++(CVT自适应)/Makefile
all: CVT_Adaptive_finite
CVT_Adaptive_finite: CVT_Adaptive_finite.o Possion.o Matrix.o density.o
g++ -std=c++0x -o CVT_Adaptive_finite CVT_Adaptive_finite.o Possion.o Matrix.o density.o
CVT_Adaptive_finite.o: CVT_Adaptive_finite.cpp Possion.h density.h
g++ -std=c++0x -c CVT_Adaptive_finite.cpp
Possion.o: Possion.cpp Possion.h
g++ -std=c++0x -c Possion.cpp
Matrix.o: Matrix.cpp Matrix.h
g++ -std=c++0x -c Matrix.cpp
density.o: density.cpp density.h
g++ -std=c++0x -c density.cpp
<file_sep>/Heat方程-C++显格式/Point.h
/*************************************************************************
> File Name: Point.h
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 08时51分59秒
************************************************************************/
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <vector>
#include <cmath>
#include <Eigen/Dense> // 线性代数库
#include <Eigen/Sparse> // 稀疏存储矩阵库,以及稀疏存储的线性方程组求解库
#include <Eigen/IterativeLinearSolvers> // 迭代法求解线性方程组的求解库
#include <unsupported/Eigen/IterativeSolvers>
class Point
{
friend std::ostream& operator<< (std::ostream&, const Point&);
friend std::istream& operator>> (std::istream&, Point&);
friend Point operator+ (const Point&, const Point&);
friend Point operator- (const Point&, const Point&);
friend Point midpoint(const Point&, const Point&);
friend double distance(const Point&, const Point&);
// 求三角形的质心,可以求加权质心
friend Point barycenter(const std::vector<Point>&, const double *);
friend double AREA(const Point&, const Point&, const Point&);
private:
double x[2];
public:
Point();
Point(const double*);
Point(const Point&);
Point(const double&, const double&);
Point& operator= (const Point&);
double& operator[] (int);
const double& operator[] (int) const;
double length() const;
Point& operator+= (const Point&);
Point& operator-= (const Point&);
Point& operator*= (const double&);
Point& operator/= (const double&);
};
#endif
<file_sep>/Possion方程-C++-p1元--Eigen(no sparse)/main.cpp
#include "Matrix.h"
using std::cout;
using std::endl;
using std::cin;
int main()
{
Matrix Possion("Trimesh.txt",7);
PDE pde;
int n_pnt = Possion.mesh.n_point(); // 得到网格点的个数
Possion.u_h.resize(n_pnt);
std::vector<std::vector<double>> A_matrix;
std::vector<double> Rhs;
Possion.buildMatrix_RHS(A_matrix,Rhs); // 得到总的左边刚度矩阵和右端刚度矩阵
Possion.DealBoundary(A_matrix, Possion.u_h, Rhs); // 边界处理
//Possion.GaussSeidel(A_matrix,Possion.u_h, Rhs); // 高斯赛德尔迭代
// k可以取1到14,取整数,每一个数字对应一种计算方法,
// 1--9 为直接解法; 10--14为迭代解法;GMRES,case12 优先选择
Possion.SolveLinearA(A_matrix,Possion.u_h,Rhs,12);
double L2Error=Possion.ComputerL2Error(Possion.u_h); // 求解L2误差
std::cout<<"L2Error="<<L2Error<<std::endl;
// 把数值解u_h和误差L2写入到文件中
std::ofstream out("Results.txt");
for (auto i : Possion.u_h)
out << i << "\n";
out.close();
return 0;
}
<file_sep>/Possion方程-C++-P1元--Eigen(Sparse)/main.cpp
#include "Matrix.h"
using std::cout;
using std::endl;
using std::cin;
int main()
{
Matrix Possion("Trimesh.txt",7);
PDE pde;
int n_pnt = Possion.mesh.n_point(); // 得到网格点的个数
Possion.u_h.resize(n_pnt);
std::vector<std::vector<double>> A_matrix;
std::vector<double> Rhs;
//Possion.buildMatrix_RHS(A_matrix,Rhs); // 得到总的左边刚度矩阵和右端刚度矩阵
// 定义一个用于存储A_matrix的稀疏矩阵A_matrix_sparse
Eigen::SparseMatrix<double> A_matrix_sparse(A_matrix.size(),A_matrix.size());
Possion.buildMatrix_RHS_Sparse(A_matrix_sparse,Rhs);
Possion.DealBoundary_Sparse(A_matrix_sparse, Possion.u_h, Rhs);
// k 可以取1-5 ; gmres:case 3
Possion.SolveLinearASparse(A_matrix_sparse,Possion.u_h,Rhs,3);
double L2Error=Possion.ComputerL2Error(Possion.u_h); // 求解L2误差
std::cout<<"L2Error="<<L2Error<<std::endl;
// 把数值解u_h和误差L2写入到文件中
std::ofstream out("Results.txt");
for (auto i : Possion.u_h)
out << i << "\n";
out.close();
return 0;
}
<file_sep>/Heat方程-C++隐格式-非零边界/PDE.cpp
/*************************************************************************
> File Name: PDE.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 09时45分37秒
************************************************************************/
#include "PDE.h"
// 边界条件(第一类边界条件)
double PDE::u_boundary(const Point &p, double t)
{
double value;
value = exp(0.5 * (p[0] + p[1]) - t);
return value;
}
double PDE::f(const Point &p, double t)
{
double value;
value = -3/2.0 * exp(0.5 * (p[0] + p[1]) - t);
return value;
}
double PDE::u_exact(const Point& p, double t)
{
double value;
value = exp(0.5 * (p[0] + p[1]) - t);
return value;
}
std::vector<double> PDE::u_exact_grad(const Point &p, double t)
{
std::vector<double> val(2);
val[0] = 0.5 * exp(0.5 * (p[0] + p[1]) - t);
val[1] = 0.5 * exp(0.5 * (p[0] + p[1]) - t);
return val;
}
<file_sep>/Heat方程-C++显格式/Test.cpp
/*************************************************************************
> File Name: Test.cpp
> Author: ZhirunZheng
> Mail: <EMAIL>
> Created Time: 2018年10月22日 星期一 15时07分53秒
************************************************************************/
#include "Parabolic.h"
int main()
{
int index = 0;
for (int i = 0; i != 5; ++i){
std::cout << "*********************"<<i<<"******************************"<<std::endl;
std::string inputFile = "Trimesh_";
std::string outputFile = "Error_";
inputFile = inputFile + std::to_string(index + i) + ".txt";
outputFile = outputFile + std::to_string(index + i) + ".txt";
Parabolic solve(inputFile, 5);
solve.runFullDiscreteFormat(outputFile); // 全离散显格式
Dt = Dt / 4.0; // 二维情况下的网格比要小于1/4
}
return 0;
}
| 973c40d65aa57953ab304fd32cac082f3ced3ee6 | [
"Markdown",
"Makefile",
"C++"
] | 28 | C++ | zhengzhirun/Finite-Element-Methods | 53150d7e15da421eb2330497f648b3d48c81f8fb | 1001db437694e30870243c825f6d4c86f6ef6ec8 | |
refs/heads/master | <file_sep># 1. Reordering Destinations
Date: 2019-04-09
## Status
Accepted
## Context
A list of destinations should be reorderable, not fixed
## Decision
A trip is made up of a list of destinations. This list should be able to be reordered, on the main site or the mobile version of the site. Draggable would be the best, but a button for moving an extry up and down will also work.
## Consequences
It may not be best to write the trip to the database everytime a destination is reordered. Perhaps better to store the trip locally, and only write to the database once (with a 'Save' button)
* Affects planned log functionality
* Affects groups (others on trip)
* Need to add JQuery UI or specialised Javascript to enable reordering
<file_sep># 1. Testing
Date: 2019-05-20
## Status
Accepted
## Context
In order to holistically test the core functionality of the website, a combination of unit testing, end-to-end testing, and manual testing is used.
Unit tests are used on back-end models and database-related code in order to validate the functionality of each essential unit of the code (which, in most cases, are functions).
On the front-end, various user actions are performed by automated testing software. During that process, key aspects relating to the front-end side of the website are tested.
High-level functionality is exclusively assessed and confirmed via manual user testing. This includes testing the following aspects of the website:
- Marker placement on maps
- Destinations being correctly added and drawn
- Trips being correctly written to and received from session storage
## Decision
The testing framework chosen for automated testing is Jest. This framework is used because:
- It has a simple installation and configuration process for Node.js
- Due to its popularity as a javascript testing framework, it has a large developer-community which produces many articles, documents and forum threads (amongst many other sources of documentation and support)
- It has a wide variety of built-in assertion abilities (which means that there is no need for the installation of a third-party assertion library)
In order to simulate in-browser user-interactions with the website, Selenium WebDriver is used. Front-end testing is performed on the https://testawaywego.azurewebsites.net website since it is the website used for development.
Ultimately, it was decided that all automated front-end user testing will be performed using Google Chrome as the browser. The reason for this is due to the fact that Google Chrome has the highest browser market share (more than 60%) globally - meaning that a majrity of the website's users will be using Google Chrome.
At multiple stages throughout the development process, manual testing on other major browsers (i.e. FireFox, Safari and Microsoft Edge) was also performed in order to ensure the cross-browser compatibility of the website. Manual testing was also used to ensure that the website is mobile-friendly.
## Consequences
The major consequences of the choice to include automated front-end browser testing include:
* Any tests involving front-end user testing have to be performed on a computer connected to the internet
* The website will have to allow for "bots" to interact with it. This means that security measures (e.g. reCAPTCHA) against harmful bots cannot be implemented on the site.
* Potential bugs in the website when viewed in other existing browsers (e.g. Opera, QQ, etc.) will not be detected in either automated or manual testing.
The major consequences of the choice to use manual user testing for high-level functionality include:
* The developers save time since their time is not spent on writing complex automated tests for these high-level functionalities
* As a trade-off, manual tests have to be repeatedly conducted on multiple browsers and devices in order to ensure functionality is maintained at several points in time throughout the development process
<file_sep># 1. Maps API choice
Date: 2019-04-09
## Status
Accepted
## Context
For the project, we need an API for a map: interface, search, marker placement, satellite or road map imagery. There are several options for maps, will be a primary mode of interacting with the site.
* Google maps
* OpenLayers
* TomTom
* MapBox
* HERE
* Mapfit
Main factor are cost, and ease of use (documentation for the API)
Google maps are highly customizable in style and appearance, and configerable for marker placement, information windows, and interface/controls.
## Decision
Upon examining the options, Google Maps was considered the most mature, easy-to-use and well-supported option. The API has excellent documentation and example code. The interface will be familiar to the majority of site users.
## Consequences
Google Maps has several modular APIs for Places, Routes, etc. A single API key will work for all of these.
* Cost: for the project purpose we should not exceed the free threshold (views per day, click rate, $300 credit)
* Limit scalability: If the project were a commercial project, Google's costs would severely limit the size the website could grow too without justifying through profitibility.
* A 3th party map API requires a URL or Javascript page which exposes the API key and the Https request.
<file_sep>'use strict'
let express = require('express')
let app = express()
let mainRouter = express.Router()
let bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
let authenticate = require('../models/authenticate')
let termsModel = require('../models/termsAndConditionsModel')
let tripManagerModel = require('../models/tripManagerModel')
let tripModel = require('../models/tripModel')
let mailManager = require('../models/email_manager')
let invitesModel = require('../models/invitesModel')
let logModel = require('../models/logModel')
let groupModel = require('../models/groupsModel')
// ------------
// URL Routing
// ------------
mainRouter.get('/', function (req, res) {
res.status(200).sendFile('/index.html', { root: req.app.get('views') })
})
mainRouter.get('/terms_and_conditions', function (req, res) {
res.status(200).sendFile('/terms_and_conditions.html', { root: req.app.get('views') })
})
mainRouter.get('/terms_and_conditions/data', function (req, res) {
res.send(termsModel.getTermsAndCondtions())
})
mainRouter.get('/profile', function (req, res) {
res.status(200).sendFile('profile.html', { root: req.app.get('views') })
})
mainRouter.get('/about', function (req, res) {
res.status(200).sendFile('/about.html', { root: req.app.get('views') })
})
mainRouter.get('/register', function (req, res) {
res.status(200).sendFile('/register.html', { root: req.app.get('views') })
})
mainRouter.get(['/sign-in', '/login', '/signin'], function (req, res) {
res.status(200).sendFile('/sign-in.html', { root: req.app.get('views') })
})
mainRouter.get(['/trip', '/map'], function (req, res) {
res.status(200).sendFile('/trip.html', { root: req.app.get('views') })
})
mainRouter.get('/hotels', function (req, res) {
res.status(200).sendFile('/hotels.html', { root: req.app.get('views') })
})
mainRouter.get(['/trip-manager', '/trips'], function (req, res) {
res.status(200).sendFile('/trip-manager.html', { root: req.app.get('views') })
})
// ----------------
// RESTFUL Routing
// ----------------
mainRouter.post('/trip/log', function (log, res) {
res.status(202)
logModel.createLog(log, res)
})
mainRouter.post('/trip-manager/log', function (tripId, res) {
res.status(202)
logModel.getLogs(tripId, res)
})
mainRouter.post('/trip/data', function (req, res) {
res.status(202)
tripModel.createDestination(req, res)
})
mainRouter.post('/trip-manager/data', function (req, res) {
res.status(202)
tripManagerModel.populateTripAndGroupTable(req, res)
})
mainRouter.post('/trip-manager/get-data', function (req, res) {
res.status(202)
tripManagerModel.getTrips(req, res)
})
mainRouter.post('/trip-manager-interface/data', function (req, res) {
res.status(202)
tripManagerModel.getDestinations(req, res)
})
mainRouter.post('/google-auth', (req, res) => {
res.status(202)
authenticate.googleUserAccountDatabaseConnection(req, res)
})
mainRouter.post('/auth', (req, res) => {
res.status(202)
authenticate.userAccountDatabaseConnection(req, res)
})
mainRouter.get('/email', function (req, res) {
res.status(202)
res.sendFile('email.html', { root: req.app.get('views') })
})
mainRouter.post('/groups', (req, res) => {
res.status(202)
groupModel.returnGroupUsers(req, res)
})
mainRouter.post('/invite', function (req, res) {
mailManager.sendInvite(req.body.emailAddress, req.body.tripName, req.body.invitee)
invitesModel.addInvite(res, req.body)
res.sendStatus(200)
})
mainRouter.post('/invites/data', function (req, res) {
res.status(202)
invitesModel.getInvites(res, req.body.emailAddress)
})
mainRouter.post('/invites/data/accept', (req, res) => {
res.status(202)
invitesModel.handleInvites(req, res, true)
})
mainRouter.post('/invites/data/deny', (req, res) => {
res.status(202)
invitesModel.handleInvites(req, res, false)
})
// -----------------------------
// Error/Page Not Found Routing
// ------------------------------
mainRouter.get('*', function (req, res) {
res.status(404)
res.sendFile('/404.html', { root: req.app.get('views') })
// res.status(404).send('404 Error: page not found')
})
module.exports = mainRouter
<file_sep>let check = window.sessionStorage.getItem('Hash')
// console.log(check)
if ((check === null) || (check === undefined)) {
window.location = '/sign-in'
}
function updateProfile () {
let usernameTag = document.getElementById('usernameTag')
usernameTag.textContent = JSON.parse(window.sessionStorage.getItem('Name') + ' ')
let emailTag = document.getElementById('emailTag')
emailTag.textContent = JSON.parse(window.sessionStorage.getItem('Email') + ' ')
}
function clearTripFromSessionStorage () {
window.sessionStorage.removeItem('trip')
}
function signOut () {
// normal sign-out
document.cookie = 'awaywegosession=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'
document.cookie = 'awaywegosession.sig=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'
window.sessionStorage.clear()
window.localStorage.clear()
}
// Get User name for menu
$(document).ready(function () {
updateProfile()
$('#signOutButton').click(() => {
let authInstance = gapi.auth2.getAuthInstance()
authInstance.signOut().then(function () {
signOut()
console.log('User signed out.')
window.location = '/'
})
})
})
<file_sep>'use strict'
let countries = {
'au': {
center: { lat: -25.3, lng: 133.8 },
zoom: 4
},
'br': {
center: { lat: -14.2, lng: -51.9 },
zoom: 4
},
'ca': {
center: { lat: 62, lng: -110.0 },
zoom: 4
},
'fr': {
center: { lat: 46.2, lng: 2.2 },
zoom: 5
},
'de': {
center: { lat: 51.2, lng: 10.4 },
zoom: 5
},
'gr': {
center: { lat: 37.59, lng: 23.43 },
zoom: 4
},
'mx': {
center: { lat: 23.6, lng: -102.5 },
zoom: 4
},
'nz': {
center: { lat: -40.9, lng: 174.9 },
zoom: 5
},
'it': {
center: { lat: 41.9, lng: 12.6 },
zoom: 5
},
'za': {
center: { lat: -30.6, lng: 22.9 },
zoom: 5
},
'es': {
center: { lat: 40.5, lng: -3.7 },
zoom: 5
},
'pt': {
center: { lat: 39.4, lng: -8.2 },
zoom: 6
},
'us': {
center: { lat: 37.1, lng: -95.7 },
zoom: 4
},
'uk': {
center: { lat: 54.8, lng: -4.6 },
zoom: 5
}
}
let darkMapType =
[
{
'featureType': 'all',
'elementType': 'all',
'stylers': [
{
'visibility': 'on'
}
]
},
{
'featureType': 'all',
'elementType': 'labels',
'stylers': [
{
'visibility': 'off'
},
{
'saturation': '-100'
}
]
},
{
'featureType': 'all',
'elementType': 'labels.text.fill',
'stylers': [
{
'saturation': 36
},
{
'color': '#000000'
},
{
'lightness': 40
},
{
'visibility': 'off'
}
]
},
{
'featureType': 'all',
'elementType': 'labels.text.stroke',
'stylers': [
{
'visibility': 'off'
},
{
'color': '#000000'
},
{
'lightness': 16
}
]
},
{
'featureType': 'all',
'elementType': 'labels.icon',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'administrative',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#000000'
},
{
'lightness': 20
}
]
},
{
'featureType': 'administrative',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#000000'
},
{
'lightness': 17
},
{
'weight': 1.2
}
]
},
{
'featureType': 'landscape',
'elementType': 'geometry',
'stylers': [
{
'color': '#000000'
},
{
'lightness': 20
}
]
},
{
'featureType': 'landscape',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#4d6059'
}
]
},
{
'featureType': 'landscape',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#4d6059'
}
]
},
{
'featureType': 'landscape.natural',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#4d6059'
}
]
},
{
'featureType': 'poi',
'elementType': 'geometry',
'stylers': [
{
'lightness': 21
}
]
},
{
'featureType': 'poi',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#4d6059'
}
]
},
{
'featureType': 'poi',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#4d6059'
}
]
},
{
'featureType': 'road',
'elementType': 'geometry',
'stylers': [
{
'visibility': 'on'
},
{
'color': '#7f8d89'
}
]
},
{
'featureType': 'road',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#7f8d89'
}
]
},
{
'featureType': 'road.highway',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#7f8d89'
},
{
'lightness': 17
}
]
},
{
'featureType': 'road.highway',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#7f8d89'
},
{
'lightness': 29
},
{
'weight': 0.2
}
]
},
{
'featureType': 'road.arterial',
'elementType': 'geometry',
'stylers': [
{
'color': '#000000'
},
{
'lightness': 18
}
]
},
{
'featureType': 'road.arterial',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#7f8d89'
}
]
},
{
'featureType': 'road.arterial',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#7f8d89'
}
]
},
{
'featureType': 'road.local',
'elementType': 'geometry',
'stylers': [
{
'color': '#000000'
},
{
'lightness': 16
}
]
},
{
'featureType': 'road.local',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#7f8d89'
}
]
},
{
'featureType': 'road.local',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#7f8d89'
}
]
},
{
'featureType': 'transit',
'elementType': 'geometry',
'stylers': [
{
'color': '#000000'
},
{
'lightness': 19
}
]
},
{
'featureType': 'water',
'elementType': 'all',
'stylers': [
{
'color': '#2b3638'
},
{
'visibility': 'on'
}
]
},
{
'featureType': 'water',
'elementType': 'geometry',
'stylers': [
{
'color': '#2b3638'
},
{
'lightness': 17
}
]
},
{
'featureType': 'water',
'elementType': 'geometry.fill',
'stylers': [
{
'color': '#24282b'
}
]
},
{
'featureType': 'water',
'elementType': 'geometry.stroke',
'stylers': [
{
'color': '#24282b'
}
]
},
{
'featureType': 'water',
'elementType': 'labels',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'water',
'elementType': 'labels.text',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'water',
'elementType': 'labels.text.fill',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'water',
'elementType': 'labels.text.stroke',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'water',
'elementType': 'labels.icon',
'stylers': [
{
'visibility': 'off'
}
]
}
]
let silverMapType =
[
{
'elementType': 'geometry',
'stylers': [
{
'color': '#f5f5f5'
}
]
},
{
'elementType': 'labels.icon',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#616161'
}
]
},
{
'elementType': 'labels.text.stroke',
'stylers': [
{
'color': '#f5f5f5'
}
]
},
{
'featureType': 'administrative.country',
'stylers': [
{
'weight': 8
}
]
},
{
'featureType': 'administrative.land_parcel',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#bdbdbd'
}
]
},
{
'featureType': 'poi',
'elementType': 'geometry',
'stylers': [
{
'color': '#eeeeee'
}
]
},
{
'featureType': 'poi',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#757575'
}
]
},
{
'featureType': 'poi.park',
'elementType': 'geometry',
'stylers': [
{
'color': '#e5e5e5'
}
]
},
{
'featureType': 'poi.park',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#9e9e9e'
}
]
},
{
'featureType': 'road',
'elementType': 'geometry',
'stylers': [
{
'color': '#ffffff'
}
]
},
{
'featureType': 'road.arterial',
'elementType': 'labels',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'road.arterial',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#757575'
}
]
},
{
'featureType': 'road.highway',
'elementType': 'geometry',
'stylers': [
{
'color': '#dadada'
}
]
},
{
'featureType': 'road.highway',
'elementType': 'labels',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'road.highway',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#616161'
}
]
},
{
'featureType': 'road.local',
'stylers': [
{
'visibility': 'off'
}
]
},
{
'featureType': 'road.local',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#9e9e9e'
}
]
},
{
'featureType': 'transit.line',
'elementType': 'geometry',
'stylers': [
{
'color': '#e5e5e5'
}
]
},
{
'featureType': 'transit.station',
'elementType': 'geometry',
'stylers': [
{
'color': '#eeeeee'
}
]
},
{
'featureType': 'water',
'elementType': 'geometry',
'stylers': [
{
'color': '#c9c9c9'
}
]
},
{
'featureType': 'water',
'elementType': 'labels.text.fill',
'stylers': [
{
'color': '#9e9e9e'
}
]
}
]
<file_sep>'user strict'
document.addEventListener('DOMContentLoaded', function () {
let lang
if (document.querySelectorAll('#map').length > 0) {
if (document.querySelector('html').lang) {
lang = document.querySelector('html').lang
} else {
lang = 'en'
}
let jsFile = document.createElement('script')
jsFile.type = 'text/javascript'
jsFile.src = 'https://maps.googleapis.com/maps/api/js?key=<KEY>&libraries=places&callback=initMap®ion=ZA&language=' + lang
document.getElementsByTagName('head')[0].appendChild(jsFile)
}
})<file_sep>let termsAndConditionsModel = require('../app/models/termsAndConditionsModel')
let fs = require('fs')
let path = require('path')
// import addTermsToSubsection from '../app/controllers/terms_and_conditions'
describe('testing the model that exports the correct terms and conditions', () => {
test('test if the preamble stord in the model is correct', () => {
let preamble = [
'When you create an account with us, you must provide us information that is accurate, complete, and current at all times. Failure to do so constitutes a breach of the Terms, which may result in immediate termination of your account on our Service.',
'You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service.',
'You agree not to disclose your password to any third party. You must notify us immediately upon becoming aware of any breach of security or unauthorized use of your account.'
]
expect(termsAndConditionsModel.getTermsAndCondtions().preamble).toEqual(preamble)
})
test('test if the information stored about accounts is correct', () => {
let accounts = [
'When you create an account with us, you must provide us information that is accurate, complete, and current at all times. Failure to do so constitutes a breach of the Terms, which may result in immediate termination of your account on our Service',
'You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service',
'You agree not to disclose your password to any third party. You must notify us immediately upon becoming aware of any breach of security or unauthorized use of your account'
]
expect(termsAndConditionsModel.getTermsAndCondtions().accounts).toEqual(accounts)
})
test('test if the information stored about other sites is correct', () => {
let otherSites = [
'Our Service may contain links to third-party web sites or services that are not owned or controlled by Away We Go',
'Away We Go has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Away We Go shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services.',
'We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or services that you visit.'
]
expect(termsAndConditionsModel.getTermsAndCondtions().otherSites).toEqual(otherSites)
})
})
// describe('testing that the controller renders the data from the model onto the HTML page', () => {
// describe('testing that the addTermsToSubsection function adds the neccesary information to each HTML div', () =>{
// let testFolderRegex = /test/gi
// let rootDir = path.resolve(__dirname).replace(testFolderRegex, '')
// let termsAndConditionsHTMLDir = path.join(rootDir, '/app/views/terms_and_conditions.html')
// // Read in the HTML file
// document.body.innerHTML = fs.readFileSync(termsAndConditionsHTMLDir)
// // require('../app/controllers/terms_and_conditions')
// const $ = require('jquery')
// // let addTermsToSubsection = function (subsection, termsArray, divider) {
// // let parentItemType = ''
// // if (divider === 'li') {
// // parentItemType = 'ol'
// // } else {
// // parentItemType = 'p'
// // }
// // let parentItem = document.createElement(parentItemType)
// // termsArray.forEach(element => {
// // let item = document.createElement(divider)
// // let term = document.createTextNode(element)
// // item.appendChild(term)
// // parentItem.appendChild(item)
// // })
// // subsection.append(parentItem)
// // }
// test('preamble section is added to the div with id="Preamble"', () => { // Get the directory of where the HTML file is for the T&Cs
// // An initial space is added to account for the fact that the preamble div's first HTML DOM child is a <p> element
// let preambleString = ' '
// // Construct the preamble string from the sentences returned by the model
// termsAndConditionsModel.getTermsAndCondtions().preamble.forEach((sentence) => {
// preambleString = preambleString + sentence
// })
// addTermsToSubsection($('#Preamble'), termsAndConditionsModel.getTermsAndCondtions().preamble, 'p')
// expect($('#Preamble').text()).toEqual(preambleString)
// })
// })
// })
<file_sep>'use strict'
jest.mock('../app/models/db')
let tripModel = require('../app/models/tripModel')
class Trip {
constructor(id, title, destinations, user) {
this.id = id
this.title = title
this.destinationList = destinations
this.user = user
}
}
class Destination {
constructor(id, lat, lng, placeId, place, name, ordering) {
this.id = String(id)
this.lat = Number(lat)
this.lng = Number(lng)
this.placeId = String(placeId)
this.place = String(place)
this.name = String(name)
this.ordering = Number(ordering)
}
}
describe('testing trip class data structures', () => {
let testTrip = new Trip(12345, "My Trip", [], 'A1B2C3D4E5F6')
test('creating a trip object succeeds', () => {
expect(testTrip.id).not.toBeNull()
expect(testTrip.title).not.toEqual('')
expect(testTrip.destinationList).toEqual([])
expect(testTrip.user).toEqual('A1B2C3D4E5F6')
})
})
describe('testing destination class data structures', () => {
let testLatLng = { lat: 0, lng: 0 }
let testDestination = new Destination(12345, 0, 0, 'A123', "My Destination", "testName", 1)
test('creating a destination object succeeds', () => {
expect(testDestination.id).not.toBeNull()
expect(testDestination.lat).toEqual(testLatLng.lat)
expect(testDestination.lng).toEqual(testLatLng.lng)
expect(testDestination.placeId).not.toEqual(undefined)
expect(testDestination.place).not.toEqual('')
expect(testDestination.place).not.toBeNull()
expect(testDestination.name).not.toBeNull()
expect(testDestination.ordering).toEqual(1)
})
})
describe('testing createDestinationQueryString function', () => {
let testTrip1 = new Trip(12345, "My Trip", [], 'A1B2C3D4E5F6')
let testQS1 = `DELETE FROM destinations WHERE trip_id = 12345;`
test('destination query string is correct when trip has no destinations', () => {
expect(tripModel.createDestinationQueryString(testTrip1)).toEqual(testQS1)
})
let testDestination1 = new Destination(12345, 0, 0, 'A123', "My Destination", "testName", 1)
let testTrip2 = new Trip(12345, "My Trip", [testDestination1], 'A1B2C3D4E5F6')
let testQS2 = testQS1 + `INSERT INTO destinations VALUES ('12345',0,0,'A123','My Destination','testName',1,12345);`
test('destination query string is correct when trip has one destination', () => {
expect(tripModel.createDestinationQueryString(testTrip2)).toEqual(testQS2)
})
let testDestination2 = new Destination(12345, 0, 0, 'A123', "My Destination", "testName", 1)
let testTrip3 = new Trip(12345, "My Trip", [testDestination1, testDestination2], 'A1B2C3D4E5F6')
let testQS3 = testQS2 + `INSERT INTO destinations VALUES ('12345',0,0,'A123','My Destination','testName',1,12345);`
test('destination query string is correct when trip has two destinations', () => {
expect(tripModel.createDestinationQueryString(testTrip3)).toEqual(testQS3)
})
})
describe('testing query functions', () => {
test('testing createDestinationQuery', async () => {
let testDestination = new Destination(12345, 0, 0, 'A123', "My Destination", "testName", 1)
let testTrip = new Trip(12345, "My Trip", [testDestination], 'A1B2C3D4E5F6')
let queryString = tripModel.createDestinationQueryString(testTrip)
let createDestination = await tripModel.createDestinationQuery(queryString)
expect(Object.keys(createDestination).length).toEqual(1)
expect(createDestination.recordset).toEqual(undefined)
})
})
<file_sep># 1. Login API Choice
Date: 2019-04-09
## Status
Accepted
## Context
It would be convenient to use the Google Login API as an alternative method for users to login. This would provide a template for our own login details stored in the DB, as well as a quick way to get the Sprint 1 User story related to login completed ASAP.
## Decision
Using a well known and widely known/supported login mechanism such as Google's OAuth2 will allow more rapid development of an appropriate security setup for the site. We will apply for an API key and start implementing the login/registration page through the Google Login API
## Consequences
We don;t want users to be required to have a gmail account. Therefore we _still_ have to build a normal login/password authentication setup, in addition to the google login, and with additiona checks to confirm the interoprability between the two registration/login methods. However, the speed in the first sprint, and leaning on established beats practice from a major and knowledgeable company such as Google means we can learn how to best structure the data stored/required for our own site login.
* Additional testing on interoperability
* The password and user details have a security context and must be labelled as such
<file_sep>'use strict'
let db = require('./db')
let SqlString = require('sqlstring')
function createLog (logInfo, res) {
let log = logInfo.body
let queryString = createLogQueryString(log)
createLogQuery(queryString)
.then(result => {
res.send('Log table added to entries')
})
.catch(err => {
console.log('populate log table error:', err)
})
}
function createLogQueryString (log) {
let queryString = ''
for (let i = 0; i < log.length; i++) {
queryString = queryString + SqlString.format('INSERT INTO log VALUES (?,?,?,?,?,?);',
[log[i].id,
log[i].userId,
log[i].code,
log[i].date,
log[i].importance,
log[i].tripId])
}
return queryString
}
function createLogQuery (queryString) {
return db.pools
.then(pool => {
return pool.request()
.query(queryString)
})
}
function getLogs (req, res) {
let tripId = req.body.tripId
getLogQuery(tripId)
.then(result => {
res.send(result.recordset)
})
.catch(err => {
console.log('Get log error:', err)
})
}
function getLogQuery (tripId) {
return db.pools
.then(pool => {
let dbrequest = pool.request()
dbrequest.input('tripId', tripId)
return dbrequest
.query('SELECT id, userId, code, date, importance, trip_id, first_name, last_name FROM log JOIN users ON log.userid = users.hash WHERE trip_id = @tripId;')
})
}
module.exports = {
createLog: createLog,
getLogs: getLogs,
createLogQueryString: createLogQueryString,
createLogQuery: createLogQuery,
getLogQuery: getLogQuery
}
<file_sep>'use strict'
let express = require('express')
let path = require('path')
let app = express()
let mainRouter = require('./app/routes/mainRoutes')
let cookieSession = require('cookie-session')
let OAuthKeys = require('./app/models/keys.json')
require('dotenv').config()
let favicon = require('serve-favicon')
let bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(favicon(path.join(__dirname, './app/public/', 'favicon.ico')))
app.set('views', path.join(__dirname, './app/views'))
app.use(express.static(path.join(__dirname, './app/public')))
app.use(express.static(path.join(__dirname, './app/controllers')))
app.use('/', mainRouter)
let port = process.env.PORT || 3000
app.listen(port)
console.log('Express server running on port', port)
<file_sep>'use strict'
$(document).ready(function () {
$('#landingPageSignInButton').click(function () {
window.location = '/sign-in'
})
$('#landingPageRegisterButton').click(function () {
window.location = '/register'
})
$('#aboutButton').click(function () {
window.location = '/about'
})
})
<file_sep>'use strict'
jest.mock('../app/models/db')
let tripManagerModel = require('../app/models/tripManagerModel')
describe('testing getTripTitlesQueryString function', () => {
let testTrip1 = { trip_id: 1234 }
let testTripArray2 = [testTrip1]
let testQS2 = `SELECT * FROM trips WHERE id IN ('1234');`
test('trip query string is correct when one trip exists', () => {
expect(tripManagerModel.getTripTitlesQueryString(testTripArray2)).toEqual(testQS2)
})
let testTrip2 = { trip_id: 5678 }
let testTripArray3 = [testTrip1, testTrip2]
let testQS3 = `SELECT * FROM trips WHERE id IN ('1234','5678');`
test('trip query string is correct when more than one trip exists', () => {
expect(tripManagerModel.getTripTitlesQueryString(testTripArray3)).toEqual(testQS3)
})
})
describe('testing tripManagerModel query functions', () => {
let tripInfo = {
id: 0,
title: 'My Trip',
user: 'a1s2d3f4g5h6j7k8'
}
test('testing populateTripAndGroupTableQuery', async () => {
let tableResult = await tripManagerModel.populateTripAndGroupTableQuery(tripInfo)
expect(Object.keys(tableResult).length).toEqual(1)
expect(tableResult.recordset).toEqual(undefined)
})
test('testing getTripsQuery', async () => {
let user = 'z<PASSWORD>'
let groups = await tripManagerModel.getTripsQuery(user)
expect(groups.recordset[0].user_hash).toEqual('z1x2c3v4b5n6m7')
expect(groups.recordset[1].user_hash).toEqual('z1x2c3v4b5n6m7')
expect(groups.recordset[0].trip_id).toEqual('123456789')
expect(groups.recordset[1].trip_id).toEqual('987654321')
})
test('testing getTripTitlesQuery', async () => {
let testTrip1 = { trip_id: 1234 }
let testTrip2 = { trip_id: 5678 }
let testTripArray3 = [testTrip1, testTrip2]
let titles = await tripManagerModel.getTripTitlesQuery(testTripArray3)
expect(titles.recordset[0].id).toEqual('0')
expect(titles.recordset[1].id).toEqual('1')
expect(titles.recordset[0].title).toEqual('My Trip')
expect(titles.recordset[1].title).toEqual('Your Trip')
})
test('testing getDestinationsQuery', async ()=>{
let tripId = 1
let trip = await tripManagerModel.getDestinationsQuery(tripId)
expect(trip.recordset[0].id).toEqual('1')
expect(trip.recordset[0].lat).toEqual('0')
expect(trip.recordset[0].lng).toEqual('0')
expect(trip.recordset[0].place_id).toEqual('place12345')
expect(trip.recordset[0].place).toEqual('London')
expect(trip.recordset[0].name).toEqual('Family visit')
expect(trip.recordset[0].ordering).toEqual(1)
expect(trip.recordset[0].trip_id).toEqual('1')
expect(trip.recordset[1].id).toEqual('2')
expect(trip.recordset[1].lat).toEqual('1')
expect(trip.recordset[1].lng).toEqual('1')
expect(trip.recordset[1].place_id).toEqual('place54321')
expect(trip.recordset[1].place).toEqual('Manchester')
expect(trip.recordset[1].name).toEqual('Football stadium visit')
expect(trip.recordset[1].ordering).toEqual(2)
expect(trip.recordset[1].trip_id).toEqual('1')
})
})<file_sep>'use strict'
let db = require('./db')
/* Populate trip and groups table */
function populateTripAndGroupTable (trip, res) {
let tripInfo = trip.body
populateTripAndGroupTableQuery(tripInfo)
.then(result => {
// console.log('trips and groups population result ', result)
res.send(tripInfo)
})
.catch(err => {
console.log('populate trips table error:', err)
})
}
function populateTripAndGroupTableQuery (tripInfo) {
return db.pools
.then(pool => {
let dbrequest = pool.request()
dbrequest.input('id', db.sql.Char, tripInfo.id)
dbrequest.input('title', tripInfo.title)
dbrequest.input('user', tripInfo.user)
return dbrequest
.query(`DELETE FROM trips WHERE id = @id; INSERT INTO trips VALUES(@id, @title); IF NOT EXISTS (SELECT * FROM groups WHERE user_hash = @user AND trip_id = @id) BEGIN INSERT INTO groups VALUES(@user, @id) END;`)
})
}
/* Get Trips Query */
function getTrips (req, res) {
let user = JSON.parse(req.body.userHash)
getTripsQuery(user)
.then(result => {
// console.log('get trips result ', result)
if (result.recordset.length !== 0) {
getTripTitles(result.recordset, res)
}
})
.catch(err => {
console.log('Get trips error:', err)
})
}
function getTripsQuery (user) {
return db.pools
.then(pool => {
let dbrequest = pool.request()
dbrequest.input('user', user)
return dbrequest
.query(`SELECT * FROM groups WHERE user_hash = @user;`)
})
}
function getTripTitles (trips, res) {
getTripTitlesQuery(trips)
.then(result => {
// console.log('get trip titles result ', result)
if (trips.legnth !== 0) { res.send(result.recordset) } else {
res.send('NoTripTitlesFound')
}
})
.catch(err => {
console.log('Get trip titles error:', err)
})
}
function getTripTitlesQuery (trips) {
return db.pools
.then(pool => {
if (trips.length !== 0) {
let queryString = getTripTitlesQueryString(trips)
return pool.request()
.query(queryString)
}
})
}
function getTripTitlesQueryString (trips) {
let queryString = `SELECT * FROM trips WHERE id IN (`
for (let i = 0; i < trips.length; i++) {
queryString = queryString + `'${trips[i].trip_id}',`
}
queryString = queryString.substring(0, queryString.length - 1)
queryString = queryString + `);`
return queryString
}
/* Get Destinations Query */
function getDestinations (req, res) {
let tripId = req.body.tripId
getDestinationsQuery(tripId)
.then(result => {
// console.log('get destinations result ', result.recordset)
res.send(result.recordset)
})
.catch(err => {
console.log('Get destinations error:', err)
})
}
function getDestinationsQuery (tripId) {
return db.pools
.then(pool => {
let dbrequest = pool.request()
dbrequest.input('tripId', tripId)
return dbrequest
.query(`SELECT * FROM destinations WHERE trip_id = @tripId;`)
})
}
module.exports = {
populateTripAndGroupTable: populateTripAndGroupTable,
getTrips: getTrips,
getDestinations: getDestinations,
getTripTitlesQueryString: getTripTitlesQueryString,
populateTripAndGroupTableQuery: populateTripAndGroupTableQuery,
getTripsQuery: getTripsQuery,
getTripTitlesQuery: getTripTitlesQuery,
getDestinationsQuery: getDestinationsQuery
}
<file_sep>'use strict'
/* DATABASE SET UP */
const mssql = require('mssql')
require('dotenv').config()
let config = {
server: process.env.DB_SERVER,
database: process.env.DB_NAME,
user: process.env.DB_ADMIN,
password: <PASSWORD>,
port: Number(process.env.DB_PORT),
options: {
encrypt: true
},
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
}
/* Get a mssql connection instance */
let isConnected = true
let connectionError = null
let pools = new mssql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to DB')
return pool
})
.catch(err => {
isConnected = false
connectionError = err
console.log('connection error', err)
});
/* Create Database Tables */
(function createUserTable () {
pools.then((pool) => {
return pool.request()
// This is only a test query, change it to whatever you need
.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='users' and xtype='U')
CREATE TABLE users (
first_name varchar(50),
last_name varchar(50),
email_address varchar(50) NOT NULL,
image_url varchar(255),
hash varchar(255) PRIMARY KEY NOT NULL
)`)
}).then(result => {
// console.log('user table created', result)
}).catch(err => {
console.log('user table creation error', err)
})
}
)();
(function createDestinationTable () {
pools.then((pool) => {
return pool.request()
.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='destinations' and xtype='U')
CREATE TABLE destinations (
id varchar(255) PRIMARY KEY,
lat float,
lng float,
place_id varchar(255),
place varchar(255),
name varchar(50),
ordering int,
trip_id varchar(255)
)`)
}).then(result => {
}).catch(err => {
console.log('destinations table creation error', err)
})
})();
(function createInvitesTable () {
pools.then((pool) => {
return pool.request()
.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='invites' and xtype='U')
CREATE TABLE invites (
trip_id varchar(255),
email_address varchar(255)
)`)
}).then(result => {
// console.log('invites table created', result)
}).catch(err => {
console.log('invites table creation error', err)
})
})();
(function createTripTable () {
pools.then((pool) => {
return pool.request()
.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='trips' and xtype='U')
CREATE TABLE trips (
id varchar(255) PRIMARY KEY,
title varchar(50)
)`)
}).then(result => {
// console.log('trips table created', result)
}).catch(err => {
console.log('trips table creation error', err)
})
}
)();
(function createGroupsTable () {
pools.then((pool) => {
return pool.request()
.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='groups' and xtype='U')
CREATE TABLE groups (
user_hash varchar(255),
trip_id varchar(255)
)`)
}).then(result => {
// console.log('groups table created', result)
}).catch(err => {
console.log('groups table creation error', err)
})
}
)();
(function createLogTable () {
pools.then((pool) => {
return pool.request()
.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='log' and xtype='U')
CREATE TABLE log (
id varchar(255) PRIMARY KEY,
userId varchar(255),
code tinyint,
date smalldatetime,
importance bit,
trip_id varchar(255)
)`)
}).then(result => {
}).catch(err => {
console.log('log table creation error', err)
})
}
)()
module.exports = {
sql: mssql,
pools: pools,
isConnected: isConnected,
connectionError: connectionError
}
<file_sep>'use strict'
// Fake test so file can be included
test('Hello World: hello should greet the world', () => {
let hello = 'world'
expect(hello).toEqual('world')
})
// Integration tests for the routing
/* You can get the status code alone using curl with:
curl -Li http://localhost:3000 -o /dev/null -w '%{http_code}\n' -s
*/
/*
Integration testing for the routing would test each of the status codes
for every possible defined route, and that a 404 is returned for all undefined routes
All data querie should return 202 (query recieved) or 201 (resurce created) for DB table creation requests
However, I could not configure the tests to work correctly, despite hours of attempts and several different
techniques. Here I have left the main methods that I tried, and failed to get working.
*/
// var express = require('express')
// const app = express()
// var router = express.Router()
// const app = require('../index')
// const router = require('../app/routes/mainRoutes')
// const request = require('supertest')
// describe('test the root path', () => {
// test('response should be status 200 (OK)', () => {
// return request(router)
// .get('/')
// .expect(200)
// })
// })
// describe('test the root path', () => {
// test('response should be status 200 (OK)', () => {
// return request(router)
// .get("/").then(response => {
// expect(response.statusCode).toBe(200)
// })
// })
// })
// An attempt with Jasmine for front end resolving on a running local instance or online:
// describe('test the root path', function() {
// it('should route "/" to index', function() {
// var controller = require('../app/routes/mainRoutes');
// var orig_this = this;
// var orig_load = require('module')._load;
// var router = jasmine.createSpyObj('Router', ['get']);
// var express = jasmine.createSpyObj('express', ['Router']);
// express.Router.and.returnValues(router);
// spyOn(require('module'), '_load').and.callFake(function() {
// if (arguments[0] == 'express') {
// return express;
// } else {
// return orig_load.apply(orig_this, arguments);
// }
// });
// require('../app/routes/mainRoutes');
// expect(router.get).toHaveBeenCalledWith('/', mainRouter);
// });
// });
// Trying to setup a local instance (or online to the test or main server) to check responses...
// describe('loading express', function () {
// let app, mainRouter
// const request = require('supertest')
// beforeEach(function () {
// mainRouter = require('../app/routes/mainRoutes')
// app = require('../index').listen(3000)
// })
// afterEach(function () {
// app.close();
// })
// it('responds to /', function testSlash(done) {
// request(mainRouter)
// .get('/')
// .expect(200, done);
// })
// it('404 everything else', function testPath(done) {
// request(mainRouter)
// .get('/foo/bar')
// .expect(404, done);
// })
// })<file_sep>const { Builder, By, Key, until } = require('selenium-webdriver')
require('selenium-webdriver/chrome')
require('selenium-webdriver/firefox')
require('chromedriver')
require('geckodriver')
const rootURL = 'https://testawaywego.azurewebsites.net/sign-in'
const d = new Builder().forBrowser('chrome').build()
const waitUntilTime = 20000
let driver, el, actual, expected
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
async function getElementById(id) {
const el = await driver.wait(until.elementLocated(By.id(id)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
async function getElementByXPath(xpath) {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
test('waits for the driver to start', async () => {
return d.then(_d => {
driver = _d
})
})
test('initialises the context', async () => {
await driver.manage().window().setPosition(0, 0)
await driver.manage().window().setSize(1280, 1024)
await driver.get(rootURL)
})
describe('testing page elements on page load', () => {
test('Email address placeholder is correct', async () => {
el = await getElementById('inputEmail')
actual = await el.getAttribute('placeholder')
expected = 'Email address'
expect(actual).toEqual(expected)
})
test('Password placeholder is correct', async () => {
el = await getElementById('inputPassword')
actual = await el.getAttribute('placeholder')
expected = 'Password'
expect(actual).toEqual(expected)
})
test('Remember password checkbox is not checked on page load', async () => {
const el = await driver.wait(until.elementLocated(By.id('customCheck1')), waitUntilTime)
actual = await el.isSelected()
expected = false
expect(actual).toEqual(expected)
})
})
describe('test successful sign in', () => {
test('User directed to trips page on successful sign in', async () => {
let email = await getElementById('inputEmail')
// email.clear()
email.sendKeys('<EMAIL>')
let password = await getElementById('inputPassword')
// password.clear()
password.sendKeys('r') // correct password for email
let button = await getElementById('signInPageSignInButton')
button.click()
// wait for an element that is unique to the trip page to be found before getting the URL
await getElementById('pac-input')
let actual = await driver.getCurrentUrl()
let expected = 'https://testawaywego.azurewebsites.net/trip'
expect(actual).toEqual(expected)
})
})
// describe('test failed sign in', () => {
// test('User not directed to trips page when password is incorrect', async () => {
// let correctEmail = await getElementById('inputEmail')
// correctEmail.sendKeys('<EMAIL>')
// let wrongPassword = await getElementById('inputPassword')
// wrongPassword.sendKeys('<PASSWORD>') // wrong password for email
// let button = await getElementById('signInPageSignInButton')
// button.click()
// // alert appears telling user that password is incorrect
// let alert = await driver.switchTo().alert()
// let actualAlert = alert.getText()
// let expectedAlert = 'Your password is incorrect.'
// expect(actualAlert).toEqual(expectedAlert)
// alert.accept()
// // page does not redirect to trips
// let actual = await driver.getCurrentUrl()
// let expected = 'https://awaywego.azurewebsites.net/sign-in'
// expect(actual).toEqual(expected)
// })
// })
afterAll(() => {
driver.quit()
});<file_sep># 1. Folder structure
Date: 2019-04-10
Modified: 2019-05-21 (Tyson)
## Status
Accepted
## Context
Having a fixed structure for a project has may advantages, limiting spread of files across multiple folders and contraining locations to known places. THere is an advantage is letting a folder strucute emerge oganically, but also a large risk, as things can break when low-level file locations change, necesitating logs of bug fixing and refactoring. Having a rigid initial structure canb lead to later restrictions, or imposed complexity.
## Decision
The following folder strucure is adopted:
.
├── app
│ ├── controllers
│ ├── models
│ ├── public
│ │ ├── css
│ │ ├── img
│ │ └── js
│ ├── routes
│ └── views
├── docs
│ ├── adr
│ ├── misc
│ ├── project_artifacts
│ └── templates
├── node_modules
├── test
└── local_only
**Update** Removed folders originally specified that were found to not be required during project development: 'log' and 'utility'
## Consequences
Will need to be disciplined in file locations and naming conventions. Will need to produce a naming convention document to accompany this folder structure ADR.
* local-only will not be on repo
* node_modules MUST not be on repo
* utility -> back-end, maintenance task folder, not related to site or site-serving
* docs must be maintained : directly to main branch, or updated in seperate branch?
<file_sep># 1. Sprint Planning and timeline
Date: 2019-04-09
## Status
Accepted
## Context
16-25 April, Thabang is away, must work remotely. Major submission period over 29th April - 10th May, will impact productivity on software project.
## Decision
4 Sprints planned, consecutively. Will only start on 17th April, but have a "Sprint 0" from 9th to 16 April, with initial planning, research and folder structure creation, setup of Azure and Travis. Will not count towards actual number of sprints.
* Sprints will begin on Wednesdays, with a 1 hr review session in the morning.
* There will be a three hour sprint planning session in the afternooon each Wednesday.
* Release will be every Tuesday, by 8pm
* Product release window will be from 2pm - 8pm, with all pull requests done before 6pm to give time for any required last minute code review and testing
* Friday coding sessions together from 12pm - 4pm
* Standups via Whatsapp, or between lectures. Preferable to do in person but may not be possible.
Rebecca: Product Manager
Tyson: SCRUM Master
Theese roles will be alternated throughout the project each week.
## Consequences
Weekends, Tuesdays and Mondays are the most productive working days for all members of the project. Stand ups will happen in person whenever possible, but with diverse schedule of members, may have to use WhatsApp video chats instead.<file_sep>jest.mock('../app/models/db')
let authenticate = require('../app/models/authenticate')
const crypto = require('crypto')
describe('testing authentication', () => {
let userInfo = {
emailAddress: '<EMAIL>',
password: '<PASSWORD>',
userID: 12345678
}
const userHash = crypto.createHash('sha256')
userHash.update(userInfo.emailAddress + userInfo.password)
let userHashKey = userHash.digest('hex')
const googleUserHash = crypto.createHash('sha256')
googleUserHash.update(userInfo.userID + userInfo.password)
let googleUserHashKey = googleUserHash.digest('hex')
test('correct user hash key generated', () => {
let user = authenticate.createHashKey(userInfo, false)
expect(user.hash).toEqual(userHashKey)
})
test('correct google user hash key generated', () => {
let googleUser = authenticate.createHashKey(userInfo, true)
expect(googleUser.hash).toEqual(googleUserHashKey)
})
})<file_sep>'use strict'
jest.mock('../app/models/db')
let logModel = require('../app/models/logModel')
describe('testing createLog', () => {
let logItem = {
id: '0',
userId: 'random',
code: '1',
date: '2019-01-01',
importance: 'True',
tripId: 'random'
}
let log = [logItem]
test('createLogQueryString is correct when creating a new log', () => {
let queryString = logModel.createLogQueryString(log)
let expectedQueryString = `INSERT INTO log VALUES ('0','random','1','2019-01-01','True','random');`
expect(queryString).toEqual(expectedQueryString)
})
test('testing createLogQuery', async () => {
let queryString = logModel.createLogQueryString(log)
let response = await logModel.createLogQuery(queryString)
expect(Object.keys(response).length).toEqual(1)
expect(response.recordset).toEqual(undefined)
})
})
describe('testing getLogs', () => {
test('testing getLogQuery', async () => {
let tripId = 0
let logs = await logModel.getLogQuery(tripId)
expect(logs.recordset[0].id).toEqual('0')
expect(logs.recordset[0].userId).toEqual('random')
expect(logs.recordset[0].code).toEqual('1')
expect(logs.recordset[0].date).toEqual('2019-01-01')
expect(logs.recordset[0].importance).toEqual('True')
expect(logs.recordset[0].tripId).toEqual('random')
})
})<file_sep># 1. Entering locations/destinations for a trip
Date: 2019-04-09
## Status
Accepted
## Context
Destinations need to be entered into a trip somehow. The two most obvious choices seem to be by typing (some kind of auto-completion feature) or by clicking directly on a map, to set markers. These paradigms are the dominant ones in most existing APIs and site/map websites.
## Decision
We will aim to support both autocomplete AND clicking on the map. This would be the most convenient for users of the site.
## Consequences
Two methods of adding destinations will mean two (or more) additional functions in code, more complexity and added maintenance and testing. The methods will both need to work on Mobile/Responsive well.
* Vastly better UX
* Additional UI work
* Additional Testing
* Additional Code
* Additional code complexity
<file_sep>'use strict'
let db = require('./db')
let SqlString = require('sqlstring')
function createDestination (tripInfo, res) {
let trip = tripInfo.body
let queryString = createDestinationQueryString(trip)
createDestinationQuery(queryString)
.then(result => {
// console.log('destination table population result ', result)
res.send('DestinationTablePopulated')
})
.catch(err => {
console.log('populate destination table error:', err)
})
}
function createDestinationQueryString (trip) {
let queryString = SqlString.format('DELETE FROM destinations WHERE trip_id = ?;', [trip.id])
for (let i = 0; i < trip.destinationList.length; i++) {
queryString = queryString + SqlString.format('INSERT INTO destinations VALUES (?,?,?,?,?,?,?,?);',
[trip.destinationList[i].id,
trip.destinationList[i].lat,
trip.destinationList[i].lng,
trip.destinationList[i].placeId,
trip.destinationList[i].place,
trip.destinationList[i].name,
trip.destinationList[i].ordering,
trip.id])
}
return queryString
}
function createDestinationQuery (queryString) {
return db.pools
.then(pool => {
return pool.request()
.query(queryString)
})
}
module.exports = {
createDestination: createDestination,
createDestinationQueryString: createDestinationQueryString,
createDestinationQuery: createDestinationQuery
}
<file_sep>Main Site:
[](https://travis-ci.com/witseie-elen4010/2019-005-project)
Test Site:
[](https://travis-ci.com/witseie-elen4010/2019-005-project)
Main Site: https://awaywego.azurewebsites.net <br>
Test Site: https://testawaywego.azurewebsites.net
# Away We Go #
## A group travel trip planning web application.##
### ELEN4010 Group Project ###
###### <NAME> 1239448 ######
###### <NAME> 1066586 ######
###### <NAME> 1364103 #####
###### <NAME> 1056673 ######
---
Database: <br>
DB_SERVER=awaywegoserver.database.windows.net <br>
DB_NAME=AwayWeGoDatabase <br>
DB_ADMIN=softwareprojectadmin <br>
DB_PASSWORD=<PASSWORD> <br>
DB_PORT=1433 <br>
Test Database: <br>
DB_SERVER=testawaywegoserver.database.windows.net <br>
DB_NAME=TestAwayWeGoDatabase <br>
DB_ADMIN=softwareprojectadmin <br>
DB_PASSWORD=<PASSWORD> <br>
DB_PORT=1433 <br>
Travis: https://travis-ci.com/witseie-elen4010/2019-005-project <br>
Coveralls: https://coveralls.io/repos/github/witseie-elen4010/2019-005-project
EDIT (13 Nov 2019): All API Keys have been destroyed for all contributors from their respective Google Developer Console.
Note that both the Test and Main site described above have been shut down.
<file_sep>const { Builder, By, Key, until } = require('selenium-webdriver')
require('selenium-webdriver/chrome')
require('selenium-webdriver/firefox')
require('chromedriver')
require('geckodriver')
const rootURL = 'https://testawaywego.azurewebsites.net/sign-in'
const d = new Builder().forBrowser('chrome').build()
const waitUntilTime = 20000
let driver, el, actual, expected
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
async function getElementById(id) {
const el = await driver.wait(until.elementLocated(By.id(id)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
async function getElementByXPath(xpath) {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
test('waits for the driver to start', async () => {
return d.then(_d => {
driver = _d
})
})
test('initialises the context', async () => {
await driver.manage().window().setPosition(0, 0)
await driver.manage().window().setSize(1280, 1024)
await driver.get(rootURL)
})
describe('testing map markers', () => {
test('Marker can be found', async () => {
// sign in to access trip page
let email = await getElementById('inputEmail')
email.sendKeys('<EMAIL>')
let password = await getElementById('inputPassword')
password.sendKeys('r') // correct password for email
let button = await getElementById('signInPageSignInButton')
button.click()
// // A marker needs to exist on the map in order to be found. This can be done using 1 or 2:
// // Option 1: create a marker on the map
// location = await getElementById('pac-input')
// location.sendKeys('Cape Town')
// CT = await driver.wait(until.elementLocated(By.className('pac-container pac-logo')), waitUntilTime)
// CT.click()
// // Option 2: go to an existing trip on trip manager to load markers on trip page
// driver.navigate().GoToUrl('https://testawaywego.azurewebsites.net/trip-manager')
// title = await getElementById('Test trip')
// title.click()
// edit = await driver.wait(until.elementLocated(By.className('editTrip btn btn-sm btn-secondary')), waitUntilTime)
// edit.click() // this redirects back to trip page with destinations loaded
// // Find the marker on the map
// map = await getElementById('map')
// marker = await map.getAttribute('gmimap0')
// // Check the attributes of the marker
// actualShape = await marker.getAttribute('shape')
// expectedShape = 'poly'
// expect(actualShape).toEqual(expectedShape)
// actualTitle = await el.getAttribute('title')
// expectedTitle = ''
// expect(actualTitle).toEqual(expectedTitle)
// actualStyle = await el.getAttribute('style')
// expectedStyle = 'cursor: pointer; touch-action: none;'
// expect(actualStyle).toEqual(expectedStyle)
})
})
afterAll(() => {
driver.quit()
});<file_sep># 1. Title
Date: 2019-05-20
## Status
Accepted
## Context
In order to join a group, a potential member must be invited (it's not correct to add a person to a group without asking permission.) A person invited can either be a member of the website (have an account) or be a new user (no account registered yet). In order to cover both of these scenarios, and to avoid the website being a "walled garden" with a tiny set of users, and to encourage potential future growt, a mechanism to invite users could be an email, sent by an existing member, to any valid email address with an invitation to join. This could be in the form of a token with a payload, or more simply, an extra table in the DB, linking the invited person's email to a trip ID.
## Decision
The mechanism of an external invitation with a specific link requires the ability to send an email (prefereably attractively styled and clearly phrased, to avoid being rejected as unsolicited or junk email). The node module 'nodemailer' was selected as appropriate, for its wide support, mature development and ease of use, and 0 dependecies.
## Consequences
Nodemailer adds extra dependecies to node, increasing the number of modules that must be maintained and installed. This is a minor concern. The restrictions that a user must use the same email that they were invited with to login to the website in order to be included in the trip invite that was sent, is a more subtle problem, that can only be migitated by instructing the user in the original email to please use the same email address.
* Invites must be visible as notifications, or on the Trip Manager page
* Once rejected, or added, an invite must be removed from the 'invites' table to avoid annoying or confusing the user.
* MIT license, means high compatibility with existing licenses on other node modules.<file_sep>let preamble = [
'When you create an account with us, you must provide us information that is accurate, complete, and current at all times. Failure to do so constitutes a breach of the Terms, which may result in immediate termination of your account on our Service.',
'You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service.',
'You agree not to disclose your password to any third party. You must notify us immediately upon becoming aware of any breach of security or unauthorized use of your account.'
]
let accounts = [
'When you create an account with us, you must provide us information that is accurate, complete, and current at all times. Failure to do so constitutes a breach of the Terms, which may result in immediate termination of your account on our Service',
'You are responsible for safeguarding the password that you use to access the Service and for any activities or actions under your password, whether your password is with our Service or a third-party service',
'You agree not to disclose your password to any third party. You must notify us immediately upon becoming aware of any breach of security or unauthorized use of your account'
]
let otherSites = [
'Our Service may contain links to third-party web sites or services that are not owned or controlled by Away We Go',
'Away We Go has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Away We Go shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services.',
'We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or services that you visit.'
]
let getTermsAndCondtions = function () {
let termsObj = { 'preamble': preamble,
'accounts': accounts,
'otherSites': otherSites
}
return termsObj
}
module.exports = {
getTermsAndCondtions
}
<file_sep># 1. Title
Date: 2019-03-01
## Status
Accepted / Not Accepted
## Context
Explain the context
## Decision
What was decided
## Consequences
The consequences and outcomes of the decision
* Consequence 1
* Consequence 2<file_sep># Testing
This folder contains all the automated testing for the core functionality of the test. The testing framework used is Jest, and the end-end testing framework used is Selenium WebDriver. This file contains an overview of the tests performed in every test folder.
## authenticate.test
This file tests:
- Generation of user hash keys
- Generation of Google user hash keys
## groups.test
This file unit-tests the groups model, which is responsible for generating database query strings for data relating to groups of individuals who edit a given trip. These tests include:
- Testing the validity of the SQL query strings passed to the database for retrieving group members according to user hashes
- Testing the validity of the SQL query strings passed to the database for retrieving group members according to the trip ID
## invites.test
This file contains unit-tests for the invites model, which is responsible for generating database query strings for data relating to invites sent to email addresses. These tests include:
- Adding invites to the invites table
- Getting invites for a particular user
## invitesFrontEnd.test
This file contains automated front-end testing for the invites modal on the website. This file tests:
- The functionality of the "INVITE SOMEBODY TO JOIN THIS TRIP" button
- Front-end email format validation
- The validity of the confirmation message after an email is sent
## log.test
This file contains unit-tests for the log model, which is responsible for generating database query strings for data relating to logs about changes made to a trip. These tests include:
- Creating logs
- Retrieving logs
## sign-in.test
This file contains automated front-end testing for the functionality of the sign-in page of the website. This file tests:
- The necessary HTML DOM elements are displayed correctly for login
- The ability to successfully login once the correct user credentials are supplied
## termsAndConditions.test
This file contains unit-tests for the terms and conditions model, which is responsible for providing terms and conditions to be rendered on the webpage. These tests include:
- Testing that the preamble returned is correct
- Testing that the terms and conditions relating to accounts is correct
- Testing that the terms and conditions relating to the other sites is correct
## termsAndConditionsFrontEnd.test
This file contains automated front-end testing that the terms and conditions from the model are rendered correctly on the on the website: These tests include:
- Testing that the preamble returned is correct
- Testing that the terms and conditions relating to accounts is correct
- Testing that the terms and conditions relating to the other sites is correct
## trip-manager.test
This file contains unit-tests for the trip-manager model, which is responsible for generating the database query strings for data relating to the trips associated with a given user. These tests include:
- Retrieving trip titles
- Adding trip titles
- Retrieving destinations that are part of a trip
## trip.test
This file contains unit-tests for the trips model, which is responsible for generating the database query strings for the destinations table. These tests include:
- Adding destinations
- Deleting destinations
## user.test
This file contains unit-tests for users model, which is responsible for generating the database query strings for the users table. These tests include:
- Creating new users
- Finding existing users
<file_sep>jest.mock('../app/models/db')
let userModel = require('../app/models/userModel')
describe('testing userModel', () => {
test('test that user information gets deleted in fail to sign-in/register server responses', () => {
let userInfo = {
firstName: 'Some',
lastName: 'Person',
emailAddress: '<EMAIL>',
password: '<PASSWORD>',
userID: 12345678,
image: 'http://some.url.com/image.jpg',
hash: 'a1b2c3d4e5f6g7h8i9',
userType: 'incorrectUser'
}
let expectServerInfoResponse = { userType: 'incorrectUser' }
userModel.deleteUnnecessaryInfo(userInfo)
expect(userInfo).toEqual(expectServerInfoResponse)
})
test('test findUserQuery', async () => {
let email = '<EMAIL>'
let user = await userModel.findUserQuery(email)
expect(user.recordset[0].first_name).toEqual('Some')
expect(user.recordset[0].last_name).toEqual('Person')
expect(user.recordset[0].email_address).toEqual('<EMAIL>')
expect(user.recordset[0].image_url).toEqual('http://image.com/image.jpg')
expect(user.recordset[0].hash).toEqual('q1w2e3r4t5y6u7i8o9')
})
test('test createUserQuery', async () => {
let userInfo = {
firstName: 'Some',
lastName: 'Person',
emailAddress: '<EMAIL>',
password: '<PASSWORD>',
userID: 12345678,
image: 'http://some.url.com/image.jpg',
hash: 'a1b2c3d4e5f6g7h8i9',
userType: 'incorrectUser'
}
let createUser = await userModel.createUserQuery(userInfo)
expect(Object.keys(createUser).length).toEqual(1)
expect(createUser.recordset).toEqual(undefined)
})
})<file_sep>'use strict'
let db = require('./db')
function findUserQuery (email) {
return db.pools
// Run query
.then((pool) => {
let dbrequest = pool.request()
dbrequest.input('email', email)
return dbrequest.query(`SELECT * FROM users WHERE email_address = @email`)
})
}
function findUser (userInfo, signin, res) {
let info = userInfo
let email = info.emailAddress
findUserQuery(email)
// both ID/Email match sought after in case of possible duplication of either ID/Email
.then(result => {
// if no match is found, it must be a new user
if (result.recordset.length === 0) {
info.userType = 'newUser'
// if user doesn't exist and tries to sign in
if (signin) {
deleteUnnecessaryInfo(info)
res.send(info)
} else {
createUser(info, res)
}
} else {
info.userType = 'currentUser'
// account that does exist and is trying to register
if (!signin) {
// console.log('trying to register')
deleteUnnecessaryInfo(info)
res.send(info)
} else if (result.recordset[0].hash === info.hash) {
// account that exists and is trying to sign in with the correct password
// console.log('correct sign in')
info.firstName = result.recordset[0].first_name
info.lastName = result.recordset[0].last_name
info.emailAddress = result.recordset[0].email_address
info.hash = result.recordset[0].hash
// console.log('lastly current', info)
res.send(info)
} else {
// account that exists and is trying to sign in with the wrong password
// console.log('incorrect sign in')
info.userType = 'incorrectUser'
deleteUnnecessaryInfo(info)
res.send(info)
}
}
})
.catch(err => {
console.log('find user error', err)
})
}
function createUserQuery (info) {
return db.pools
// Run query
.then((pool) => {
let dbrequest = pool.request()
dbrequest.input('firstName', info.firstName)
dbrequest.input('lastName', info.lastName)
dbrequest.input('emailAddress', info.emailAddress)
dbrequest.input('image', info.image)
dbrequest.input('hash', info.hash)
return dbrequest.query(`INSERT INTO users VALUES(@firstName,@lastName,@emailAddress,@image,@hash)`)
})
}
function createUser (userInfo, res) {
let info = userInfo
createUserQuery(info)
// Send back the result
.then(result => {
res.send(info)
})
// If there's an error, return that with some description
.catch(err => {
console.log('create users error', err)
})
}
function deleteUnnecessaryInfo (info) {
delete info.emailAddress
delete info.password
delete info.hash
delete info.image
delete info.firstName
delete info.lastName
delete info.userID
}
module.exports = {
findUser: findUser,
deleteUnnecessaryInfo: deleteUnnecessaryInfo,
findUserQuery: findUserQuery,
createUserQuery: createUserQuery
}
<file_sep># 1. Use of GitHub's Project feature for a KanBan
Date: 2019-04-09
## Status
Accepted
## Context
A SCRUM-based agile devlopment workflow would benefit from a central KANBAN board to keep track of userstories that have been written, are in progress, and are complete. This will help identify the sprint backlog, and the current focus of the sprint. Labels could be used to indicate size/priority/difficuly or value to the project, to help calculate the sprint velocity and determine what can get done inside a single sprint.
## Decision
Using the GitHib Project page with a single project for the repo, and using Issues labelled as User Stories, with columns for "To Do", "In progress", and "Completed". We can leverage some of the automatic rules in Git to help automate some of the completetion of tasks ties to Milestones for each sprint:
https://github.com/witseie-elen4010/2019-005-project/projects/1
## Consequences
Manually Use story cards used so far will become redundant. Need to tie physical cards into the digital version in the interim. Will not maintain the physical cards beyond Sprint 1.
* simplifies workflow
* Directly ties git issues and User Stories to individual developers
* Easy to modify an existing User story - need to maintain discipline to avoid retroactively modifying tasks
* Acceptance tests can be specified as sub-issues, or as checkboxes on an issue.
<file_sep>'use strict'
const $ = window.$
export default function addTermsToSubsection (subsection, termsArray, divider) {
let parentItemType = ''
if (divider === 'li') {
parentItemType = 'ol'
} else {
parentItemType = 'p'
}
let parentItem = document.createElement(parentItemType)
termsArray.forEach(element => {
let item = document.createElement(divider)
let term = document.createTextNode(element)
item.appendChild(term)
parentItem.appendChild(item)
})
subsection.append(parentItem)
}
$(document).ready(() => {
$.ajax({
url: '/terms_and_conditions/data',
type: 'GET',
success: (data) => {
addTermsToSubsection($('#Preamble'), data.preamble, 'p')
addTermsToSubsection($('#Accounts'), data.accounts, 'li')
addTermsToSubsection($('#OtherSites'), data.otherSites, 'li')
}
})
})
<file_sep>const { Builder, By, Key, until } = require('selenium-webdriver')
require('selenium-webdriver/chrome')
require('selenium-webdriver/firefox')
require('chromedriver')
require('geckodriver')
const rootURL = 'https://testawaywego.azurewebsites.net/sign-in'
const d = new Builder().forBrowser('chrome').build()
const waitUntilTime = 20000
let driver, el, actual, expected
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
async function getElementById(id) {
const el = await driver.wait(until.elementLocated(By.id(id)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
async function getElementByClass(className) {
const el = await driver.wait(until.elementLocated(By.className(className)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
async function getElementByXPath(xpath) {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), waitUntilTime)
return await driver.wait(until.elementIsVisible(el), waitUntilTime)
}
test('waits for the driver to start', async () => {
return d.then(_d => {
driver = _d
})
})
test('initialises the context', async () => {
await driver.manage().window().setPosition(0, 0)
await driver.manage().window().setSize(1280, 1024)
await driver.get(rootURL)
})
describe('test invites modal', () => {
let validEmailAddress = '<EMAIL>'
let invalidEmailAddress = 'invalidEmailAddress.com'
test('Invites modal appears when "INVITE SOMEBODY TO JOIN THIS TRIP" is pressed', async () => {
let email = await getElementById('inputEmail')
email.clear()
email.sendKeys('<EMAIL>')
let password = await getElementById('inputPassword')
password.clear()
password.sendKeys('r') // correct password for email
let button = await getElementById('signInPageSignInButton')
button.click()
// wait for an element that is unique to the trip page to be found before getting the URL
await getElementById('pac-input')
let inviteSomebodyButton = await getElementById('inviteEditorButton')
inviteSomebodyButton.click()
let invitesModal = await getElementByClass('modal')
let modalVisibility = invitesModal.isDisplayed()
expect(modalVisibility).toBeTruthy()
})
test('test if an a warning message appears after an invalid email address is entered', async () => {
let emailAddressField = await getElementById('emailAddressField')
emailAddressField.clear()
emailAddressField.sendKeys(invalidEmailAddress)
let inviteButton = await getElementById('inviteEmailAddressButton')
inviteButton.click()
let warningMessgae = await getElementById('inviteEmailAddressButton')
warningMessageVisibility = await warningMessgae.isDisplayed()
expect(warningMessageVisibility).toBeTruthy()
})
test('test if an a warning message appears after an invalid email address is entered', async () => {
let emailAddressField = await getElementById('emailAddressField')
emailAddressField.clear()
emailAddressField.sendKeys('invalidEmailAddress.com')
let inviteButton = await getElementById('inviteEmailAddressButton')
inviteButton.click()
let warningMessgae = await getElementById('inviteEmailAddressButton')
warningMessageVisibility = await warningMessgae.isDisplayed()
expect(warningMessageVisibility).toBeTruthy()
})
test('test if an a "group invite sent" message appears after a valid email address is entered', async () => {
let emailAddressField = await getElementById('emailAddressField')
emailAddressField.clear()
emailAddressField.sendKeys(validEmailAddress)
let inviteButton = await getElementById('inviteEmailAddressButton')
inviteButton.click()
let inviteSentMessage = await getElementById('inviteSendHeader')
inviteSentMessageVisibility = await inviteSentMessage.isDisplayed()
expect(inviteSentMessageVisibility).toBeTruthy()
})
test('test if the email addres in the "group invite sent" message is correct', async () => {
let inviteSentAddress = await getElementById('InviteEmailAddress')
inviteSentAddressText = await inviteSentAddress.getText()
expect(inviteSentAddressText).toBe(validEmailAddress)
})
})
afterAll(() => {
driver.quit()
});<file_sep># 1. Trunk-Based Development
Date: 2019-04-24
Modified: 2019-05-02 (Tyson)
Modified: 2019-05-07 (Tyson)
## Status
Accepted
## Context
To perform Continual Integration and development, with weekly releases, it would be convenient and useful to have a testing branch as well. Accidental pull requests into the main branch may introduce features that have not been tested from the interfac/front-end. It is difficult to automate these front-end interface tests, and there may be factors not present in a localhost/express server that only become apparent in an online scanario.
The use of **master** branch as the release branch is useful, as 'master' is usually the most protected on GitHub, with the most warnings about deleting, modifying, etc.
Code reviews ar essential from all developers, to become familiar with each other's code, and to learn about javascript, and web-development. THis way we all learn from each other, and also learn good review and communicaton practice.
## Decision
**master** will be the release branch
**development** will be the main development/test branch. This will also be made into the "default" branch for all pull requests, to avoid accidentaly PR into master
**feature** branches must be made off development, with unique names. All pull requests for completed features to be made into "development".
* All PRs must be reviewed by at least two developers to merge into "development"
* All PRs must be reviewed by at the three other developers to merge into "master"
* All PRs must pass all tests (Jest, Travis, and Coveralls) in order to be considered valid for a merge
* Stale reviews will be automatically dismissed if a new commit is pushed to the same branch
* Accepted PRs for completed features (User Stories) should be deleted after sucessfully merging
## Consequences
This setup complexifies the deployment requirements, and a seperate test website will need to be setup in Azure.
Travis CI -> main site / GitHub CI -> directly to test site
**Update** Coveralls has a problem with repos that use "development" as their main branch: cannot see "master" at all.
**Update** Coveralls has resolved its error with not seeing "master" - logged issue and was fixed
**Update** Change in Admin rights on GitHut means we can no longer deploy directly to testawaywego from GitHub. Instead, Travis will use azure push features with branch rules to both sites (on: master / on: development) but lack of deployment slots means that we must use the same login/password between both test and main sites, with script-specified config for the sitename
**Update** The Travis azure deplyment is very flaky and doesn't complete the deployment predictably. Instead, a script has been written which directly issues a git force push command to send the repo from Travis to azure, if the tests complete sucessfully.
| 45bda2cca46f29157f80cd02b4294125d8bf54ae | [
"Markdown",
"JavaScript"
] | 36 | Markdown | Farai-Mutsva/ELEN4010 | 05f7e11d2f6dd2fe631bab41c88aedcbc74dd9b6 | c23fc880ed44213a202579dff34845947da7625f | |
refs/heads/master | <file_sep># "Stopwatch: The Game"
# Import modules
import simplegui
# define global variables
display_text = "0:00.0"
interval = 100
timer_count = 0
a = 0
b = 0
c = 0
success_stops = 0
failed_stops = 0
total_stops = 0
results = "0 / 0"
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
return get_min(t) + ":" + get_sec(t) + "." + get_milli_sec(t)
# get milli seconds
def get_milli_sec(t):
global c
t = str(t)
c = int(t[-1])
return t[-1]
# get seconds
def get_sec(t):
t = str(t)
if len(t) == 2 and int(t) < 600:
b = t[0]
elif len(t) == 3 and int(t) < 600:
b = t[:2]
elif int(t) > 600:
b = str((int(t) % 600) // 10)
else:
b = "00"
return pad_sec(b)
# get minutes
def get_min(t):
if t >= 600:
a = str(t // 600)
else:
a = "0"
return a
# pad out seconds to 2 digits
def pad_sec(t):
if len(t)== 0:
t = "00"
elif len(t) == 1:
t = "0" + t
else:
t = t
return t
# define event handlers for buttons; "Start", "Stop", "Reset"
def button_start():
timer.start()
def button_stop():
if timer.is_running():
timer.stop()
global timer_count, success_stops, failed_stops, total_stops, results
#print timer_count, get_milli_sec(timer_count)
total_stops += 1
if int(get_milli_sec(timer_count)) == 0:
success_stops += 1
else:
failed_stops += 1
results = str(success_stops) + " / " + str(total_stops)
def button_reset():
timer.stop()
global timer_count, a, b, c, success_stops, failed_stops, results, total_stops
timer_count = 0
a = 0
b = 0
c = 0
failed_stops = 0
success_stops = 0
total_stops = 0
results = "0 / 0"
#print "\nNew Game\n"
# define event handler for timer with 0.1 sec interval
def tick():
global timer_count
timer_count += 1
# define draw handler
def draw(canvas):
canvas.draw_text(format(timer_count), [60, 110], 36, "White")
canvas.draw_text(results, [140, 25], 24, "Green")
# create frame
frame = simplegui.create_frame("Stopwatch: The Game", 200, 200)
# register event handlers
frame.set_draw_handler(draw)
timer = simplegui.create_timer(interval, tick)
frame.add_button("Start", button_start, 100)
frame.add_button("Stop", button_stop, 100)
frame.add_button("Reset", button_reset, 100)
# start frame
frame.start()
<file_sep># "Guess the number" mini-project
import simplegui
import random
import math
# initialize global variables used in your code
num_range = 100
random_number = 0
guesses_left = 0
# define event handlers for control panel
def init():
range100()
f.start()
def range100():
# button that changes range to range [0,100) and restarts
global random_number, guesses_left, num_range
num_range = 100
random_number, guesses_left = random.randrange(0, 100), 7
print "New game. Range is from 0 to 100"
print "Number of guesses remaining: ", guesses_left, "\n"
def range1000():
# button that changes range to range [0,1000) and restarts
global random_number, guesses_left, num_range
num_range = 1000
random_number, guesses_left = random.randrange(0, 1000), 10
print "New game. Range is from 0 to 1000"
print "Number of guesses remaining: ", guesses_left, "\n"
def within_range(guess):
# make sure user is entering a number that falls within the
# specified range
global num_range
if int(guess) >= 0 and int(guess) < num_range:
return True
else:
return False
def get_input(guess):
# main game logic goes here
global guesses_left, random_number
guesses_left -= 1
print "Guess entered: ", guess
print "Number of remaining guesses is ", guesses_left
if int(guess) > random_number and within_range(guess) and guesses_left != 0:
print "Lower!\n"
elif int(guess) < random_number and within_range(guess) and guesses_left != 0:
print "Higher!\n"
elif int(guess) == random_number:
print "You got it right!\n"
range100()
elif guesses_left == 0 and int(guess) != random_number:
print "You ran out of guesses, the correct number is ", random_number, "\n"
range100()
else:
print "Guess does not fall within range, Try Again.\n"
# create frame
f = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements
f.add_button("Range is [0,100)", range100, 200)
f.add_button("Range is [0,1000)", range1000, 200)
f.add_input("Enter a guess", get_input, 200)
# start frame
init()<file_sep># implementation of card game - Memory
import simplegui
import random
list_cards = []
list_status = []
cards_clicked = []
num_moves = 0
# helper function to initialize globals
def init():
global list_cards, list_status, num_moves
temp_list1 = range(0,8)
temp_list2 = range(0,8)
list_cards = temp_list1 + temp_list2
random.shuffle(list_cards)
list_status = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
del cards_clicked[:]
num_moves = 0
# define event handlers
def mouseclick(pos):
global list_cards, list_status, cards_clicked, num_moves
# add game state logic here
if num_moves == 0:
num_moves += 1
if list_status[pos[0] // 50] == 0:
list_status[pos[0] // 50] = 1
cards_clicked.append(pos[0] // 50)
if len(cards_clicked) == 3:
num_moves += 1
if list_cards[cards_clicked[0]] == list_cards[cards_clicked[1]]:
list_status[cards_clicked[0]] = 2
list_status[cards_clicked[1]] = 2
del cards_clicked[:2]
else:
list_status[cards_clicked[0]] = 0
list_status[cards_clicked[1]] = 0
del cards_clicked[:2]
# cards are logically 50x100 pixels in size
def draw(canvas):
global list_cards, list_status, num_moves
position = 15
cover = 0
check = 0
box = 0
for x in list_cards:
if list_status[check] != 0:
canvas.draw_text(str(x), (position, 65), 48, "Red")
else:
canvas.draw_polygon([[box, 0], [box + 50, 0], [box + 50, 100], [box,100]], 1, "white", "green")
position += 50
check += 1
box += 50
label.set_text("Moves = " + str(num_moves))
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Restart", init)
label = frame.add_label("Moves = 0")
# initialize global variables
init()
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
frame.start()<file_sep>This repository contains Projects from Coursera: An Introduction to Interactive Programming in Python | 578001f86f8996ae51f1c1974dd171cc1d108a51 | [
"Markdown",
"Python"
] | 4 | Python | jjh5030/Coursera_Intro_to_Python | 6b8ae12790e2c89fa4ab966052e0368e0e1c7b09 | 40df4b0d708dca79ca6bd688aa3116a28ae42175 | |
refs/heads/master | <repo_name>rohacompany/TestProject<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/custom/CountryInfo.java
package color.test.roha.com.colortestproject.custom;
import java.text.Collator;
import java.util.Locale;
class CountryInfo implements Comparable<CountryInfo> {
private final Collator collator;
public final Locale locale;
public final int countryCode;
public CountryInfo(Locale locale, int countryCode) {
collator = Collator.getInstance(Locale.getDefault());
collator.setStrength(Collator.PRIMARY);
this.locale = locale;
this.countryCode = countryCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final CountryInfo that = (CountryInfo) o;
if (countryCode != that.countryCode) return false;
return !(locale != null ? !locale.equals(that.locale) : that.locale != null);
}
@Override
public int hashCode() {
int result = locale != null ? locale.hashCode() : 0;
result = 31 * result + countryCode;
return result;
}
@Override
public String toString() {
return this.locale.getDisplayCountry() + "(+" + countryCode + ")";
}
@Override
public int compareTo(CountryInfo info) {
return collator.compare(this.locale.getDisplayCountry(), info.locale.getDisplayCountry());
}
}<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/IntroActivity.java
package color.test.roha.com.colortestproject;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class IntroActivity extends AppCompatActivity implements View.OnClickListener{
LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
ll = (LinearLayout) findViewById(R.id.activity_intro);
Button btnColor1 = (Button) findViewById(R.id.color1);
Button btnColor2 = (Button) findViewById(R.id.color2);
Button btnColor3 = (Button) findViewById(R.id.color3);
Button btnColor4 = (Button) findViewById(R.id.color4);
btnColor1.setOnClickListener(this);
btnColor2.setOnClickListener(this);
btnColor3.setOnClickListener(this);
btnColor4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int colorResdId = R.color.intro1;
switch (v.getId()){
case R.id.color1:
colorResdId = R.color.intro1;
break;
case R.id.color2:
colorResdId = R.color.intro2;
break;
case R.id.color3:
colorResdId = R.color.intro3;
break;
case R.id.color4:
colorResdId = R.color.intro4;
break;
}
if(ll!=null){
ll.setBackgroundColor(getResources().getColor(colorResdId));
}
}
}
<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/ProfileDialogActivity.java
package color.test.roha.com.colortestproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
public class ProfileDialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
int screenHeight = (int) (metrics.heightPixels * 0.80);
setContentView(R.layout.activity_profile_dialog);
getWindow().setLayout(screenWidth, screenHeight); //set below the setContentvie
setFinishOnTouchOutside(true);
}
}
<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/URLManager.java
package color.test.roha.com.colortestproject;
/**
* Created by dev on 2016-11-24.
*/
public class URLManager {
public static String _MAIN_JSON_QUERY_HOST =
"http://command.roha.co.kr/json/query.php";
public static String _VERSION = "3.0";
}
<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/AuthPinConfirmActivity.java
package color.test.roha.com.colortestproject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import color.test.roha.com.colortestproject.datas.SMSAuthVO;
public class AuthPinConfirmActivity extends BaseActivity {
CountDownTimer timer;
int init_timer_value = 10000;
String param_country_code,param_phone_number;
public static final String CS_NUMBER = "07073538495";
private SMSReceiver _receiver;
SMSAuthVO _receivedVO;
private String _received_auth_code = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth_pin_confirm);
aq = new AQuery(this);
param_country_code = getIntent().getStringExtra("country_code");
param_phone_number = getIntent().getStringExtra("phone_number");
aq.id(R.id.phone_number).text( "+" + param_country_code + " " + param_phone_number);
setTimerText(3 , 0);
startTimer();
aq.id(R.id.timer).clicked(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestSMS();
startTimer();
}
});
aq.id(R.id.btnSendAuthPinCode).clicked(new View.OnClickListener() {
@Override
public void onClick(View v) {
confirmVerification();
}
});
registerReceiver();
requestSMS();
setupTop();
}
@Override
public void setupTop() {
super.setupTop();
setTitle(R.string.activity_auth_2_name);
setStep(2);
}
/**
* REQUEST SMS
*/
private void requestSMS(){
HashMap<String,Object> paramMap = new HashMap<String,Object>();
paramMap.put("version" , "3.0");
paramMap.put("method" , "sms_auth");
paramMap.put("rphone" , param_country_code +"-"+ param_phone_number);
paramMap.put("alert" , "TW");
aq.ajax(URLManager._MAIN_JSON_QUERY_HOST , paramMap , JSONObject.class , new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
Logger.log("object - > " + object);
if(object!=null){
Gson gson = new Gson();
_receivedVO = gson.fromJson(object.toString() , SMSAuthVO.class);
}
}
});
}
private void startTimer(){
//타이머 설정
timer = new CountDownTimer(init_timer_value, 1000) {
@Override
public void onFinish() {
aq.id(R.id.timer).text(getText(R.string.re_send)).background(R.drawable.img_btn_bg_red);
}
@Override
public void onTick(long millisUntilFinished) {
long min = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
long sec = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished));
Log.v("KTH", min + "," + sec);
setTimerText(min , sec);
}
};
timer.start();
}
private void setTimerText(long min , long sec){
aq.id(R.id.timer).text(String.format(getString(R.string.auth_pine_code_timeout_format) , min , sec)).background(R.drawable.img_btn_bg_grey);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return super.onOptionsItemSelected(item);
}
private void registerReceiver() {
unregisterReceiver();
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SMSReceiver.ACTION);
_receiver = new SMSReceiver();
registerReceiver(_receiver, intentFilter);
}
private void unregisterReceiver() {
if(_receiver != null) {
unregisterReceiver(_receiver);
_receiver = null;
}
}
public void confirmVerification(){
String mPineCode = aq.id(R.id.pin_code).getText().toString();
if(_receivedVO!=null){
if(mPineCode.equalsIgnoreCase(_received_auth_code)
&& mPineCode.equalsIgnoreCase(_receivedVO.getAuth_code())
){
Intent intent = new Intent(AuthPinConfirmActivity.this , ProfileMainActivity.class);
startActivity(intent);
}else{
Toast.makeText(this , "인증코드가 일치하지 않습니다." , Toast.LENGTH_SHORT).show();
aq.id(R.id.pin_code).text(null).getView().requestFocus();
}
}
}
private class SMSReceiver extends BroadcastReceiver {
private static final String TAG="KTH";
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
// 문자만 수신받음
Logger.log("receive intent!!");
if(intent.getAction().equals(ACTION)) {
final Bundle bundle = intent.getExtras();
if(bundle == null)
return;
final Object[] pdusObj = (Object[])bundle.get("pdus");
if(pdusObj == null)
return;
final SmsMessage[] smsMessages = new SmsMessage[pdusObj.length];
for(int i=0; i<smsMessages.length; i++) {
smsMessages[i] = SmsMessage.createFromPdu((byte[])pdusObj[i]);
final String address = smsMessages[i].getOriginatingAddress();
final String message = smsMessages[i].getDisplayMessageBody();
if(address.equals(CS_NUMBER)) {
// String adjustMessage = message.replace("[Web발신]", "");
// int begin = adjustMessage.indexOf('[');
// int end = adjustMessage.indexOf(']');
//
// // 인증번호를 찾았다
// final String codeMessage = adjustMessage.substring(begin+1, end);
final String codeMessage = removeCharExceptNumber(message);
_received_auth_code = codeMessage;
runOnUiThread(new Runnable() {
@Override
public void run() {
Logger.log("code -> " + codeMessage);
// _code.setText(codeMessage);
aq.id(R.id.pin_code).text(codeMessage);
mHandler.sendEmptyMessageDelayed( 1 , 1000);
}
});
}
}
}
}
private String removeCharExceptNumber(String str) {
return str.replaceAll("[^0-9]", "");
}
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == 1){
confirmVerification();
}
}
};
@Override
protected void onDestroy() {
if(_receiver!=null)
unregisterReceiver();
super.onDestroy();
}
}
<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/custom/CustomProfileImage.java
package color.test.roha.com.colortestproject.custom;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import color.test.roha.com.colortestproject.R;
/**
* Created by dev on 2016-11-25.
*/
public class CustomProfileImage extends RelativeLayout{
public CustomProfileImage(Context context) {
super(context);
init();
}
public CustomProfileImage(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomProfileImage(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
setBackgroundResource(R.drawable.img_profile_center);
}
}
<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/AuthMainActivity.java
package color.test.roha.com.colortestproject;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.digits.sdk.android.models.PhoneNumber;
import java.util.Locale;
import java.util.regex.Pattern;
import color.test.roha.com.colortestproject.custom.CountryListSpinner;
import static color.test.roha.com.colortestproject.MainActivity._PERMISSION_REQUEST_CODE;
public class AuthMainActivity extends BaseActivity {
TextView tvLinkify;
CountryListSpinner countryListSpinner;
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "kc1Das6xy7btT2jyqCg5alErx";
private static final String TWITTER_SECRET = "<KEY>";
boolean isTestMode = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth_main);
aq = new AQuery(this);
tvLinkify = (TextView)findViewById(R.id.aggrement);
countryListSpinner = (CountryListSpinner)findViewById(R.id.dgts__countryCode);
checkPermission();
setupTop();
}
@Override
public void setupTop() {
super.setupTop();
setTitle(R.string.activity_auth_1_name);
aq.id(R.id.ibtn_common_back).gone();
}
private void setLinkfy(){
String text = getString(R.string.auth_phone_1);
tvLinkify.setText(text);
Pattern pattern1 = Pattern.compile("이용약관");
Pattern pattern2 = Pattern.compile("개인 정보 취급 방침");
Linkify.addLinks(tvLinkify, pattern1, "agreement1://");
Linkify.addLinks(tvLinkify, pattern2, "agreement2://");
}
public void checkPermission(){
int permissionCheck1 = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int permissionCheck2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS);
int permissionCheck3 = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionCheck4 = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if(permissionCheck1 == PackageManager.PERMISSION_DENIED
|| permissionCheck2 == PackageManager.PERMISSION_DENIED
|| permissionCheck3 == PackageManager.PERMISSION_DENIED
|| permissionCheck4 == PackageManager.PERMISSION_DENIED
){
ActivityCompat.requestPermissions(this , new String[]{
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE} ,
_PERMISSION_REQUEST_CODE);
}else{
setup();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
setup();
}
public void setup(){
setLinkfy();
final PhoneNumber validPhoneNumber = new PhoneNumber("01064292256", "KR", "82");
final CountryListSpinner countryListSpinner = (CountryListSpinner) findViewById(R.id.dgts__countryCode);
countryListSpinner.setSelectedForCountry(new Locale("",
validPhoneNumber.getCountryIso()),
validPhoneNumber.getCountryCode());
aq.id(R.id.btnSendAuthPinCode).clicked(new View.OnClickListener(){
@Override
public void onClick(View v) {
String country_code = countryListSpinner.getSelectedCountCode() + "";
String phone_number = aq.id(R.id.phone_number).getText().toString();
Log.d("KTH" , country_code + "," + phone_number);
if(isTestMode){
Intent intent = new Intent(AuthMainActivity.this, ProfileMainActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(AuthMainActivity.this, AuthPinConfirmActivity.class);
intent.putExtra("country_code", country_code);
intent.putExtra("phone_number", phone_number);
startActivity(intent);
}
}
});
aq.id(R.id.phone_number).text(getMyPhoneNumber());
}
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = mTelephonyMgr.getLine1Number();
if(phoneNumber.startsWith("82")){
phoneNumber.replace("82","0");
}else if(phoneNumber.startsWith("+82")){
phoneNumber.replace("+82","0");
}
return phoneNumber;
}
private String getMy10DigitPhoneNumber(String phoneNumber){
String s = phoneNumber;
return s.substring(2);
}
}
<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/custom/CountryListAdapter.java
package color.test.roha.com.colortestproject.custom;
import android.content.Context;
import android.graphics.Movie;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import color.test.roha.com.colortestproject.R;
import static android.R.attr.data;
class CountryListAdapter extends ArrayAdapter<CountryInfo> implements SectionIndexer {
final private HashMap<String, Integer> alphaIndex = new LinkedHashMap<>();
final private HashMap<String, Integer> countryPosition = new LinkedHashMap<>();
private String[] sections;
Context ctx;
public CountryListAdapter(Context context) {
super(context, R.layout.view_spinner_auth_phone_number, android.R.id.text1);
this.ctx = context;
}
// The list of countries should be sorted using locale-sensitive string comparison
public void setData(List<CountryInfo> countries) {
// Create index and add entries to adapter
int index = 0;
for (CountryInfo countryInfo : countries) {
final String key = countryInfo.locale.getDisplayCountry().substring(0, 1)
.toUpperCase(Locale.getDefault());
if (!alphaIndex.containsKey(key)) {
alphaIndex.put(key, index);
}
countryPosition.put(countryInfo.locale.getDisplayCountry(), index);
index++;
add(countryInfo);
}
sections = new String[alphaIndex.size()];
alphaIndex.keySet().toArray(sections);
notifyDataSetChanged();
}
@Override
public Object[] getSections() {
return sections;
}
@Override
public int getPositionForSection(int index) {
if (sections == null) {
return 0;
}
// Check index bounds
if (index <= 0) {
return 0;
}
if (index >= sections.length) {
index = sections.length - 1;
}
// Return the position
return alphaIndex.get(sections[index]);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
public int getPositionForCountry(String country) {
final Integer position = countryPosition.get(country);
return position == null ? 0 : position;
}
// @Override
// public View getView(int position, View convertView, ViewGroup parent){
//
// if(convertView==null){
// //inflate the layout
// LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = inflater.inflate(R.layout.view_spinner_auth_phone_number, parent, false);
// }
//
//
// CountryInfo info = getItem(position);
// //movie item based on the position
//
// //get the TextView and then set the text(movie name) and tag(show_Movie.i) values
// TextView textViewItem = (TextView)convertView.findViewById(android.R.id.text1);
// textViewItem.setText(info.countryCode);
//
//
// return convertView;
//
//
// }
}<file_sep>/app/src/main/java/color/test/roha/com/colortestproject/custom/CustomDigits.java
package color.test.roha.com.colortestproject.custom;
import com.digits.sdk.android.Digits;
import com.digits.sdk.android.DigitsEventLogger;
import java.util.concurrent.ExecutorService;
import io.fabric.sdk.android.Fabric;
/**
* Created by dev on 2016-11-22.
*/
public class CustomDigits extends Digits{
protected CustomDigits(int themeResId, DigitsEventLogger externalLogger) {
super(themeResId, externalLogger);
}
public static CustomDigits getInstance() {
return (CustomDigits) Fabric.getKit(Digits.class);
}
@Override
protected ExecutorService getExecutorService() {
return super.getExecutorService();
}
}
| caaaff3e9370bdc1de33517512f8cef7f58ff9a4 | [
"Java"
] | 9 | Java | rohacompany/TestProject | f31a3183c989b27073d296758ac51b3b360a1c08 | ffc04c6872b7fd56030f2792adf5a23824cbadc5 | |
refs/heads/master | <file_sep>const ROW_ANIMATION_DURATION = 250;
const ANIMATION_ACCELERATION_EXPONENT = 1 / 2;
const ANIMATION_EQUATION_DENOMINATOR = 2 * Math.pow(0.5, ANIMATION_ACCELERATION_EXPONENT);
function invertHeaderSorting(header, animate) {
var table = document.getElementById("transcript").children[0];
var rows = [];
const numLoops = table.children.length - 1;
for (var i = 0; i < numLoops; i++) {
rows[i] = table.children[i + 1];
}
var firstTableRow = table.firstChild;
var tableHeaders = firstTableRow.children;
var selectedHeaderCell = tableHeaders[header];
var selectedHeaderCellArrows = selectedHeaderCell.children[1];
var cellsAtRowHeaderIntersect = [];
for (var i = 0; i < rows.length; ++i) {
cellsAtRowHeaderIntersect.push(rows[i].children[header].children[0].textContent);
}
var oldArray = cellsAtRowHeaderIntersect.slice(0);
if (selectedHeaderCellArrows.className == "arrows sorted_up") {
cellsAtRowHeaderIntersect.sort(reverseCellComparator);
selectedHeaderCellArrows.className = "arrows sorted_down";
} else {
cellsAtRowHeaderIntersect.sort(cellComparator);
selectedHeaderCellArrows.className = "arrows sorted_up";
}
for (var i = 0; i < tableHeaders.length; i++) {
if (i != header) {
tableHeaders[i].children[1].className = "arrows neutral";
}
}
var originalPositions = [];
var rowShifts = [];
for (var i = 0; i < oldArray.length; ++i) {
for (var n = 0; n < cellsAtRowHeaderIntersect.length; ++n) {
if (oldArray[i] == cellsAtRowHeaderIntersect[n]) {
cellsAtRowHeaderIntersect[n] = null; // to avoid duplicates
originalPositions[n] = i;
rowShifts[i] = n - i;
break;
}
}
}
while (table.firstChild) {
table.removeChild(table.firstChild);
}
table.appendChild(firstTableRow);
for (var i = 0; i < rows.length; ++i) {
const row = rows[originalPositions[i]];
table.appendChild(row);
var posChange = i - originalPositions[i];
var rowShiftAmount = -posChange * row.offsetHeight;
for (var n = 0; n < 3; n++) {
if (animate) {
animatePosChange(rowShiftAmount, row.children[n].children[0]);
}
}
}
}
function animatePosChange(yChange, element) {
var id = setInterval(animate, 16)
var frameCount = Math.round(ROW_ANIMATION_DURATION / 16.0);
var framesComplete = 0;
var currentTop = Math.round(yChange).toString() + "px";
element.style.top = currentTop;
function animate() {
var offset;
if (framesComplete >= frameCount) {
clearInterval(id);
offset = 0;
} else {
var percentDone = framesComplete / frameCount;
var changePercentage;
if (percentDone >= 0.5) {
changePercentage = Math.pow(percentDone - 0.5, ANIMATION_ACCELERATION_EXPONENT) / ANIMATION_EQUATION_DENOMINATOR + 0.5;
} else {
changePercentage = -Math.pow(0.5 - percentDone, ANIMATION_ACCELERATION_EXPONENT) / ANIMATION_EQUATION_DENOMINATOR + 0.5;
}
offset = yChange * (1 - changePercentage);
framesComplete++;
}
currentTop = Math.round(offset).toString() + "px";
element.style.top = currentTop;
}
}
function positionOfString(string, array) {
for (var i = 0; i < array.length; ++i) {
if (array[i] == string) {
return i;
}
}
return -1;
}
function cellComparator(a, b) {
const intVal1 = parseInt(a);
const intVal2 = parseInt(b);
if (!isNaN(intVal1) && isNaN(intVal2)) {
return -1;
} else if (isNaN(intVal1) && !isNaN(intVal2)) {
return 1;
} else if (!isNaN(intVal1)) {
return b - a;
}
return a.localeCompare(b);
}
function reverseCellComparator(a, b) {
return cellComparator(b, a);
}
function setupTableSorting() {
var headers = document.getElementsByTagName("th");
for (var i = 0; i < headers.length; ++i) {
const headerNum = i;
headers[i].addEventListener("click", function() {invertHeaderSorting(headerNum, true)})
}
}
setupTableSorting();
invertHeaderSorting(0, false); | c23195d886fc8bc05e09f17e41c4561c71733bad | [
"JavaScript"
] | 1 | JavaScript | JacobBrunsting/personal-website | 4d5beb1b63462d7a4758b03437b2c2980293fa0d | 891762ae1a2f7b93c51623bc971c01f57afbdd2f | |
refs/heads/master | <repo_name>xuewengeophysics/xwStudyNLP<file_sep>/text_classification/Transformer/model/Transformer.py
import tensorflow as tf
import math
import numpy as np
from tensorflow.python.ops import array_ops
class Muti_head_Attention(object):
def __init__(self, max_length, num_classes, vocab_size, embedding_size, hidden_num, num_blocks, num_heads):
# placeholders for input output and dropout
self.input_x = tf.placeholder(tf.int32, shape=[None, max_length], name='input_x')
self.input_y = tf.placeholder(tf.int32, shape=[None, num_classes], name='input_y')
self.drop_out_prob = tf.placeholder(tf.float32, name='drop_out_keep')
# embedding layer
with tf.device('/gpu:0'), tf.name_scope("embedding"):
self.embedding = tf.Variable(tf.truncated_normal([vocab_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)),
name="embedding", trainable=True)
self.embedding_chars = tf.nn.embedding_lookup(self.embedding, self.input_x)
# Positional Encoding
N = array_ops.shape(self.embedding_chars)[0]
T = max_length
self.embedding_chars += self.positional_encoding(N, T,
num_units=hidden_num,
zero_pad=False,
scale=False,
scope="enc_pe")
# Dropout
self.enc = tf.layers.dropout(self.embedding_chars, rate=self.drop_out_prob)
# Blocks
for i in range(num_blocks):
with tf.variable_scope("num_blocks_{}".format(i)):
# Multihead Attention
self.enc = self.multihead_attention(queries=self.enc,
keys=self.enc,
num_units=hidden_num,
num_heads=num_heads,
dropout_rate=self.drop_out_prob,
causality=False)
# Feed Forward
self.enc = self.feedforward(self.enc, num_units=[4 * hidden_num, hidden_num])
# 将特征进行拼接
self.enc = tf.reshape(self.enc, [-1, max_length * hidden_num, 1])
self.enc = tf.squeeze(self.enc, -1)
fc_w = tf.Variable(tf.truncated_normal([max_length * hidden_num, num_classes], stddev=0.1), name='fc_w')
fc_b = tf.Variable(tf.zeros([num_classes]), name='fc_b')
# 定义损失函数
l2_loss = 0
l2_loss += tf.nn.l2_loss(fc_w)
l2_loss += tf.nn.l2_loss(fc_b)
self.logits = tf.matmul(self.enc, fc_w) + fc_b
self.score = tf.nn.softmax(self.logits, name='score')
self.predictions = tf.argmax(self.score, 1, name="predictions")
self.cost = tf.losses.softmax_cross_entropy(self.input_y, self.logits)
# l2_reg_lambda = 0.01
# self.cost = self.cost + l2_reg_lambda * l2_loss
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars), 5)
optimizer = tf.train.AdamOptimizer(0.001)
self.train_op = optimizer.apply_gradients(zip(grads, tvars))
self.accuracy = tf.reduce_mean(
tf.cast(tf.equal(tf.argmax(self.input_y, axis=1), tf.argmax(self.score, axis=1)), tf.float32))
def positional_encoding(self, N, T,
num_units,
zero_pad=True,
scale=True,
scope="positional_encoding",
reuse=None):
'''Sinusoidal Positional_Encoding.
Args:
inputs: A 2d Tensor with shape of (N, T).
num_units: Output dimensionality
zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero
scale: Boolean. If True, the output will be multiplied by sqrt num_units(check details from paper)
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A 'Tensor' with one more rank than inputs's, with the dimensionality should be 'num_units'
'''
with tf.variable_scope(scope, reuse=reuse):
position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1]) # tf.expand_dims(tf.range(T), 0) --> [1, T]
# tf.tile([1, T], [N, 1]) --> [N, T]
# N为batch_size,T为最长句子长度
# First part of the PE function: sin and cos argument
position_enc = np.array([
[pos / np.power(10000, 2. * i / num_units) for i in range(num_units)]
for pos in range(T)]) # dim [T, num_units], num_units=hidden_num
# Second part, apply the cosine to even columns and sin to odds.
position_enc[:, 0::2] = np.sin(position_enc[:, 0::2]) # dim 2i
position_enc[:, 1::2] = np.cos(position_enc[:, 1::2]) # dim 2i+1
# Convert to a tensor
lookup_table = tf.convert_to_tensor(position_enc)
if zero_pad:
lookup_table = tf.concat((tf.zeros(shape=[1, num_units]),
lookup_table[1:, :]), 0)
outputs = tf.nn.embedding_lookup(lookup_table, position_ind)
if scale:
outputs = outputs * num_units ** 0.5
outputs = tf.cast(outputs, dtype=tf.float32)
return outputs
def multihead_attention(self, queries,
keys,
num_units=None,
num_heads=8,
dropout_rate=0,
causality=False,
scope="multihead_attention",
reuse=None):
'''Applies multihead attention.
Args:
queries: A 3d tensor with shape of [N, T_q, C_q].
keys: A 3d tensor with shape of [N, T_k, C_k].
num_units: A scalar. Attention size.
dropout_rate: A floating point number.
is_training: Boolean. Controller of mechanism for dropout.
causality: Boolean. If true, units that reference the future are masked.
num_heads: An int. Number of heads.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns
A 3d tensor with shape of (N, T_q, C)
'''
with tf.variable_scope(scope, reuse=reuse):
# Set the fall back option for num_units
if num_units is None:
num_units = queries.get_shape().as_list[-1]
# Linear projections
Q = tf.layers.dense(queries, num_units, activation=tf.nn.relu) # (N, T_q, C)
K = tf.layers.dense(keys, num_units, activation=tf.nn.relu) # (N, T_k, C)
V = tf.layers.dense(keys, num_units, activation=tf.nn.relu) # (N, T_k, C)
# Split and concat
Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, C/h)
K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, C/h)
V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, C/h)
# Multiplication
outputs = tf.matmul(Q_, tf.transpose(K_, [0, 2, 1])) # (h*N, T_q, T_k)
# Scale
outputs = outputs / (K_.get_shape().as_list()[-1] ** 0.5)
# Key Masking
key_masks = tf.sign(tf.abs(tf.reduce_sum(keys, axis=-1))) # (N, T_k)
key_masks = tf.tile(key_masks, [num_heads, 1]) # (h*N, T_k)
key_masks = tf.tile(tf.expand_dims(key_masks, 1), [1, tf.shape(queries)[1], 1]) # (h*N, T_q, T_k)
paddings = tf.ones_like(outputs) * (-2 ** 32 + 1)
outputs = tf.where(tf.equal(key_masks, 0), paddings, outputs) # (h*N, T_q, T_k)
# Causality = Future blinding
if causality:
diag_vals = tf.ones_like(outputs[0, :, :]) # (T_q, T_k)
tril = tf.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense() # (T_q, T_k)
masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(outputs)[0], 1, 1]) # (h*N, T_q, T_k)
paddings = tf.ones_like(masks) * (-2 ** 32 + 1)
outputs = tf.where(tf.equal(masks, 0), paddings, outputs) # (h*N, T_q, T_k)
# Activation
outputs = tf.nn.softmax(outputs) # (h*N, T_q, T_k)
# Query Masking
query_masks = tf.sign(tf.abs(tf.reduce_sum(queries, axis=-1))) # (N, T_q)
query_masks = tf.tile(query_masks, [num_heads, 1]) # (h*N, T_q)
query_masks = tf.tile(tf.expand_dims(query_masks, -1), [1, 1, tf.shape(keys)[1]]) # (h*N, T_q, T_k)
outputs *= query_masks # broadcasting. (N, T_q, C)
# Dropouts
outputs = tf.layers.dropout(outputs, rate=dropout_rate)
# Weighted sum
outputs = tf.matmul(outputs, V_) # ( h*N, T_q, C/h)
# Restore shape
outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2) # (N, T_q, C)
# Residual connection
outputs += queries
# Normalize
outputs = self.normalize(outputs) # (N, T_q, C)
return outputs
def feedforward(self, inputs,
num_units=[2048, 512],
scope="multihead_attention",
reuse=None):
'''Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the same shape and dtype as inputs
'''
with tf.variable_scope(scope, reuse=reuse):
# Inner layer
params = {"inputs": inputs, "filters": num_units[0], "kernel_size": 1,
"activation": tf.nn.relu, "use_bias": True}
outputs = tf.layers.conv1d(**params)
# Readout layer
params = {"inputs": outputs, "filters": num_units[1], "kernel_size": 1,
"activation": None, "use_bias": True}
outputs = tf.layers.conv1d(**params)
# Residual connection
outputs += inputs
# Normalize
outputs = self.normalize(outputs)
return outputs
def normalize(self, inputs,
epsilon=1e-8,
scope="ln",
reuse=None):
'''Applies layer normalization.
Args:
inputs: A tensor with 2 or more dimensions, where the first dimension has
`batch_size`.
epsilon: A floating number. A very small number for preventing ZeroDivision Error.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A tensor with the same shape and data dtype as `inputs`.
'''
with tf.variable_scope(scope, reuse=reuse):
inputs_shape = inputs.get_shape()
params_shape = inputs_shape[-1:]
mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)
beta = tf.Variable(tf.zeros(params_shape))
gamma = tf.Variable(tf.ones(params_shape))
normalized = (inputs - mean) / ((variance + epsilon) ** (.5))
outputs = gamma * normalized + beta
return outputs
<file_sep>/XLNet/README.md
# XLNet: Generalized Autoregressive Pretraining for Language Understanding
参考资料
==
1 [论文BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)<br>
2 [代码BERT: zihangdai/xlnet](https://github.com/zihangdai/xlnet)<br>
<file_sep>/text_classification/HierarchicalAttentionNetwork/HanModel.py
# -*- coding: utf-8 -*-
"""
HierarchicalAttention:
1.Word Encoder
2.Word Attention
3.Sentence Encoder
4.Sentence Attention
5.linear classifier
"""
import tensorflow as tf
import numpy as np
import math
class HierarchicalAttention(object):
def __init__(self, config):
self.config = config
# placeholders for input output and dropout
# input_x的维度是[batch_size, sequence_length]
# num_sentences在原文中用 L 表示,num_words在原文中用 T 表示,num_words * num_sentences = sequence_length
# input_x的维度是[batch_size, num_classes]
self.input_x = tf.placeholder(tf.int32, shape=[None, self.config.sequence_length], name='input_x')
self.input_y = tf.placeholder(tf.int32, shape=[None, self.config.num_classes], name='input_y')
self.dropout_keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob')
self.global_step = tf.Variable(0, trainable=False, name='global_step')
# word embedding
with tf.name_scope("embedding"):
# 将输入的序列进行拆分,拆分成num_sentences个句子
# 得到了num_sentences个维度为[None, num_words]的张量
input_x = tf.split(self.input_x, self.config.num_sentences, axis=1) # 在某个维度上split
# 矩阵拼接,得到的张量维度为[None, self.num_sentences, num_words]
input_x = tf.stack(input_x, axis=1)
self.embedding = tf.get_variable("embeddings", shape=[self.config.vocab_size, self.config.embedding_size],
initializer=tf.constant_initializer(self.config.pre_training),
trainable=True) # 是否使用预训练词向量,静态(False)或动态(默认True)
# 张量维度为[None, num_sentences, num_words, embedding_size]
embedding_vectors = tf.nn.embedding_lookup(self.embedding, input_x)
# 输入到word encoder层的张量的维度为[batch_size*num_sentences, num_words, embedding_size]
self.embedding_inputs = tf.reshape(embedding_vectors, shape=[-1, self.config.num_words, self.config.embedding_size])
# word encoder
with tf.name_scope("word_encoder"):
# 给定文本词向量x(it),得到正向隐藏状态h(it)、反向隐藏状态h(it)
# 输出的隐藏状态张量的维度为[batch_size*num_sentences, num_words, hidden_size]
hidden_state_fw, hidden_state_bw = self.build_bidirectional_rnn(self.embedding_inputs, "word_encoder")
# 拼接得到h(it) = [正向h(it), 反向h(it)],维度为[batch_size*num_sentences, num_words, hidden_size*2]
word_hidden_state = tf.concat((hidden_state_fw, hidden_state_bw), 2)
# word attention
with tf.name_scope("word_attention"):
# 得到sentence_vector s(i)=sum(alpha(it)*h(it))
# 张量维度为[batch_size*num_sentences, hidden_size*2]
sentence_vector = self.build_attention(word_hidden_state, "word_attention")
# sentence encoder
with tf.name_scope("sentence_encoder"):
# 句子级输入的是句子,reshape得到维度为[batch_size, num_sentences, hidden_size*2]的张量
sentence_vector = tf.reshape(sentence_vector, shape=[-1, self.config.num_sentences, self.config.hidden_size * 2])
# 给定句子级向量s(i),得到正向隐藏状态h(i)、反向隐藏状态h(i)
# 输出的隐藏状态张量的维度为[batch_size, num_sentences, hidden_size]
hidden_state_fw, hidden_state_bw = self.build_bidirectional_rnn(sentence_vector, "sentence_encoder")
# 拼接得到h(i) = [正向h(i), 反向h(i)],维度为[batch_size, num_sentences, hidden_size*2]
sentence_hidden_state = tf.concat((hidden_state_fw, hidden_state_bw), 2)
# sentence attention
with tf.name_scope("sentence_attention"):
# 得到document_vector v=sum(alpha(i)*h(i))
# 张量维度为[batch_size, hidden_size * 2]
document_vector = self.build_attention(sentence_hidden_state, "sentence_attention")
# dropout
with tf.name_scope("dropout"):
h_drop = tf.nn.dropout(document_vector, self.dropout_keep_prob)
# classifier
with tf.name_scope("output"):
# 添加一个全连接层
self.logits = tf.layers.dense(h_drop, self.config.num_classes, name='fc2')
# 预测类别
self.predict = tf.argmax(tf.nn.softmax(self.logits), 1, name="prediction")
# loss
with tf.name_scope('loss'):
losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y)
self.loss = tf.reduce_mean(losses)
# optimizer
with tf.name_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(self.config.learning_rate)
gradients, variables = zip(*optimizer.compute_gradients(self.loss)) # 计算变量梯度,得到梯度值、变量
gradients, _ = tf.clip_by_global_norm(gradients, self.config.gradient_clip)
self.optimizer = optimizer.apply_gradients(zip(gradients, variables), global_step=self.global_step)
# global_step 自动+1
# accuracy
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(self.predict, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
def rnn_cell(self):
"""获取rnn的cell,可选RNN、LSTM、GRU"""
if self.config.rnn_type == "Vanilla":
return tf.nn.rnn_cell.BasicRNNCell(self.config.hidden_size)
elif self.config.rnn_type == "LSTM":
return tf.nn.rnn_cell.BasicLSTMCell(self.config.hidden_size)
elif self.config.rnn_type == "GRU":
return tf.nn.rnn_cell.GRUCell(self.config.hidden_size)
else:
raise Exception("rnn_type must be Vanilla、LSTM or GRU!")
def build_bidirectional_rnn(self, inputs, name):
with tf.variable_scope(name):
fw_cell = self.rnn_cell()
fw_cell = tf.nn.rnn_cell.DropoutWrapper(fw_cell, output_keep_prob=self.config.dropout_keep_prob)
bw_cell = self.rnn_cell()
bw_cell = tf.nn.rnn_cell.DropoutWrapper(bw_cell, output_keep_prob=self.config.dropout_keep_prob)
(output_fw, output_bw), states = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell,
cell_bw=bw_cell,
inputs=inputs,
dtype=tf.float32)
return output_fw, output_bw
def build_attention(self, inputs, name):
with tf.variable_scope(name):
# inputs词级h(it)的维度为[batch_size*num_sentences, num_words, hidden_size*2]
# inputs句子级h(i)的维度为[batch_size, num_sentences, hidden_size*2]
# 采用general形式计算权重,采用单层神经网络来给出attention中的score得分
hidden_vec = tf.layers.dense(inputs, self.config.hidden_size * 2, activation=tf.nn.tanh, name='u_hidden')
u_key = tf.Variable(tf.truncated_normal([self.config.hidden_size * 2]), name='u_key')
# alpha就是attention中的score得分
alpha = tf.nn.softmax(tf.reduce_sum(tf.multiply(hidden_vec, u_key), axis=2, keep_dims=True), dim=1)
# 对隐藏状态进行加权
attention_output = tf.reduce_sum(tf.multiply(inputs, alpha), axis=1)
return attention_output
<file_sep>/text_classification/TextCNN/model/Textcnn.py
#encoding:utf-8
import tensorflow as tf
class Textcnn(object):
def __init__(self, config):
config = config
# placeholders for input output and dropout
self.input_x = tf.placeholder(tf.int32, shape=[None, config.seq_length], name='input_x')
self.input_y = tf.placeholder(tf.float32, shape=[None, config.num_classes], name='input_y')
self.dropout_keep_prob = tf.placeholder(tf.float32, name='dropout')
self.global_step = tf.Variable(0, trainable=False, name='global_step')
# global_step 代表全局步数,比如在多少步该进行什么操作,现在神经网络训练到多少轮等等,类似于一个钟表。
l2_loss = tf.constant(0.0)
# embedding layer
with tf.device('/gpu:0'):
self.embedding = tf.get_variable("embeddings", shape=[config.vocab_size, config.embedding_size],
initializer=tf.constant_initializer(config.pre_training),
trainable=False) # 是否使用预训练词向量,静态(False)或动态(默认True)
embedding_input = tf.nn.embedding_lookup(self.embedding, self.input_x)
# conv2d操作接收一个4维的张量,维度分别代表batch, width, height 和 channel,这里的embedding不包含channel维度
# 因此要手动添加,得到形状为[None, sequence_length, embedding_size, 1]的embedding层。
self.embedding_expand = tf.expand_dims(embedding_input, -1)
# 添加卷积层、池化层
pooled_outputs = []
for i, filter_size in enumerate(config.filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# CNN layer
# conv2d的卷积核形状[filter_height, filter_width, in_channels, out_channels]
filter_shape = [filter_size, config.embedding_size, 1, config.num_filters] # 卷积核维度
# 设定卷积核的参数 W b
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name= 'W') # 图变量初始化,截断正态分布
b = tf.Variable(tf.constant(0.1, shape=[config.num_filters]), name='b') # 生成常量
conv = tf.nn.conv2d(self.embedding_expand, W, strides=[1, 1, 1, 1], padding='VALID', name='conv')
# nonlinearity activate funtion
h = tf.nn.relu(tf.nn.bias_add(conv, b), name='relu')
# global max pooling layer
# 每个filter的max-pool输出形状:[batch_size, 1, 1, num_filters]
pooled = tf.nn.max_pool(h,
ksize=[1, config.seq_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name='pool')
pooled_outputs.append(pooled)
# combine all the pooled features
# 有三种卷积核尺寸, 每个卷积核有num_filters个channel,因此一共有 num_filters * len(filter_sizes)个
num_filter_total = config.num_filters * len(config.filter_sizes)
self.h_pool = tf.concat(pooled_outputs, 3) # 在第3个维度进行张量拼接
self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filter_total])
# add dropout
with tf.name_scope('dropout'):
self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
# final (unnormalized) scores and predictions
with tf.name_scope('output'):
W_fc = tf.get_variable("W_fc", shape=[num_filter_total, config.num_classes],
initializer=tf.contrib.layers.xavier_initializer())
b_fc = tf.Variable(tf.constant(0.1, shape=[config.num_classes]), name='b_fc')
self.logits = tf.matmul(self.h_drop, W_fc) + b_fc
self.pro = tf.nn.softmax(self.logits)
self.predicitions = tf.argmax(self.pro, 1, name='predictions')
# calculate mean cross-entropy loss
with tf.name_scope('loss'):
# 损失函数,交叉熵
loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y)
self.loss = tf.reduce_mean(loss) # 对交叉熵取均值非常有必要
l2_loss += tf.nn.l2_loss(W_fc)
l2_loss += tf.nn.l2_loss(b_fc)
self.loss = tf.reduce_mean(loss) + config.l2_reg_lambda * l2_loss
# 优化器
with tf.name_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(config.learning_rate)
gradients, variables = zip(*optimizer.compute_gradients(self.loss)) # 计算变量梯度,得到梯度值,变量
gradients, _ = tf.clip_by_global_norm(gradients, config.clip)
#对g进行l2正则化计算,比较其与clip的值,如果l2后的值更大,让梯度*(clip/l2_g),得到新梯度
self.optimizer = optimizer.apply_gradients(zip(gradients, variables), global_step=self.global_step)
# accuracy
with tf.name_scope('accuracy'):
correct_predictions = tf.equal(tf.argmax(self.input_y, 1), self.predicitions)
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, 'float32'), name='accuracy')
<file_sep>/word2vec/gensim_word2vec.py
"""
主要参数介绍如下:
01) sentences:语料,可以是一个列表,或者从文件中遍历读出(word2vec.LineSentence(filename))。
02) size:词向量的维度,默认值是100。这个维度的取值一般与我们的语料的大小相关;
如果是不大的语料,比如小于100M的文本语料,则使用默认值一般就可以了;如果是超大的语料,建议增大维度。
03) window:即词向量上下文最大距离,window越大,则和某一词较远的词也会产生上下文关系。
默认值为5,在实际使用中,可以根据实际的需求来动态调整这个window的大小。
如果是小语料则这个值可以设的更小。对于一般的语料这个值推荐在[5, 10]之间。
04) sg:如果是0则是CBOW模型;是1则是Skip-Gram模型;默认是0即CBOW模型。
05) hs:即word2vec的两个解法。如果是0,则是Negative Sampling;
是1并且负采样个数negative大于0,则是Hierarchical Softmax。默认是0即Negative Sampling。
06) negative:即使用Negative Sampling时负采样的个数,默认是5。推荐在[3, 10]之间。
07) cbow_mean:仅用于CBOW在做投影的时候,为0,则算法中的xw为上下文的词向量之和,为1则为上下文的词向量的平均值。默认值也是1。
08) min_count:需要计算词向量的最小词频。这个值可以去掉一些很生僻的低频词,默认是5。如果是小语料,可以调低这个值。
09) iter:随机梯度下降法中迭代的最大次数,默认是5。对于大语料,可以增大这个值。
10) alpha:在随机梯度下降法中迭代的初始步长,默认是0.025。
11) min_alpha: 由于算法支持在迭代的过程中逐渐减小步长,min_alpha给出了最小的迭代步。
"""
gensim.models.word2vec.Word2Vec(
sentences=None,
corpus_file=None,
size=100,
alpha=0.025,
window=5,
min_count=5,
max_vocab_size=None,
sample=0.001,
seed=1,
workers=3,
min_alpha=0.0001,
sg=0,
hs=0,
negative=5,
ns_exponent=0.75,
cbow_mean=1,
hashfxn=<built-in function hash>,
iter=5,
null_word=0,
trim_rule=None,
sorted_vocab=1,
batch_words=10000,
compute_loss=False,
callbacks=(),
max_final_vocab=None)
<file_sep>/named_entity_recognition/README.md
# Named Entity Recognition
## 参考资料
1 [源码Determined22/zh-NER-TF](https://github.com/Determined22/zh-NER-TF) [对应博客BiLSTM-CRF模型做基于字的中文命名实体识别](https://www.cnblogs.com/Determined22/p/7238342.html)<br>
2 [源码jiesutd/LatticeLSTM](https://github.com/jiesutd/LatticeLSTM)<br>
3 [源码guillaumegenthial/tf_ner](https://github.com/guillaumegenthial/tf_ner)<br>
4 [博客Guillaume Genthial blog/Sequence Tagging with Tensorflow](https://guillaumegenthial.github.io/sequence-tagging-with-tensorflow.html) [对应源码guillaumegenthial/sequence_tagging](https://github.com/guillaumegenthial/sequence_tagging)<br>
5 [源码liuhuanyong/MedicalNamedEntityRecognition](https://github.com/liuhuanyong/MedicalNamedEntityRecognition)<br>
6 [源码zyh961117/CCKS-2017-task2](https://github.com/zyh961117/CCKS-2017-task2)<br>
<file_sep>/text_classification/TextCNN/README.md
# TextCNN
本文是参考gaussic大牛的“text-classification-cnn-rnn”后,基于同样的数据集,嵌入词级别所做的CNN文本分类实验结果,gaussic大牛是基于字符级的;<br><br>
进行了第二版的更新:1.加入不同的卷积核;2.加入正则化;3.词仅为中文或英文,删掉文本中数字、符号等类型的词;4.删除长度为1的词;<br>
<br>
训练结果较第一版有所提升,验证集准确率从96.5%达到97.8%,测试准备率从96.7%达到97.2%。<br>
<br>
本实验的主要目是为了探究基于Word2vec训练的词向量嵌入CNN后,对模型的影响,实验结果得到的模型在验证集达到97.8%的效果,gaussic大牛为94.12%;<br><br>
更多详细可以阅读gaussic大牛的博客:[text-classification-cnn-rnn](https://github.com/gaussic/text-classification-cnn-rnn)<br><br>
使用TextCNN进行中文文本分类
## 数据预处理流程

## TextCNN模型网络结构

## 参考资料
1 [文献Convolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1408.5882)<br>
2 [文献Character-level Convolutional Networks for Text Classification](https://arxiv.org/abs/1509.01626)<br>
3 [大牛dennybritz的博客Implementing a CNN for Text Classification in TensorFlow](http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/)<br>
4 [源码dennybritz/cnn-text-classification-tf](https://github.com/dennybritz/cnn-text-classification-tf)<br>
5 [源码gaussic/text-classification-cnn-rnn](https://github.com/gaussic/text-classification-cnn-rnn)<br>
6 [源码cjymz886/text-cnn](https://github.com/cjymz886/text-cnn)<br>
7 [源码NLPxiaoxu/Easy_TextCnn_Rnn](https://github.com/NLPxiaoxu/Easy_TextCnn_Rnn)<br>
8 [源码YCG09/tf-text-classification](https://github.com/YCG09/tf-text-classification)<br>
9 [源码pengming617/text_classification](https://github.com/pengming617/text_classification)<br>
<file_sep>/Transformer/README.md
# transformer
## 参考资料
论文1:[Attention Is All You Need](https://arxiv.org/pdf/1706.03762.pdf)<br>
论文2:[Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860)<br>
源码1:[kimiyoung/transformer-xl](https://github.com/kimiyoung/transformer-xl)<br>
博客1:[<NAME>/The Illustrated Transformer](https://jalammar.github.io/illustrated-transformer)<br>
博客2:[<NAME>/Dissecting BERT Part 1: The Encoder](https://medium.com/dissecting-bert/dissecting-bert-part-1-d3c3d495cdb3)<br>
博客3:[harvardnlp/The Annotated Transformer](http://nlp.seas.harvard.edu/2018/04/03/attention.html)<br>
博客4:[张俊林/放弃幻想,全面拥抱Transformer:自然语言处理三大特征抽取器(CNN/RNN/TF)比较](https://zhuanlan.zhihu.com/p/54743941)
博客5:[机器翻译模型Transformer代码详细解析](https://blog.csdn.net/mijiaoxiaosan/article/details/74909076)
博客5对应源码:[Kyubyong/transformer](https://github.com/Kyubyong/transformer)
博客6:[文本分类实战之Transformer模型](https://www.cnblogs.com/jiangxinyang/p/10210813.html)
博客6对应源码:[jiangxinyang227/textClassifier/Transformer](https://github.com/jiangxinyang227/textClassifier/tree/master/Transformer)<br>
源码1:https://github.com/brightmart/text_classification/tree/master/a07_Transformer<br>
源码2:https://github.com/pengming617/text_classification/tree/master/model/transformer<br>
源码3:https://github.com/SamLynnEvans/Transformer
对应博客[<NAME>/How to code The Transformer in Pytorch](https://towardsdatascience.com/how-to-code-the-transformer-in-pytorch-24db27c8f9ec)
中文翻译[大数据文摘/百闻不如一码!手把手教你用Python搭一个Transformer](https://mp.weixin.qq.com/s/zLptc5bvo3rY_Jvu-rA6Pg)<br>
<file_sep>/README.md
# Natural Language Processing
NLP任务总结
=

NLP常用算法
=

## 参考资料
1 [大牛<NAME>的博客](https://jalammar.github.io/)<br>
2 [大牛<NAME>博客](http://ruder.io/)<br>
## 中文NLP
1 [中文自然语言处理相关资料crownpku/Awesome-Chinese-NLP](https://github.com/crownpku/Awesome-Chinese-NLP)<br>
2 [大规模中文自然语言处理语料brightmart/nlp_chinese_corpus](https://github.com/brightmart/nlp_chinese_corpus)<br>
<file_sep>/text_classification/TextRCNN/TextRCnnModel.py
"""
参考资料:
[1] https://github.com/roomylee/rcnn-text-classification
"""
import tensorflow as tf
class TextRCnn(object):
"""
Recurrent Convolutional neural network for text classification
1. embeddding layer,
2. Bi-LSTM layer,
3. max pooling,
4. FC layer
5. softmax
"""
def __init__(self, config):
self.config = config
# placeholders for input output and dropout
# input_x的维度是[batch_size, sequence_length]
# input_y的维度是[batch_size, num_classes]
self.input_x = tf.placeholder(tf.int32, shape=[None, self.config.sequence_length], name='input_x')
self.input_y = tf.placeholder(tf.int32, shape=[None, self.config.num_classes], name='input_y')
self.dropout_keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob')
self.global_step = tf.Variable(0, trainable=False, name='global_step')
l2_loss = tf.constant(0.0)
text_length = self._length(self.input_x)
# 1.get emebedding of words in the sentence
with tf.name_scope("embedding"):
# self.embedding = tf.Variable(tf.random_uniform([self.config.vocab_size, self.config.word_embedding_size], -1.0, 1.0),
# name="embedding", trainable=True)
# self.embedding = tf.Variable(tf.truncated_normal([self.config.vocab_size, self.config.word_embedding_size],
# stddev=1.0 / math.sqrt(self.config.word_embedding_size)),
# name="embedding", trainable=True)
self.embedding = tf.get_variable("embeddings", shape=[self.config.vocab_size, self.config.word_embedding_size],
initializer=tf.constant_initializer(self.config.pre_training),
trainable=True) # 是否使用预训练词向量,静态(False)或动态(默认True)
# 张量维度为[None, sequence_length, word_embedding_size]
self.embedding_words = tf.nn.embedding_lookup(self.embedding, self.input_x)
# 2. Bidirectional(Left&Right) Recurrent Structure
# 输出张量 x_i = [c_l(w_i); e(w_i); c_r(w_i)], shape:[None, sequence_length, embedding_size*3]
with tf.name_scope("bi-rnn"):
fw_cell = self._get_cell(self.config.context_embedding_size, self.config.rnn_type)
fw_cell = tf.nn.rnn_cell.DropoutWrapper(fw_cell, output_keep_prob=self.dropout_keep_prob)
bw_cell = self._get_cell(self.config.context_embedding_size, self.config.rnn_type)
bw_cell = tf.nn.rnn_cell.DropoutWrapper(bw_cell, output_keep_prob=self.dropout_keep_prob)
(self.output_fw, self.output_bw), states = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell,
cell_bw=bw_cell,
inputs=self.embedding_words,
sequence_length=text_length,
dtype=tf.float32)
with tf.name_scope("context"):
shape = [tf.shape(self.output_fw)[0], 1, tf.shape(self.output_fw)[2]]
self.context_left = tf.concat([tf.zeros(shape), self.output_fw[:, :-1]], axis=1, name="context_left")
self.context_right = tf.concat([self.output_bw[:, 1:], tf.zeros(shape)], axis=1, name="context_right")
with tf.name_scope("word-representation"):
self.x = tf.concat([self.context_left, self.embedding_words, self.context_right], axis=2, name="x")
embedding_size = 2*self.config.context_embedding_size + self.config.word_embedding_size
# 2.1 apply nonlinearity
with tf.name_scope("text-representation"):
W2 = tf.Variable(tf.random_uniform([embedding_size, self.config.hidden_size], -1.0, 1.0), name="W2")
b2 = tf.Variable(tf.constant(0.1, shape=[self.config.hidden_size]), name="b2")
self.y2 = tf.tanh(tf.einsum('aij,jk->aik', self.x, W2) + b2)
with tf.name_scope("text-representation"):
W2 = tf.Variable(tf.random_uniform([embedding_size, self.config.hidden_size], -1.0, 1.0), name="W2")
b2 = tf.Variable(tf.constant(0.1, shape=[self.config.hidden_size]), name="b2")
self.y2 = tf.tanh(tf.einsum('aij,jk->aik', self.x, W2) + b2)
# 3. max-pooling
with tf.name_scope("max-pooling"):
self.y3 = tf.reduce_max(self.y2, axis=1) # shape:[None, hidden_size]
# 4. classifier
with tf.name_scope("output"):
# inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of the input network.
W4 = tf.get_variable("W4", shape=[self.config.hidden_size, self.config.num_classes],
initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.constant(0.1, shape=[self.config.num_classes]), name="b4")
l2_loss += tf.nn.l2_loss(W4)
l2_loss += tf.nn.l2_loss(b4)
self.logits = tf.nn.xw_plus_b(self.y3, W4, b4, name="logits")
self.prediction = tf.argmax(tf.nn.softmax(self.logits), 1, name='prediction')
# loss
with tf.name_scope('loss'):
losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + self.config.l2_reg_lambda * l2_loss
# optimizer
with tf.name_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(self.config.learning_rate)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))#计算变量梯度,得到梯度值、变量
gradients, _ = tf.clip_by_global_norm(gradients, self.config.gradient_clip)
#对g进行l2正则化计算,比较其与clip的值,如果l2后的值更大,让梯度*(clip/l2_g),得到新梯度
self.optimizer = optimizer.apply_gradients(zip(gradients, variables), global_step=self.global_step)
#global_step 自动+1
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(self.prediction, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
@staticmethod
def _get_cell(hidden_size, rnn_type):
if rnn_type == "Vanilla":
return tf.nn.rnn_cell.BasicRNNCell(hidden_size)
elif rnn_type == "LSTM":
return tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
elif rnn_type == "GRU":
return tf.nn.rnn_cell.GRUCell(hidden_size)
else:
print("ERROR: '" + rnn_type + "' is a wrong cell type !!!")
return None
# Length of the sequence data
@staticmethod
def _length(seq):
relevant = tf.sign(tf.abs(seq))
length = tf.reduce_sum(relevant, reduction_indices=1)
length = tf.cast(length, tf.int32)
return length
# Extract the output of last cell of each sequence
# Ex) The movie is good -> length = 4
# output = [ [1.314, -3.32, ..., 0.98]
# [0.287, -0.50, ..., 1.55]
# [2.194, -2.12, ..., 0.63]
# [1.938, -1.88, ..., 1.31]
# [ 0.0, 0.0, ..., 0.0]
# ...
# [ 0.0, 0.0, ..., 0.0] ]
# The output we need is 4th output of cell, so extract it.
@staticmethod
def last_relevant(seq, length):
batch_size = tf.shape(seq)[0]
max_length = int(seq.get_shape()[1])
input_size = int(seq.get_shape()[2])
index = tf.range(0, batch_size) * max_length + (length - 1)
flat = tf.reshape(seq, [-1, input_size])
return tf.gather(flat, index)
<file_sep>/0_Class/README.md
# NLP Class
<file_sep>/notes.md
# 笔记
## 1 模型分类(生成式与判别式)
.png)
<file_sep>/elmo/README.md
# Embedding from Language Model
参考资料
==
1 [论文Deep contextualized word representations](https://arxiv.org/abs/1802.05365)<br>
<file_sep>/sentiment_analysis/README.md
# Sentiment Analysis
## 参考资料
1 https://github.com/sebastianruder/NLP-progress/blob/master/english/sentiment_analysis.md<br><br>
2 https://github.com/songyouwei/ABSA-PyTorch<br><br>
3 https://github.com/HSLCY/ABSA-BERT-pair<br><br>
4 https://github.com/AlexYangLi/ABSA_Keras<br><br>
<file_sep>/text_classification/BiLstmAttention/BiLstmAttentionModel.py
"""
参考资料:
[1] https://github.com/SeoSangwoo/Attention-Based-BiLSTM-relation-extraction
"""
import tensorflow as tf
class BiLstmAttention(object):
"""
Attention-Based Bidirectional Long Short-Term Memory Networks for Relation Classification
1. Embeddding layer,
2. Bi-LSTM layer,
3. Attention layer,
4. FC layer
5. softmax
"""
def __init__(self, config):
self.config = config
# placeholders for input output and dropout
# input_x的维度是[batch_size, sequence_length]
# input_y的维度是[batch_size, num_classes]
self.input_x = tf.placeholder(tf.int32, shape=[None, self.config.sequence_length], name='input_x')
self.input_y = tf.placeholder(tf.int32, shape=[None, self.config.num_classes], name='input_y')
self.dropout_keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob')
self.global_step = tf.Variable(0, trainable=False, name='global_step')
# 定义l2损失
l2_loss = tf.constant(0.0)
text_length = self._length(self.input_x)
# 1.get embedding of words in the sentence
with tf.name_scope("embedding"):
# self.embedding = tf.Variable(tf.random_uniform([self.config.vocab_size, self.config.word_embedding_size], -1.0, 1.0),
# name="embedding", trainable=True)
# self.embedding = tf.Variable(tf.truncated_normal([self.config.vocab_size, self.config.word_embedding_size],
# stddev=1.0 / math.sqrt(self.config.word_embedding_size)),
# name="embedding", trainable=True)
self.embedding = tf.get_variable("embeddings", shape=[self.config.vocab_size, self.config.word_embedding_size],
initializer=tf.constant_initializer(self.config.pre_training),
trainable=True) # 是否使用预训练词向量,静态(False)或动态(默认True)
# 张量维度为[None, sequence_length, word_embedding_size]
self.embedding_words = tf.nn.embedding_lookup(self.embedding, self.input_x)
# 2. BiLSTM layer to get high level features
# 输出张量 x_i = [c_l(w_i); e(w_i); c_r(w_i)], shape:[None, sequence_length, embedding_size*3]
with tf.name_scope("bi-rnn"):
fw_cell = self._get_cell(self.config.context_embedding_size, self.config.rnn_type)
fw_cell = tf.nn.rnn_cell.DropoutWrapper(fw_cell, output_keep_prob=self.dropout_keep_prob)
bw_cell = self._get_cell(self.config.context_embedding_size, self.config.rnn_type)
bw_cell = tf.nn.rnn_cell.DropoutWrapper(bw_cell, output_keep_prob=self.dropout_keep_prob)
# 采用动态rnn,可以动态的输入序列的长度,若没有输入,则取序列的全长
# outputs是一个元组(output_fw, output_bw),其中两个元素的维度都是[batch_size, max_time, hidden_size]
# fw和bw的hidden_size一样
# states是最终的状态,二元组(state_fw, state_bw),state_fw=[batch_size, s],s是一个元组(h, c)
self.outputs, states = tf.nn.bidirectional_dynamic_rnn(cell_fw=fw_cell, cell_bw=bw_cell,
inputs=self.embedding_words,
sequence_length=text_length,
dtype=tf.float32)
# 对outputs中的fw和bw的结果拼接 [batch_size, time_step, hidden_size * 2], 传入到下一层Bi-LSTM中
self.rnn_outputs = tf.add(self.outputs[0], self.outputs[1])
# 3. Attention layer
# produce a weight vector,
# and merge word-level features from each time step into a sentence-level feature vector,
# by multiplying the weight vector
with tf.variable_scope('attention'):
self.attention, self.alphas = self._get_attention(self.rnn_outputs)
# Dropout
with tf.variable_scope('dropout'):
self.h_drop = tf.nn.dropout(self.attention, self.dropout_keep_prob)
# 4. classifier
with tf.variable_scope('output'):
# Fully connected layer
self.logits = tf.layers.dense(self.h_drop, self.config.num_classes,
kernel_initializer=tf.keras.initializers.glorot_normal())
self.prediction = tf.argmax(self.logits, 1, name="prediction")
# loss
with tf.name_scope('loss'):
losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + self.config.l2_reg_lambda * l2_loss
# optimizer
with tf.name_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(self.config.learning_rate)
gradients, variables = zip(*optimizer.compute_gradients(self.loss)) # 计算变量梯度,得到梯度值、变量
gradients, _ = tf.clip_by_global_norm(gradients, self.config.gradient_clip)
# 对g进行l2正则化计算,比较其与clip的值,如果l2后的值更大,让梯度*(clip/l2_g),得到新梯度
self.optimizer = optimizer.apply_gradients(zip(gradients, variables), global_step=self.global_step)
# global_step 自动+1
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(self.prediction, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
def _get_attention(self, inputs):
# Trainable parameters
hidden_size = inputs.shape[2].value # inputs的维度为[batch_size, time_step, hidden_size * 2]
# omega_T的维度为[hidden_size * 2]
omega_T = tf.get_variable("omega_T", [hidden_size], initializer=tf.keras.initializers.glorot_normal())
with tf.name_scope('M'):
# M的维度为[batch_size, time_step, hidden_size * 2]
M = tf.tanh(inputs)
# For each of the timestamps its vector of size A from `M` is reduced with `omega` vector
vu = tf.tensordot(M, omega_T, axes=1, name='vu') # [batch_size, time_step] shape
alphas = tf.nn.softmax(vu, name='alphas') # [batch_size, time_step] shape
# Output of (Bi-)RNN is reduced with attention vector; the result has [batch_size, hidden_size * 2] shape
output = tf.reduce_sum(inputs * tf.expand_dims(alphas, -1), 1)
# Final output with tanh
output = tf.tanh(output)
return output, alphas
@staticmethod
def _get_cell(hidden_size, rnn_type):
if rnn_type == "Vanilla":
return tf.nn.rnn_cell.BasicRNNCell(hidden_size)
elif rnn_type == "LSTM":
return tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
elif rnn_type == "GRU":
return tf.nn.rnn_cell.GRUCell(hidden_size)
else:
print("ERROR: '" + rnn_type + "' is a wrong cell type !!!")
return None
# Length of the sequence data
@staticmethod
def _length(seq):
relevant = tf.sign(tf.abs(seq))
length = tf.reduce_sum(relevant, reduction_indices=1)
length = tf.cast(length, tf.int32)
return length
<file_sep>/GPT/README.md
# Generative Pre-trained Transformer
参考资料
==
论文1 [GPT-Improving Language Understanding by Generative Pre-Training](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf)<br>
论文2 [Language Models are Unsupervised Multitask Learners](https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf)<br>
代码1 [openai/finetune-transformer-lm](https://github.com/openai/finetune-transformer-lm)<br>
代码2 [openai/gpt-2](https://github.com/openai/gpt-2)<br>
代码3 [ConnorJL/GPT2](https://github.com/ConnorJL/GPT2)<br>
<file_sep>/text_classification/TextCNN/config/Config.py
class TextcnnConfig(object):
"""Textcnn配置参数"""
# 文本参数
seq_length = 600 # max length of sentence
num_classes = 10 # number of labels
vocab_size = 8000 # number of vocabulary
# 模型参数
embedding_size = 100 # dimension of word embedding
num_filters = 128 # number of convolution kernel
kernel_size = [2, 3, 4] # size of convolution kernel
pre_trianing = None # use vector_char trained by word2vec
# 训练参数
batch_size = 8 # 每批训练大小
num_epochs = 5 # 总迭代轮次
dropout_keep_prob = 0.5 # dropout保留比例
learning_rate = 1e-3 # 学习率
lr_decay = 0.9 # learning rate decay
clip = 7.0 # gradient clipping threshold
print_per_batch = 100 # 每多少轮输出一次结果
save_per_batch = 10 # 每多少轮存入tensorboard
<file_sep>/text_classification/README.md
# Text Classification
0 参考资料
=
### 1、论文
1 [[<NAME> et al. 2019]Text Classification Algorithms: A Survey](https://arxiv.org/abs/1904.08067)<br>
### 2、代码
1 [徐亮brightmart/text_classification](https://github.com/brightmart/text_classification)<br>
2 [cjymz886/text-cnn](https://github.com/cjymz886/text-cnn)<br>
3 [文本分类实战--从TFIDF到深度学习CNN系列效果对比(附代码)](https://github.com/lc222/text_classification_AI100)<br>
4 [gaussic/CNN-RNN中文文本分类](https://github.com/gaussic/text-classification-cnn-rnn)<br>
5 [clayandgithub/基于cnn的中文文本分类算法](https://github.com/clayandgithub/zh_cnn_text_classify)<br>
6 [pengming617/text_classification](https://github.com/pengming617/text_classification)<br>
7 [roomylee/rcnn-text-classification](https://github.com/roomylee/rcnn-text-classification)<br>
8 [jiangxinyang227/textClassifier](https://github.com/jiangxinyang227/textClassifier)<br>
1 数据集
=
本实验使用THUCNews的一个子集进行训练与测试,数据集请自行到[THUCTC:一个高效的中文文本分类工具包](http://thuctc.thunlp.org/)下载,请遵循数据提供方的开源协议。<br>
文本类别涉及10个类别:categories = \['体育', '财经', '房产', '家居', '教育', '科技', '时尚', '时政', '游戏', '娱乐'],每个分类6500条数据;<br>
cnews.train.txt: 训练集(5000*10)<br>
cnews.val.txt: 验证集(500*10)<br>
cnews.test.txt: 测试集(1000*10)<br>
数据下载:训练数据以及训练好的词向量:<br>
链接: [https://pan.baidu.com/s/1DOgxlY42roBpOKAMKPPKWA](https://pan.baidu.com/s/1DOgxlY42roBpOKAMKPPKWA)<br>
密码: <PASSWORD><br><br>
2 预处理
=
本实验主要对训练文本进行分词处理,一来要分词训练词向量,二来输入模型的以词向量的形式;<br><br>
另外,词仅为中文或英文,词的长度大于1;<br><br>
处理的程序都放在loader.py文件中;<br><br>
3 运行步骤
=
python train_word2vec.py,对训练数据进行分词,利用Word2vec训练词向量(vector_word.txt)<br><br>
python text_train.py,进行训练模型<br><br>
python text_test.py,对模型进行测试<br><br>
python text_predict.py,提供模型的预测<br><br>
## TextCNN
## Transformer
<file_sep>/attention/README.md
# Attention
参考资料
==
### 1、论文
1 [[Bahdanau et al. ICLR2015]Neural Machine Translation by Jointly Learning to Align and Translate](https://arxiv.org/abs/1409.0473v7)<br>
2 [[Luong et al. EMNLP2015]Effective Approaches to Attention-based Neural Machine Translation](https://aclweb.org/anthology/D15-1166)<br>
3 [[Kel<NAME> et al. ICML2015]Show, Attend and Tell: Neural Image Caption Generation with Visual Attention](https://arxiv.org/abs/1502.03044)<br>
4 [[<NAME> et al. 2016]Hierarchical Attention Networks for Document Classification](https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf)<br>
5 [[Vaswani et al. ICCL2017]Attention Is All You Need](https://arxiv.org/abs/1706.03762)<br>
6 [[Y<NAME> et al. 2016]Attention-based LSTM for Aspect-level Sentiment Classification](https://aclweb.org/anthology/D16-1058)<br>
7 [[Zhouhan Lin et al. 2017]A Structured Self-attentive Sentence Embedding](https://arxiv.org/abs/1703.03130)<br>
### 2、博客
1 [Nir Arbel/Attention in RNNs](https://medium.com/datadriveninvestor/attention-in-rnns-321fbcd64f05) [对应翻译/AI公园/戎怀阳/使用详细的例子来理解RNN中的注意力机制](https://mp.weixin.qq.com/s/j21govyAwBQehmJYmSsYIw)<br>
### 3、代码
<file_sep>/probabilistic_graphical_models/README.md
# 概率图模型
0 参考资料
=
crf
=
1 [苏剑林/简明条件随机场CRF介绍(附带纯Keras实现)](https://kexue.fm/archives/5542)<br>
<file_sep>/seq2seq/README.md
# sequence to sequence
## 参考资料
[[1] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2014). Learning phrase representations using RNN encoder-decoder for statistical machine translation.](https://arxiv.org/abs/1406.1078.pdf)<br>
[[2] <NAME>., <NAME>., & <NAME>. (2014). Sequence to sequence learning with neural networks.](https://arxiv.org/pdf/1409.3215.pdf)<br>
博客1:[完全图解RNN、RNN变体、Seq2Seq、Attention机制](https://www.leiphone.com/news/201709/8tDpwklrKubaecTa.html)
博客2:[自然语言处理中的Attention机制总结](https://blog.csdn.net/hahajinbu/article/details/81940355)
<file_sep>/text_classification/TextRNN/TextRnnModel.py
import tensorflow as tf
class TextRnn(object):
"""
RNN for text classification
"""
def __init__(self, config):
self.config = config
# placeholders for input output and dropout
# input_x的维度是[batch_size, sequence_length]
# input_y的维度是[batch_size, num_classes]
self.input_x = tf.placeholder(tf.int32, shape=[None, self.config.sequence_length], name='input_x')
self.input_y = tf.placeholder(tf.int32, shape=[None, self.config.num_classes], name='input_y')
self.seq_length = tf.placeholder(tf.int32, shape=[None], name='seq_length')
self.dropout_keep_prob = tf.placeholder(tf.float32, name='dropout_keep_prob')
self.global_step = tf.Variable(0, trainable=False, name='global_step')
# word embedding
with tf.name_scope("embedding"):
# self.embedding = tf.Variable(tf.random_uniform([self.config.vocab_size, self.config.embedding_size], -1.0, 1.0),
# name="embedding", trainable=True)
# self.embedding = tf.Variable(tf.truncated_normal([self.config.vocab_size, self.config.embedding_size],
# stddev=1.0 / math.sqrt(self.config.embedding_size)),
# name="embedding", trainable=True)
self.embedding = tf.get_variable("embeddings", shape=[self.config.vocab_size, self.config.embedding_size],
initializer=tf.constant_initializer(self.config.pre_training),
trainable=True) # 是否使用预训练词向量,静态(False)或动态(默认True)
# 张量维度为[None, sequence_length, embedding_size]
self.embedding_inputs = tf.nn.embedding_lookup(self.embedding, self.input_x)
# RNN layer
with tf.name_scope("rnn_layer"):
cells = []
for _ in range(self.config.hidden_layer_num):
lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.config.hidden_size, forget_bias=0.0, state_is_tuple=True)
lstm_cell = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=self.dropout_keep_prob)
cells.append(lstm_cell)
cell = tf.nn.rnn_cell.MultiRNNCell(cells, state_is_tuple=True)
self.embedding_inputs = tf.nn.dropout(self.embedding_inputs, self.dropout_keep_prob)
# sequence_length: (可选)大小为[batch_size],数据的类型是int32/int64向量
outputs, states = tf.nn.dynamic_rnn(cell, self.embedding_inputs, dtype=tf.float32,
sequence_length=self.seq_length)
# outputs:[batch_size, sequence_length, hidden_size]
self.outputs = tf.reduce_sum(outputs, axis=1)
# dropout
with tf.name_scope('dropout'):
self.outputs_dropout = tf.nn.dropout(self.outputs, keep_prob=self.dropout_keep_prob)
# classifier
with tf.name_scope('output'):
W = tf.Variable(tf.truncated_normal([self.config.hidden_size, self.config.num_classes], stddev=0.1), name='W')
b = tf.Variable(tf.constant(0.1, shape=[self.config.num_classes]), name='b')
self.logits = tf.matmul(self.outputs_dropout, W) + b
self.predict = tf.argmax(tf.nn.softmax(self.logits), 1, name='predict')
# loss
with tf.name_scope('loss'):
losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y)
self.loss = tf.reduce_mean(losses)
# optimizer
with tf.name_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(self.config.learning_rate)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))#计算变量梯度,得到梯度值、变量
gradients, _ = tf.clip_by_global_norm(gradients, self.config.gradient_clip)
#对g进行l2正则化计算,比较其与clip的值,如果l2后的值更大,让梯度*(clip/l2_g),得到新梯度
self.optimizer = optimizer.apply_gradients(zip(gradients, variables), global_step=self.global_step)
#global_step 自动+1
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(self.predict, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
<file_sep>/word2vec/README.md
# word2vec
## 参考资料
源码1:[AimeeLee77/wiki_zh_word2vec](https://github.com/AimeeLee77/wiki_zh_word2vec)
<file_sep>/scrapy/README.md
# 爬虫
## 使用Scrapy实现爬虫的主要步骤:
1. 创建一个Scrapy项目。
scrapy startproject tianya_textclassify
2. 定义提取的Item。在items.py文件定义想要提取的实体:
class TianyaTextclassifyItem(scrapy.Item):
label = scrapy.Field() # 文档标签
content = scrapy.Field() # 文档内容
3. 编写爬取网站的 spider 并提取 Item。创建并修改spiders中蜘蛛文件tianya_ly.py:
scrapy genspider tianya_ly tianya.cn
4. 编写 Item Pipeline 来存储提取到的Item(即数据)。在pipelines.py中定义函数用于存储数据:
def process_item(self, item, spider):
with open('train_ly.txt', 'a', encoding='utf8') as fw:
fw.write(item['label'] + "," + item['content'] + '\n')
return item
5. 创建执行程序的文件main.py。有两种执行方式:
(1):用cmdline执行cmd命令
from scrapy import cmdline
cmdline.execute("scrapy crawl tianya_ly".split())
(2):常用方式
from scrapy.cmdline import execute
execute(["scrapy", "crawl", "tianya_ly"])
## scrapy工作原理图

## 参考资料
[1] https://scrapy-chs.readthedocs.io/zh_CN/latest/intro/overview.html
<file_sep>/text_classification/BiLstmAttention/README.md
# Attention-Based Bidirectional Long Short-Term Memory Networks for Text Classification
参考资料
=
1 [论文[<NAME> et al. 2016]Attention-Based Bidirectional Long Short-Term Memory Networks for Relation Classification](https://www.aclweb.org/anthology/P16-2034)<br>
2 [代码SeoSangwoo/Attention-Based-BiLSTM-relation-extraction](https://github.com/SeoSangwoo/Attention-Based-BiLSTM-relation-extraction)<br>
<file_sep>/text_classification/Transformer/README.md
# Transformer
## 参考资料
论文:[Attention Is All You Need](https://arxiv.org/pdf/1706.03762.pdf)
源码1:[brightmart/text_classification/a07_Transformer](https://github.com/brightmart/text_classification/tree/master/a07_Transformer)
源码2:[pengming617/text_classification/model/transformer](https://github.com/pengming617/text_classification/tree/master/model/transformer)
博客1:[文本分类实战之Transformer模型](https://www.cnblogs.com/jiangxinyang/p/10210813.html)
博客1对应源码:[jiangxinyang227/textClassifier/Transformer](https://github.com/jiangxinyang227/textClassifier/tree/master/Transformer)
<file_sep>/0_Class/CMU CS 11-747/README.md
# Study CMU CS 11-747 nn4nlp2019
## 学习资料
1 [课程官网Neural Networks for NLP](http://www.phontron.com/class/nn4nlp2019/)<br>
2 [课程代码neubig/nn4nlp-code](https://github.com/neubig/nn4nlp-code)<br>
3 [课程翻译AI研习社](https://ai.yanxishe.com/page/groupDetail/33)<br>
4 [课程第9课讨论的代码xnmt](https://github.com/neulab/xnmt)<br>
5 [课程第9课讨论的代码compare-mt](https://github.com/neulab/compare-mt)<br>
<file_sep>/BERT/README.md
# Bidirectional Encoder Representations from Transformers
参考资料
==
1 [论文BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)<br>
| b63995a2e2944a649d58d7395b6031c0ad697253 | [
"Markdown",
"Python"
] | 28 | Python | xuewengeophysics/xwStudyNLP | 60555770680e964241284318f935f3783aa7076c | df43be97b1fda9dc0ae5aa2b7e98d58d4e2421f2 | |
refs/heads/master | <file_sep>//
// Movie+CoreDataProperties.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 23/02/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Movie {
@NSManaged var desc: String?
@NSManaged var image: NSData?
@NSManaged var link: String?
@NSManaged var title: String?
@NSManaged var year: String?
@NSManaged var rated: String?
@NSManaged var director: String?
@NSManaged var imdbRating: String?
@NSManaged var genre: String?
}
<file_sep>//
// SearchBar.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 23/02/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
import UIKit
class SearchBar: UISearchBar {
var preferredFont: UIFont!
var preferredTextColor: UIColor!
init(frame: CGRect, font: UIFont, textColor: UIColor) {
super.init(frame: frame)
self.frame = frame
preferredFont = font
preferredTextColor = textColor
searchBarStyle = UISearchBarStyle.Prominent
translucent = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func indexOfSearchFieldInSubviews() -> Int! {
var index: Int!
let searchBarView = subviews[0] as! UIView
for var i=0; i<searchBarView.subviews.count; ++i {
if searchBarView.subviews[i].isKindOfClass(UITextField) {
index = i
break
}
}
return index
}
}
<file_sep>//
// MovieCell.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 15/02/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
import UIKit
import Foundation
import GPUImage
class MovieCell: UITableViewCell {
@IBOutlet weak var movieTitle: UILabel!
@IBOutlet weak var movieImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
movieImage.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(movie: Movie) {
movieTitle.text = movie.title
let inputImage = movie.getMovieImg()
let blurFilter = GPUImageGaussianBlurFilter()
let monochrome = GPUImageGrayscaleFilter()
let filterGroup = GPUImageFilterGroup()
blurFilter.blurRadiusInPixels = 10
filterGroup.addFilter(blurFilter)
filterGroup.addFilter(monochrome)
monochrome.addTarget(blurFilter)
monochrome.useNextFrameForImageCapture()
let outputImage = blurFilter.imageByFilteringImage(inputImage)
movieImage.image = outputImage
}
}
<file_sep>//
// DetailedViewVC.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 16/02/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
import UIKit
import CoreData
import Spring
import UICountingLabel
class DetailedViewVC: UIViewController {
@IBOutlet weak var movieDesc: UILabel!
@IBOutlet weak var movieImg: UIImageView!
@IBOutlet weak var viewBg: UIImageView!
@IBOutlet weak var movieImdb: UILabel!
@IBOutlet weak var movieYear: UILabel!
@IBOutlet weak var movieRating: UILabel!
@IBOutlet weak var movieDirector: UILabel!
var movie: Movie?
override func viewDidLoad() {
super.viewDidLoad()
self.viewBg.image = movie?.getMovieImg()
self.movieImg.image = movie?.getMovieImg()
self.movieImg.layer.cornerRadius = movieImg.frame.size.width / 2
self.movieImg.clipsToBounds = true
self.movieImg.layer.borderWidth = 5
self.movieImg.layer.borderColor = UIColor.whiteColor().CGColor
self.movieImg.layer.shadowColor = UIColor(red: 157.0 / 255.0, green: 157.0 / 255.0, blue: 157.0 / 255.0, alpha: 0.5).CGColor
self.movieImg.layer.shadowOpacity = 0.8
self.movieImg.layer.shadowRadius = 5.0
self.movieImg.layer.shadowOffset = CGSizeMake(0.0, 2.0)
if let dir = movie?.director {
self.movieDirector.text = dir
} else {
self.movieDirector.text = "N/A"
}
if let rate = movie?.rated {
self.movieRating.text = rate
} else {
self.movieRating.text = "N/A"
}
if let year = movie?.year {
self.movieYear.text = year
} else {
self.movieYear.text = "N/A"
}
if let desc = movie?.desc {
self.movieDesc.text = desc
}else {
self.movieDesc.text = "N/A"
}
if let imdb = movie?.imdbRating {
self.movieImdb.text = imdb
} else {
self.movieImdb.text = "N/A"
}
blurCI()
}
func blurCI() {
let darkBlur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = self.view.frame
viewBg.addSubview(blurView)
}
@IBAction func dismiss(sender: AnyObject){
dismissViewControllerAnimated(true, completion: nil)
}
}
<file_sep>//
// NavigationBar.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 17/02/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
import UIKit
class NavigationBar: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.translucent = true
}
}
<file_sep>//
// AddMovieButton.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 06/03/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
import UIKit
class AddMovieButton: UIButton {
override func awakeFromNib() {
let shadowColor: CGFloat = 0.0 / 255.0
layer.cornerRadius = 10.0
layer.shadowColor = UIColor(red: shadowColor, green: shadowColor, blue: shadowColor, alpha: 0.5).CGColor
layer.shadowOpacity = 0.5
layer.shadowRadius = 2.0
layer.shadowOffset = CGSizeMake(0.0, 2.0)
}
}
<file_sep>//
// addMovieVC.swift
// SeeMe
//
// Created by Leandersson, Johan (Grey London) on 15/02/2016.
// Copyright © 2016 Leandersson, Johan (Grey London). All rights reserved.
//
import UIKit
import CoreData
import Alamofire
import SwiftyJSON
class addMovieVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UISearchBarDelegate {
@IBOutlet weak var movieTitle: UILabel!
@IBOutlet weak var movieImg: UIImageView!
@IBOutlet weak var searchBar: UISearchBar!
var imagePicker: UIImagePickerController!
var imdbRating = ""
var movieYear = ""
var movieRating = ""
var movieDirector = ""
var movieDesc = ""
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
imagePicker = UIImagePickerController()
imagePicker.delegate = self
movieImg.layer.cornerRadius = 5.0
movieImg.clipsToBounds = true
movieTitle.text = ""
self.movieImg.layer.cornerRadius = movieImg.frame.size.width / 2
self.movieImg.clipsToBounds = true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
movieImg.image = image
}
@IBAction func addImg(sender: AnyObject) {
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func addMovie(sender: AnyObject){
if let title = movieTitle.text where title != "" {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Movie", inManagedObjectContext: context)!
let movie = Movie(entity: entity, insertIntoManagedObjectContext: context)
movie.title = title
movie.desc = movieDesc
movie.setMovieImage(movieImg.image!)
movie.imdbRating = imdbRating
movie.year = movieYear
movie.rated = movieRating
movie.director = movieDirector
context.insertObject(movie)
do {
try context.save()
} catch {
print("Could not save movie")
}
dismissViewControllerAnimated(true, completion: nil)
}
}
@IBAction func dismiss(sender: AnyObject){
dismissViewControllerAnimated(true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
movieTitle.resignFirstResponder()
return true
}
func searchIMDB(){
if let search = searchBar.text {
let spaceless = search.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let url = NSURL(string: "http://www.omdbapi.com/?t=\(spaceless)&y=&plot=short&r=json")!
Alamofire.request(.GET, url).responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) -> Void in
let result = response.result
if let JSON = result.value as? Dictionary<String, String> {
if let title = JSON["Title"] {
self.movieTitle.text = title.uppercaseString
}
if let desc = JSON["Plot"] {
self.movieDesc = desc
}
if let imdb = JSON["imdbRating"] {
self.imdbRating = imdb
}
if let year = JSON["Year"] {
self.movieYear = year
}
if let dir = JSON["Director"] {
self.movieDirector = dir
}
if let rate = JSON["Rated"] {
self.movieRating = rate
}
if let image = JSON["Poster"] {
if image != "N/A"{
let url = NSURL(string: image)!
let data = NSData(contentsOfURL: url)!
let moviePoster = UIImage(data: data)
self.movieImg.image = moviePoster
} else {
self.movieImg.image = UIImage(named: "noposter")
}
}
}
})
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchIMDB()
searchBar.resignFirstResponder()
searchBar.text = ""
}
func userTappedInView(recognizer: UITapGestureRecognizer)
{
self.searchBar.resignFirstResponder()
}
}
| e94a58519004b33466833b419d00dfff2cf7dbfd | [
"Swift"
] | 7 | Swift | Leandersson/WatchMe | 300209e5961c8c08774e6bc4b85e5ea0b830ed5c | 0dab586d209f4250bc615345878fc8224ce855db | |
refs/heads/master | <file_sep>import React from 'react';
import {shallow} from 'enzyme';
import {toggleInfoModal} from '../actions'
import {InfoModal} from './info-modal';
describe('<InfoModal />', () => {
it('Renders without crashing', () => {
shallow(<InfoModal />);
});
it('Fires the onClose callback when the close button is clicked', () => {
const callback = jest.fn();
const wrapper = shallow(<InfoModal dispatch={callback} />);
const instance = wrapper.instance();
instance.hide({preventDefault(){} });
expect(callback).toHaveBeenCalledWith(toggleInfoModal());
});
});<file_sep>import reducer from './reducer';
import {makeGuess, MAKE_GUESS, toggleInfoModal, TOGGLE_INFO_MODAL, newGame, NEW_GAME} from './actions';
describe("Reducer", () => {
const makeGuessState = {
guesses: [],
feedback: "Make your guess!",
correctAnswer: 25,
showInfoModal: false
};
it("should set the initial state when nothing is passed in", ()=> {
const state = reducer(undefined, {type: '__UNKNOWN'});
expect(state.guesses).toEqual([]);
expect(state.feedback).toEqual("Make your guess!");
expect(state.showInfoModal).toEqual(false);
expect(state.correctAnswer).toBeGreaterThanOrEqual(0);
expect(state.correctAnswer).toBeLessThanOrEqual(100);
});
it("should return the current state for an unknown action", () =>{
const currentState = {};
const state = reducer(currentState, {type: '__UNKNOWN'});
expect(state).toEqual(currentState);
});
it("newGame", ()=>{
const currentState = {};
const state = reducer(currentState, newGame());
expect(state).not.toEqual(currentState);
expect(state.guesses).toEqual([]);
expect(state.feedback).toEqual("Make your guess!");
expect(state.showInfoModal).toEqual(false);
expect(state.correctAnswer).toBeGreaterThanOrEqual(0);
expect(state.correctAnswer).toBeLessThanOrEqual(100);
});
it("toggleInfoModal", () => {
const currentState = {showInfoModal: false};
const state = reducer(currentState, toggleInfoModal());
expect(state).not.toEqual(currentState);
expect(typeof state.showInfoModal).toBe("boolean");
});
it("makeGuess, not a number guess", () => {
const nanGuess = "your mom";
const state = reducer(makeGuessState, makeGuess(nanGuess));
expect(state.feedback).toEqual("Please enter a valid number");
expect(state.guesses).toEqual(makeGuessState.guesses);
expect(state.correctAnswer).toEqual(makeGuessState.correctAnswer);
expect(state.showInfoModal).toEqual(makeGuessState.showInfoModal);
});
it("makeGuess, make a valid but incorrect guess", () => {
const validGuess = 76;
const state = reducer(makeGuessState, makeGuess(validGuess));
expect(state.guesses).toEqual([76]);
expect(state.feedback).toEqual("You're Ice Cold...");
expect(state.correctAnswer).toEqual(makeGuessState.correctAnswer);
expect(state.showInfoModal).toEqual(makeGuessState.showInfoModal);
});
it("makeGuess, make valid and correct guess", () => {
const correctGuess = 25;
const state = reducer(makeGuessState, makeGuess(correctGuess));
expect(state.guesses).toEqual([25]);
expect(state.feedback).toEqual("You got it!");
expect(state.correctAnswer).toEqual(makeGuessState.correctAnswer);
expect(state.showInfoModal).toEqual(makeGuessState.showInfoModal);
});
it("makeGuess, not valid due to range", () => {
const invalidGuess = 176;
const state = reducer(makeGuessState, makeGuess(invalidGuess));
expect(state.guesses).toEqual([176]);
expect(state.feedback).toEqual("You're Ice Cold...");
expect(state.correctAnswer).toEqual(makeGuessState.correctAnswer);
expect(state.showInfoModal).toEqual(makeGuessState.showInfoModal);
});
});<file_sep>import React from 'react';
import {shallow} from 'enzyme';
import {makeGuess} from '../actions'
import {GuessForm} from './guess-form';
describe('<InfoModal />', () => {
it('Renders without crashing', () => {
shallow(<GuessForm />);
});
it('Fires the onClose callback when the close button is clicked', () => {
const callback = jest.fn();
const wrapper = shallow(<GuessForm dispatch={callback} />);
const instance = wrapper.instance();
instance.input = {value: "34"};
instance.submitGuess({preventDefault(){} });
expect(callback).toHaveBeenCalledWith(makeGuess(instance.input.value));
});
}); | 3143f6b2c8d2db2416995baa1daffd49519006dd | [
"JavaScript"
] | 3 | JavaScript | thinkful-c11/Testing-Redux-With-Sonja-And-Tanner | 37ea31eee65218c019df5c8e098210b9a3cee5ea | a3fc3da0da8086608567d59a74747c1090f59467 | |
refs/heads/main | <repo_name>AvijitDasAdhikary/laravel8<file_sep>/app/Http/Controllers/TodoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Todo;
use Redirect,Response;
use Validator;
class TodoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// $todos = Todo::get();
$todos = Todo::paginate(5);
return view('todos.todo', compact('todos'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('todos.createTodo');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'todoName' => 'required',
],[
'todoName.required' => 'Please select TodoName',
]);
if ($validator->fails())
{
return Response::json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 400);
}
$todos = new Todo();
$todos->name = $request->todoName;
$todos->status = $request->todoStatus;
if ($request->hasFile('inputImage')) {
$document = $request->file('inputImage');
$documentExtension = $document->getClientOriginalExtension();
$documentName = time() . '.' . $documentExtension;
$path = 'uploads/'.date('Y').'/'.date('m').'/'.date('d');
$document->move(public_path($path), $documentName);
$dbDocumentPath = $path.'/'.$documentName;
}else{
$dbDocumentPath = '';
}
$todos->image = $dbDocumentPath;
$todos->save();
return redirect('todos');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$todos = Todo::findOrFail($id);
return view('todos.edittodo', compact('todos','id'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$todos = Todo::findOrFail($id);
$todos->name = $request->todoName;
$todos->status = $request->todoStatus;
$todos->save();
return redirect('todos');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$todos = Todo::findOrFail($id);
$todos->delete();
return Response::json(array('success' => true), 200);
}
}
<file_sep>/app/Http/Controllers/FormCodesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FormCodes;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
use App\Models\Department;
class FormCodesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$formcodes = FormCodes::with('departmentId')->get();
return view('form_codes.view', compact('formcodes'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$departments = Department::get();
return view('form_codes.create', compact('departments'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
validator::make($request->all(),[
'department' => 'required',
'formCode' => 'required',
'formDescription' => 'required',
])->validate();
$formcodes = new FormCodes();
$formcodes->department_id = $request->department;
$formcodes->form_code = $request->formCode;
$formcodes->description = $request->formDescription;
$formcodes->is_active = $request->formStatus;
$formcodes->save();
return redirect('formcodes');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$departments = Department::get();
$formcodes = FormCodes::findOrFail($id);
return view('form_codes.edit', compact('formcodes','id','departments'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
validator::make($request->all(),[
'department' => 'required',
'formCode' => 'required',
'formDescription' => 'required',
])->validate();
$formcodes = FormCodes::findOrFail($id);
$formcodes->department_id = $request->department;
$formcodes->form_code = $request->formCode;
$formcodes->description = $request->formDescription;
$formcodes->is_active = $request->formStatus;
$formcodes->save();
return redirect('formcodes');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$formcodes = FormCodes::findOrFail($id);
$formcodes->delete();
return Response::json(array('success' => true), 200);
}
}
<file_sep>/database/migrations/2021_02_11_143756_create_form_item_options_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFormItemOptionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('form_item_options', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->integer('id')->autoIncrement();
$table->integer('item_id');
$table->integer('option_id');
$table->tinyinteger('is_active')->comment('0 => Inactive, 1=> Active');
$table->foreign('item_id')->references('id')->on('form_items');
$table->foreign('option_id')->references('id')->on('master_form_options');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('form_item_options');
}
}
<file_sep>/public/dist/custom/my.js
/*
* ***************************************************************
* Script :
* Version :
* Date :
* Author : <NAME>.
* Email : <EMAIL>
* Description :
* ***************************************************************
*/
function toast(message,title,typemessage = "info"){
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
toastr[typemessage](title,message);
}
function data_terbilang(bilangan) {
if(bilangan==="" || bilangan==="0"){
return "Nol Rupiah";
}
bilangan = String(bilangan);
var angka = new Array('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0');
var kata = new Array('','Satu','Dua','Tiga','Empat','Lima','Enam','Tujuh','Delapan','Sembilan');
var tingkat = new Array('','Ribu','Juta','Milyar','Triliun');
var panjang_bilangan = bilangan.length;
/* pengujian panjang bilangan */
if (panjang_bilangan > 15) {
kaLimat = "Diluar Batas";
return kaLimat;
}
/* mengambil angka-angka yang ada dalam bilangan, dimasukkan ke dalam array */
for (i = 1; i <= panjang_bilangan; i++) {
angka[i] = bilangan.substr(-(i),1);
}
i = 1;
j = 0;
kaLimat = "";
/* mulai proses iterasi terhadap array angka */
while (i <= panjang_bilangan) {
subkaLimat = "";
kata1 = "";
kata2 = "";
kata3 = "";
/* untuk Ratusan */
if (angka[i+2] != "0") {
if (angka[i+2] == "1") {
kata1 = "Seratus";
} else {
kata1 = kata[angka[i+2]] + " Ratus";
}
}
/* untuk Puluhan atau Belasan */
if (angka[i+1] != "0") {
if (angka[i+1] == "1") {
if (angka[i] == "0") {
kata2 = "Sepuluh";
} else if (angka[i] == "1") {
kata2 = "Sebelas";
} else {
kata2 = kata[angka[i]] + " Belas";
}
} else {
kata2 = kata[angka[i+1]] + " Puluh";
}
}
/* untuk Satuan */
if (angka[i] != "0") {
if (angka[i+1] != "1") {
kata3 = kata[angka[i]];
}
}
/* pengujian angka apakah tidak nol semua, lalu ditambahkan tingkat */
if ((angka[i] != "0") || (angka[i+1] != "0") || (angka[i+2] != "0")) {
subkaLimat = kata1+" "+kata2+" "+kata3+" "+tingkat[j]+" ";
}
/* gabungkan variabe sub kaLimat (untuk Satu blok 3 angka) ke variabel kaLimat */
kaLimat = subkaLimat + kaLimat;
i = i + 3;
j = j + 1;
}
/* mengganti Satu Ribu jadi Seribu jika diperlukan */
if ((angka[5] == "0") && (angka[6] == "0")) {
kaLimat = kaLimat.replace("Satu Ribu","Seribu");
}
return kaLimat + "Rupiah";
}
function set_date(tahun,bulan,hari){
var d = new Date();
if(Number(tahun) > d.getFullYear()){
tahun = 0;
}
if(!(bulan)){
bulan = 12;
}else if(Number(bulan) === 0 && isNaN(bulan) === false){
bulan = d.getMonth() + 1;
}else if(Number(bulan) > 0 && isNaN(bulan) === false){
bulan = (d.getMonth() - Number(bulan));
}else if(Number(bulan) > 12 && isNaN(bulan) === false){
bulan = 12;
}else{
bulan = 12;
}
if(!(hari)){
hari = 31;
}else if(Number(hari) === 0 && isNaN(bulan) === false){
hari = d.getDate();
}else if(Number(hari) > 0 && isNaN(bulan) === false){
hari = d.getDate() - Number(hari);
}else if(Number(hari) > 31 && isNaN(bulan) === false){
hari = 31;
}else{
hari = 31;
}
var res = d.setFullYear(d.getFullYear() - Number(tahun));
var newyear = new Date(res);
var resdate = Number(hari) + "/" + Number(bulan) + "/" + newyear.getFullYear();
return resdate;
}
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};<file_sep>/app/Http/Controllers/FormItemController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FormItem;
use App\Models\FormSection;
use App\Models\Forms;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class FormItemController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$formitems = FormItem::with('formSectionId')->get();
return view('form_item.view', compact('formitems'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$forms = Forms::get();
$formsections = FormSection::get();
return view('form_item.create',compact('formsections','forms'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
validator::make($request->all(),[
'sectionTitle' => 'required',
'formItemTitle' => 'required',
'formItemPoint' => 'required',
'formItemComment' => 'required',
'formItemPicture1' => 'required',
'formItemPicture2' => 'required',
])->validate();
$formitems = new FormItem();
$formitems->section_id = $request->sectionTitle;
$formitems->title = $request->formItemTitle;
$formitems->points = $request->formItemPoint;
$formitems->is_comment = $request->formItemComment;
$formitems->is_picture_1 = $request->formItemPicture1;
$formitems->is_picture_2 = $request->formItemPicture2;
$formitems->is_active = $request->formItemStatus;
$formitems->save();
return redirect('formitem');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$forms = Forms::get();
$formsections = FormSection::get();
$formitems = FormItem::findOrFail($id);
return view('form_item.edit', compact('formitems','id','formsections','forms'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
validator::make($request->all(),[
'sectionTitle' => 'required',
'formItemTitle' => 'required',
'formItemPoint' => 'required',
'formItemComment' => 'required',
'formItemPicture1' => 'required',
'formItemPicture2' => 'required',
])->validate();
$formitems = FormItem::findOrFail($id);
$formitems->section_id = $request->sectionTitle;
$formitems->title = $request->formItemTitle;
$formitems->points = $request->formItemPoint;
$formitems->is_comment = $request->formItemComment;
$formitems->is_picture_1 = $request->formItemPicture1;
$formitems->is_picture_2 = $request->formItemPicture2;
$formitems->is_active = $request->formItemStatus;
$formitems->save();
return redirect('formitem');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$formitems = FormItem::findOrFail($id);
$formitems->delete();
return Response::json(array('success' => true), 200);
}
public function getFormTitle($formId){
$formtitles = FormSection::where(['form_id'=>$formId])->get();
$returndata = [];
foreach($formtitles as $formtitle){
$returndata[] = [
'id' => $formtitle->id,
'title' => $formtitle->section_title,
];
}
return Response::json($returndata,200);
}
}
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
Route::get('/home','DeveloperController@index');
Route::get('/dashboard','DashboardController@index');
Route::get('/task','DashboardController@task');
Route::get('/developer','DeveloperController@index');
Route::resources([
'photos' => PhotoController::class,
'todos' => TodoController::class,
'departments' => DepartmentController::class,
'masterformoptions' => MasterFormOptionsController::class,
'formcodes' => FormCodesController::class,
'forms' => FormsController::class,
'formsection' => FormSectionController::class,
'formitem' => FormItemController::class,
'formitemcodes' => FormItemCodeController::class,
'formitemoptions' => FormItemOptionController::class,
]);
Route::post('formitem/create/{formId}', ['uses' => 'FormItemController@getFormTitle']);
Route::post('formitemcodes/create/formSection/{formId}', ['uses' => 'FormItemCodeController@getFormTitle']);
Route::post('formitemcodes/create/formItem/{SectionId}', ['uses' => 'FormItemCodeController@getSectionTitle']);
Route::post('formitemcodes/create/formCode/{CodeId}', ['uses' => 'FormItemCodeController@getformItemTitle']);
Route::post('formitemoptions/create/formSection/{formId}', ['uses' => 'FormItemOptionController@getFormTitle']);
Route::post('formitemoptions/create/formItem/{SectionId}', ['uses' => 'FormItemOptionController@getSectionTitle']);<file_sep>/app/Http/Controllers/DepartmentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Department;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class DepartmentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$departments = Department::get();
return view('departments.view', compact('departments'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('departments.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Validator::make($request->all(),[
'departmentName' => 'required|unique:departments,name',
'departmentAlias' => 'required|unique:departments,alias',
])->validate();
$departments = new Department();
$departments->name = $request->departmentName;
$departments->alias = $request->departmentAlias;
$departments->description = $request->departmentDescription;
$departments->is_active = $request->departmentStatus;
$departments->save();
return redirect('departments');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$departments = Department::findOrFail($id);
return Response::json(array(
'success' => true,
'departments' => $departments,
), 200);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$departments = Department::findOrFail($id);
return view('departments.edit', compact('departments','id'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
Validator::make($request->all(),[
'departmentName' => 'required|unique:departments,name,'.$id,
'departmentAlias' => 'required|unique:departments,alias,'.$id,
// 'departmentDescription' => 'required',
])->validate();
$departments = Department::findOrFail($id);
$departments->name = $request->departmentName;
$departments->alias = $request->departmentAlias;
$departments->description = $request->departmentDescription;
$departments->is_active = $request->departmentStatus;
$departments->save();
return redirect('departments');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$departments = Department::findOrFail($id);
$departments->delete();
return Response::json(array('success' => true), 200);
}
}
<file_sep>/app/Http/Controllers/DashboardController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index(){
$records1 = ['record1'];
$records2 = [];
$value = 4;
$users = [
['id'=>1, 'code'=>'DEVELOPER', 'age'=> 25],
['id'=>2, 'code'=>'HR', 'age'=> 52],
['id'=>3, 'code'=>'Accounts', 'age'=> 62],
['id'=>4, 'code'=>'Manager', 'age'=> 46],
];
$admins = [
['name'=>'ADMIN', 'status'=> 'Active'],
];
return view('dashboard',compact('records1','records2','value','users','admins'));
}
public function task(){
$tasks = ['task1','task2','task3'];
$tasks2 = ['list1','list2','list3'];
return view('task', compact('tasks','tasks2'));
}
}
<file_sep>/app/Http/Controllers/FormSectionController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FormSection;
use App\Models\Forms;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class FormSectionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$formsections = FormSection::with('formId')->get();
return view('form_section.view', compact('formsections'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$forms = Forms::get();
return view('form_section.create', compact('forms'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
validator::make($request->all(),[
'formTitle' => 'required',
'sectionTitle' => 'required',
'parentID' => 'required',
])->validate();
$formsections = new FormSection();
$formsections->form_id = $request->formTitle;
$formsections->section_title = $request->sectionTitle;
$formsections->parent_id = $request->parentID;
$formsections->is_active = $request->sectionStatus;
$formsections->save();
return redirect('formsection');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$forms = Forms::get();
$formsections = FormSection::findOrFail($id);
return view('form_section.edit', compact('formsections','id','forms'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
validator::make($request->all(),[
'formTitle' => 'required',
'sectionTitle' => 'required',
'parentID' => 'required',
])->validate();
$formsections = FormSection::findOrFail($id);
$formsections->form_id = $request->formTitle;
$formsections->section_title = $request->sectionTitle;
$formsections->parent_id = $request->parentID;
$formsections->is_active = $request->sectionStatus;
$formsections->save();
return redirect('formsection');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$formsections = FormSection::findOrFail($id);
$formsections->delete();
return Response::json(array('success' => true), 200);
}
}
<file_sep>/app/Models/FormSection.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class FormSection extends Model
{
//use HasFactory;
use SoftDeletes;
protected $table = 'forms_sections';
public function formId()
{
return $this->belongsTo('App\Models\Forms','form_id');
}
}
<file_sep>/app/Models/FormItemOption.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class FormItemOption extends Model
{
//use HasFactory;
protected $table = 'form_item_options';
public $timestamps = false;
public function ItemId()
{
return $this->belongsTo('App\Models\FormItem','item_id');
}
public function OptionId()
{
return $this->belongsTo('App\Models\masterFormOptions','option_id');
}
}
<file_sep>/app/Models/FormItem.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class FormItem extends Model
{
//use HasFactory;
use SoftDeletes;
protected $table = 'form_items';
public function formSectionId()
{
return $this->belongsTo('App\Models\FormSection','section_id');
}
}
<file_sep>/app/Http/Controllers/FormItemCodeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FormItemCode;
use App\Models\FormItem;
use App\Models\FormCodes;
use App\Models\Forms;
use App\Models\FormSection;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class FormItemCodeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$formitemcodes = FormItemCode::with('formItemId','formCodeId')->get();
return view('form_item_codes.view', compact('formitemcodes'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$forms = Forms::get();
$formsections = FormSection::get();
$formitems = FormItem::get();
$formcodes = FormCodes::get();
return view('form_item_codes.create',compact('formitems','formcodes','forms','formsections'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
validator::make($request->all(),[
'formItemTitle' => 'required',
'formCode' => 'required',
])->validate();
$formitemcodes = new FormItemCode();
$formitemcodes->item_id = $request->formItemTitle;
$formitemcodes->code_id = $request->formCode;
$formitemcodes->is_active = $request->formItemCodeStatus;
$formitemcodes->save();
return redirect('formitemcodes');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$formitems = FormItem::get();
$formcodes = FormCodes::get();
$formitemcodes = FormItemCode::findOrFail($id);
return view('form_item_codes.edit', compact('formitemcodes','id','formitems','formcodes'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
validator::make($request->all(),[
'formItemTitle' => 'required',
'formCode' => 'required',
])->validate();
$formitemcodes = FormItemCode::findOrFail($id);
$formitemcodes->item_id = $request->formItemTitle;
$formitemcodes->code_id = $request->formCode;
$formitemcodes->is_active = $request->formItemCodeStatus;
$formitemcodes->save();
return redirect('formitemcodes');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$formitemcodes = FormItemCode::findOrFail($id);
$formitemcodes->delete();
return Response::json(array('success' => true), 200);
}
public function getFormTitle($formId){
$formtitles = FormSection::where(['form_id'=>$formId])->get();
$returndata = [];
foreach($formtitles as $formtitle){
$returndata[] = [
'id' => $formtitle->id,
'title' => $formtitle->section_title,
];
}
return Response::json($returndata,200);
}
public function getSectionTitle($SectionId){
$formsections = FormItem::where(['section_id'=>$SectionId])->get();
$returndata = [];
foreach($formsections as $formsection){
$returndata[] = [
'id' => $formsection->id,
'title' => $formsection->title,
];
}
return Response::json($returndata,200);
}
public function getformItemTitle($CodeId){
$formcodes = FormCodes::where(['id'=>$CodeId])->get();
$returndata = [];
foreach($formcodes as $formcode){
$returndata[] = [
'id' => $formcode->id,
'form_code' => $formcode->form_code,
];
}
return Response::json($returndata,200);
}
}
<file_sep>/app/Http/Controllers/MasterFormOptionsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\masterFormOptions;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class MasterFormOptionsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$masterformoptions = masterFormOptions::get();
return view('master_form_options.view', compact('masterformoptions'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('master_form_options.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Validator::make($request->all(),[
'masterFormLabel' => 'required|unique:master_form_options,label',
'inputColorCode' => 'required|unique:master_form_options,color_code'
],[
'inputColorCode.required' => 'Please select a color',
'inputColorCode.unique' => 'duplicate'
])->validate();
$masterformoptions = new masterFormOptions();
$masterformoptions->label = $request->masterFormLabel;
$masterformoptions->color_class = $request->masterFormColorClass;
$masterformoptions->color_code = $request->inputColorCode;
$masterformoptions->is_active = $request->masterFormStatus;
$masterformoptions->save();
return redirect('masterformoptions');
}
/**
* Display the specified resource.
*
* @param \App\Models\masterFormOptions $masterFormOptions
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$masterformoptions = masterFormOptions::findOrFail($id);
return Response::json(array(
'success' => true,
'masterformoptions' => $masterformoptions,
), 200);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\masterFormOptions $masterFormOptions
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$masterformoptions = masterFormOptions::findOrFail($id);
return view('master_form_options.edit', compact('masterformoptions','id'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\masterFormOptions $masterFormOptions
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
Validator::make($request->all(),[
'masterFormLabel' => 'required',
'inputColorCode' => 'required'
],[
'inputColorCode.required' => 'Please select a color',
'inputColorCode.unique' => 'duplicate'
])->validate();
$masterformoptions = masterFormOptions::findOrFail($id);
$masterformoptions->label = $request->masterFormLabel;
$masterformoptions->color_class = $request->masterFormColorClass;
$masterformoptions->color_code = $request->inputColorCode;
$masterformoptions->is_active = $request->masterFormStatus;
$masterformoptions->save();
return redirect('masterformoptions');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\masterFormOptions $masterFormOptions
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$masterformoptions = masterFormOptions::findOrFail($id);
$masterformoptions->delete();
return Response::json(array('success' => true), 200);
}
}
<file_sep>/app/Http/Controllers/FormsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Forms;
use App\Models\Department;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class FormsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$forms = Forms::with('departmentId')->get();
return view('forms.view', compact('forms'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$departments = Department::get();
return view('forms.create',compact('departments'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
validator::make($request->all(),[
'department' => 'required',
'formTitle' => 'required',
'formsDescription' => 'required',
])->validate();
$forms = new Forms();
$forms->department_id = $request->department;
$forms->title = $request->formTitle;
$forms->description = $request->formsDescription;
$forms->is_active = $request->formStatus;
$forms->save();
return redirect('forms');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$departments = Department::get();
$forms = Forms::findOrFail($id);
return view('forms.edit', compact('forms','id','departments'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
validator::make($request->all(),[
'department' => 'required',
'formTitle' => 'required|unique:forms,title,'.$id,
'formsDescription' => 'required',
])->validate();
$forms = Forms::findOrFail($id);
$forms->department_id = $request->department;
$forms->title = $request->formTitle;
$forms->description = $request->formsDescription;
$forms->is_active = $request->formStatus;
$forms->save();
return redirect('forms');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$forms = Forms::findOrFail($id);
$forms->delete();
return Response::json(array('success' => true), 200);
}
}
<file_sep>/database/migrations/2021_02_11_143949_create_form_item_codes_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFormItemCodesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('form_item_codes', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->integer('id')->autoIncrement();
$table->integer('item_id');
$table->integer('code_id');
$table->tinyInteger('is_active')->comment('0 => Inactive, 1 => Active');
$table->foreign('item_id')->references('id')->on('form_items');
$table->foreign('code_id')->references('id')->on('form_codes');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('form_item_codes');
}
}
<file_sep>/app/Http/Controllers/FormItemOptionController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\FormItemOption;
use App\Models\FormItem;
use App\Models\masterFormOptions;
use App\Models\Forms;
use App\Models\FormSection;
use Redirect,Response;
use Illuminate\Support\Facades\Validator;
class FormItemOptionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$formitemoptions = FormItemOption::with('ItemId','OptionId')->get();
return view('form_item_options.view',compact('formitemoptions'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$forms = Forms::get();
$formsections = FormSection::get();
$formitems = FormItem::get();
$masterformoptions = masterFormOptions::get();
return view('form_item_options.create',compact('formitems','masterformoptions','forms','formsections'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
validator::make($request->all(),[
'formItemTitle' => 'required',
'masterFormLabel' => 'required',
])->validate();
$option_id = $request->input('masterFormLabel');
foreach($option_id as $option)
{
$formitemoptions = new FormItemOption();
$formitemoptions->item_id = $request->formItemTitle;
$formitemoptions->option_id = $option;
$formitemoptions->is_active = $request->formItemOptionStatus;
$formitemoptions->save();
}
return redirect('formitemoptions');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$formitems = FormItem::get();
$masterformoptions = masterFormOptions::get();
$formitemoptions = FormItemOption::findOrFail($id);
return view('form_item_options.edit', compact('formitemoptions','id','formitems','masterformoptions'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
validator::make($request->all(),[
'formItemTitle' => 'required',
'masterFormLabel' => 'required',
])->validate();
$option_id = $request->input('masterFormLabel');
foreach($option_id as $option)
{
$formitemoptions = FormItemOption::findOrFail($id);
$formitemoptions->item_id = $request->formItemTitle;
$formitemoptions->option_id = $option;
$formitemoptions->is_active = $request->formItemOptionStatus;
$formitemoptions->save();
}
return redirect('formitemoptions');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$formitemoptions = FormItemOption::findOrFail($id);
$formitemoptions->delete();
return Response::json(array('success' => true), 200);
}
public function getFormTitle($formId){
$formtitles = FormSection::where(['form_id'=>$formId])->get();
$returndata = [];
foreach($formtitles as $formtitle){
$returndata[] = [
'id' => $formtitle->id,
'title' => $formtitle->section_title,
];
}
return Response::json($returndata,200);
}
public function getSectionTitle($SectionId){
$formsections = FormItem::where(['section_id'=>$SectionId])->get();
$returndata = [];
foreach($formsections as $formsection){
$returndata[] = [
'id' => $formsection->id,
'title' => $formsection->title,
];
}
return Response::json($returndata,200);
}
}
<file_sep>/app/Models/FormItemCode.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class FormItemCode extends Model
{
//use HasFactory;
protected $table = 'form_item_codes';
public $timestamps = false;
public function formItemId()
{
return $this->belongsTo('App\Models\FormItem','item_id');
}
public function formCodeId()
{
return $this->belongsTo('App\Models\FormCodes','code_id');
}
}
| 648cb0e7e7f03a88184d99993f221be87c74de19 | [
"JavaScript",
"PHP"
] | 18 | PHP | AvijitDasAdhikary/laravel8 | e18903c054cfe37114b51500624322c2deb47bab | 690d5e3642812100e167a644b3f0142a1c936cb8 | |
refs/heads/master | <repo_name>KirillZhdanov/reverse-int<file_sep>/src/index.js
module.exports = function reverse (n) {
n=Math.abs(n);
let s=n.toString().split("").reverse();
n=Number(s.join(""));
console.log("output type is <"+typeof(n)+"> and output value is: "+n)
return n;
}
| 4380ab4dc8bd001995bece756f469d30f365b807 | [
"JavaScript"
] | 1 | JavaScript | KirillZhdanov/reverse-int | 70a8e2d4e09bb47e585a881120a5b98f367d3f41 | 9d0d2afe4ccef254cc8bcb8b642ec8f75fdc7e94 | |
refs/heads/master | <repo_name>nghiatv/mvc-routes<file_sep>/resources/views/admin/edit_user.php
<?php include '_admin_template/header.php' ?>
<body class="hold-transition skin-blue sidebar-mini">
<?php include '_admin_template/menu.php' ?>
<?php include '_admin_template/sidebar.php' ?>
<div class="register-box">
<div class="register-logo">
<a href="<?php echo BASE_PATH; ?>">Chỉnh sửa thông tin của <b><?php echo $data['user_name']; ?></b></a>
</div>
<div class="register-box-body">
<form action="<?php echo BASE_PATH ?>/admin/user/update/<?php echo $data['id']; ?>" method="post">
<?php if (isset($_SESSION['error'])) : ?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
<ul>
<?php foreach ($_SESSION['error'] as $row) : ?>
<li> <?php echo $row; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if (isset($_SESSION['mes'])) : ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
<ul>
<?php foreach ($_SESSION['mes'] as $row) : ?>
<li> <?php echo $row; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Username" name="username"
value="<?php echo $data['user_name']; ?>">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email"
name="email" value="<?php echo $data['user_email']; ?>"
>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password"
name="password" value="<?php echo $data['user_pass']; ?>">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Retype password" name="repassword"
value="<?php echo $data['user_pass']; ?>">
<span class="glyphicon glyphicon-log-in form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-6">
<button type="submit" class="btn btn-success btn-block btn-flat">Cập nhật thông tin</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.form-box -->
</div>
<!-- /.register-box -->
<?php unset($_SESSION['error']); ?>
<?php unset($_SESSION['mes']); ?>
<?php include '_admin_template/footer.php' ?><file_sep>/libs/Validation.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/8/16
* Time: 10:25 AM
*/
class Validation
{
// Kiem tra tinh hop le cua input
static public function isValidUser($user) {
$pattern = "/^[a-zA-Z0-9]{6,18}$/";
if(preg_match($pattern, $user)) {
return true;
} else {
return false;
}
}
// kiem tra tinh hop le cua password
static function isValidPass($pass) {
$pattern = "/^[a-zA-Z0-9]{8,32}$/";
if(preg_match($pattern, $pass)) {
return true;
} else {
return false;
}
}
}<file_sep>/config.php
<?php
/**
* Created by PhpStorm.
* User: Nimo
* Date: 07/08/2016
* Time: 10:08 CH
*/
//Thong so ve database
//define("DB_TYPE",'mysql');
//define('DB_HOST', 'localhost');
//define('DB_USER', 'root');
//define('DB_PASS', '');
//define('DB_DBNAME', 'blog-v1');
define('PATH_APPLICATION', __DIR__ . "/app");
define('BASE_PATH',"http://localhost:8000");
define('ENVIRONMENT', 'development');
if (ENVIRONMENT == 'development' || ENVIRONMENT == 'dev') {
error_reporting(E_ALL);
ini_set("display_errors", 1);
} else {
error_reporting(0);
ini_set("display_errors", 0);
}
<file_sep>/libs/application.php
<?php
namespace Libs;
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/8/16
* Time: 11:26 AM
*/
class Application
{
private $controller;
private $action = 'view';
private $param;
private $request_path = array();
public function __construct()
{
$this->request_path = $this->request_path();
$this->splitURL();
$controller = empty($this->controller) ? 'index' : $this->controller;
$controller = strtolower($controller)."_controller";
//KIEM TRA FILE CO TON TAI HAY KHONG?
// echo "<pre>";var_dump($this->param);echo "</pre>"; exit;
if (!file_exists(PATH_APPLICATION . "/frontend/controller/".$controller.".php")){
// header("Location:".BASE_PATH."/p404");
}
require PATH_APPLICATION."/frontend/controller/".$controller.".php";
// KIEM TRA XEM CLASS CO TON TAI HAY KHONG?
$controllerObj = new $controller();
if(!class_exists($controller)){
header("Location:".BASE_PATH."/p404");
}
//Kiem tra xem method co ton tai hay ko?
if(method_exists($controller,$this->action)){
if(!empty($this->param)){
call_user_func_array(array($controllerObj,$this->action), $this->param);
}else{
$controllerObj->{$this->action}();
}
}else{
header("Location:".BASE_PATH."/p404");
}
}
private function request_path()
{
$request_uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$script_name = explode('/', trim($_SERVER['SCRIPT_NAME'], '/'));
$parts = array_diff_assoc($request_uri, $script_name);
if (empty($parts) && empty($parts[0])) {
return '/';
}
$path = implode('/', $parts);
if (($position = strpos($path, '?')) !== FALSE) {
$path = substr($path, 0, $position);
}
return $path;
}
private function splitURL()
{
if (empty($this->request_path)) {
$this->controller = null;
$this->param = null;
} else {
$url = $this->request_path; // truyen $url la doan url cat dc
$url = filter_var($url, FILTER_SANITIZE_URL); // kiem tra voi filter
$url = explode("/", $url); // cat theo dau / de lay gia tri
$this->controller = isset($url[0]) ? $url[0] : null; // dau tien se la Controllers xu ly
// $this->action = isset($url[1]) ? $url[0] : null; // tiep theo la action
unset($url[0]); // cat Controllers ra khoi mang
$this->param = array_values($url);
}
}
}<file_sep>/resources/views/admin/_admin_template/footer.php
<!-- jQuery 2.2.3 -->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<!--<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>-->
<!-- Bootstrap 3.3.6 -->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/bootstrap/js/bootstrap.min.js"></script>
<!--datatable-->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/datatables/jquery.dataTables.min.js"></script>
<!-- Slimscroll -->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/dist/js/app.min.js"></script>
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/iCheck/icheck.min.js"></script>
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/select2/select2.min.js"></script>
<!-- CK Editor -->
<script src="<?php echo BASE_PATH; ?>/public/vendor/adminlte/plugins/ckeditor/ckeditor.js"></script>
<!--<script src="--><?php //echo BASE_PATH ; ?><!--/public/vendor/adminlte/dist/js/pages/dashboard.js"></script>-->
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script>
$(function () {
$('#data-search').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true
});
});
</script>
</body>
</html>
<file_sep>/app/frontend/controller/index_controller.php
<?php
/**
* Created by PhpStorm.
* User: Nimo
* Date: 08/08/2016
* Time: 8:23 CH
*/
include "controller.php";
class index_controller extends controller
{
public function view()
{
$limit = 5;
//load view nao
$this->loadModel('index');
// $this->model la 1 object cua cai model dc load
// truyen du lieu vao view
$this->loadView('index', array(
'result' => [],
'title' => "luong's Blog",
'description' => " Một sản phẩm của Nghĩa nhé!",
'current_page' => isset($_GET['page']) ? $_GET['page'] : 1,
'total_page' => 20
));
}
}<file_sep>/app/frontend/controller/controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/8/16
* Time: 2:53 PM
*/
//use Validation;
class controller
{
public $model;
public $view;
public function loadView($view,$param = array())
{
if (!file_exists(dirname(PATH_APPLICATION) . "/resources/views/" . $view . ".php")) {
header("Location:".BASE_PATH."/p404");
}
extract($param);
require dirname(PATH_APPLICATION) . "/resources/views/__template/header.php";
require dirname(PATH_APPLICATION) . "/resources/views/" . $view . ".php";
require dirname(PATH_APPLICATION) . "/resources/views/__template/footer.php";
}
public function loadAdminView($view,$param = array()){
if (!file_exists(dirname(PATH_APPLICATION) . "/resources/views/admin/" . $view . ".php")) {
header("Location:".BASE_PATH."/p404");
}
extract($param);
require dirname(PATH_APPLICATION) . "/resources/views/admin/" . $view . ".php";
}
public function loadModel($model)
{
$model = strtolower($model) . "_model";
if (!file_exists(PATH_APPLICATION . "/model/" . $model . ".php")) {
header("Location:".BASE_PATH."/p404");
}
include PATH_APPLICATION."/model/".$model.".php";
$this->model = new $model();
}
public function load404()
{
if (!file_exists(dirname(PATH_APPLICATION) . "/resources/views/404/404.php")) {
header("Location:".BASE_PATH."/p404");
}
include dirname(PATH_APPLICATION) . "/resources/views/404/404.php";
}
}<file_sep>/app/backend/controller/register_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/10/16
* Time: 3:14 PM
*/
include dirname(PATH_APPLICATION) . "/libs/Helper.php";
include dirname(PATH_APPLICATION) . "/libs/Validation.php";
class register_controller extends base_controller
{
function view()
{
$this->loadAdminView('register');
}
public function check()
{
// echo "<pre>";var_dump($_POST);echo "</pre>"; exit;
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['repassword']) && isset($_POST['email']) && $_POST['agree'] == 'on') {
// echo "<pre>";var_dump(1);echo "</pre>"; exit;
$username = $_POST['username'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$email = $_POST['email'];
Helper::oldInputResgister($username, $password, $repassword, $email);
$flag = 0; // dat co cho no mau
if (!Validation::isValidUser($username)) {
Helper::setError('username', "Sai dinh dang username");
$flag = 1;
}
if (!Validation::isValidPass($password)) {
Helper::setError('password', "Sai dinh dang password");
$flag = 1;
}
if (!Validation::isValidPass($repassword)) {
Helper::setError('repassword', "Sai dinh dang repassword");
$flag = 1;
}
if (!filter_var($email, FILTER_SANITIZE_EMAIL)) {
Helper::setError('email', "Email khong hop le");
$flag = 1;
}
if ($password != $repassword) {
Helper::setError('repassword', "Hai mat khau khong trung nhau");
$flag = 1;
}
if ($flag == 0) {
$this->loadModel('register_admin');
if ($this->model->checkExist($username, $email)) {
Helper::setError('sys', 'Tài khoản hoặc Email đã tồn tại nhé con chó');
header("Location:" . BASE_PATH . "/admin/register");
} else {
$result = $this->model->add($username, $password, $email);
if ($result) {
$_SESSION['admin'] = $username;
header("Location:" . BASE_PATH . "/admin ");
} else {
Helper::setError('sys', 'Co gi do sai sai');
header("Location:" . BASE_PATH . "/admin/register");
}
}
} else {
header("Location:" . BASE_PATH . "/admin/register");
}
}
}
}<file_sep>/app/model/model.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/8/16
* Time: 2:53 PM
*/
abstract class model
{
protected $conn;
protected $stmt;
function __construct()
{
try {
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
$this->conn = new PDO(getenv('DB_TYPE'). ":host=" . getenv('DB_HOST') . ";dbname=" . getenv('DB_DBNAME') . ";charset=utf8", getenv('DB_USER'), getenv('DB_PASS'), $options);
} catch (PDOException $e) {
die($e->getMessage());
}
}
public function getAll($table)
{
$sql = "SELECT * FROM " . $table;
try {
$this->stmt = $this->conn->prepare($sql);
$this->stmt->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
return $this->stmt->fetchAll();
}
public function getById($table, $id)
{
$sql = "SELECT * FROM " . $table . " WHERE id = ?";
try {
$this->stmt = $this->conn->prepare($sql);
$this->stmt->bindParam(1, $id, PDO::PARAM_INT);
$this->stmt->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
return $this->stmt->fetch();
}
public function deleteById($table, $id)
{
$sql = "DELETE FROM " . $table . " WHERE id = ?";
try {
$this->stmt = $this->conn->prepare($sql);
$this->stmt->bindValue(1, $id, PDO::PARAM_INT);
$this->stmt->execute();
} catch (PDOException $e) {
echo "<pre>";
var_dump($e->getMessage());
echo "</pre>";
exit;
}
if ($this->getById($table, $id) !== false) {
return false;
} else {
return true;
}
}
public function getByName($table, $name, $column)
{
$sql = "SELECT * FROM " . $table . " WHERE " . $column . " = ?";
try {
$this->stmt = $this->conn->prepare($sql);
$this->stmt->bindValue(1, $name);
$this->stmt->execute();
} catch (PDOException $e) {
echo "<pre>";
var_dump($e->getMessage());
echo "</pre>";
exit;
}
$result = $this->stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
}<file_sep>/libs/helper.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/9/16
* Time: 10:17 AM
*/
class Helper
{
static function setError($name, $value)
{
$_SESSION['error'][$name] = $value;
}
static function setInput($name, $value)
{
$_SESSION['input'][$name] = $value;
}
static function setMes($name, $val)
{
$_SESSION['mes'][$name] = $val;
}
static function oldInputLogin($username, $password)
{
self::setInput('old_username', $username);
self::setInput('old_password', $password);
}
static function oldInputResgister($username, $password, $repassword, $email)
{
self::setInput('old_username', $username);
self::setInput('old_password', $password);
self::setInput('old_repassword', $repassword);
self::setInput('old_email', $email);
}
}<file_sep>/resources/views/index.php
<?php //echo "<pre>";var_dump($result);echo "</pre>"; exit; ?>
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('public/img/home-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="site-heading">
<h1><?php echo $title ?></h1>
<hr class="small">
<span class="subheading"><?php echo $description ?></span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<?php foreach ($result as $row) : ?>
<div class="post-preview">
<a href="post/<?php echo $row['id'] ?>">
<h2 class="post-title">
<?php echo $row['title'] ?>
</h2>
</a>
<h4 class="post-subtitle" style="font-weight: 300">
<span><?php echo strip_tags(substr($row['content'], 0, 200)); ?>
<a href="post/<?php echo $row['id'] ?>"> <span class="see-more"><h3> See more</h3></span>
</a>
</span>
</h4>
<p class="post-meta">Posted by <a href="#"><?php echo $row['user_name'] ?></a> on September 24, 2014
</p>
</div>
<hr>
<?php endforeach; ?>
<!-- Pager -->
<ul class="pager">
<?php if ($current_page > $total_page) : ?>
<li class="back_to_home">
<a style="float: left" href="<?php echo BASE_PATH ?>"> Back to homepage </a>
</li>
<?php endif; ?>
<?php if ($current_page > 1 && $current_page <= $total_page) : ?>
<li class="prev">
<a style="float: left" href="?page=<?php echo($current_page - 1) ?>">← Newer Posts </a>
</li>
<?php endif; ?>
<?php if ($current_page < $total_page) : ?>
<li class="next">
<a href="?page=<?php echo($current_page + 1) ?>">Older Posts →</a>
</li>
<?php endif; ?>
</ul>
</div>
</div>
</div>
<hr>
<file_sep>/resources/views/admin/dashboard.php
<?php include '_admin_template/header.php' ?>
<?php //echo "<pre>"; var_dump($newestPosts); echo "</pre>"; exit; ?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!--//cho nay de header nhe-->
<?php include '_admin_template/menu.php'?>
<!-- Left side column. contains the logo and sidebar -->
<?php include '_admin_template/sidebar.php'?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Small boxes (Stat box) -->
<div class="row">
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-aqua">
<div class="inner">
<h3><?php echo $totalPosts; ?></h3>
<p>Tổng số bài đăng</p>
</div>
<div class="icon">
<i class="ion ion-bag"></i>
</div>
<a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-green">
<div class="inner">
<h3>53<sup style="font-size: 20px">%</sup></h3>
<p>Bounce Rate</p>
</div>
<div class="icon">
<i class="ion ion-stats-bars"></i>
</div>
<a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3><?php echo $totalUsers; ?></h3>
<p>Tổng số thành viên</p>
</div>
<div class="icon">
<i class="ion ion-person-add"></i>
</div>
<a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-red">
<div class="inner">
<h3>65</h3>
<p>Unique Visitors</p>
</div>
<div class="icon">
<i class="ion ion-pie-graph"></i>
</div>
<a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
</div>
<!-- /.row -->
<!-- Main row -->
<div class="row">
<!-- Left col -->
<section class="col-sm-12 ">
<div class="box">
<div class="box-header">
<h3 class="box-title">Responsive Hover Table</h3>
<div class="box-tools">
<form action="<?php echo BASE_PATH ; ?>/admin/search" method="get">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="s" class="form-control pull-right"
placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="fa fa-search"></i>
</button>
</div>
</div>
</form>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Title</th>
<th>Date</th>
<th>Category</th>
<th>Author</th>
</tr>
<?php foreach ($newestPosts as $row) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td>
<a href="<?php echo BASE_PATH; ?>/admin/post/edit/<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</td>
<td><?php echo $row['created_time']; ?></td>
<td>
<a href="<?php echo BASE_PATH; ?>admin/category/edit/<?php echo $row['category_ID']; ?>">
<span class="label label-success"><?php echo $row['category_name']; ?></span></a>
</td>
<td><?php echo $row['user_name']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</section>
<!-- /.Left col -->
<!-- right col (We are only adding the ID to make the widgets sortable)-->
<section class="col-sm-6">
<!-- quick email widget -->
<div class="box box-info">
<div class="box-header">
<i class="fa fa-envelope"></i>
<h3 class="box-title">Quick Email</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<button type="button" class="btn btn-info btn-sm" data-widget="remove"
data-toggle="tooltip" title="Remove">
<i class="fa fa-times"></i></button>
</div>
<!-- /. tools -->
</div>
<div class="box-body">
<form action="#" method="post">
<div class="form-group">
<input type="email" class="form-control" name="emailto" placeholder="Email to:">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" placeholder="Subject">
</div>
<div>
<textarea class="textarea" placeholder="Message"
style="width: 100%; height: 125px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
</form>
</div>
<div class="box-footer clearfix">
<button type="button" class="pull-right btn btn-default" id="sendEmail">Send
<i class="fa fa-arrow-circle-right"></i></button>
</div>
</div>
</section>
<!-- right col -->
</div>
<!-- /.row (main row) -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.6
</div>
<strong>Copyright © 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights
reserved.
</footer>
</div>
<!-- ./wrapper -->
<?php include '_admin_template/footer.php' ?>
<file_sep>/app/backend/controller/post_controller.php
<?php
/**
* Created by PhpStorm.
* User: Nimo
* Date: 10/08/2016
* Time: 9:41 CH
*/
include dirname(PATH_APPLICATION) . "/libs/Helper.php";
class post_controller extends base_controller
{
function create()
{
if (isset($_SESSION['admin']) && isset($_SESSION['admin_id'])) {
if (isset($_POST['title']) && isset($_POST['content']) && isset($_POST['category']) && isset($_POST['status'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$category = $_POST['category'];
$status = $_POST['status'];
$status = filter_var($status, FILTER_SANITIZE_NUMBER_INT);
$category = filter_var($category, FILTER_SANITIZE_NUMBER_INT);
// var_dump(empty($status));
if (empty($title) || empty($content) || empty($status) || empty($category)) {
Helper::setError('edit', "Something wrong");
} else {
$this->loadModel('post_admin');
$result = $this->model->insertPost($title, $content, $category, $status);
if ($result != false) {
header('location:' . BASE_PATH . '/admin/post/edit/' . $result);
} else {
Helper::setError('insert', "Không thể thêm bài viết");
}
}
} else {
$this->loadModel('post_admin');
$this->loadAdminView('create', array(
'listCategories' => $this->model->getListCategories()
));
}
} else {
header('location:' . BASE_PATH . '/admin/login ');
}
}
function edit($id)
{
if (isset($_SESSION['admin']) && isset($_SESSION['admin_id'])) {
if (isset($_POST['title']) && isset($_POST['content']) && isset($_POST['category']) && isset($_POST['status'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$category = $_POST['category'];
$status = $_POST['status'];
$status = filter_var($status, FILTER_SANITIZE_NUMBER_INT);
$category = filter_var($category, FILTER_SANITIZE_NUMBER_INT);
if (empty($title) || empty($content) || empty($status) || empty($category)) {
Helper::setError('edit', "Something wrong");
} else {
$this->loadModel('post_admin');
$result = $this->model->updatePost($id, $title, $content, $category, $status);
if ($result != false) {
Helper::setMes('success', "Update thành công rồi nhé cứng!");
header('location:' . BASE_PATH . '/admin/post/edit/' . $id);
} else {
Helper::setError('edit', "Không thể cập nhật bài viết");
}
}
} else {
$this->loadModel('post_admin');
$this->model->getPostById($id);
$this->loadAdminView('edit', array(
'listCategories' => $this->model->getListCategories(),
'oldData' => $this->model->getPostById($id)
));
// $this->loadModel()
}
} else {
header('location:' . BASE_PATH . '/admin/login ');
}
}
function view()
{
// echo "<pre>";var_dump("DCm sao the");echo "</pre>"; exit;
if (isset($_SESSION['admin']) && isset($_SESSION['admin_id'])) {
$this->loadModel('post_admin');
$this->loadAdminView('list_posts', array(
'data' => $this->model->getAllPost(),
));
// $this->loadModel()
} else {
header('location:' . BASE_PATH . '/admin/login ');
}
}
// xu ly load anh
// public function ckeditor($a = 0){
// include dirname(PATH_APPLICATION).'/public/vendor/AdminLTE/plugins/ckeditor/plugins/imageuploader/imgbrowser.php';
// }
}<file_sep>/app/model/index_model.php
<?php
/**
* Created by PhpStorm.
* User: Nimo
* Date: 08/08/2016
* Time: 10:05 CH
*/
include 'model.php';
class index_model extends model
{
public $table = "posts";
public function getAll($table = null)
{
return parent::getAll($this->table); // TODO: Change the autogenerated stub
}
public function getTotalPost()
{
$sql = "SELECT count(*) as total_post FROM " . $this->table;
$this->stmt = $this->conn->prepare($sql);
$this->stmt->execute();
return $this->stmt->fetch();
// return $this->conn->
}
public function getData($limit = 5, $page = 1)
{
$sql = "SELECT p.*, u.user_name FROM posts p INNER JOIN users u ON p.user_ID = u.id ORDER BY p.created_time DESC";
if ($limit !== 'all') {
$sql .= " LIMIT " . (($page - 1) * $limit) . "," . $limit;
}
// echo "<pre>";var_dump($sql);echo "</pre>"; exit;
$this->stmt = $this->conn->prepare($sql);
$this->stmt->execute();
return $this->stmt->fetchAll();
}
}<file_sep>/libs/config.php
<?php
class config{
/**
* con constructor.
*/
public function __construct()
{
}
}<file_sep>/app/backend/controller/login_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/10/16
* Time: 10:49 AM
*/
//include dirname(PATH_APPLICATION) . "/libs/Validation.php";
//include dirname(PATH_APPLICATION) . "/libs/Helper.php";
class login_controller extends base_controller
{
public function view()
{
if (isset($_SESSION['admin'])) { // kiem tra xem session hay khong?
header("Location:" . BASE_PATH . "/admin");
} else {
$this->loadAdminView('login');
}
}
public function check()
{
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
Helper::oldInputLogin($username, $password);
$flag = 0;
if (!Validation::isValidUser($username)) {
Helper::setError('username', " Chỉ nhận 5->17 kí tự thôi");
$flag = 1;
}
if (!Validation::isValidPass($password)) {
Helper::setError('password', '<PASSWORD>');
$flag = 1;
}
if ($flag != 0) {
header("Location:" . BASE_PATH . "/admin/login");
} else {
$this->loadModel('login_admin');
// echo "<pre>"; var_dump($this->model->checkLogin($username,$password)); echo "</pre>"; exit;
if ($this->model->checkLogin($username, $password)) {
// Helper::setMes('success', "Đăng nhập thành công");
$_SESSION['admin'] = $username;
$_SESSION['admin_id'] = $this->model->getIdByName($username)['id'];
unset($_SESSION['input']);
// unset($_SESSION['admin_id']);
header("Location:" . BASE_PATH . "/admin ");
} else {
Helper::setError('system', "Tài khoản mật khẩu không đúng ");
header("Location:" . BASE_PATH . "/admin/login");
}
}
} else {
header("Location:" . BASE_PATH . "/admin/login");
}
}
public function logout()
{
unset($_SESSION['admin']);
unset($_SESSION['admin_id']);
header('Location:' . BASE_PATH . '/admin/login');
}
}<file_sep>/app/frontend/controller/about_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 11/24/16
* Time: 12:05
*/
include 'controller.php';
class about_controller extends controller
{
function view()
{
$this->loadView('about-coroi');
}
}<file_sep>/resources/views/admin/edit.php
<?php include '_admin_template/header.php' ?>
<?php //echo "<pre>"; var_dump($newestPosts); echo "</pre>"; exit; ?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!--//cho nay de header nhe-->
<?php include '_admin_template/menu.php' ?>
<!-- Left side column. contains the logo and sidebar -->
<?php include '_admin_template/sidebar.php' ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box box-info">
<div class="box-body">
<form method="post" action="">
<div class="row" style="margin-bottom: 10px;">
<div class="col-sm-12">
<div class="toolbar">
<?php if (isset($_SESSION['error'])) : ?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×
</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
<ul>
<?php foreach ($_SESSION['error'] as $row): ?>
<li> <?php echo $row; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if (isset($_SESSION['mes'])) : ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×
</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
<ul>
<?php foreach ($_SESSION['mes'] as $row): ?>
<li> <?php echo $row; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<a href="<?php echo BASE_PATH; ?>/admin/posts">
<button type="button" class="btn btn-default">
<i class="fa fa-angle-left"></i> Back
</button>
</a>
<a href="#" class="pull-right">
<button type="submit" class="btn btn-success">
<i class="fa fa-check"></i> Chỉnh sửa hàng
</button>
</a>
</div>
</div>
</div>
<div class="row">
<div class="col-md-9 col-sm-9">
<div class="form-group">
<label for="title">Tiêu đề <span class="required">*</span></label>
<input type="text" class="form-control" required name="title" id="title"
value="<?php echo $oldData['title']; ?>"
autocomplete="off">
</div>
<div class="form-group">
<label for="full_text">Nội dung*</label>
<textarea id="editor1" class="form-control" required
name="content"><?php echo $oldData['content']; ?></textarea>
</div>
</div>
<div class="col-md-3 col-sm-3">
<div class="form-group">
<label for="published">Trạng thái*</label>
<select id="published" class="form-control" required name="status">
<option value="1" <?php if ($oldData['status'] == 1) echo "selected" ?> >
Bản nháp
</option>
<option value="2" <?php if ($oldData['status'] == 2) echo "selected" ?> >
Hay là thật luôn đi
</option>
</select>
</div>
<div class="form-group">
<label for="category">Danh mục*</label>
<?php //echo "<pre>";var_dump($listCategories);echo "</pre>"; exit; ?>
<div id="category">
<select class=" form-control" name="category" required>
<option selected value="">Chọn một chủ đề</option>
<?php foreach ($listCategories as $row) : ?>
<option
value="<?php echo $row['id']; ?>" <?php if ($oldData['cate_id'] == $row['id']) echo "selected" ?> ><?php echo $row['category_name']; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- ./row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.6
</div>
<strong>Copyright © 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights
reserved.
</footer>
</div>
<!-- ./wrapper -->
<?php unset($_SESSION['error'], $_SESSION['mes']) ?>
<?php include '_admin_template/footer.php' ?>
<script>
var roxyFileman = '<?php echo BASE_PATH?>/public/fileman/index.html';
$(function () {
CKEDITOR.replace('editor1', {
filebrowserBrowseUrl: roxyFileman,
filebrowserImageBrowseUrl: roxyFileman + '?type=image',
removeDialogTabs: 'link:upload;image:upload'
});
});
</script><file_sep>/resources/views/admin/search.php
<?php include '_admin_template/header.php'; ?>
<body class="hold-transition skin-blue sidebar-mini">
<!-- Automatic element centering -->
<?php include '_admin_template/menu.php'?>
<?php include '_admin_template/sidebar.php'?>
<div class="wrapper">
<div class="content-wrapper">
<section class="content-header">
<h1>
Users
<small></small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<section class="content">
<div class="lockscreen-wrapper" style="margin-top: 0">
<div class="lockscreen-logo">
<a href="../../index2.html"><b>Nghĩa's</b>Blog</a>
</div>
<!-- User name -->
<div class="lockscreen-name"><NAME></div>
<!-- START LOCK SCREEN ITEM -->
<div class="lockscreen-item">
<!-- lockscreen image-->
<div class="lockscreen-image" style="top: -18px;">
<img src="<?php echo BASE_PATH ; ?>/public/vendor/AdminLTE/dist/img/user1-128x128.jpg" alt="User Image">
</div>
<!-- /.lockscreen-image -->
<!-- lockscreen credentials (contains the form) -->
<form class="lockscreen-credentials" action="<?php echo BASE_PATH ; ?>/admin/search">
<div class="input-group">
<input type="text" class="form-control input-lg" placeholder="Keyword" name="s">
<div class="input-group-btn">
<button type="submit" class="btn"><i class="fa fa-search text-muted"></i></button>
</div>
</div>
</form>
<!-- /.lockscreen credentials -->
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Data Table With Full Features</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="data-search" class="table table-bordered table-striped">
<thead>
<tr>
<th>id</th>
<th>Tít tờ le</th>
<th>Ca te go ri </th>
<th>Au tho</th>
<th>x</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $row) : ?>
<tr>
<td><?php echo $row['id'] ; ?></td>
<td><a href="<?php echo BASE_PATH ; ?>/admin/post/edit/<?php echo $row['id'] ; ?>"><?php echo $row['title'] ; ?></a>
</td>
<td><span class="label label-success"><?php echo $row['category_name']; ?></span></td>
<td> <?php echo $row['author'] ; ?></td>
<td>X</td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>id</th>
<th>Tít tờ le</th>
<th>Ca te go ri </th>
<th>Au tho</th>
<th>x</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</body>
<!-- /.center -->
<?php include '_admin_template/footer.php'?>
<file_sep>/app/backend/controller/dashboard_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/10/16
* Time: 10:08 AM
*/
class dashboard_controller extends base_controller
{
function view(){
if(isset($_SESSION['admin'])){
$this->loadModel('dashboard_admin');
$this->loadAdminView('dashboard',array(
'totalPosts' => $this->model->getTotalPosts(),
'totalUsers' => $this->model->getTotalUsers(),
'newestPosts' => $this->model->getNewestPosts(),
));
// unset($_SESSION['admin']);
}else{
header("Location:".BASE_PATH."/admin/login");
}
}
}<file_sep>/app/frontend/controller/p404_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/9/16
* Time: 10:20 AM
*/
class p404_controller extends base_controller
{
public function view(){
$this->load404();
}
}<file_sep>/resources/views/admin/list_users.php
<?php include '_admin_template/header.php' ?>
<?php //echo "<pre>"; var_dump($newestPosts); echo "</pre>"; exit; ?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!--//cho nay de header nhe-->
<?php include '_admin_template/menu.php'?>
<!-- Left side column. contains the logo and sidebar -->
<?php include '_admin_template/sidebar.php'?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Users
<small></small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Main row -->
<div class="row">
<!-- Left col -->
<section class="col-sm-12 ">
<?php if(isset($_SESSION['mes']['delete'])) : ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Alert!</h4>
<?php echo $_SESSION['mes']['delete'] ; ?>
</div>
<?php endif; ?>
<div class="box">
<div class="box-header">
<h3 class="box-title">Danh sách người dùng</h3>
<div class="box-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="table_search" class="form-control pull-right"
placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Tên Người dùng</th>
<th>Email</th>
<th>Ngày tham gia</th>
<th>Cập nhật</th>
<th>Xóa</th>
</tr>
<!-- --><?php //var_dump($data) ?>
<?php foreach ($data as $row) : ?>
<!-- --><?php //echo "<pre>";var_dump($row);echo "</pre>"; exit; ?>
<tr>
<td><?php echo $row['id'] ; ?></td>
<td><a href="<?php echo BASE_PATH ; ?>/admin/user/edit/<?php echo $row['id'] ; ?>"><?php echo $row['user_name'] ; ?></a></td>
<td><?php echo $row['user_email'] ; ?></td>
<td><?php echo $row['created_time'] ; ?></td>
<td><a href="<?php echo BASE_PATH ; ?>/admin/user/edit/<?php echo $row['id'] ; ?>"><button class="btn btn-primary">Sửa</button></a> </td>
<td><a href="<?php echo BASE_PATH ; ?>/admin/user/delete/<?php echo $row['id'] ; ?>"><button class="btn btn-danger">Xóa</button></a> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</section>
<!-- /.Left col -->
</div>
<!-- /.row (main row) -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.6
</div>
<strong>Copyright © 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights
reserved.
</footer>
</div>
<!-- ./wrapper -->
<?php unset($_SESSION['mes']); ?>
<?php include '_admin_template/footer.php' ?>
<file_sep>/resources/views/admin/list_posts.php
<?php include '_admin_template/header.php' ?>
<?php //echo "<pre>"; var_dump($newestPosts); echo "</pre>"; exit; ?>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!--//cho nay de header nhe-->
<?php include '_admin_template/menu.php'?>
<!-- Left side column. contains the logo and sidebar -->
<?php include '_admin_template/sidebar.php'?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>Control panel</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">Dashboard</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Main row -->
<div class="row">
<!-- Left col -->
<section class="col-sm-12 ">
<div class="box">
<div class="box-header">
<h3 class="box-title">Responsive Hover Table</h3>
<div class="box-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="table_search" class="form-control pull-right"
placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Title</th>
<th>Date</th>
<th>Category</th>
<th>Author</th>
</tr>
<?php foreach ($data as $row) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td>
<a href="<?php echo BASE_PATH; ?>/admin/post/edit/<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</td>
<td><?php echo $row['created_time']; ?></td>
<td>
<a href="<?php echo BASE_PATH; ?>admin/category/edit/<?php echo $row['category_ID']; ?>">
<span class="label label-success"><?php echo $row['category_name']; ?></span></a>
</td>
<td><?php echo $row['user_name']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</section>
<!-- /.Left col -->
</div>
<!-- /.row (main row) -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.6
</div>
<strong>Copyright © 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights
reserved.
</footer>
</div>
<!-- ./wrapper -->
<?php include '_admin_template/footer.php' ?>
<file_sep>/app/backend/controller/user_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/17/16
* Time: 9:17 AM
*/
class user_controller extends base_controller
{ //De hien thi ra danh sach nguoi dung
function view()
{
if (isset($_SESSION['admin'])) {
//goi cai model day ra (user_admin_model)
$this->loadModel('user_admin');
$data = $this->model->getAllUser();
// echo "<pre>";var_dump($data);echo "</pre>"; exit;
$this->loadAdminView('list_users', array(
'data' => $data
));// load view de xem co load dc view hay khong?
}
}
function create()
{
}
function edit($id) // load du lieu cua nguoi dung + form de chinh sua
{
if (isset($_SESSION['admin'])) {
$this->loadModel('user_admin');
$result = $this->model->getUserById($id);
// echo "<pre>";var_dump($result);echo "</pre>"; exit;
$this->loadAdminView('edit_user', array(
'data' => $result
));
} else {
header('location:' . BASE_PATH . '/admin/login');
}
}
function update($id)
{ // chinh sua thong tin cua nguoi dung vao database
if (isset($_SESSION['admin'])) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// echo "<pre>";var_dump($_POST);echo "</pre>"; exit;
if (isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['repassword'])) {
// dieu kien dung o day
$flag = 1; // Co` dung la 1 con khac 1 la sai
// Kiem tra dau vao cua username
if (Validation::isValidUser($_POST['username'])) {
$username = $_POST['username'];
} else {
$flag = 0;
Helper::setError('username', "Username deo dung chuan");
}
//Kiem tra dau vao cua email
if (filter_var($_POST['email'], FILTER_SANITIZE_EMAIL)) {
$email = $_POST['email'];
} else {
$flag = 0;
Helper::setError('email', "Email nhu cec");
}
// Kiem tra password
if (Validation::isValidPass($_POST['password'])) {
$password = $_POST['password'];
} else {
$flag = 0;
Helper::setError('password', '<PASSWORD>');
}
//Kiem tra repassword
if (Validation::isValidPass($_POST['repassword'])) {
$repassword = $_POST['repassword'];
} else {
$flag = 0;
Helper::setError('repassword', 'Repassword danh ngu nhu cho');
}
if ($_POST['password'] !== $_POST['repassword']) {
$flag = 0;
Helper::setError('repassword', "Khong biet danh mat khau giong nhau a");
}
if ($flag != 1) {
header('location:' . BASE_PATH . '/admin/user/edit/' . $id . '');
} else {
$this->loadModel('user_admin');
$data = $this->model->getUserById($id);
$check = 1;
// Kiem tra username ton tai
if ($username !== $data['user_name']) {
if ($this->model->checkUserExist($username)) {
$check = 0; // neu co thang nao day co username giong roi thi chuyen co
Helper::setError('username', "Trung roi username nhe!");
}
}
// Kiem tra email ton tai hay khong?
if ($email !== $data['user_email']) {
if ($this->model->checkEmailExist($email)) {
$check = 0;
Helper::setError('email', "Trung roi email nhe!");
}
}
if ($check != 1) {
header("location:" . BASE_PATH . "/admin/user/edit/" . $id);
} else {
$password = password_hash($password,PASSWORD_BCRYPT);
$result = $this->model->updateUser($username, $password, $email, $id);
if ($result) {
Helper::setMes('update', "Thanh cong gan la thanh roi nhe");
} else {
Helper::setError('update', "XIt roi, deo hieu vi sao");
}
header('location:' . BASE_PATH . '/admin/user/edit/' . $id);
}
//
}
} else {
// dieu kien sai o day
die("Thieu input roi anh");
}
} else {
die('Wrong request method');
}
} else {
header("Location:" . BASE_PATH . "/admin/login");
}
}
function delete($id) // xoa nguoi dung
{
if (isset($_SESSION['admin'])) {
$this->loadModel('user_admin');
$result = $this->model->deleteUserById($id);
if ($result) {
// echo "<pre>";var_dump("Xoa duoc roi nhe");echo "</pre>"; exit;
Helper::setMes('delete', "Em đã xóa thành công thằng có ID là " . $id . " ");
header('location:' . BASE_PATH . '/admin/user');
} else {
echo "<pre>";
var_dump("Xoa xit roi nhe");
echo "</pre>";
exit;
}
} else {
header('location:' . BASE_PATH . '/admin/login'); // Neu khong phai la admin thi day ra trang dang ki
}
}
}<file_sep>/app/backend/controller/search_controller.php
<?php
/**
* Created by PhpStorm.
* User: nghia
* Date: 8/13/16
* Time: 9:34 AM
*/
class search_controller extends base_controller
{
function view()
{
if (!isset($_SESSION['admin'])) {
header("location:" . BASE_PATH . "/admin/login");
} else {
if (!isset($_GET['s'])) {
$this->loadAdminView('search');
} else {
$key = $_GET['s'];
$this->loadModel('search_admin');
$result = $this->model->getDataByKey($key);
$this->loadAdminView('search',array(
'data' => $result
));
}
}
}
}<file_sep>/resources/views/detail-post.php
<?php //echo "<pre>";var_dump($post);echo "</pre>"; exit; ?>
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('<?php echo BASE_PATH ?>/public/img/post-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-heading">
<h1><?php echo $post['title'] ?></h1>
<h2 class="subheading"><?php echo substr($post['content'],0,50)?></h2>
<span class="meta">Đăng bởi <a href="#"><?php echo $post['user_name'] ?></a> vào hồi <?php echo $post['created_time']?> trong <?php echo $post['category_name'] ?></span>
</div>
</div>
</div>
</div>
</header>
<!-- Post Content -->
<article>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<?php echo $post['content'] ; ?>
</div>
</div>
</div>
</article>
<hr>
<file_sep>/index.php
<?php
session_start();
//echo "<pre>";var_dump($_SESSION);echo "</pre>";
/*
* Created by PhpStorm.
* User: Nimo
* Date: 07/08/2016
* Time: 8:01 CH
*/
require __DIR__ . '/vendor/autoload.php';
require "config.php";
//$admin_pattern = "/(\/admin).*$/";
/*
* Cai dm tai thang xammp no build nhu the nen phai chiu nhe.
* con de chay binh thuong thi no phai la
* $admin_pattern = "/^(\/admin).*$/";
* nhe
*/
//echo "<pre>";var_dump(Validation::isValidUser("ahihihihih"));echo "</pre>"; exit;
$dotenv = new \Dotenv\Dotenv(__DIR__);
$dotenv->load();
$app = new Libs\Application();
//if (preg_match($admin_pattern, $_SERVER['REQUEST_URI'])) {
// $app = new application_admin();
//} else {
//
// $app = new application();
//
//
//}
//
//
<file_sep>/resources/views/404/404.php
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE HTML>
<html>
<head>
<title>404 NOT FOUND</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="<?php echo BASE_PATH ?>/public/vendor/404/css/style.css">
</head>
<body>
<div class="wrap">
<h1>Nghia's Blog</h1>
<div class="banner">
<img src="<?php echo BASE_PATH ?>/public/vendor/404/images/banner.png" alt="" />
</div>
<div class="page">
<h2>Không tìm thấy trang thì phải làm sao</h2>
</div>
<div class="footer">
<p>Design by <a href="<?php echo BASE_PATH; ?>">Nghia's Blog</a></p>
</div>
</div>
</body>
</html>
<file_sep>/resources/views/about.php
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('<?php echo BASE_PATH ?>/public/img/about-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Giới thiệu về anh Nghĩa á!</h1>
<hr class="small">
<span class="subheading">Ngay dưới nhé.</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>Nghĩa trang liệt sỹ Trường Sơn tọa lạc trên khu đồi Bến Tắt, cạnh đường quốc lộ 15, thuộc địa phận xã
Vĩnh Trường, huyện Gio Linh; cách trung tâm tỉnh lỵ (thị xã Đông Hà) khoảng 38km về phía Tây bắc; cách
quốc lộ 1A (ở đoạn thị trấn huyện lỵ Gio Linh) chừng hơn 20km về phía Tây bắc.
</p>
<p>Sau ngày đất nước thống nhất, Trung ương Đảng và Bộ Quốc phòng đã phê chuẩn dự án xây dựng nghĩa trang
liệt sỹ Trường Sơn tại địa bàn tỉnh Quảng Trị làm nơi tưởng niệm, tôn vinh những người con thân yêu của
tổ quốc đã anh dũng hy sinh xương máu của mình trên các nẻo đường Trường Sơn vì sự nghiệp giải phóng dân
tộc. Nghĩa trang được khởi công xây dựng vào ngày 24/10/1975 và hoàn thành vào ngày 10/4/1977. Chỉ huy
xây dựng là Bộ tư lệnh sư đoàn 559 với sự tham gia của hơn 40 đơn vị bộ đội chủ lực và bộ đội địa
phương.
</p>
<p> Ngoài ra còn có tổ công nhân chuyên khắc chữ vào bia đá xã Hoà Hải, huyện Hòa Vang, tỉnh Quảng Nam.</p>
</div>
</div>
</div>
<hr>
| 2655313741b48166bce540cc84056d8134ddd134 | [
"PHP"
] | 29 | PHP | nghiatv/mvc-routes | e08b718e247ce2570d47e985f7532f5352deaf73 | 51862b6aa276a510e8c979f14570fff781a2f5a4 | |
refs/heads/master | <repo_name>MusicBoxOUYA/MusicBoxContent<file_sep>/server.js
var express = require("express"),
app = express(),
http = require("http");
app.get("/", function(req,res)
{
res.send("I'm up!");
});
app.use("/resources", express.static("resources"));
app.listen(process.env.PORT||3000);<file_sep>/resources/js/table.js
function Table(col, header){
this.columns = cloneArray(col);
this.names = cloneArray(col);
this.tableProperties = {"table":{}, "head-row":{}, "head-data":{},"body-row":{}, "body-data":{}};
this.columnProcesses = [];
this.headerProperties = [];
this.columnProperties = [];
this.headerProcesses = [];
this.advancedColumnProcesses = [];
if(header != undefined){
for(var i = 0; header.length > i; i++){
this.names[i] = header[i];
}
}
this.setColumns = function(col){
this.columns = cloneArray(col);
}
this.setHeaders = function(header){
this.names = cloneArray(this.columns);
for(var i = 0; header.length > i; i++){
this.names[i] = header[i];
}
}
this.setProperties = function(type, prop){
setObject(this.tableProperties[type], prop);
}
this.addColumnProperty = function(col, proc){
this.columnProperties[col] = proc;
}
this.addHeaderProcessor = function(col, proc){
this.headerProcesses[col] = proc;
}
this.addColumnProcessor = function(col, proc){
this.columnProcesses[col] = proc;
}
this.addAdvancedColumnProcessor = function(col, proc){
this.advancedColumnProcesses[col] = proc;
}
this.buildTable = function(rows){
var table = createElement("table", this.tableProperties["table"]);
var head = createElement("thead");
var headRow = createElement("tr", this.tableProperties["head-row"]);
var body = createElement("tbody");
for(row in this.names){
var properties = cloneArray(this.tableProperties["head-data"]);
var data = this.names[row];
for (var attrname in this.columnProperties[this.columns[row]]) { properties[attrname] = this.columnProperties[this.columns[row]][attrname]; }
console.log(properties);
var header = createElement("th", properties);
if(this.columns[row] in this.headerProcesses){
data = this.headerProcesses[this.columns[row]](data);
}
if(typeof data == "object")
insertElementAt(data, header);
else
header.innerHTML = data;
insertElementAt(header, headRow);
}
for(row in rows){
var properties = cloneArray(this.tableProperties["body-data"]);
var bodyRow = createElement("tr", this.tableProperties["body-row"]);
var workingRow = rows[row];
for(col in this.columns){
console.log(this.tableProperties["body-data"]);
var properties = cloneArray(this.tableProperties["body-data"]);
var data = workingRow[this.columns[col]];
for (var attrname in this.columnProperties[this.columns[col]]) { properties[attrname] = this.columnProperties[this.columns[col]][attrname]; }
console.log(properties);
var cell = createElement("td", properties);
if(this.columns[col] in this.columnProcesses){
data = this.columnProcesses[this.columns[col]](data);
}
if(this.columns[col] in this.advancedColumnProcesses){
data = this.advancedColumnProcesses[this.columns[col]](workingRow);
}
if(typeof data == "object")
insertElementAt(data, cell)
else
cell.innerHTML = data;
insertElementAt(cell, bodyRow);
}
insertElementAt(bodyRow, body);
}
insertElementAt(headRow, head);
insertElementAt(head, table);
insertElementAt(body, table);
return table;
}
return this;
}
<file_sep>/resources/js/queue.js
function call(){
request("api/queue", "", function(result){
buildQueueTable($("#queue-list"), JSON.parse(result));
}, function(){
stopCall();
$("#connection-error-alert").modal({
keyboard: false,
backdrop:"static"
}).modal("show");
});
}
function startCall(){
window.console&&console.log("Starting Call");
callID = setInterval(call, 1000);
}
function stopCall(){
window.console&&console.log("Stopping Call");
clearInterval(callID);
}
$( document ).ready(function(){
call();
startCall();
$("#connection-error-alert").on("hidden.bs.modal", function () {
startCall();
})
});
<file_sep>/package.json
{
"name": "MusicBox_ContentServer",
"description": "Metadata lookup for MusicBox",
"version": "1.0.0",
"dependencies": {
"express": "*",
"xml2js": "*",
"memjs": "*"
}
}<file_sep>/resources/js/bridge.js
function request(url, sendData, callBack, errorCallBack){
errorCallBack = typeof errorCallBack === "function" ? errorCallBack : function(){};
$.ajax({
url:url,
type:"GET",
data:sendData,
success:function(result){
callBack(result)
},
error:function(result){
errorCallBack(result);
}
})
}
function likeSong(id, parentEle) {
var cookie = $.cookie("songs");
var songs = cookie != null ? JSON.parse(cookie) : Array();
songs.push(id);
$.cookie("songs", JSON.stringify(songs), 1);
request("api/like", "song="+id, function(data){
console.log("Liking song");
});
$(".like-dislike").attr("disabled", "disabled");
}
function dislikeSong(id, parentEle) {
var cookie = $.cookie("songs");
var songs = cookie != null ? JSON.parse(cookie) : Array();
songs.push(id);
$.cookie("songs", JSON.stringify(songs), 1);
request("api/dislike", "song="+id, function(data){
console.log("Disliking song");
});
$(".like-dislike").attr("disabled", "disabled");
}
function queueSong(id){
request("api/queue", "song="+id, function(data){
console.log(JSON.parse(data))
});
}
function buildAlbumArt(imgEle, ccEle, data){
var source = data.song.art;
if(imgEle.data("src") != source) {
imgEle.fadeOut("slow", function() {
$(this).data("src", source).attr("src", source).load(function(){
$(this).fadeIn();
});
});
}
}
function buildSongInfo(parentEle, data){
var name = createElement("h2", {"class":"song-title"}, data.song.title);
var div = createElement("div", {"class":"row"});
var p = createElement("p", {"class":"col-xs-10"});
var artist = createElement("span", {"class":"song-artist"}, data.song.artist);
var br = createElement("br");
var album = createElement("span", {"class":"song-album"}, data.song.album);
var likeHolder = createElement("div", {"class":"col-xs-2"});
var likes = createElement("span", null, Math.abs(data.song.score));
var space = createText(" ");
var icon = createElement("span", {"class":"glyphicon glyphicon-thumbs-" + (data.song.score >= 0 ? "up":"down") });
parentEle.html("");
insertElementAt(name, parentEle[0]);
insertElementAt(p, div);
insertElementAt(likeHolder, div);
insertElementAt(likes, likeHolder);
insertElementAt(space, likeHolder);
insertElementAt(icon, likeHolder);
insertElementAt(div, parentEle[0]);
insertElementAt(album, p);
insertElementAt(br, p);
insertElementAt(artist, p);
}
function buildSongTime(parentEle, data){
var currentMinutes = Math.floor((data.position/1000)/60);
var currentSeconds = Math.floor((data.position/1000)%60);
if(currentSeconds < 10){
currentSeconds = "0" + currentSeconds;
}
var durationMinutes = Math.floor((data.duration/1000)/60);
var durationSeconds = Math.floor((data.duration/1000)%60);
if(durationSeconds < 10){
durationSeconds = "0" + durationSeconds;
}
var currentTimeParent = createElement("div", {"class":"small-1 columns"});
var currentTime = createElement("span", {"class":""}, currentMinutes + ":" + currentSeconds);
var durationTime = createElement("span", {"class":""}, durationMinutes + ":" + durationSeconds);
var percent = ((data.position/data.duration)*100);
var progressPercent = createElement("div", {"class":"progress-bar progress-bar-info", "role":"progressbar","style":"width: " + percent + "%"});
parentEle.html("");
insertElementAt(currentTime,parentEle[0]);
insertElementAt(progressPercent,parentEle[1]);
insertElementAt(durationTime,parentEle[2]);
}
function buildUpNext(parentEle, data){
parentEle.html("");
if ( data.length == 0 )
return;
var p = createElement("p");
var title = createElement("b", null, "Up Next: ");
var artist = createElement("span", null, data[0].title);
var album = createElement("span", null, data[0].artist);
var dash = createText(" - ");
insertElementAt(title, p);
insertElementAt(artist, p);
insertElementAt(dash, p);
insertElementAt(album, p);
if(data.length != 0)
insertElementAt(p, parentEle[0]);
}
function setButtonSongId(parentEle, data){
var cookie = $.cookie("songs");
var songs = cookie != null ? JSON.parse(cookie) : Array();
if($.inArray(data.song.id, songs) == -1) {
parentEle.removeAttr("disabled");
parentEle.data("song-id", data.song.id);
}
else {
parentEle.attr("disabled", "disabled");
parentEle.data("song-id", 0);
}
}
function buildQueueTable(parentEle, data){
var table = new Table(["order", "title", "album", "artist", "score"], ["#", "Song", "Album", "Artist", "+1"]);
parentEle.html("");
var counter = 1;
table.addAdvancedColumnProcessor("order", function(data){
return counter++;
});
table.setProperties("table", {"class":"table table-condensed table-striped"});
var html = table.buildTable(data);
insertElementAt(html, parentEle[0]);
}
function buildSongTable(parentEle, res){
var table = new Table(["title", "score", "add"], ["Song", "+1", ""]);
parentEle.html("");
table.setProperties("table", {"class":"table table-condensed table-striped"});
table.addAdvancedColumnProcessor("add", function(data){
var button = createElement("button", {"class":"btn btn-info btn-sm pull-right"}, "Add To Queue");
$(button).click(function(){
$(this).attr("disabled", "disabled").delay(10000).queue(function(next){
$(this).removeAttr("disabled");
next();
});
console.log("queuing song " + data["id"]);
queueSong(data["id"]);
});
return button;
});
var html = table.buildTable(res);
insertElementAt(html, parentEle[0]);
}
function buildAlbumList(parentEle, data){
var albumSongs = [];
parentEle.html("");
var rows = [];
var currentRow = 0;
for(album in data){
var div = createElement("div", {"class":"col-sm-3"});
var holder = createElement("div", {"class":"album-holder"});
var holderInner = createElement("div", {"class":"place-holder album-holder-inner"})
var a = createElement("a", {"href":"#", "data-toggle":"modal", "data-target":"#album-song-list", "data-album-id":album})
var img = createElement("img", {"src":"http://placehold.it/250x250", "class":"img-responsive album-art loading"});
var info = createElement("div", {"class":"text-center"});
var title = createElement("p", {"class":"album-artist"}, data[album].title);
var artist = createElement("p", {"class":"album-artist lead small"}, data[album].artist);
var source = data[album].songs[0].art;
$(img).attr("src", source).load(function(){
$(this).hide().removeClass("loading").fadeIn();
});
if(album % 4 == 0) {
currentRow++;
rows[currentRow] = createElement("div", {"class":"row"});
insertElementAt(rows[currentRow], parentEle[0]);
}
insertElementAt(img, holderInner);
insertElementAt(holderInner, a);
insertElementAt(a, holder);
insertElementAt(title, info);
insertElementAt(artist, info);
insertElementAt(holder, div);
insertElementAt(info, div);
insertElementAt(div, rows[currentRow]);
albumSongs.push(data[album].songs);
$(a).data("songs", data[album].songs);
$(a).data("title", data[album].title);
$(a).click(function(){
$this = $(this);
$("#album-list-title").html($this.data("title"));
buildSongTable($("#album-song-table"), $this.data("songs"));
});
}
return albumSongs;
}
| 0cc7d1bd05691d7727531d1a087bb3e0518338eb | [
"JavaScript",
"JSON"
] | 5 | JavaScript | MusicBoxOUYA/MusicBoxContent | 6798053add02accdef6dcfb703569283724ea76d | a96b239436c8cb64ceb8903084749b0ed6633cfe | |
refs/heads/master | <repo_name>raytieu/to-make-or-to-go<file_sep>/js/to_make.js
$(document).foundation();
$(document).ready(function () {
// Took the Current Url
let queryString = window.location.search;
// Splitting the Url Parameters from the current URL
let urlParams = new URLSearchParams(queryString);
let modalResult = $("#result-modal")
let type = urlParams.get('type');
let resultDisplay = $(".result-display");
let resultModalContent = $(".result-modal-content")
if (type === "make") {
let search = urlParams.get('search')
callRecipe(search)
} else {
let search = urlParams.get('search')
let location = urlParams.get('location')
yelpCaller(search, location)
}
function callRecipe(searchVal) {
let apiKey1 = "<KEY>" // Jeorge's Key
let apiKey2 = "<KEY>" // Raymond's Key
let apiKey3 = "<KEY>" // Alex's Key
let apiKey4 = "9a93dadb97mshe001d742b476bfep136ad9jsna2e0130232fb" // Duyen's Key
let queryURL = `https://tasty.p.rapidapi.com/recipes/list?rapidapi-key=${apiKey2}&from=0&sizes=10&q=${searchVal}`;
$.ajax({
url: queryURL,
method: "GET"
}).then(function (res) {
// Filter out inconsistencies from results, for sort feature
let filteredResults = res.results.filter(function (result) {
return result.user_ratings;
});
// Assign a value of 0, if user_rating.score is null, for sort feature
for (let i = 0; i < filteredResults.length; i++) {
if (filteredResults[i].user_ratings && filteredResults[i].user_ratings.score === null) {
filteredResults[i].user_ratings.score = 0;
}
}
// Div to append all the search results
let recipeDiv = $(".result-display").css({ "text-align": "center" });
// Add Dropdown menu to sort the search results
let recipeForm = $(".dropdown-sort").css({ "text-align": "center" });
let sortForm = $("<form>").text("Sort by: ");
let sortSelect = $("<select>").addClass("sort-by").css("width", "220px");
recipeForm.append(sortForm);
sortForm.append(sortSelect);
let sortDefault = $("<option>");
let sortHighApprove = $("<option>").attr("value", "highest-approve").text("Highest Approval %");
let sortLowApprove = $("<option>").attr("value", "lowest-approve").text("Lowest Approval %");
let sortHighPositive = $("<option>").attr("value", "most-reviews").text("Most Reviews");
let sortHighNegative = $("<option>").attr("value", "least-reviews").text("Least Reviews");
sortSelect.append(sortDefault, sortHighApprove, sortLowApprove, sortHighPositive, sortHighNegative);
// Gatekeeper to render if search results exist
if (filteredResults.length > 0) {
renderDataMake();
// Function that re-populates search results upon change in Dropdown option
sortSelect.change(function () {
let dropDown = sortSelect.val();
if (dropDown === "highest-approve") {
recipeDiv.empty();
filteredResults.sort(function (a, b) { return parseFloat(b.user_ratings.score) - parseFloat(a.user_ratings.score) });
renderDataMake();
}
else if (dropDown === "lowest-approve") {
recipeDiv.empty();
filteredResults.sort(function (a, b) { return parseFloat(a.user_ratings.score) - parseFloat(b.user_ratings.score) });
renderDataMake();
}
else if (dropDown === "most-reviews") {
recipeDiv.empty();
filteredResults.sort(function (a, b) { return parseFloat(b.user_ratings.count_positive + b.user_ratings.count_negative) - parseFloat(a.user_ratings.count_positive + a.user_ratings.count_negative) });
renderDataMake();
}
else if (dropDown === "least-reviews") {
recipeDiv.empty();
filteredResults.sort(function (a, b) { return parseFloat(a.user_ratings.count_positive + a.user_ratings.count_negative) - parseFloat(b.user_ratings.count_positive + b.user_ratings.count_negative) });
renderDataMake();
}
});
// Fill Recipe Div section with search result cards
function renderDataMake() {
// For-loop to append data from each object in array
for (let i = 0; i < filteredResults.length; i++) {
// Variable for looping through filteredResults array
let recipe = filteredResults[i];
// Condition because API call is inconsistent
if (recipe.instructions) {
// Create card for each recipe
let recipeCard = $("<div>").addClass("card").css({ "width": '60%', "display": "inline-block" });
let recipeDivider = $("<div>").addClass("card-divider");
let recipeSection = $("<div>").addClass("card-section");
// Recipe Name
let recipeName = $("<h5>").append($("<a>").addClass("recipe-name").attr("data-id", recipe.id).text(recipe.name));
// Recipe image
let recipeImage = $("<img>").attr("src", recipe.thumbnail_url).css({ "margin-top": "20px", "width": "300", "height": "200" });
recipeCard.append(recipeImage);
// User rating
let recipeRating = $("<p>").html("<strong>User Ratings:</strong> " + recipe.user_ratings.count_positive + " positive, " + recipe.user_ratings.count_negative + " negative; " + (recipe.user_ratings.score * 100).toFixed(2) + "% approval");
recipeDiv.append(recipeCard);
recipeDivider.append(recipeName);
recipeSection.append(recipeRating);
recipeCard.append(recipeDivider, recipeImage, recipeSection);
// Click function to open modal and append target data
$(".recipe-name").click(function (e) {
e.preventDefault();
let recipeID = $(this).attr("data-id");
if (recipe.id == recipeID) {
resultModalContent.empty();
let recipeCard = $("<div>").addClass("card");
let recipeDivider = $("<div>").addClass("card-divider");
let recipeSection = $("<div>").addClass("card-section");
let recipeName = $("<h4>").addClass("recipe-name").attr("data-id", recipe.id).text(recipe.name);
let recipeImage = $("<img>").attr("src", recipe.thumbnail_url).css({ "margin-top": "20px", "width": "300", "height": "200" });
let recipeRating = $("<p>").html("<strong>User Ratings:</strong> " + recipe.user_ratings.count_positive + " positive, " + recipe.user_ratings.count_negative + " negative, " + (recipe.user_ratings.score * 100).toFixed(2) + "% approval");
resultModalContent.append(recipeCard);
recipeCard.append(recipeDivider, recipeImage, recipeSection);
recipeDivider.append(recipeName);
recipeSection.append(recipeRating);
// Append video link if it exists
if (recipe.original_video_url) {
let recipeVideo = $("<p>").html("<strong>Video:</strong> ").append($("<a>").attr({ "href": recipe.original_video_url, "target": "_blank" }).text(recipe.original_video_url));
recipeSection.append(recipeVideo);
}
// Recipe Ingredients
recipeSection.append($("<h5>").html("<strong>Ingredients:</strong>"));
let ingredientList = $("<ul>");
let appendIngredients = "";
recipeSection.append(ingredientList);
for (let j = 0; j < recipe.sections.length; j++) {
for (let k = 0; k < recipe.sections[j].components.length; k++) {
ingredientList.append($("<li>").text(recipe.sections[j].components[k].raw_text));
appendIngredients += `<tr><td>${recipe.sections[j].components[k].raw_text}</td></tr>`
}
}
// Recipe Instructions
recipeSection.append($("<h5>").html("<strong>Instructions:</strong>"));
let appendInstructions = "";
for (let x = 0; x < recipe.instructions.length; x++) {
recipeSection.append($("<p>").html("<strong>" + recipe.instructions[x].position + "</strong>" + ". " + recipe.instructions[x].display_text));
appendInstructions += `<tr><td><strong>${recipe.instructions[x].position}</strong>. ${recipe.instructions[x].display_text}</td></tr>`
}
recipeSection.append(`<div class="error-call"></div>`)
recipeSection.append($(`<div></div>`).addClass("grid-x").css({ "margin-top": "10px" })
.append($(`<input type="email" class="cell email-input" placeholder="E.g. <EMAIL>" />`),
$(`<button>Send to Email <i class="fa fa-paper-plane" aria-hidden="true"></i></button>`).addClass("cell primary button send-email")
.attr({ 'data-name': recipe.name, "data-ingredients": appendIngredients, "data-instructions": appendInstructions, "data-type": "make", "data-src": recipe.thumbnail_url })));
// console.log(recipe)
}
modalResult.foundation('open');
});
}
}
}
}
// Remove dropdown menu and display callout if no search results
else {
recipeForm.empty();
resultDisplay.html(`< div class="callout alert" style = "text-align:center;margin-top:10px;" >
<h5>No Results Found!</h5></div > `);
}
// Store search terms and queryURL into Local Storage
storeSearches(searchVal, 'make', queryURL);
});
}
function yelpCaller(searchVal, location) {
let queryUrl = `https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=${searchVal}&location=${location}&limit=20`;
const apiKey = '<KEY>';
// console.log(queryUrl)
$.ajax({
url: queryUrl,
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`
},
dataType: 'json'
}).then(function (res) {
let businesses = res.businesses;
// console.log(res)
if (businesses.length > 0) {
//Adding a dropdown to dropdown-sort
let dropDown = $(".dropdown-sort").css({ "text-align": "center" });
dropDown.html(`
<form >Sort By:
<select name="sort-to-go" class="sort-to-go" style="width:220px;">
<option value="default" selected></option>
<option value="high-rating">Highest Rating</option>
<option value="low-rating">Lowest Rating</option>
<option value="high-review">Most Reviews</option>
<option value="low-review">Least Reviews</option>
</select>
</form>
`);
for (business of businesses) {
let address = business.location.display_address;
resultDisplay.append(
$(`<div ></div>`).html(
//Adding data id and data type for checking
//Encasing the output to a card
`<div class="card-divider" style="margin-bottom:5px;">
<h5><a href="#" class="result-btn" data-type="to-go" data-id="${business.id}">${business.name}</a></h5>
</div>
<img src="${business.image_url}" alt="${business.name}" style="width:300px;height:200px"/>
<div class="card-section">
<p>${address[0]}, ${address[1]}</p>
<p>${business.phone}</p>
</div>
`).addClass("card go-card").css({ "width": '60%', "display": "inline-block" }).attr({ "data-rating": business.rating, "data-review": business.review_count })
).css({ "text-align": "center" });
}
storeSearches([searchVal, location], 'go', queryUrl);
} else {
resultDisplay.html(`<div class="callout alert" style="text-align:center;margin-top:10px;">
<h5>No Results Found!</h5>
</div>`)
}
})
}
//Attached a listener to result-display class to check if were clicking the button to show modal and parse our data
resultDisplay.on("click", ".result-btn", function (e) {
e.preventDefault()
let type = $(this).attr("data-type");
let id = $(this).attr("data-id");
if (type === 'to-go') {
yelpResultCaller(id)
}
});
//On change of the dropdown
$(".dropdown-sort").on("change", ".sort-to-go", function (e) {
let changeVal = $(this).val();
// console.log("changed")
//Find all the div inside the result display
let divCards = resultDisplay.find(".go-card");
if (changeVal === "high-rating") {
divCards.sort(function (a, b) {
let cardARating = parseFloat($(a).attr("data-rating"));
let cardBRating = parseFloat($(b).attr("data-rating"));
return cardBRating - cardARating;
});
resultDisplay.html(divCards)
} else if (changeVal === "low-rating") {
divCards.sort(function (a, b) {
let cardARating = parseFloat($(a).attr("data-rating"));
let cardBRating = parseFloat($(b).attr("data-rating"));
return cardARating - cardBRating;
});
resultDisplay.html(divCards)
} else if (changeVal === "high-review") {
divCards.sort(function (a, b) {
let cardAReview = parseFloat($(a).attr("data-review"));
let cardBReview = parseFloat($(b).attr("data-review"));
return cardBReview - cardAReview;
});
resultDisplay.html(divCards)
} else if (changeVal === "low-review") {
divCards.sort(function (a, b) {
let cardAReview = parseFloat($(a).attr("data-review"));
let cardBReview = parseFloat($(b).attr("data-review"));
return cardAReview - cardBReview;
});
resultDisplay.html(divCards)
}
});
function yelpResultCaller(id) {
let queryUrl = `https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/${id}`;
resultModalContent.empty()
const apiKey = '<KEY>';
$.ajax({
url: queryUrl,
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`
},
dataType: 'json'
}).then(function (res) {
resultModalContent.empty();
//Initializing Card
let card = $(`<div></div>`).addClass("card")
let cardDivider = $(`<div></div>`).addClass("card-divider").html(`<h4>${res.name} ${res.price ? res.price : ""}</h4>`)
let resImg = $(`<img src="${res.image_url}" alt="${res.name}"/>`).css({ "width": 300, "height": 200 })
let cardSection = $(`<div></div>`).addClass("card-section")
let phoneNum = $(`<p></p>`).html(`<strong>Phone Number</strong> : ${res.display_phone}`);
let address = $(`<p></p>`).html(`<strong>Address</strong> : ${res.location.display_address[0]}, ${res.location.display_address[1]}`);
let rating = $(`<p></p>`).html(`<strong>Rating</strong> : ${res.rating ? res.rating + " / 5" : "N/A"}`);
//Check if transactions have property then map the array take the first letter (charAt(0)) make it to upper case and take the remaining characters and add it to the Uppercased character substring(1) then join all the strings
let transaction = $(`<p></p>`).html(`<strong>Transaction</strong> : ${res.transactions.length > 0 ? res.transactions.map((t) => t.charAt(0).toUpperCase() + t.substring(1)).join(', ') : "N/A"}</p>`);
//Implemented Google Maps to show the directions of the restaurant
//Used iframe per google's requirement
let map = $(`<iframe
width="500"
height="450"
frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/search?key=AIzaSyA-GRo-XmaBhR1SmutbREnSA6IlbJFJi0g&q=${res.name.trim().replace("&", "")}¢er=${res.coordinates.latitude + "," + res.coordinates.longitude}&zoom=18" allowfullscreen>
</iframe>`)
let sendEInput = $(`<div class="error-call"></div> <div className="grid-x" style="margin-top:10px;">
<input type="email" class="cell email-input" placeholder="E.g. <EMAIL>">
<button class="cell primary button send-email" data-name="${res.name}" data-type="go" data-address="${res.location.display_address[0]}, ${res.location.display_address[1]}" data-url="${res.url}" data-src="${res.image_url}">Send to Email <i class="fa fa-paper-plane" aria-hidden="true"></i></button>
</div>`);
cardSection.append(phoneNum, address, rating, transaction, map, sendEInput)
card.append(cardDivider, resImg, cardSection)
resultModalContent.append(card);
modalResult.foundation('open');
})
}
function storeSearches(search, type, url) {
let storedSearches = JSON.parse(localStorage.getItem("toMakeToGo"));
const searchVal = Array.isArray(search) ? search[0] : search;
const locationVal = Array.isArray(search) ? search[1] : '';
const searchObjInit = {
search: searchVal.toLowerCase(),
location: locationVal.toLowerCase(),
url: url,
type: type,
};
if (storedSearches === null) {
storedSearches = [];
storedSearches.push(searchObjInit);
} else {
let searchObj = storedSearches.find(element => element.search === searchVal.toLowerCase() && element.type === type && element.location === locationVal.toLowerCase());
// console.log(searchObj)
if (!searchObj) {
storedSearches.push(searchObjInit);
}
}
localStorage.setItem("toMakeToGo", JSON.stringify(storedSearches));
}
resultModalContent.on("click", ".send-email", sendEmail);
//Source https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function sendEmail() {
const emailAdd = $(".email-input").val();
if (emailAdd && validateEmail(emailAdd)) {
let body = parseEmailContent(this)
// console.log(body)
Email.send({
SecureToken: "672072a2-d24f-4024-bc1e-c170cf07a781",
To: emailAdd,
From: "<EMAIL>",
Subject: "Thank you for your using To Make or To Go!",
Body: body
}).then(
$(".error-call").html(`<div class="callout success" style="text-align:center;margin-top:10px;">
<h5>Email Sent!</h5>
</div>`)
);
} else {
$(".error-call").html(`<div class="callout alert" style="text-align:center;margin-top:10px;">
<h5>Invalid Email!</h5>
</div>`);
}
}
function parseEmailContent(container) {
let that = $(container);
if (that.data('type') === "make") {
// console.log(ingredients)
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>To Make or To Go</title>
</head>
<body style="margin: 0; padding: 0;">
<table align="center" border="1" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse;">
<tr>
<td bgcolor="#52bf6c" style="padding: 40px 30px 40px 30px;"></td>
</tr>
<tr>
<td align="center">
<img width="300px" height="200px" src="${that.data("src")}" alt="To Make or To Go">
</td>
</tr>
<tr>
<td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;">
<p><strong>Recipe Name : </strong> ${that.data("name")}</p>
<p><strong>Ingredients : </strong><table style="margin: 10px 40px;">${that.data("ingredients")}</table></p>
<p><strong>Instructions : </strong><table style="margin: 10px 40px;">${that.data("instructions")}</table></p>
</td>
</tr>
<tr>
<td bgcolor="#52bf6c" style="padding: 40px 10px 40px 10px;" align="center">© Created by <NAME>, <NAME>, <NAME>, and <NAME> © 2020</td>
</tr>
</table >
</body >
</html > `
} else {
return `<!DOCTYPE html >
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>To Make or To Go</title>
</head>
<body style="margin: 0; padding: 0;">
<table align="center" border="1" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse;">
<tr>
<td bgcolor="#52bf6c" style="padding: 40px 30px 40px 30px;"></td>
</tr>
<tr>
<td align="center">
<img width="300px" height="200px" src="${that.data("src")}" alt="To Make or To Go">
</td>
</tr>
<tr>
<td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;">
<p><strong>Restaurant Name : </strong> ${that.data('name')}</p>
<p><strong>Address : </strong> ${that.data('address')}</p>
<p><strong>Yelp URL : </strong> <a href="${that.data('url')}" target="_blank">${that.data('name')}</a></p>
</td>
</tr>
<tr>
<td bgcolor="#52bf6c" style="padding: 40px 10px 40px 10px;" align="center">© Created by <NAME>, <NAME>, <NAME>, and <NAME> © 2020</td>
</tr>
</table>
</body>
</html>`
}
}
});
<file_sep>/README.md
# to-make-or-to-go
UCI Project 1, To Make or To Go
### PROJECT TITLE:
```To Make or To Go```
### PROJECT DESCRIPTION:
```
Eating meals are an essential part of our daily lives. The problem we are always faced with though, is, "What to eat?"
With "TO MAKE OR TO GO", we aim to make it more convenient for you to tackle this daily struggle.
Users can decide whether TO MAKE their meal or TO GO to a restaurant by clicking on the appropriate button on the front page. Upon deciding TO MAKE or TO GO, the user will be prompted to enter a food search-term (and location for TO GO). Once the user clicks on the search button, they will be provided with results to help them decide on a recipe TO MAKE or a restaurant TO GO to. Then simply click on the name of a recipe or restaurant and additional details will be shown in a pop-up display.
Additional features include:
-Local Storage capability that will store the user's previous search terms/locations as clickable links for convenient access.
-Dropdown in the results page that can sort the results by the following options: highest rated, lowest rated, most reviews, and least reviews.
-E-mail function at the bottom of each result's pop-up where you can e-mail the recipe/restaurant details to yourself or friends/family!
```
### USER STORY:
```
AS a hungry person
I WANT to see a list of possible recipes and/or restaurants
SO THAT I can decide to either cook a meal or dine out
```
### APIS USED:
```
Google Map
Tasty
Yelp
```
### Link:
https://raytieu.github.io/to-make-or-to-go/
### Application's Screenshots:


<file_sep>/js/restaurantCaller.js
//Initializing Foundation Framework
$(document).foundation();
$(document).ready(function () {
let searchModalContent = $(".search-modal-content");
let modal = $("#search-modal");
//Attaching a click event to the buttons
$(".to-make-btn").on("click", function (e) {
e.preventDefault()
parseSearchContent("to make");
});
$(".to-go-btn").on("click", function (e) {
e.preventDefault()
parseSearchContent("to go");
});
//Populate the modal content
let parseSearchContent = (type) => {
searchModalContent.empty()
if (type === "to make") {
let searches = retrieveSearches('make');
// console.log(constructSearches(searches))
searchModalContent.append(
$(`<h4></h4>`).text("To Make"),
$(`<label></label>`).html(`Search Criteria <input type="text" placeholder="E.g. Pho, Steak, Chicken" class="search-input" />`),
$(`<label></label>`).addClass("modal-error"),
$(`<label></label>`).html(`Search History`),
$(`<br>`),
$(`<ul class="dropdown menu searches" data-dropdown-menu></ul>`).html(constructSearches(searches)),
$(`<br>`),
$(`<button type="button" class="button clear-to-make" style="color:white;float:left;"></button>`).html(`<i class="fa fa-trash" aria-hidden="true"></i> Clear History`),
$(`<button type="button" class="success button search-modal-btn" data-search-type="make" style="color:white;float:right;"></button>`).html(`<i class="fa fa-search" aria-hidden="true"></i> Search`)
);
new Foundation.DropdownMenu($('.searches'));
} else {
let searches = retrieveSearches('go');
// console.log(constructSearches(searches))
searchModalContent.append(
$(`<h4></h4>`).text("To Go"),
$(`<label></label>`).html(`Search Criteria <input type="text" placeholder="E.g. Pho, Steak, Fried Chicken" class="search-input" />`),
$(`<label></label>`).html(`Search Location <input type="text" placeholder="E.g. Orange County, Irvine, Texas" class="search-location" />`),
$(`<label></label>`).addClass("modal-error"),
$(`<label></label>`).html(`Search History`),
$(`<br>`),
$(`<ul class="dropdown menu searches" data-dropdown-menu></ul>`).html(constructSearches(searches)),
$(`<br>`),
$(`<button type="button" class="button clear-to-go" style="color:white;float:left;"></button>`).html(`<i class="fa fa-trash" aria-hidden="true"></i> Clear History`),
$(`<button type="button" class="success button search-modal-btn" data-search-type="go" style="color:white;float:right;"></button>`).html(`<i class="fa fa-search" aria-hidden="true"></i> Search`)
);
new Foundation.DropdownMenu($('.searches'));
}
modal.foundation('open');
}
function constructSearches(searches) {
let li = '';
if (searches) {
searches.slice(0, 5).forEach(s => {
if (s.type === 'make') {
li += `<li class='li-search' data-type='make' data-search='${s.search}'><a href="#" style="font-size:18px;">${s.search}</a></li>`
} else {
li += `<li class='li-search' data-type='go' data-search='${s.search}' data-location='${s.location}'><a href="#" style="font-size:18px;">${s.search} - ${s.location}</a></li>`
}
});
return li;
} else {
return '';
}
}
//Attaching a click event to modal's search button
// Event delegation using jQuery container.on(event,selector,function)
searchModalContent.on("click", ".search-modal-btn", function (e) {
e.preventDefault();
const type = $(this).attr("data-search-type");
if (type === "make") {
let value = $(".search-input").val();
if (value) {
window.location.href = `result.html?type=make&search=${value}`;
} else {
$(".modal-error").html(`<div style="padding:5px" class="callout alert"><strong>Search Criteria is Required! </strong></div>`);
}
} else {
let value = $(".search-input").val();
let location = $(".search-location").val();
if (value && location) {
window.location.href = `result.html?type=go&search=${value}&location=${location}`;
} else {
$(".modal-error").html(`<div style="padding:5px" class="callout alert"><strong>All Fields are Required!</strong></div>`);
}
}
});
searchModalContent.on('click', '.li-search', function (e) {
e.preventDefault();
const type = $(this).attr('data-type');
if (type === 'make') {
let search = $(this).attr('data-search');
window.location.href = `result.html?type=make&search=${search}`;
} else {
let search = $(this).attr('data-search');
let location = $(this).attr('data-location');
window.location.href = `result.html?type=go&search=${search}&location=${location}`;
}
})
function retrieveSearches(type) {
let storedSearches = JSON.parse(localStorage.getItem("toMakeToGo"));
if (storedSearches !== null) {
if (storedSearches.length > 0) {
storedSearches.slice(0, 5)
return storedSearches.reverse().filter(element => element.type === type)
} else {
return null;
}
}
}
// Click event to clear to-make history
searchModalContent.on('click', '.clear-to-make', function (e) {
e.preventDefault();
let storedSearches = JSON.parse(localStorage.getItem("toMakeToGo"));
let clearToMake = storedSearches.filter(function (search) {
return search.type === "go";
});
localStorage.setItem("toMakeToGo", JSON.stringify(clearToMake));
searchModalContent.empty();
parseSearchContent("to make");
});
// Click event to clear to-go history
searchModalContent.on('click', '.clear-to-go', function (e) {
e.preventDefault();
let storedSearches = JSON.parse(localStorage.getItem("toMakeToGo"));
let clearToGo = storedSearches.filter(function (search) {
return search.type === "make";
});
localStorage.setItem("toMakeToGo", JSON.stringify(clearToGo));
searchModalContent.empty();
parseSearchContent("to go");
});
}); | 40ec0e9b7f090cd154da698f3438de25616486f6 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | raytieu/to-make-or-to-go | 5c15a8fc31eeff4df72f79b14da20c99ed70c975 | b3c51bc31c11054af7641519391283680baebf54 | |
refs/heads/master | <repo_name>kaolaqi/alittleQQ<file_sep>/src/server/dataStore/index.js
var DataStoreServer = function() {
}
// 设置长期数据
DataStoreServer.prototype.setLongData = function(key, value) {
window.localStorage.setItem(key, JSON.stringify(value))
}
// 读取长期数据
DataStoreServer.prototype.getLongData = function(key) {
return JSON.parse(window.localStorage.getItem(key))
}
// 清除长期数据
DataStoreServer.prototype.removeLongData = function(key, clearAll) {
if (!key && clearAll) {
window.localStorage.clear()
return false
}
window.localStorage.removeItem(key)
}
// 设置会话数据
DataStoreServer.prototype.set = function(key, value) {
window.sessionStorage.setItem(key, JSON.stringify(value))
}
// 读取会话数据
DataStoreServer.prototype.get = function(key) {
return JSON.parse(window.sessionStorage.getItem(key))
}
// 清除会话数据
DataStoreServer.prototype.remove = function(key, clearAll) {
if (!key && clearAll) {
window.sessionStorage.clear()
return false
}
window.sessionStorage.removeItem(key)
}
export default new DataStoreServer()
<file_sep>/src/filters/aes.js
var dsbCode = require('crypto-js')
var key = dsbCode.enc.Utf8.parse('BE56E057F20F883E')
var iv = dsbCode.enc.Utf8.parse('E10ADC3949BA59AB')
// var str = dsbCode.MD5('um81msQiWfOiiqGC').toString();
// //新的
// var key = dsbCode.enc.Utf8.parse(str.substring(16).toUpperCase());
// var iv = dsbCode.enc.Utf8.parse(str.substring(0,16).toUpperCase());
/* 加密*/
function encrypt(word) {
// console.log(word)
var text = dsbCode.enc.Utf8.parse(word) // 转128bit
var encrypted = dsbCode.AES.encrypt(text, key, {
iv: iv,
mode: dsbCode.mode.CBC,
padding: dsbCode.pad.Pkcs7
})
var encryptedStr = encrypted.ciphertext.toString()
var encryptedHexStr = dsbCode.enc.Hex.parse(encryptedStr)
var encryptedBase64Str = dsbCode.enc.Base64.stringify(encryptedHexStr)
return encryptedBase64Str
}
function iGetInnerText(testStr) {
var resultStr = testStr.replace(/\ +/g, '') // 去掉空格
resultStr = testStr.replace(/[ ]/g, '') // 去掉空格
resultStr = testStr.replace(/[\r\n]/g, '') // 去掉回车换行
return resultStr
}
/* 解密*/
function decrypt(word) {
word = iGetInnerText(word)
// console.log(word)
var decrypted = dsbCode.AES.decrypt(word, key, {
iv: iv,
mode: dsbCode.mode.CBC,
padding: dsbCode.pad.Pkcs7
})
return dsbCode.enc.Utf8.stringify(decrypted).toString()
}
export { encrypt, decrypt }
<file_sep>/src/filters/status.js
import provinceData from '../lib/provinceCode.js'
// 上游消费明细
function consumeTypeFilter(status) {
switch (+status) {
case 11:
return '任务创建扣款'
case 12:
return '任务失败加款'
default:
return '未知状态'
}
}
// 根据提现状态返回文本
function withdrawStatus(status) {
switch (status) {
case 87:
return '审核中'
case 88:
return '已到账'
case 89:
return '未到账'
default:
return '未知状态'
}
}
// 根据订单状态返回文本
function orderStatus(status) {
switch (status) {
case 81:
return '审核中'
case 82:
return '审核中'
case 83:
return '已成功'
case 84:
return '已失败'
case 85:
return '已放弃'
default:
return '未知状态'
}
}
// 微信扫码任务类型
function wechatScanMissionType(type) {
switch (type) {
case 80:
return '微信辅助'
default:
return '未知状态'
}
}
// 任务类型
function orderTypeFilter(type) {
switch (type) {
case 1:
return '微信扫码辅助'
case 2:
return '微信解封辅助'
default:
return '未知状态'
}
}
// 保证金状态
function ensureMoneyFilter(type) {
switch (type) {
case 41:
return '充值'
case 42:
return '违规扣款'
case 43:
return '退还'
case 44:
return '申诉退款'
default:
return '未知状态'
}
}
// 提现状态
function withdrawFilter(status) {
switch (status) {
case 87:
return '待审核'
case 88:
return '转账成功'
case 89:
return '转账失败'
case 90:
return '审核不通过'
default:
return '未知状态'
}
}
// 过滤省名
function provinceFilter(code) {
var province = provinceData[code]
if (!province) {
return '未知地区'
}
return province.province
}
// 提现状态
function walletChangeType(status) {
switch (status) {
case 21:
return '赏金加款'
case 22:
return '抽成加款'
case 26:
return '提现扣款'
case 27:
return '提现退款'
case 49:
return '下游邀请金额转入个人余额'
default:
return '未知状态'
}
}
// 申诉状态
function appealStatus(status) {
switch (status) {
case 1:
return '待审核'
case 2:
return '申诉成功'
case 3:
return '申诉失败'
default:
return '未知状态'
}
}
export {
consumeTypeFilter,
withdrawStatus,
orderStatus,
wechatScanMissionType,
orderTypeFilter,
provinceFilter,
ensureMoneyFilter,
withdrawFilter,
walletChangeType,
appealStatus
}
<file_sep>/src/server/token/index.js
import Cookies from 'js-cookie'
const TokenKey = 'Admin-Token'
var TokenServer = function() {
this.getToken = function() {
return Cookies.get(TokenKey)
}
this.setToken = function(token) {
return Cookies.set(TokenKey, token)
}
this.removeToken = function() {
return Cookies.remove(TokenKey)
}
}
export default new TokenServer()
<file_sep>/src/server/modals/loading/index.js
/* eslint-disable */
import Vue from 'vue'
import loadingComponent from './main.vue'
// 组件初始化的实例
var loadingInstance = false
// 组件添加初始化挂载方法
loadingComponent.installMessage = function() {
if (loadingInstance) {
return loadingInstance
}
var loading = Vue.extend(loadingComponent)
var component = new loading({}).$mount()
document.querySelector('body').appendChild(component.$el)
loadingInstance = component
// 把实例返回出来
return loadingInstance
}
/** *********** 组件服务 ****************/
// 将组件实例赋给服务 使用函数调用组件方法
var LoadingServer = function() {
this.instance = loadingComponent.installMessage()
}
// 组件服务方法加载
LoadingServer.prototype.loading = function(message) {
if (!this.instance) {
this.instance = loadingComponent.installMessage()
}
this.instance.loading(message)
}
// 组件服务卸载
LoadingServer.prototype.unload = function() {
if (!this.instance) {
this.instance = loadingComponent.installMessage()
}
this.instance.unload()
}
var modalLoadingServer = new LoadingServer()
export default modalLoadingServer
<file_sep>/src/main.js
import Vue from 'vue'
import App from './App'
import store from './store'
import router from './router'
import Vant from 'vant'
import 'vant/lib/index.css'
// 控制台调试工具
// var VConsole = require('vconsole');
// var vConsole = new VConsole();
// require('eruda').init();
import './permission' // permission control
import { clipboard } from '@/directive/index'
// 引入自定义组件
Vue.directive('clipboard', clipboard)
Vue.use(Vant)
Vue.config.productionTip = false
router.beforeEach((to, from, next) => {
document.title = to.meta.title
next()
})
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
<file_sep>/src/constants/index.js
// 定义全局变量,配置请求服务器地址
var socketUrl = '' // websocket服务地址
if (process.env.NODE_ENV === 'production') {
// 正式环境
socketUrl = 'ws://172.16.58.3:8040'
} else {
// 测试环境地址
socketUrl = 'ws://localhost:8050'
}
export {
socketUrl
}
<file_sep>/src/server/modals/alert/index.js
/* eslint-disable */
import Vue from 'vue'
import alertComponent from './main.vue'
// 组件初始化的实例
var alertInstance = false
// 组件添加初始化挂载方法
alertComponent.installMessage = function() {
if (alertInstance) {
return alertInstance
}
var loading = Vue.extend(alertComponent)
var component = new loading({}).$mount()
document.querySelector('body').appendChild(component.$el)
alertInstance = component
// 把实例返回出来
return alertInstance
}
/** *********** 组件服务 ****************/
// 将组件实例赋给服务 使用函数调用组件方法
var alertServer = function() {
this.instance = alertComponent.installMessage()
}
// 使用组件服务
// config.title='标题'
// config.message = '内容' *必传*
// config.confirm = '按钮文本'
// config.onClickConfirm = '点击确认回调' 默认关闭
alertServer.prototype.use = function(config) {
if (!this.instance) {
this.instance = alertComponent.installMessage()
}
this.instance.use(config)
}
// 取消
alertServer.prototype.hide = function() {
if (!this.instance) {
this.instance = alertComponent.installMessage()
}
this.instance.hide()
}
var modalAlertServer = new alertServer()
export default modalAlertServer
<file_sep>/build/build.js
require('./check-versions')()
process.env.NODE_ENV = 'production'
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
var webpackTestConfig = require('./webpack.test.conf')
//打包测试环境
function pacelTest (){
process.env.NODE_ENV = 'test'
var spinner = ora('开始打包测试环境')
spinner.start()
rm(path.join(config.buildTest.assetsRoot, config.buildTest.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackTestConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build-test complete 测试环境打包成功.\n'))
})
})
}
var spinner = ora('开始打包正式环境')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
//开始打包测试环境
pacelTest();
})
})
<file_sep>/src/server/http/index.js
import axios from 'axios'
import { modalMessageServer, modalAlertServer } from '../modals/index'
import router from '@/router'
// import store from '@/store'
// import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: '/',
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
// if (store.getters.token) {
// // let each request carry token
// // ['X-Token'] is a custom headers key
// // please modify it according to the actual situation
// config.headers['X-Token'] = getToken()
// }
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.statusCode === 401) {
modalAlertServer.use({
content: '登录失效,请重新登录!',
onClickConfirm: function() {
// window.location.hash = '/login';
router.push({ name: 'login' })
modalAlertServer.hide()
}
})
}
if (res.statusCode !== 200) {
modalMessageServer.show(res.message || 'Error', 2000)
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
modalMessageServer.show(error.message, 2000)
return Promise.reject(error)
}
)
export default service
<file_sep>/src/filters/common.js
// 时间输出格式
function dateFormat(date, format) {
if (!format || typeof format !== 'string') {
console.log('format is undefiend or type is Error')
}
// console.log(date,format)
date = date instanceof Date ? date : (typeof date === 'number' || typeof date === 'string') ? new Date(date) : new Date()
var formatReg = {
'y+': date.getFullYear(),
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (var reg in formatReg) {
if (new RegExp(reg).test(format)) {
var match = RegExp.lastMatch
format = format.replace(match, formatReg[reg] < 10 ? '0' + formatReg[reg] : formatReg[reg].toString().slice(-match.length))
}
}
return format
}
// 计算相差时分秒
function dateCountDown(countDownTime) {
if (!countDownTime || typeof countDownTime !== 'number') {
console.log('countDownTime is undefiend or type is Error')
return false
}
var date3 = countDownTime // 时间差的毫秒数
// ------------------------------
// 计算出小时数
var hours = Math.floor(date3 / (3600 * 1000))
// 计算相差分钟数
var leave1 = date3 % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
var leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
var minutes = Math.floor(leave2 / (60 * 1000))
// 计算相差秒数
var leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
var seconds = Math.round(leave3 / 1000)
return (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)
}
export { dateFormat, dateCountDown }
<file_sep>/src/http/user.js
import httpRequestServer from '../server/http/index'
export default {
// 用户注册
userResigter(data) {
return httpRequestServer({
method: 'POST',
url: '/api/client/register',
data: data
})
},
// 登录
userLogin(data) {
return httpRequestServer({
method: 'POST',
url: '/api/client/login',
data: data
})
},
// 获取用户信息
getUserInfo(data) {
return httpRequestServer({
method: 'GET',
url: '/api/client/userInfo',
params: data
})
},
// 退出登录
outUser() {
return httpRequestServer({
method: 'GET',
url: '/api/client/logout'
})
},
// 获取用户好友列表
getUserFriendList(data) {
return httpRequestServer({
method: 'GET',
url: '/api/client/getFriendList',
params: data
})
},
// 模糊查询系统用户列表
searchUserList(data) {
return httpRequestServer({
method: 'GET',
url: '/api/client/userList',
params: data
})
},
// 发送好友列表
sendFriendMessage(data) {
return httpRequestServer({
method: 'POST',
url: '/api/client/sendFriendMessage',
data: data
})
},
// 获取好友消息列表
queryFriendMessage(data) {
return httpRequestServer({
method: 'POST',
url: '/api/client/queryFriendMessage',
data: data
})
},
// 查看是否是好友
chickIsFriend(data) {
return httpRequestServer({
method: 'GET',
url: '/api/client/chickIsFriend',
params: data
})
},
// 添加为好友
addUserFriend(data) {
return httpRequestServer({
method: 'POST',
url: '/api/client/addFriend',
data: data
})
},
// 跟新用户的聊天状态
setInchatStatus(data) {
return httpRequestServer({
method: 'PUT',
url: '/api/client/setInchatStatus',
data: data
})
}
}
<file_sep>/src/permission.js
import router from './router'
import store from './store'
import tokenServer from '@/server/token/index.js' // get token from cookie
const whiteList = ['/login', '/registe'] // no redirect whitelist
router.beforeEach((to, from, next) => {
// determine whether the user has logged in
const hasToken = tokenServer.getToken()
if (hasToken) {
if (to.path === '/login') {
next({
path: '/'
})
} else {
// 刷新的时候 store 被重置,要重新请求用户信息数据 需要权限可以在这里添加权限控制
const hasInfo = store.getters.userId
if (hasInfo) {
next()
} else {
store.dispatch('user/GetUserInfo', {
mobile: hasToken
}).then(() => {
next() // dispatch 同步store之后再执行后续操作
})
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
}
}
})
<file_sep>/src/store/modules/user.js
import {
userModel
} from '@/http/index'
import {
modalMessageServer,
modalAlertServer
} from '@/server/modals/index'
import tokenServer from '@/server/token'
const state = {
mobile: '',
nickname: '',
avatar: '',
email: '',
rule: [],
token: '',
userInfo: {}
}
const mutations = {
SET_MOBILE: (state, name) => {
state.mobile = name
},
SET_NICKNAME: (state, name) => {
state.nickname = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_EMAIL: (state, email) => {
state.email = email
},
SET_USERINFO: (state, userInfo) => {
state.userInfo = userInfo
},
SET_TOKEN: (state, token) => {
state.token = token
}
}
const actions = {
// 登录
Login({
commit
}, payload) {
return new Promise((resolve, reject) => {
userModel.userLogin({
mobile: payload.mobile.trim(),
password: <PASSWORD>.trim()
}).then((data) => {
if (data.statusCode === 200) {
commit('SET_MOBILE', data.data.mobile)
commit('SET_NICKNAME', data.data.nickname)
commit('SET_AVATAR', data.data.avatar)
commit('SET_EMAIL', data.data.email)
commit('SET_USERINFO', data.data)
commit('SET_TOKEN', data.data.mobile)
tokenServer.setToken(data.data.mobile)
resolve(data)
} else if (data.statusCode === 111) {
modalMessageServer.show(data.message, 1000)
} else if (data.statusCode === 413) {
modalMessageServer.show('验证码错误,请重试', 1000)
} else {
modalAlertServer.use({
content: data.message
})
}
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
GetUserInfo({
commit
}, payload) {
return new Promise((resolve, reject) => {
userModel.getUserInfo({
mobile: payload.mobile.trim()
}).then((data) => {
if (data.statusCode === 200) {
commit('SET_MOBILE', data.data.mobile)
commit('SET_NICKNAME', data.data.nickname)
commit('SET_AVATAR', data.data.avatar)
commit('SET_EMAIL', data.data.email)
commit('SET_USERINFO', data.data)
commit('SET_TOKEN', data.data.mobile)
tokenServer.setToken(data.data.mobile)
resolve(data)
} else if (data.statusCode === 111) {
modalMessageServer.show(data.message, 1000)
} else if (data.statusCode === 413) {
modalMessageServer.show('验证码错误,请重试', 1000)
} else {
modalAlertServer.use({
content: data.message
})
}
}).catch(error => {
reject(error)
})
})
},
// 退出登录
Logout({
commit
}) {
return new Promise((resolve, reject) => {
userModel.outUser().then((data) => {
if (data.statusCode === 200) {
commit('SET_TOKEN', '')
tokenServer.removeToken()
resolve(data)
} else {
modalAlertServer.use({
content: data.message
})
}
}).catch(error => {
reject(error)
})
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
<file_sep>/src/lib/provinceCode.js
export default {
'110000': {
province: '北京市',
code: '110000'
},
'120000': {
province: '天津市',
code: '120000'
},
'130000': {
province: '河北省',
code: '130000'
},
'140000': {
province: '山西省',
code: '140000'
},
'150000': {
province: '内蒙古自治区',
code: '150000'
},
'210000': {
province: '辽宁省',
code: '210000'
},
'220000': {
province: '吉林省',
code: '220000'
},
'230000': {
province: '黑龙江省',
code: '230000'
},
'310000': {
province: '上海市',
code: '310000'
},
'320000': {
province: '江苏省',
code: '320000'
},
'330000': {
province: '浙江省',
code: '330000'
},
'340000': {
province: '安徽省',
code: '340000'
},
'350000': {
province: '福建省',
code: '350000'
},
'360000': {
province: '江西省',
code: '360000'
},
'370000': {
province: '山东省',
code: '370000'
},
'410000': {
province: '河南省',
code: '410000'
},
'420000': {
province: '湖北省',
code: '420000'
},
'430000': {
province: '湖南省',
code: '430000'
},
'440000': {
province: '广东省',
code: '440000'
},
'450000': {
province: '广西壮族自治区',
code: '450000'
},
'460000': {
province: '海南省',
code: '460000'
},
'500000': {
province: '重庆市',
code: '500000'
},
'510000': {
province: '四川省',
code: '510000'
},
'520000': {
province: '贵州省',
code: '520000'
},
'530000': {
province: '云南省',
code: '530000'
},
'540000': {
province: '西藏自治区',
code: '540000'
},
'610000': {
province: '陕西省',
code: '610000'
},
'620000': {
province: '甘肃省',
code: '620000'
},
'630000': {
province: '青海省',
code: '630000'
},
'640000': {
province: '宁夏回族自治区',
code: '640000'
},
'650000': {
province: '新疆维吾尔自治区',
code: '650000'
},
'710000': {
province: '台湾省',
code: '710000'
},
'810000': {
province: '香港特别行政区',
code: '810000'
},
'820000': {
province: '澳门特别行政区',
code: '820000'
},
'990000': {
province: '国外地区',
code: '990000'
}
}
<file_sep>/src/server/modals/message/index.js
/* eslint-disable */
import Vue from 'vue'
import MessageComponent from './main.vue'
// 组件初始化的实例
var messageInstance = false
// 组件添加初始化挂载方法
MessageComponent.installMessage = function() {
if (messageInstance) {
return messageInstance
}
var message = Vue.extend(MessageComponent)
var component = new message({}).$mount()
document.querySelector('body').appendChild(component.$el)
messageInstance = component
// 把实例返回出来
return messageInstance
}
/** *********** 组件服务 ****************/
// 将组件实例赋给服务 使用函数调用组件方法
var MessageServer = function() {
this.instance = MessageComponent.installMessage()
}
// 组件服务方法
MessageServer.prototype.show = function(message, delayTime) {
if (!this.instance) {
this.instance = MessageComponent.installMessage()
}
this.instance.show(message, delayTime)
}
var modalMessageServer = new MessageServer()
export default modalMessageServer
<file_sep>/src/utils/index.js
/**
* 初始化页面根元素字体大小
* @param {Number} designWidth 设计稿宽度
* @param {Number} baseFontSize 默认初始化字体大小
*/
function initFontSize(designWidth, baseFontSize) {
designWidth = designWidth || 750
baseFontSize = baseFontSize || 100
// 根据客户端宽度、设计稿宽度和初始化字体大小,计算并设置根元素字体大小
function calculateFontSize() {
var e = document.documentElement
var t = e.clientWidth || 640
e.style.fontSize = t / designWidth * baseFontSize + 'px'
}
calculateFontSize()
// 监听页面分辨率改变事件
window.addEventListener('orientationchange' in window ? 'orientationchange' : 'resize', calculateFontSize)
}
export {
initFontSize
}
| e6e0c5a549fe24fa23da100e5f1fc24e91655d05 | [
"JavaScript"
] | 17 | JavaScript | kaolaqi/alittleQQ | 316898204db8f25cbb474408515091589f75f886 | 704281a3edcf95f299b3c1dd7aad6c069cfdfb9c | |
refs/heads/master | <repo_name>ashvi23/My-Malloc<file_sep>/memgrind90noprint.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "mymalloc.c"
#include "mymalloc.h"
#define malloc(x) mymalloc(x,__FILE__,__LINE__)
#define free(x) myfree(x,__FILE__,__LINE__)
int main (int argc, char**argv){
time_t starttime;
time_t endtime;
double difference=0;
double sumtimeA=0;
double sumtimeB=0;
double sumtimeC=0;
double sumtimeD=0;
double sumtimeE=0;
double sumtimeF=0;
int* ptrarr2[150];
srand(time(NULL));
// case a
time(&starttime);//get time at start
int i=0;
for( i =0 ; i< 150; i++){
ptrarr2[i] = (int*) malloc(1);
free(ptrarr2[i]);
ptrarr2[i] = NULL;
}
time(&endtime);//get time at end
difference=difftime(endtime, starttime);//save runtime of iteration
sumtimeA+=difference;
printf("case a done\n");
//case b
int *ptrarr[50];
int malcounter=0;
int *ptr;
time(&starttime);//get time at start
int x ;
for(x =0; x<3; x++){
for(i =0; i< 50; i++){
ptr = (int*) malloc(1);
ptrarr[i] =ptr;
malcounter++;
if(malcounter == 50){
int j;
for (j =0; j<malcounter;j++ ){
free(ptrarr[j]);
ptrarr[j]=NULL;
}
malcounter =0;
}
}
}
time(&endtime);//get time at end
difference=difftime(endtime, starttime);//save runtime of iteration
sumtimeB+=difference;
// case c
malcounter = 0;
int freedptr = 0;
int ptr2free =-1;
int freeindex =0;
int* pointers[50];
int mallocindex =0;
int random;
time(&starttime);//get time at start
while(malcounter <=50){
random = rand()%2;
if(random == 0){ //malloc if 0
pointers[mallocindex] = (int*)malloc(1);
malcounter++;
mallocindex++;
ptr2free =malcounter - freedptr;
}
else if (random == 1){ // free if 1
if (ptr2free != 0 && malcounter!=0){
free(pointers[freeindex]);
pointers[freeindex] = NULL;
++freeindex;
++freedptr;
ptr2free =malcounter - freedptr;
}
}
if(malcounter == 50){
break;
}
}
// if (malcounter == 50){
while(ptr2free!= 0){
free(pointers[freeindex]);
pointers[freeindex] = NULL;
++freedptr;
++freeindex;
ptr2free= malcounter-freedptr;
}
//}
time(&endtime);//get time at end
difference=difftime(endtime, starttime);//save runtime of iteration
sumtimeC+=difference;
//case d
int memleft=4092; //the amount of memory left
int memalloc =0; // the total of memory that is currently allocated
int* pointers2[50]; // pointer array to all of allocations
freedptr=0; //amount of pointers that have been freed
freeindex=0; // index to free at, starts at 0 and frees sequentially. used for pointers2
malcounter=0; // amount of times malloc has been called
ptr2free =-1; // amount of pointers left to free
mallocindex=0; // where to store the next mallocd pointer in pointers2
int memarr[50];// stores the amount of memory mallocd on each malloc
time(&starttime);//get time at start
while(malcounter<=50){
if (memleft >0){
random = rand()%2;
if(random ==0){// malloc if even
random = rand();
while(random < 1 || random > 64){
random = rand();
if (random <=64 && random >= 1){
break;
}
}
if(memleft >=random){
pointers2[mallocindex]= (int*)malloc(random);
memarr[mallocindex] = random;
memalloc +=random;
mallocindex++;
malcounter++;
memleft-=random;
}
}
else if (random ==1){//free if odd
if(ptr2free!=0&& malcounter!=0){
free(pointers2[freeindex]);
memalloc = memalloc - memarr[freeindex];
freeindex++;
freedptr++;
ptr2free = malcounter-freedptr;
memleft = 4092- memalloc;
}
}
}
if (malcounter ==50){
break;
}
}
//if(malcounter ==50){
while(freeindex <=50){
free(pointers2[freeindex]);
freedptr++;
ptr2free = malcounter -freedptr;
memalloc = memalloc - memarr[freeindex];
freeindex++;
memleft = 4092- memalloc;
if(ptr2free == 0){
break;
}
}
time(&endtime);//get time at end
difference=difftime(endtime, starttime);//save runtime of iteration
sumtimeD+=difference;
int *fiboptrArr[100];
int prevprev=0;
int prev=1;
int sum=0;
int totalmem=0;
int index=0;
//case E
while(totalmem<(4092/2)){
sum=prevprev+prev;
fiboptrArr[index]= (int*)malloc(sum);
prevprev=prev;
prev=sum;
totalmem+=(sum+2);
index++;
}
fiboptrArr[index]= (int*)malloc(prevprev);
totalmem+=(prevprev+2);
index++;
while(totalmem+(prev-prevprev)<(4092)&& sum>1){
sum=prev-prevprev;
fiboptrArr[index]= (int*)malloc(sum);
prev=prevprev;
prevprev=sum;
totalmem+=(sum+2);
index++;
}
for(i=index-1; i>=0; i--){
free(fiboptrArr[i]);
}
int* alternptrArr[250];
index=0;
random=0;
while(sum<=4092 && index<250){
if((index/4)==0){
free(alternptrArr[index-1]);//every third element gets freed
alternptrArr[index-1]=NULL;
}
random=abs(rand()%64);
alternptrArr[index]=(int*)malloc(random);
index++;
sum+=random+2;
}
for(i=0; i<250; i++){
if(alternptrArr[i]!=NULL){
free((alternptrArr[i]));
}
}
//print mean times
printf("Mean time of protocol A was %lf\n", (sumtimeA/100));
printf("Mean time of protocol B was %lf\n", (sumtimeB/100));
printf("Mean time of protocol C was %lf\n", (sumtimeC/100));
printf("Mean time of protocol D was %lf\n", (sumtimeD/100));
printf("Mean time of protocol E was %lf\n", (sumtimeE/100));
printf("Mean time of protocol F was %lf\n", (sumtimeF/100));
return 0;
}
<file_sep>/splitBlock.c
unsigned char* splitBlock(unsigned char* curr, int blockSize, int dataSize){
unsigned char* hi=curr;
unsigned char* lo=curr+1;
setBlock(1, *hi);
if((blockSize-3)>dataSize){//if block can fit at least two bytes of free space, including metadata, make free space
splitBin(dataSize, hi, lo);//set curr's size to the size of data requested (truncating it)
hi=curr+dataSize+2;//iterate our new pointers along
lo=hi+1;
blockSize=blockSize-dataSize-2;//blocksize of free block created when you allocate less than space in curr block
*hi=0;//zero out garbage vals in these bytes
*lo=0;
splitBin(blockSize, hi, lo);//set metadata for new metadata block
setBlock(0, *hi);
}
return curr;//curr was never iterated so we can return it as-is
}
<file_sep>/mymalloc.h
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define malloc(x) mymalloc(x,__FILE__,__LINE__)
#define free(x) myfree(x,__FILE__,__LINE__)
#define KEY 11474
char myMem[4096];
void* mymalloc(int, char *filename, int linenum);
void myfree(void*, char *filename, int linenum);
int bitadd(unsigned char high11, unsigned char low11, unsigned char high22, unsigned char low22);
int bitsub(unsigned char high11, unsigned char low11, unsigned char high22, unsigned char low22);
void combineBoth(char* prev, char* curr, char* next);
void combineNext(char* curr, char* next);
void combinePrev(char* curr, char* prev);
int getbit(int num, int position);
char getsizebits(char bits);
int bin2int(char highbyte, char lowbyte);
char* mallocTraverse(char* curr, int dataSize);
void setInUse(int inUse, char* hiMeta);
void splitBin(unsigned int currInt, char* hiMeta, char* loMeta);
char* splitBlock(char* curr, int blockSize, int dataSize);
char* bootStrap(char* ptr, char* hi, char* lo, int usrBlock);//set key, initialize first metadata
void printBin(char hi, char lo);
<file_sep>/free.c
#include <stdlib.h>
#include <stdio.h>
char* firstmeta = mem[2];
char* firstMallocPtr = mem[4];
char*lastaddress = mem[4095];
void combineNext(unsigned char* curr, unsigned char* next){
int nextinusebit = getbit(*next, 1);
if (nextinusebit == 0){
unsigned char currlowbits = *(curr+1);
unsigned char nextlowbits = *(next+1);
printf("Starting combining process. \n");
int sum= bitadd(*curr, currlowbits, *next, nextlowbits);
splitBin(sum, curr, curr+1);
setInUse(0, curr);
printf("Curr and Next combined.\n");
}
else if (nextinusebit ==1){
printf("Can't Combine. Next is in use.\n");
}
}
void combinePrev(unsigned char* curr, unsigned char* prev){
int previnusebit = getbit(*prev, 1);
if (previnusebit == 0){
unsigned char currlowbits = *(curr+1);
unsigned char prevlowbits = *(prev+1);
printf("Starting combining process. \n");
int sum= bitadd( *prev, prevlowbits, *curr, currlowbits);
splitBin(sum, curr, curr+1);
setInUse(0, prev);
printf("Curr and Prev combined.\n");
}
else if (previnusebit ==1){
printf("Can't Combine. Next is in use.\n");
}
}
void combineBoth(unsigned char* prev, unsigned char* curr, unsigned char* next){
int nextinuse = getbit(*next, 1);
int previnuse = getbit(*prev, 1);
if (nextinuse == 0){
combineNext(curr, next);
}
if (previnuse == 0){
combinePrev(curr, prev);
}
}
/*
in main:
//key = 11474
unsigned char lowbits = *(curr-1);
unsigned char highbits = *(curr -2);
int checkKey = bin2int(highbits, lowbits);
if (checkKey == 11474){
combineRight(curr, curr+1+currsize);
}
*/
/*
- prev = inuse curr next = inuse
- prev = !inuse curr next = inuse
- prev = !inuse curr next = !inuse
- prev = inuse curr next = !inuse
check left
if prev = free
extract 16-1 rightmost bits (the size bits) on curr
bin2int size bits on curr
extract size bits from prev
bin2int size bits on prev
bitadd prevsize curr size
int2bin sum
change prev ptr size to sum bits
set char ptr curr in use bit to 0
check right
if prev! freeblocks
check if curr + metadata at(currsize + sizeof(metadata)) is free
extract 16-1 rightmost bits (the size bits) on curr
bin2int size bits on curr
extract size bits from prev
bin2int size bits on prev
bitadd prevsize curr size
int2bin sum
change prev ptr size to sum bits
set char ptr curr in use bit to 0
if left in use and right in Use
do nothing. there is nothing to combine.
*/
/*
unsigned char* mallocTraverse(unsigned char* curr, int dataSize){
*curr=myMem[2];
while(curr>=lowerBound && curr<=upperbound){//lowerBound & upperBound will be global vars
int currMeta=bin2int(*curr, *(curr+1));
int inUse=getbit(currMeta, 15);//hopefully this works
char hiBits=getsizeBits(*curr);//blocking out in use bit
int currBlockSize=(hiBits, *(curr+1));//getting block size of current block
if(inUse==0 && currBlockSize>=dataSize){
//call split fxn
} else{
curr=(curr+currBlockSize);
}
}
printf("Memory full\n");
return NULL;
}
*/
checkptr(){
/*
checks if the pointer given to free is a valid ptr pointing at the start of block
while()
*/
}
void myfree(void *tofree, char*file, int*linenum){
tofree = (char*) tofree;
if (tofree == NULL){
printf("Error in %s line %d: Pointer received is NULL. \n", file, linenum);
}
if (ismeminit = 0){
printf("Error in %s line %d: Nothing malloc'd yet\n", file, linenum);
}
if(tofree<=lowerBound || tofree>upperbound){
printf("Error in %s line %d: Pointer is not in range of memory\n", file, linenum);
}
if(tofree>firstmeta && tofree<=lastaddress){
char *curr = firstmeta;
char *prev = NULL;
char *next = NULL;
while(curr < lastaddress ){
unsigned char currsizebits = getsize(curr);
int currsize = bin2int(currsizebits, curr+1);
if ((curr+2) > tofree){ // pointer is not pointing at the starting address of a block
printf("Error in %s line %d: Pointer is not the one given by malloc\n", file, linenum);
break;
}
if(curr+2 == tofree){
int isValid = getbit(curr, 1); //get inuse bit
if (isValid == 0){ // address already freed
printf("Error in %s line %d: Pointer is already freed.\n", file, linenum);
break;
}
else if (isValid == 1){ //this pointer can be freed
//free inuse bit, combine block
setInUse(0, curr);
// check if curr is the first and last block (only block)
if ((curr+1+currsize) == lastaddress && prev == NULL){
setInUse(0, curr);
break;
}
// check if prev is null / curr is first block
else{
if (prev == NULL){
next = (curr+1+currsize);
combineNext(curr, next);
break;
}
// check if curr is the last block / there is no next block
if((curr+1+currsize) == lastaddress){
combinePrev(curr, prev);
break;
}
// else combine both
else if((curr+1+currsize) < lastaddress && prev!=NULL){
next = (curr+1+currsize);
combineBoth(prev, curr, next);
break;
}
}
//break;
}
}
//update pointers
prev = curr;
curr = curr+1+currsize;
}
}
}
<file_sep>/bin2int.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include<stdbool.h>
#define KEY 0010110011010010
/*
CONTAINS: getbit, setbit, bin2int, bitadd, bitsub, getsizebits
*/
int bin2int(unsigned char, unsigned char);
int getbit(int , int);
//int adding(unsigned char, unsigned char, unsigned char, unsigned char);
//int bitsub(unsigned char, unsigned char, unsigned char, unsigned char);
unsigned char getsizebits(bits);
//send in the whole byte. returns size bits.
unsigned char getsizebits(unsigned char bits){
unsigned char sizebits, mask;
mask = (1 << 7) -1;
sizebits = bits & mask;
return sizebits;
}
/*
send in high and low bytes for the meta data you want to add TO (highleva2, lowleva2) send in metadata bytes for the meta data you have to add (the one youre gonna free)
bit add will call a method to retreive the size bits from the whole bytes and then send that to bin2int and then add+return the resulting ints' sum
*/
int bitadd(unsigned char high11, unsigned char low11, unsigned char high22, unsigned char low22){
unsigned char high1, high2;
high1 = getsize(high11);
//low1 = getsize(low11);
high2 = getsize(high22);
//low2 = getsize(low22);
int add2 = bin2int(high1, low11);
int add1 = bin2int(high2, low22);
int sum = add2+add1;
return sum;
}
/*
look at notes for bit add, does the same thing. highlevel/lowlevel subfrom should be the bigger number you subtract FROM
bitsub will follow same procedure as bitadd, dont forget to call split in mymalloc()
call method that retrieves the size bits.
*/
int bitsub(unsigned char high11, unsigned char low11, unsigned char high22, unsigned char low22){
unsigned char high1, high2;
high1 = getsize(high11);
//low1 = getsize(low11);
high2 = getsize(high22);
//low2 = getsize(low22);
int subfrom = bin2int(high1, low11);
int tosub = bin2int(high2, low22);
int sum = subfrom-tosub;
return sum;
}
int getbit(int num, int position){ //WORKS
int bitstate = (num >> position) &1;
return bitstate;
}
/*
MUST SEND IN SIZE BYTES ONLY
this method will NOT take inuse bit into account when converting.
getbit will give you the bit at any given position
send in the lowlevel and high level bits you want to convert into ints, will return the int
*/
int bin2int(unsigned char highbyte, unsigned char lowbyte){ //WORKS
int j =0;
int i=0;
char binarr[15];
for(i = 7; i>=0; i--){
binarr[i] = getbit(highbyte, j);
j++;
}
j=0;
for(i = 15; i>= 8; i--){
binarr[i] = getbit(lowbyte, j);
j++;
}
//bin arr gives you full binary array ex. byte holds 14 -> binarr = [0,0,0,0,0,0,0,0,1,1,1,0]
j = 0;
int sum = 0;
// this loop goes through binarr and calculate 2^binarr[i] power and sums it to give you the final int. starts at 2^0 (binarr[15])
for(i =15; i>=0; i-- ){
int bin = binarr[i];
if(bin == 0){
j++;
}
else if (bin == 1){
sum += pow(2, j);
j++;
}
}
return sum;
}
int main (int argc, char**argv){
unsigned char high= 0b0000001;
unsigned char low = 0b00001111;
int f = bin2int(high, low);
printf("INT : %d", f);
unsigned char high2= 0b0000000;
unsigned char low2 = 0b00001111;
int added = bitadd(high, low, high2, low2);
printf("sum : %d \n", added);
int subtracted = bitsub(high, low, high2, low2);
printf("subtracted : %d\n", subtracted);
return 0;
}
<file_sep>/mallocfinal.c
#include "mymalloc.h"
void* mymalloc(int size, char *filename, int linenum){
char* first=&(myMem[0]);
char* second=&(myMem[1]);
char* ptr= &(myMem[0]);
int usrBlock=4092;//size of arr-metadata bits- size of key
int firstBytes=bin2int(*first, *second);
if(firstBytes!=KEY){//set key to initialize method
ptr=bootStrap(ptr, first, second, usrBlock);//set key, initialize first metadata
}
if(size>usrBlock || size<=0){//if user tries to allocate more memory than size of array/metadata/key allows for, or a negative value
if(size>usrBlock){
printf("Memory request exceeds size of working memory in file %s at line %d\n", __FILE__, __LINE__);
return NULL;
} else{
printf("Invalid memory request in file %s at line %d\n", __FILE__, __LINE__);
}
}else{
ptr=mallocTraverse(ptr, size);//calling the meat of the program, returns either a pointer to usable memory or a null pointer
}
return (void*)ptr;
}
void myfree(void *tofree, char *filename, int linenum){
char* firstmeta = &(myMem[2]);
tofree = (char*) tofree;
char* first=&(myMem[0]);//set pointer to first index of arr
char* second=&(myMem[1]);//set pointer to second byte of arr
int firstbytes=bin2int(*first, *second);
if ((char*)tofree == NULL){
printf("Error in %s line %d: Pointer received is NULL. \n", __FILE__, __LINE__);
return;
}
if(firstbytes!= KEY){
printf("Error in %s line %d: Nothing malloc'd yet\n", __FILE__, __LINE__);
return;
}
if((char*)tofree<(char*)(&(myMem[2])) || (char*)tofree>(char*)(&(myMem[4095]))){
printf("Error in %s line %d: Pointer is not in range of memory\n", __FILE__, __LINE__);
return;
}
if((char*)tofree>=(char*)(&(myMem[2])) && (char*)tofree<=(char*)(&(myMem[4095]))){
char *curr = firstmeta;
char *prev = NULL;
char *next = NULL;
//traversal
while(curr <= (&(myMem[4095]))){
char currsizebits = getsizebits(*(curr));
int currsize = bin2int(currsizebits, *(curr+1));
if ((char*)(curr+2) > (char*)tofree){ // pointer is not pointing at the starting address of a block
printf("Error in %s line %d: Pointer is not the one given by malloc\n", __FILE__, __LINE__);
return;
}
else if((char*)(curr+2) == tofree){
int isValid = getbit(*(curr), 15); //get inuse bit
if (isValid == 0){ // address already freed
printf("Error in %s line %d: Pointer is already freed.\n", __FILE__, __LINE__);
return;
}
else if (isValid == 1){ //this pointer can be freed
//free inuse bit, combine block
setInUse(0, curr);
// check if curr is the first and last block (only block)
if ((curr+1+currsize) == (&(myMem[4095])) && prev == NULL){
setInUse(0, curr);
return;
}
// check if prev is null / curr is first block
else{
if (prev == NULL){
next = (curr+2+currsize);
combineNext(curr, next);
return;
}
if((curr+1+currsize) == (&(myMem[4095]))){
combinePrev(curr, prev);
break;
}
else{
next = (curr+2+currsize);
combineBoth(prev, curr, next);
break;
}
}
}
}
//update pointers
prev = curr;
curr = (char*)(curr+2+currsize);
if ((char*)(curr+2) > (char*)tofree){ // pointer is not pointing at the starting address of a block
printf("Error in %s line %d: Pointer is not the one given by malloc\n", __FILE__, __LINE__);
return;
}
}
}
}
char* splitBlock(char* curr, int blockSize, int dataSize){
char* hi=curr;
char* lo=curr+1;
if((blockSize-3)>dataSize){//if block can fit at least two bytes of free space, including metadata, make free space
splitBin(dataSize, hi, lo);//set curr's size to the size of data requested (truncating it)
setInUse(1, hi);
hi=curr+dataSize+2;//iterate our new pointers along
lo=hi+1;
blockSize=blockSize-dataSize-2;//blocksize of free block created when you allocate less than space in curr block
*hi=0;//zero out garbage vals in these bytes
*lo=0;
splitBin(blockSize, hi, lo);//set metadata for new metadata block
setInUse(0, hi);
}else{
splitBin(blockSize, hi, lo);
setInUse(1, hi);
}
return curr;//curr was never iterated so we can return it as-is
}
void splitBin(unsigned int currInt, char* hiMeta, char* loMeta){
*hiMeta=0;
*loMeta=0;
int i =0;
unsigned int mask=0;
unsigned int currBit=0;
for(i=15; i>=0; i--){
mask=0;
currBit=currInt>>i;
if(i<=7){
mask=1<<(i);
*loMeta=(*loMeta & ~mask) | ((currBit << i) & mask);
} else{
mask=1<<(i-8);
*hiMeta=(*hiMeta & ~mask) | ((currBit << (i-8)) & mask);
}
}
return;
}
char* bootStrap(char* ptr, char* hi, char* lo, int usrBlock){
hi=ptr;//set key
lo=ptr+1;
splitBin(KEY, hi, lo);
hi=ptr+2;//initialize metadata after key
lo=hi+1;
*hi=0;
*lo=0;
splitBin(usrBlock, hi, lo);//set metadata for new metadata block
setInUse(0, hi);
return hi;
}
/*sets the in use bit , takes in an integer (functioning as a boolean), to tell it whether to assign the val to be either 1 or 0*/
void setInUse(int inUse, char* hiMeta){
unsigned int mask=1<<7;
unsigned int currBit=0;
if(inUse==0){
*hiMeta=(*hiMeta & ~mask) | ((currBit) & mask);
} else if(inUse==1){
currBit=1<<7;
*hiMeta=(*hiMeta & ~mask) | ((currBit) & mask);
}
return;
}
char* mallocTraverse(char* curr, int dataSize){
curr=&(myMem[2]);
*curr=myMem[2];
while(curr>=(&(myMem[2])) && curr<(&(myMem[4095]))){//lowerBound & upperBound will be global vars
int currMeta=bin2int(*curr, *(curr+1));//converting chars to an int to send to getbit
int inUse=getbit(currMeta, 15);//getting the in use bit
char hiBits=getsizebits(*curr);//blocking out in use bit to get size of block
int currBlockSize=bin2int(hiBits, *(curr+1));//getting block size of current block
if(inUse==0 && currBlockSize>=dataSize){//if there's enough space to return to the user
curr=splitBlock(curr, currBlockSize, dataSize);//prepare it to return
return curr+2;//return pointer to actual data block, not trying to overwrite metadata
break;
}
else{
curr=(curr+2+currBlockSize);
}
}
/* got to end of array without finding an empty block */
printf("Memory request exceeds size of working memory in file %s at line %d\n", __FILE__, __LINE__);
return NULL;
}
// methods for free:
int bin2int(char highbyte, char lowbyte){
int j =0;
int i=0;
char binarr[15];
for(i = 7; i>=0; i--){
binarr[i] = getbit(highbyte, j);
j++;
}
j=0;
for(i = 15; i>= 8; i--){
binarr[i] = getbit(lowbyte, j);
j++;
}
//bin arr gives you full binary array ex. byte holds 14 -> binarr = [0,0,0,0,0,0,0,0,1,1,1,0]
j = 0;
int sum = 0;
// this loop goes through binarr and calculate 2^binarr[i] power and sums it to give you the final int. starts at 2^0 (binarr[15])
for(i =15; i>=0; i-- ){
int bin = binarr[i];
if(bin == 0){
j++;
}
else if (bin == 1){
sum += pow(2, j);
j++;
}
}
return sum;
}
char getsizebits(char bits){
char sizebits, mask;
mask = (1 << 7) -1;
sizebits = bits & mask;
return sizebits;
}
int getbit(int num, int position){ //WORKS
int bitstate = (num >> position) &1;
return bitstate;
}
int bitadd(unsigned char high11, unsigned char low11, unsigned char high22, unsigned char low22){
char high1, high2;
high1 = getsizebits(high11);
high2 = getsizebits(high22);
int add2 = bin2int(high1, low11);
int add1 = bin2int(high2, low22);
int sum = add2+add1;
return sum;
}
void combineNext(char* curr, char* next){
int nextinusebit = getbit(*next, 7);
if (nextinusebit == 0){
char currhibits=getsizebits(*curr);
char nexthibits=getsizebits(*next);
int currNum=bin2int(currhibits, *(curr+1));
int nextNum=bin2int(nexthibits,*(next+1));
int sum= bitadd(*curr, currlowbits, *next, nextlowbits);
sum = sum+2; // add next's meta data
splitBin(sum, curr, curr+1);
setInUse(0, curr);
}
}
void combinePrev(char* curr, char* prev){
int previnusebit = getbit(*prev, 7);
if (previnusebit == 0){
int sum= bitadd( *prev, *(prev+1), *curr,*(curr+1));
sum = sum+2;
splitBin(sum, prev, prev+1);
setInUse(0, prev);
}
}
void combineBoth(char* prev, char* curr, char* next){
int nextinuse = getbit(*next, 7);
int previnuse = getbit(*prev, 7);
if (nextinuse == 0){
combineNext(curr, next);
}
if (previnuse == 0){
combinePrev(curr, prev);
}
}
<file_sep>/splitBin.c
#include <stdio.h>
#include <stdlib.h>
void splitBin(unsigned int currInt, unsigned char* hiMeta, unsigned char* loMeta);
void printBin(unsigned char hi, unsigned char lo);
void printSingleBin(unsigned char byte);
void printBinInt(unsigned int val);
void setInUse(int inUse, unsigned char* hiMeta);
int main(int argc, char** argv){
unsigned int input=93;
unsigned char hi='0';
unsigned char lo='0';
printf("begin: \n");
printBin(hi, lo);
unsigned char* ptrhi=&hi;
unsigned char* ptrlo=&lo;
splitBin(input, ptrhi, ptrlo);
printf("high: ");
printSingleBin(hi);
printf("low: ");
printSingleBin(lo);
setInUse(0, ptrhi);
printf("calling printBin: \n");
printBin(hi, lo);
return 0;
}
/*
it effectively works like a function to set size metadata
use after int arithmetic to save new sum to metadata chars
send in an int, this extracts the bits from it and directly inserts them into the meta data chars using the given high and low byte pointers to the metadata -> int holds 615 (equiv.: 0000001001100111): *hiMeta:00000010 *loMeta: 01100111
(as of right now it deletes the value in the 'in use' bit when assigning the new val to the chars)
*/
void splitBin(unsigned int currInt, unsigned char* hiMeta, unsigned char* loMeta){
*hiMeta=0;
*loMeta=0;
printf("currInt: ");
printBinInt(currInt);
unsigned int mask=0;
unsigned int currBit=0;
for(int i=11; i>=0; i--){
printf("i: %d \n", i);
mask=0;
currBit=currInt>>i;
if(i<=7){
mask=1<<(i);
*loMeta=(*loMeta & ~mask) | ((currBit << i) & mask);
} else{
mask=1<<(i-8);
*hiMeta=(*hiMeta & ~mask) | ((currBit << (i-8)) & mask);
}
printf("currBit ");
printBinInt(currBit);
printf("mask: ");
printBinInt(mask);
printf("at %d: ", i);
printBin(*hiMeta, *loMeta);
}
return;
}
void printBin(unsigned char hi, unsigned char lo){
int shift=0;
int currBit=0;
for(int i=15; i>=0; i--){
if(i>7){
shift=(i-8);
currBit=hi>>shift;
} else{
shift=i;
currBit=lo>>shift;
}
if(currBit & 1){
printf("1");
}else{
printf("0");
}
}
printf("\n");
return;
}
void printBinInt(unsigned int val){
int shift=0;
int currBit=0;
for(int i=31; i>=0; i--){
shift=i;
currBit=val>>shift;
if(currBit & 1){
printf("1");
}else{
printf("0");
}
}
printf("\n");
return;
}
void printSingleBin(unsigned char byte){
int shift=0;
int currBit=0;
for(int i=7; i>=0; i--){
shift=i;
currBit=byte>>shift;
if(currBit & 1){
printf("1");
}else{
printf("0");
}
}
printf("\n");
return;
}
<file_sep>/readme.txt
Extra Credit:
- Metadata size: 2 Bytes
The meta data was sorted in chars because the chars are guaranteed to be a single byte. We are using two chars to store all of the metadata ().
we bit shifted and masked in order to store data. Since the memory array is 4096 bytes, we need a minimum of 12 bits (2^12=4096) to store the size. Since the key takes up 2 bytes and metadata blocks take up 2 bytes, the most we can allocate in one block is 4092, therefore, 2^12 fits our requirements in terms of bits. The 12 rightmost bits store the size bits and the left most bit is the in use bit. If the block has been given to the user by malloc then the in use bit will be 1 else, if the block is free the in use bit is 0. Were using 16 bits however, we really only need 13 bits, however, the extra 3 bits that are wasted do not make much of a difference in terms of space usage. The 3 bits will take some time to add up to a significant amount of bytes. Keeping the extra 3 bits help storing and accessing data easier because it makes up 2 blocks of the array.
Metadata structure: | 1 000 1111| 11110000|
^ ^
in use bits starting of the size bits
Bit shifting and Masking:
Methods:
setInUse - takes in a byte and the bit you want to set the in use bit to
getbit - takes in the byte and the position of bit to extract and returns the value of the bit at that position. used to check the inuse bit
getsizebits - removes the in use bit and returns the size bits from the given byte.
bin2int - takes in pointers to high and low bytes and converts it into an integer. used for bit add to find the new sum size after combining blocks
splitbin - takes in an integer and divides the bits into two chars to set the size of the metadata
Malloc
- Algorithm:
- Traversing: mallocTraverse
-Traverses through the array, checking size bits and in use bits until it reaches a block the same size as or larger than the amount of space requested that isn't in use. If such a block is found, splitblock is called, otherwise an insufficient memory message is displayed.
- Splitting Blocks: splitBlock
- How many bytes to give back to user:
*If the space found is the exact same size as the amount of memory requested by the user, return just that, without altering the blocks adjacent to it.
*If the space found is larger than the amount being malloced by the user, and has enough space to store metadata plus 2 bytes of memory, the block is split into a block the same size as the size requested, and the in use bit is flipped. The adjacent block's size is set to that of the original block - user requested size, with an in use bit set to zero.
*If the space found is larger than the user requested size, but fewer than 4 bytes larger (2 metadata bytes + 2 data bytes), the whole block is returned to the user, without splitting.
- Setting in use bits: In use bits are set using the get bit method, specifically to set a block to 'in use' status, or if a block is being split, to 'not in use'.
- Error Checkings
- size input validity: Checked for a request larger than 4092 bytes (the size of the array, minus the key bytes and the first metadata block) in the main 'mymalloc' function, and for requests less than or equal to zero (because obviously neither a negative malloc nor a malloc of size zero can occur)
Free:
- Algorithm:
- Traversing:
I start at the first metadata (&mem[2]) and move to (metadata size +2) and continue until I find the pointer given in by the user or the current pointer to the meta data is greater than the pointer received. Traverses by comparing pointers and accessing size bits in order to move to the next metadata.
- Fragmentation:
Upon every free, when the right block to free is found, I try to combine any free blocks surrounding the current block. I check if:
- Current block is the only block in the whole memory (mallocd blocksize is 4092 bytes)
-> Just change set bit to 0
- Curr is first block -> prev is null but next is not
- combine with next block if next block is not inuse
set currents inuse bit to 0
- just change set bit of current block to 0 if next block is in use
- Curr is last block -> next is null
- combine with previous block if previous block's set bit is 0
update size of prev to be prev size + curr size+ 2 for metadata block
- do nothing if previous block is in use
- Prev block is not null and Next block is not null
-check if next block's set bit block is 0, if it is then combine current and next by changing the size bits of current to currentsize+nextsize+2 and set current's set bit to 0.
- check if previous block's inuse bit is 0 if it is 0 combine by updating prev block size to prevsize+currentsize+2
change current block inuse bit to 0
- Error Checks:
If any of the following errors were encountered with the pointer received, the error message was returned.
- if pointer given is null
- if key is not initialized --> first two bytes should equal 11474 (a predefined key)
means that no pointers have been mallocd yet
- if pointer is outside the array length/bounds
pointer is not mallocd by mymalloc
- if pointer given does not point to the starting of a block of data --> Checked by seeing if address of pointer given matched address of metadata+2
| metadata byte 1 | metadata byte 2 | blocks of data |
^ ^
where pointer should be pointing where pointer is pointing
^
if pointer sent in doesnt = address | of above pointer, then return error
Findings:
We are able to confirm that our version of malloc and free works because after the workloads were completed, when the first block's size was printed out, it equaled 4092, which is the amount memory we started out with.
The workloads helped verify that we are able to deal with extremely small mallocs of 1 byte. We are able to give the user exactly what they ask for. Freeing the one byte pointers showed immediately that free worked. When printing out addresses of the pointers given by malloc showed that each of the 50 pointers were of the same address because they were freed after the malloc call.
For B, the workload tested free's fragmentation algorithms. By freeing pointers one by one, we are required to combine the blocks if we want to return to the original free block of 4092.
C verified that free wont work on not mallocd array. Shows that program can handle what is asked for regardless of when
For D, mallocing random bytes tested malloc's ability to take in any given request for bytes and evaluate it. If the request can be fulfilled, malloc sent back a pointer.
The workloads helped us find errors in our code. In one space the wrong parametor was sent in.
<file_sep>/setInUse.c
/*sets the in use bit , takes in an integer (functioning as a boolean), to tell it whether to assign the val to be either 1 or 0*/
void setInUse(int inUse, unsigned char* hiMeta){
unsigned int mask=1<<7;
unsigned int currBit=0;
if(inUse==0){
*hiMeta=(*hiMeta & ~mask) | ((currBit) & mask);
} else if(inUse==1){
currBit=1<<7;
printf("currBit: ");
printBinInt(currBit);
printf("mask: ");
printBinInt(mask);
printf("*hiMeta: ");
printSingleBin(*hiMeta);
unsigned int combo=(*hiMeta & ~mask);
printf("*hiMeta & ~mask: ");
printBinInt(combo);
*hiMeta=(*hiMeta & ~mask) | ((currBit) & mask);
}
return;
}
<file_sep>/decompressor.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <math.h>
struct HeapNode* makeHeapNode(struct HeapNode* node, int freq, char* token);
void reverse(char*, int length) ;
char* itoa(int num, char* str, int base) ;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
struct HeapNode* treeFromCBook(struct HeapNode* head, char* codebook);
struct HeapNode* insertEntry(struct HeapNode* head, char* directions, char* token, int index, int count);
void printTree(struct HeapNode* head);
struct HeapNode* makeHeapNode(struct HeapNode* node, int freq, char* token);
void decompress( char* compressed, char* codebook);
//remember to free everything everwhere
char* itoa(int num, char* str, int base)
{
int i = 0;
int isNegative = 0;
/* Handle 0 explicitely, otherwise empty string is printed for 0 */
if (num == 0)
{
str[i++] = '0';
str[i] = '\0';
return str;
}
// Process individual digits
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}
str[i] = '\0'; // Append string terminator
// Reverse the string
//reverse(str, i);
printf("STR :%s ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", str);
return str;
}
/*void reverse(char* str, int length)
{
int start = 0;
int end = length -1;
while (start < end)
{
swap(*(str+start), *(str+end));
start++;
end--;
}
} */
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& (duplicate from other file)
struct HeapNode{
int frequency;
char* name;//token gathered
int height;
struct HeapNode* left;
struct HeapNode* right;
};
int isFile(char *to_read) ;
int isFile(char *to_read) {
struct stat s;
if(stat(to_read, &s) == 0) {
if(s.st_mode & S_IFDIR) {
return 0;
} else if(s.st_mode & S_IFREG) {
return 1;
} else {
printf("Error, not found\n");
return -7;
}
} else {
return -6;
}
}
//struct HeapNode* makeHeapNode(struct HeapNode* node, int freq, char* token);
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
//struct HeapNode* treeFromCBook(struct HeapNode* head, char* codebook);
struct HeapNode* treeFromCBook(struct HeapNode* head, char* codebook){
printf("CODEBOOK IN TREEFROMC: %s", codebook);
char* dictEntry[2];
dictEntry[0]=NULL;
dictEntry[1]=NULL;
int fd=open(codebook, O_RDONLY);
int size=lseek(fd, 0, SEEK_END);//find the size of the file
printf("filesize: %d\n", size);
int l= lseek(fd, 0, SEEK_SET);
char* buffer= NULL;
buffer = (char*)malloc(size*sizeof(char));
int bufIndex=0;
read(fd, buffer,size);
int count =0; // total number of nodes that
int startingindex=0;
int toklen=0;
while( bufIndex < size){
printf("buffer at index %d: %c\n", bufIndex, buffer[bufIndex]);
if(buffer[bufIndex]=='\n' || buffer[bufIndex]==' '|| buffer[bufIndex]=='\t' || buffer[bufIndex]=='\r' || buffer[bufIndex]== '\v'){
char* delim=(char*) malloc(sizeof(char)*2);
if(delim == NULL){
printf("malloc failed in decompress\n");
return;
}
delim[0]=buffer[bufIndex];
printf("_%c_\n", delim[0]);
delim[1]='\0';
buffer[bufIndex]='\0';//make token complete string
toklen = bufIndex-startingindex;
printf("toklen: %d\n", toklen);
char* currNodeName= (char*) malloc(sizeof(char)*toklen+1);
strncpy(currNodeName, buffer+startingindex, toklen);
currNodeName[toklen] = '\0';
startingindex = bufIndex+1; //move up starting index
if(delim[0]!='\n' && toklen!=0){
dictEntry[0]=currNodeName;
}
else if(delim[0]=='\n' && toklen!=0){
printf("EXCUSE ME\n");
dictEntry[1]=currNodeName;
int length=strlen(dictEntry[0]);
printf("binary in dict: %s\n", dictEntry[0]);
printf("length: %d\n", length);
printf("Dictionaru entries: 0:%s 1:%s\n\n", dictEntry[0],dictEntry[1]);
head=insertEntry(head, dictEntry[0], dictEntry[1], 0, count);//call fxn
count = count + length;
printf("count : %d\n\n", count);
free(dictEntry[0]);
free(dictEntry[1]);
}
}
bufIndex++;
}
/*create head of tree
open code book, read from it line by line, tokenizing the first thing after each newline, for each line take binary token and parse it, but also tokenize value,
char by char, if char==0, give current node a left node, else give a right node, once binary token has been parsed (having checked each time if any more vals in binary token), fill final node with name of token*/
printTree(head);
return head;
}
struct HeapNode* insertEntry(struct HeapNode* head, char* directions, char* token, int index, int count){
printf("Insert Entry DIRECTIONS: %s\n", directions);
if(head==NULL){
int count2 = count;
printf("hello\n");
int digits = 0;
do {
count2 /= 10;
digits++;
}
while (count2 != 0);
printf("NEW COUNT %d AND DIGITS %d", count, digits);
char* cstr = (char*) malloc(digits+1 * sizeof(char));
cstr = itoa(count, cstr, 10);
printf("cstr %s\n", cstr);
struct HeapNode* node=makeHeapNode(node, 0, cstr);
printf("PRINT TREE for dir:%s\n", directions);
printTree(node);
printf("PRINTED TREE\n\n");
//printf("the name: %s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", directions);
count++;
head=node;
printf("IE: inserted %d\n", node->height);
if(index==strlen(directions)){
printf("IE: index: %d\n", index);
node->name=token;
printf("nnnode name :%s \n", node->name);
return node;
}
//return node;
}
if(directions[index]=='1'){//if(directions[0]='1')
printf("going right\n");
count++;
index++;
printf("count in right %d\n", count);
head->right=insertEntry(head->right,directions, token, index, count);//syntax
}
if(directions[index]=='0'){//if(directions[0]='1')
printf("going left\n");
count++;
printf("count in left %d\n", count);
index++;
head->left=insertEntry(head->left,directions, token, index, count);
printf("returned\n");
}
printf("index: %d, returning\n", index);
return head;
}
void printTree(struct HeapNode* head){
if(head==NULL){
return;
}
if(head->name==NULL){
printf("NULL\n");
}
else{
printf("Name: %s\n", head->name);
}
printf("going left: ");
printTree(head->left);
printf("going right: ");
printTree(head->right);
}
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
struct HeapNode* makeHeapNode(struct HeapNode* node, int freq, char* token){
node=(struct HeapNode*)malloc(sizeof(struct HeapNode)*1);
node->name=token;
node->frequency=freq;
node->left=NULL;
node->right=NULL;
return node;
}
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
void decompress( char* compressed, char* codebook){
if (isFile(compressed) == 1){
printf("Compressed: %s\n",compressed);
printf("Codebook: %s\n",codebook);
//WOULD REALISTICALLY HAVE TO SEARCH FOR CODEBOOK IN DIRECTORY, NEED ALGO FOR THAT
struct HeapNode* head= treeFromCBook( head, codebook); // ????needs head
struct HeapNode* ptr=NULL;
ptr=head;
int td=open(compressed, O_RDONLY);
if(td == -1){
printf("Error: Cannot open Compressed file\n");
}
int clen = strlen(compressed);
clen = clen - 4; // subtract ".hcz"
char* decompressed = (char*) malloc(clen*sizeof(char));
decompressed[0] = '\0';
strncpy(decompressed, compressed, clen);
int fd=open(codebook, O_RDONLY);
if(fd == -1){
printf("Error: Cannot open Codebook\n");
}
int id=open(decompressed, O_CREAT | O_WRONLY| O_APPEND);
if(id == -1){
printf("Error: Cannote open Codebook\n");
}
char* buffer=NULL;
buffer = (char*) malloc(2*sizeof(char));
if(buffer == NULL){
printf("Malloc failed in decompress\n");
return;
}
while(read(fd, buffer,1)){
if(ptr==NULL){
printf("invalid data in compressed file\n");
ptr=head;//reset
return; // ??????
}
if(ptr->name==NULL){
if(buffer[0]=='0'){
ptr=ptr->left;
}
else if(buffer[0]=='1'){
ptr=ptr->right;
}
else{
printf("Error in Decompress:Compressed file contained a non 1 or 0 number \n");
return;
}
}
else{
int currSize=strlen(ptr->name);
char* currToken= NULL;
currToken=(char*)malloc(currSize*sizeof(char));
if(currToken == NULL){
printf("Malloc failed in decompress\n");
return;
}
currToken=ptr->name;
int written = write(id, currToken, strlen(currToken));
if(written <1){
printf("Error Write to file failed in Decompress\n");
return;
}
ptr=head;//reset ptr to top of stack
}
}
return;
//call buildtree or whatev its called
//read from file char by char
//on a 0, go left in tree, on a 1 go right, at each node check to see if name is null
//if name isn't null, write that to file
//if directions steer u to null node, print error message
}
else{
printf("decompress not given file error\n");
return;
}
}
int main(int argc, char** argv){
if(argc<2){
printf("error");
return 0;
}
struct HeapNode* head=NULL;
head=treeFromCBook(head, argv[2]);
decompress(argv[1], argv[2]);
return 0;
}
<file_sep>/_myMalloc.c
//main: if first (2? 4?) bytes arent set to key, set key, and set the first piece of metadata.
/*split method: see how much data user is requesting (takes pointer to metadata block, amount of space user requested)
at first instance of a space big enough
error checking: did user ask for too much?
-->if space is bigger than requested
--> reduce
-->if too small for metadata+2 bytes, return the whole thing to user as is
else: --> make new metadata, set size to the value originally stored for size of currblock MINUS size of space being allocated MINUS
size of metadata
else if space==size:
continue
else if no eligible space: print error message
traverse array method(returns pointer):
while index!=4095
if in use bit==flipped
bintoInt-> traverse that many spaces onward
move to next
else bin2Int ->compare to amount of space user asks for, if too small move on
else return pointer to space */
// make global vars with the address range of the array, size of metadata, key
#include "mymalloc.h"
int getbit(int num, int position);
unsigned char getsizebits(unsigned char bits);
int bin2int(unsigned char highbyte, unsigned char lowbyte);
unsigned char* mallocTraverse(unsigned char* curr, int dataSize);
void setInUse(int inUse, unsigned char* hiMeta);
void splitBin(unsigned int currInt, unsigned char* hiMeta, unsigned char* loMeta);
unsigned char* splitBlock(unsigned char* curr, int blockSize, int dataSize);
void* mymalloc(int size, __FILE__, __LINE__);
void* mymalloc(int size, __FILE__, __LINE__){
unsigned char* first=myMem[0];
unsigned char* second=myMem[1];
unsigned char* ptr= myMem[0];
int firstBytes=bit2int(*first, *second);
if(firstBytes!=key){//set key to initialize method
int usrBlock=4092;//size of arr-metadata bits- size of key
*ptr=key;
ptr=ptr+2;
first=ptr;//initialize metadata after key
second=ptr+1;
*first=0;
*second=0;
splitBin(usrBlock, first, second);//set metadata for new metadata block
setBlock(0, *hi);
}
if(size>usrBlock || size<0){//if user tries to allocate more memory than size of array/metadata/key allows for, or a negative value
if(size>usrBlock){
printf("Memory request exceeds size of working memory in file %d at line %d\n", __FILE__, __LINE__);
return NULL;
} else{
printf("Invalid memory request in file %d at line %d\n", __FILE__, __LINE__);
}
}else{
ptr=mallocTraverse(ptr, size);//calling the meat of the program, returns either a pointer to usable memory or a null pointer
}
return (void*)ptr;
}
unsigned char* splitBlock(unsigned char* curr, int blockSize, int dataSize){
unsigned char* hi=curr;
unsigned char* lo=curr+1;
setBlock(1, *hi);
if((blockSize-3)>dataSize){//if block can fit at least two bytes of free space, including metadata, make free space
splitBin(dataSize, hi, lo);//set curr's size to the size of data requested (truncating it)
hi=curr+dataSize+2;//iterate our new pointers along
lo=hi+1;
blockSize=blockSize-dataSize-2;//blocksize of free block created when you allocate less than space in curr block
*hi=0;//zero out garbage vals in these bytes
*lo=0;
splitBin(blockSize, hi, lo);//set metadata for new metadata block
setBlock(0, *hi);
}
return curr;//curr was never iterated so we can return it as-is
}
void splitBin(unsigned int currInt, unsigned char* hiMeta, unsigned char* loMeta){
*hiMeta=0;
*loMeta=0;
unsigned int mask=0;
unsigned int currBit=0;
for(int i=11; i>=0; i--){
mask=0;
currBit=currInt>>i;
if(i<=7){
mask=1<<(i);
*loMeta=(*loMeta & ~mask) | ((currBit << i) & mask);
} else{
mask=1<<(i-8);
*hiMeta=(*hiMeta & ~mask) | ((currBit << (i-8)) & mask);
}
}
return;
}
/*sets the in use bit , takes in an integer (functioning as a boolean), to tell it whether to assign the val to be either 1 or 0*/
void setInUse(int inUse, unsigned char* hiMeta){
unsigned int mask=1<<7;
unsigned int currBit=0;
if(inUse==0){
*hiMeta=(*hiMeta & ~mask) | ((currBit) & mask);
} else if(inUse==1){
currBit=1<<7;
unsigned int combo=(*hiMeta & ~mask);
*hiMeta=(*hiMeta & ~mask) | ((currBit) & mask);
}
return;
}
unsigned char* mallocTraverse(unsigned char* curr, int dataSize){
*curr=myMem[2];
while(curr>=lowerBound && curr<=upperbound){//lowerBound & upperBound will be global vars
int currMeta=bin2int(*curr, *(curr+1));//converting chars to an int to send to getbit
int inUse=getbit(currMeta, 1);//getting the in use bit
char hiBits=getsizeBits(*curr);//blocking out in use bit to get size of block
int currBlockSize=bin2int(hiBits, *(curr+1));//getting block size of current block
if(inUse==0 && currBlockSize>=dataSize){//if there's enough space to return to the user
curr=splitBlock(curr, currBlockSize, dataSize);//prepare it to return
return curr+2;//return pointer to actual data block, not trying to overwrite metadata
} else{
curr=(curr+currBlockSize);
}
}
/* got to end of array without finding an empty block */
printf("Memory request exceeds size of working memory in file %d at line %d\n", __FILE__, __LINE__);
return NULL;
}
int bin2int(unsigned char highbyte, unsigned char lowbyte){ //WORKS
int j =0;
int i=0;
char binarr[15];
for(i = 7; i>=0; i--){
binarr[i] = getbit(highbyte, j);
j++;
}
j=0;
for(i = 15; i>= 8; i--){
binarr[i] = getbit(lowbyte, j);
j++;
}
//bin arr gives you full binary array ex. byte holds 14 -> binarr = [0,0,0,0,0,0,0,0,1,1,1,0]
j = 0;
int sum = 0;
// this loop goes through binarr and calculate 2^binarr[i] power and sums it to give you the final int. starts at 2^0 (binarr[15])
for(i =15; i>=0; i-- ){
int bin = binarr[i];
if(bin == 0){
j++;
}
else if (bin == 1){
sum += pow(2, j);
j++;
}
}
return sum;
}
unsigned char getsizebits(unsigned char bits){
unsigned char sizebits, mask;
mask = (1 << 7) -1;
sizebits = bits & mask;
return sizebits;
}
int getbit(int num, int position){ //WORKS
int bitstate = (num >> position) &1;
return bitstate;
}
<file_sep>/tempfree.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include<stdbool.h>
#define KEY 0010110011010010
/*
CONTAINS: getbit, setbit, bin2int, bitadd, bitsub, getsizebits
*/
char* firstmeta = mem[2];
char* firstMallocPtr = mem[4];
char*lastaddress = mem[4095];
int bin2int(unsigned char, unsigned char);
int getbit(int , int);
//int adding(unsigned char, unsigned char, unsigned char, unsigned char);
//int bitsub(unsigned char, unsigned char, unsigned char, unsigned char);
unsigned char getsizebits(bits);
/*
send in high and low bytes for the meta data you want to add TO (highleva2, lowleva2) send in metadata bytes for the meta data you have to add (the one youre gonna free)
bit add will call a method to retreive the size bits from the whole bytes and then send that to bin2int and then add+return the resulting ints' sum
*/
int bitadd(unsigned char high11, unsigned char low11, unsigned char high22, unsigned low22){
unsigned char, high1, high2;
high1 = getsize(high11);
//low1 = getsize(low11);
high2 = getsize(high22);
//low2 = getsize(low22);
int add2 = bin2int(high1, low11);
int add1 = bin2int(high2, low22);
int sum = add2+add1;
return sum;
}
/*
look at notes for bit add, does the same thing. highlevel/lowlevel subfrom should be the bigger number you subtract FROM
bitsub will follow same procedure as bitadd, dont forget to call split in mymalloc()
call method that retrieves the size bits.
*/
int bitsub(unsigned char high11, unsigned char low11, unsigned char high22, unsigned low22){
unsigned char, high1, high2;
high1 = getsize(high11);
//low1 = getsize(low11);
high2 = getsize(high22);
//low2 = getsize(low22);
int subfrom = bin2int(high1, low11);
int tosub = bin2int(high2, low22);
int sum = subfrom-tosub;
return sum;
}
/*
MUST SEND IN SIZE BYTES ONLY
this method will NOT take inuse bit into account when converting.
getbit will give you the bit at any given position
send in the lowlevel and high level bits you want to convert into ints, will return the int
*/
void combineNext(unsigned char* curr, unsigned char* next){
int nextinusebit = getbit(*next, 1);
if (nextinusebit == 0){
unsigned char currlowbits = *(curr+1);
unsigned char nextlowbits = *(next+1);
printf("Starting combining process. \n");
int sum= bitadd(*curr, currlowbits, *next, nextlowbits);
splitBin(sum, curr, curr+1);
setInUse(0, curr);
printf("Curr and Next combined.\n");
}
else if (nextinusebit ==1){
printf("Can't Combine. Next is in use.\n");
}
}
void combinePrev(unsigned char* curr, unsigned char* prev){
int previnusebit = getbit(*prev, 1);
if (previnusebit == 0){
unsigned char currlowbits = *(curr+1);
unsigned char prevlowbits = *(prev+1);
printf("Starting combining process. \n");
int sum= bitadd( *prev, prevlowbits, *curr, currlowbits);
splitBin(sum, curr, curr+1);
setInUse(0, prev);
printf("Curr and Prev combined.\n");
}
else if (previnusebit ==1){
printf("Can't Combine. Next is in use.\n");
}
}
void combineBoth(unsigned char* prev, unsigned char* curr, unsigned char* next){
int nextinuse = getbit(*next, 1);
int previnuse = getbit(*prev, 1);
if (nextinuse == 0){
combineNext(curr, next);
}
if (previnuse == 0){
combinePrev(curr, prev);
}
}
void myfree(void *tofree, __FILE__, __LINE__){
tofree = (char*) tofree;
if (tofree == NULL){
printf("Error in %s line %d: Pointer received is NULL. \n", __FILE__, __LINE__);
}
if (ismeminit = 0){
printf("Error in %s line %d: Nothing malloc'd yet\n", file, linenum);
}
if(tofree<=lowerBound || tofree>upperbound){
printf("Error in %s line %d: Pointer is not in range of memory\n", __FILE__, __LINE__);
}
if(tofree>firstmeta && tofree<=lastaddress){
char *curr = firstmeta;
char *prev = NULL;
char *next = NULL;
while(curr < lastaddress ){
unsigned char currsizebits = getsize(curr);
int currsize = bin2int(currsizebits, curr+1);
if ((curr+2) > tofree){ // pointer is not pointing at the starting address of a block
printf("Error in %s line %d: Pointer is not the one given by malloc\n", __FILE__, __LINE__);
break;
}
if(curr+2 == tofree){
int isValid = getbit(curr, 1); //get inuse bit
if (isValid == 0){ // address already freed
printf("Error in %s line %d: Pointer is already freed.\n", __FILE__, __LINE__);
break;
}
else if (isValid == 1){ //this pointer can be freed
//free inuse bit, combine block
setInUse(0, curr);
// check if curr is the first and last block (only block)
if ((curr+1+currsize) == lastaddress && prev == NULL){
setInUse(0, curr);
break;
}
// check if prev is null / curr is first block
else{
if (prev == NULL){
next = (curr+1+currsize);
combineNext(curr, next);
break;
}
// check if curr is the last block / there is no next block
if((curr+1+currsize) == lastaddress){
combinePrev(curr, prev);
break;
}
// else combine both
else if((curr+1+currsize) < lastaddress && prev!=NULL){
next = (curr+1+currsize);
combineBoth(prev, curr, next);
break;
}
}
//break;
}
}
//update pointers
prev = curr;
curr = curr+1+currsize;
}
}
}
int main (int argc, char**argv){
unsigned char high= 0b0000001;
unsigned char low = 0b00001111;
int f = bin2int(high, low);
printf("INT : %d", f);
unsigned char high2= 0b0000000;
unsigned char low2 = 0b00001111;
int added = bitadd(high, low, high2, low2);
printf("sum : %d \n", added);
int subtracted = bitsub(high, low, high2, low2);
printf("subtracted : %d\n", subtracted);
return 0;
}
<file_sep>/ignorebitadd.c
#include <math.h>
#include <stdbool.h>
#define KEY 0010110011010010
int bitadd(unsigned char highleva2, unsigned char lowleva2, unsigned char highlevl2add, unsigned char lowlev2add){
//call bin2int twice. save those numbers. add ints. call int2binary. call split
int add2int = bin2int(unsigned char lowleva2, unsigned char highleva2);
int toadd = bin2int(unsigned char lowlev2a, unsigned char highlev2a);
int newsize = add2int+toadd;
return newsize;
//char[] newbinary = int2binary(newsize);
//return newbinary;
//myfree will receive the full 16 bit char array, then call split on the array from within myfree()
}
int bitsub(unsigned char highlevsubfrom, unsigned char lowlevsubfrom, unsigned char highlevl2sub, unsigned char lowlev2sub){
//bitsub will follow same procedure as bitadd, dont forget to call split in mymalloc()
int sub = bin2int(unsigned char lowlevsubfrom, unsigned char highlevsubfrom);
int tosub = bin2int(unsigned char lowlev2sub, unsigned char highlev2sub);
int newsize = sub - tosub;
char[] newbinary = int2binary(newsize);
return newbinary;
}
//converts binary to int
bool getBit(unsigned char byte, int position){ // position in range 0-7
//copied code MODIFY
return (byte >> position) & 0x1;
}
//getbit will give you the bit at any given position
int bin2int(unsigned char lowlev, unsigned char highlev){
int j =0;
for(int i = 0; i< 8; i++){
binarr[i] = getbit(highlev, j);
j++;
}
j=0;
for(int i = 8; i< 16; i++){
binarr[i] = getbit(lowlev, j);
j++;
}
///bin arr gives you full binary array ex. byte holds 14 -> binarr = [0,0,0,0,0,0,0,0,1,1,1,0]
int j = 0;
int sum = 0;
// this loop goes through binarr and calculate 2^binarr[i] power and sums it to give you the final int. starts at 2^0 (binarr[15])
for(int i =15; i>=0; i-- ){
int bin = binarr[i]
if (bin == 0){
j++;
}
else if (bin == 1){
sum += pow(2, j);
j++;
}
}
return sum;
}
//http://www.java2s.com/Code/Java/Language-Basics/Setsaspecificbitofanint.htm
//MUST MODIFY
int setBit(int bit, int target) {
// Create mask
int mask = 1 << bit;
// Set bit
return target | mask;
}
int main(){
unsigned char somebit = 0xF;
printf("bit: %u", somebit);
}
/*char* int2binary(int toconvert){
static char binum[16]; //idk if this works figure out types later, conversion code should work tho
//do i need to null terminate? is this a string or a array of characters?
int i =0;
for (i = 0; i < 16; i++){
binum[i]=0;
}
i =0;
while(num>0){
binum[i] = num%2;
num = num/2;
i++;
}
//now binum contains reversed binary numbers
//this loop makes the numbers forward again
int start = 0;
int end = 15;
while(start < end){
int temp = binum[start];
binum[start] = binum[end];
binum[end]= temp;
start++;
end--;
}
char finbin[16];
for(int i =0; i<16; i++){
finbin[i] = binum[i];
}
}*/
/*unsgined char splitbinary(char* tosplit, int split){
//split = 1 means high split aka obtain the high level bits
// split == 0 means low split aka obtain the low level bits
//https://stackoverflow.com/questions/2666440/how-to-store-binary-string-in-the-binary-form-in-a-file
if (split ==1){
return 0;
}
else if (split ==0){
return;
}
}*/
//unsgined char lowsplitbinary(char* tosplit){}
//following for setting bit is from geeksforgeeks MUST MODIFY!
//Use the bitwise OR operator (|) to set a bit.
//number |= 1UL << n;
//That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1,
//if you want to set the nth bit.
//Use 1ULL if number is wider than unsigned long;
//promotion of 1UL << n doesn't happen until after evaluating 1UL << n where
//it's undefined behaviour to shift by more than the width of a long. T
//he same applies to all the rest of the examples.
/*
binary2int(unsigned char highlev, unsigned char lowlev){
//copied code MUST MODIFY
//https://stackoverflow.com/questions/37487528/how-to-get-the-value-of-every-bit-of-an-unsigned-char
//extracts bits from unsigned char and puts in an int array called bits
int lowbits[8];
for (int i = 0 ; i != 8 ; i++) {
bits[i] = (lowlev & (1 << i)) != 0;
}
int highbits[8];
for (int i = 0 ; i != 8 ; i++) {
highbits[i] = (highlev & (1 << i)) != 0;
}
*/
<file_sep>/memgrind.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include "mymalloc.c"
#include "mymalloc.h"
#define malloc(x) mymalloc(x,__FILE__,__LINE__)
#define free(x) myfree(x,__FILE__,__LINE__)
int main (int argc, char**argv){
double difference=0;
double sumtimeA=0;
double sumtimeB=0;
double sumtimeC=0;
double sumtimeD=0;
double sumtimeE=0;
double sumtimeF=0;
int* ptrarr2[150];
srand(time(NULL));
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int f=0;
int i=0;
struct timeval start, end;
// case a
for(a=0; a<100;a++){
//time(&starttime);//get time at start
gettimeofday(&start, NULL);
for(i=0 ; i< 150; i++){
ptrarr2[i] = (int*) malloc(1);
free(ptrarr2[i]);
ptrarr2[i] = NULL;
}
//time(&endtime);//get time at end
gettimeofday(&end, NULL);
difference=((end.tv_sec-start.tv_sec)*1000000)+(end.tv_usec-start.tv_usec);//save runtime of iteration
sumtimeA+=difference;
}
//case b
int *ptrarr[50];
int malcounter=0;
int *ptr;
for(b=0; b<100; b++){
gettimeofday(&start, NULL);//get time at start
int x ;
for(x =0; x<3; x++){
for(i =0; i< 50; i++){
ptr = (int*) malloc(1);
ptrarr[i] =ptr;
malcounter++;
if(malcounter == 50){
int j;
for (j =0; j<malcounter;j++ ){
free(ptrarr[j]);
ptrarr[j]=NULL;
}
malcounter =0;
}
}
}
gettimeofday(&end, NULL);//get time at end
difference=((end.tv_sec-start.tv_sec)*1000000)+(end.tv_usec-start.tv_usec);//save runtime of iteration
sumtimeB+=difference;
}
// case c
malcounter = 0;
int freedptr = 0;
int ptr2free =-1;
int freeindex =0;
int* pointers[50];
int mallocindex =0;
int random;
for(c=0; c<100; c++){
gettimeofday(&start, NULL);//get time at start
while(malcounter <=50){
random = rand()%2;
if(random == 0){ //malloc if 0
pointers[mallocindex] = (int*)malloc(1);
malcounter++;
mallocindex++;
ptr2free =malcounter - freedptr;
}
else if (random == 1){ // free if 1
if (ptr2free != 0 && malcounter!=0){
free(pointers[freeindex]);
pointers[freeindex] = NULL;
++freeindex;
++freedptr;
ptr2free =malcounter - freedptr;
}
}
if(malcounter == 50){
break;
}
}
// if (malcounter == 50){
while(ptr2free!= 0){
free(pointers[freeindex]);
pointers[freeindex] = NULL;
++freedptr;
++freeindex;
ptr2free= malcounter-freedptr;
}
//}
gettimeofday(&end, NULL);//get time at end
difference=((end.tv_sec-start.tv_sec)*1000000)+(end.tv_usec-start.tv_usec);//save runtime of iteration
sumtimeC+=difference;
}
//case d
int memleft=4092; //the amount of memory left
int memalloc =0; // the total of memory that is currently allocated
int* pointers2[50]; // pointer array to all of allocations
int memarr[50];// stores the amount of memory mallocd on each malloc
for(d=0; d<100; d++){
gettimeofday(&start, NULL);//get time at start
memleft=4092;
freedptr=0; //amount of pointers that have been freed
freeindex=0; // index to free at, starts at 0 and frees sequentially. used for pointers2
malcounter=0; // amount of times malloc has been called
ptr2free =-1; // amount of pointers left to free
mallocindex=0; // where to store the next mallocd pointer in pointers2
while(malcounter<=50){
if (memleft >0){
random = rand()%2;
if(random ==0){// malloc if even
random = (rand()%64);
if(random==0){
random=64;
}
/*while(random < 1 || random > 64){
random = rand();
if (random <=64 && random >= 1){
break;
}
}*/
if(memleft >=random){
pointers2[mallocindex]= (int*)malloc(random);
memarr[mallocindex] = random;
memalloc +=random;
mallocindex++;
malcounter++;
memleft-=random;
}
}
else if (random ==1){//free if odd
if(ptr2free!=0&& malcounter!=0){
free(pointers2[freeindex]);
memalloc = memalloc - memarr[freeindex];
freeindex++;
freedptr++;
ptr2free = malcounter-freedptr;
memleft = 4092- memalloc;
}
}
}
if (malcounter ==50){
break;
}
}
//if(malcounter ==50){
while(freeindex <=50){
free(pointers2[freeindex]);
freedptr++;
ptr2free = malcounter -freedptr;
memalloc = memalloc - memarr[freeindex];
freeindex++;
memleft = 4092- memalloc;
if(ptr2free == 0){
break;
}
}
gettimeofday(&end, NULL);//get time at end
difference=((end.tv_sec-start.tv_sec)*1000000)+(end.tv_usec-start.tv_usec);//save runtime of iteration
sumtimeD+=difference;
}
int *fiboptrArr[100];
int index=0;//used in E and F
int sum=0;//used in E and F
for(e=0; e<100; e++){
gettimeofday(&start, NULL);//get time at start
int prevprev=0;
int prev=1;
int totalmem=0;
index=0;
//case E
while(totalmem<(4092/2)){
sum=prevprev+prev;
fiboptrArr[index]= (int*)malloc(sum);
prevprev=prev;
prev=sum;
totalmem+=(sum+2);
index++;
}
fiboptrArr[index]= (int*)malloc(prevprev);
totalmem+=(prevprev+2);
index++;
while(totalmem+(prev-prevprev)<(4092)&& sum>1){
sum=prev-prevprev;
fiboptrArr[index]= (int*)malloc(sum);
prev=prevprev;
prevprev=sum;
totalmem+=(sum+2);
index++;
}
for(i=index-1; i>=0; i--){
free(fiboptrArr[i]);
}
gettimeofday(&end, NULL);//get time at end
difference=((end.tv_sec-start.tv_sec)*1000000)+(end.tv_usec-start.tv_usec);//save runtime of iteration
sumtimeD+=difference;
}
//F begins here
int* alternptrArr[250];
int* alternptr;
for(f=0; f<100; f++){
gettimeofday(&start, NULL);//get time at start
index=0;
random=0;
while(sum<=4092 && index<250){
random=rand()%67;
if(random==0){
random=67;
}
alternptr=(int*)malloc(random);
alternptrArr[index]=alternptr;
if((index%3)==0){
free(alternptrArr[index]);//every third element gets freed
alternptrArr[index]=NULL;
}
index++;
sum+=random+2;
}
for(i=0; i<index; i++){
if(alternptrArr[i]!=NULL){
free((alternptrArr[i]));
}}
gettimeofday(&end, NULL);//get time at end
difference=((end.tv_sec-start.tv_sec)*1000000)+(end.tv_usec-start.tv_usec);//save runtime of iteration
sumtimeD+=difference;
//Check for successful freeing
char* testptr;
char* testptrArr[4];
//malloc 1000 4X
for(i=0; i<4; i++){
testptr=(char*)malloc(1000);
testptrArr[i]=testptr;
}
//free prev mallocs
for(i=0; i<4; i++){
free((testptrArr[i]));
}
//test to see how this worked
testptr=(char*)malloc(4092);
testptrArr[0]=testptr;
free((testptrArr[0]));
//test our free
testptr=(char*)malloc(1);
testptrArr[0]=testptr;
free((testptrArr[0]));
//test splitblock
testptr=(char*)malloc(4088);
testptrArr[0]=testptr;
testptr=(char*)malloc(1);
testptrArr[1]=testptr;
free((testptrArr[1]));
free((testptrArr[0]));
testptr=(char*)malloc(4092);
testptrArr[0]=testptr;
free((testptrArr[0]));
}
//print mean times
printf("Mean time of protocol A was %lf milliseconds\n", (sumtimeA/100));
printf("Mean time of protocol B was %lf milliseconds\n", (sumtimeB/100));
printf("Mean time of protocol C was %lf milliseconds\n", (sumtimeC/100));
printf("Mean time of protocol D was %lf milliseconds\n", (sumtimeD/100));
printf("Mean time of protocol E was %lf milliseconds\n", (sumtimeE/100));
printf("Mean time of protocol F was %lf milliseconds\n", (sumtimeF/100));
return 0;
}
<file_sep>/mallocTraverse.c
unsigned char* mallocTraverse(unsigned char* curr, int dataSize){
*curr=myMem[2];
while(curr>=lowerBound && curr<=upperbound){//lowerBound & upperBound will be global vars
int currMeta=bin2int(*curr, *(curr+1));//converting chars to an int to send to getbit
int inUse=getbit(currMeta, 1);//getting the in use bit
char hiBits=getsizeBits(*curr);//blocking out in use bit to get size of block
int currBlockSize=bin2int(hiBits, *(curr+1));//getting block size of current block
if(inUse==0 && currBlockSize>=dataSize){//if there's enough space to return to the user
curr=splitBlock(curr, currBlockSize, dataSize);//prepare it to return
return curr+2;//return pointer to actual data block, not trying to overwrite metadata
} else{
curr=(curr+currBlockSize);
}
}
/* got to end of array without finding an empty block */
printf("Memory request exceeds size of working memory in file %d at line %d\n", __FILE__, __LINE__);
return NULL;
}
| 6df961062a633cda5f7ff927c06dd6adf84fdf32 | [
"C",
"Text"
] | 15 | C | ashvi23/My-Malloc | f240f7c88a4700e53a308eed7990586fbd9917df | b7e090500fe6e4fa78259b997f8bac26c21ea966 | |
refs/heads/master | <file_sep>namespace System //Conversor_BIN_DEC_HEX.Functions
{
class ConvertHexDecBin
{
public void ConvertBinDec()
{
int contador = 0;
Console.WriteLine();
Console.Write("Digite um número hexadecimal: ");
ConversorDecimal dec = new ConversorDecimal { digito = Console.ReadLine() };
ConversorBinario bin = new ConversorBinario();
char[] s = dec.digito.ToCharArray();
while (contador == 0)
{
foreach (char w in s)
{
if (w != '0' && w != '1' && w != '2' && w != '3' && w != '4' && w != '5' && w != '6' && w != '7' && w != '8' && w != '9' && w != 'a' && w != 'b' && w != 'c' && w != 'd' && w != 'e' && w != 'f' && w != 'A' && w != 'B' && w != 'C' && w != 'D' && w != 'E' && w != 'F') contador = 1;
}
if (contador == 1)
{
Console.WriteLine("FAVOR DIGITAR ALGARISMOS ENTRE 0 ATÉ 9 E OU A ATÉ F!!!");
Console.WriteLine();
Console.Write("Digite um número hexadecimal: ");
dec.digito = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Número digitado é: " + dec.digito.ToUpper());
s = dec.digito.ToCharArray();
contador = 0;
}
else
{
Console.WriteLine();
Console.Write("Número digitado é: " + dec.digito.ToUpper());
contador = 1;
}
}
Console.WriteLine();
dec.DeciHex();
Console.WriteLine();
bin.digito = dec.y.ToString();
bin.Bina();
Console.WriteLine();
Console.WriteLine();
}
}
}<file_sep>namespace System //Conversor_BIN_DEC_HEX.Functions
{
class ConvertDecBinHex
{
public void ConvertBinHex()
{
int contador = 0;
Console.WriteLine();
Console.Write("Digite um número decimal: ");
ConversorBinario bin = new ConversorBinario { digito = Console.ReadLine() };
ConversorHexadecimal hex = new ConversorHexadecimal();
char[] s = bin.digito.ToCharArray();
while (contador == 0)
{
foreach (char w in s)
{
if (w != '0' && w != '1' && w != '2' && w != '3' && w != '4' && w != '5' && w != '6' && w != '7' && w != '8' && w != '9') contador = 1;
}
if (contador == 1)
{
Console.WriteLine("FAVOR DIGITAR ALGARISMOS ENTRE 0 À 9!!!");
Console.WriteLine();
Console.Write("Digite um número decimal: ");
bin.digito = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Número digitado foi: " + bin.digito);
s = bin.digito.ToCharArray();
contador = 0;
}
else
{
Console.WriteLine();
Console.Write("Número digitado é: " + bin.digito);
contador = 1;
}
}
Console.WriteLine();
bin.Bina();
Console.WriteLine();
hex.digito = bin.digito;
hex.Hexa();
Console.WriteLine();
Console.WriteLine();
}
}
}<file_sep>using System;
namespace Conversor_BIN_DEC_HEX
{
class Program
{
static void Main()
{
Decisao decidir = new Decisao();
decidir.Decide();
}
}
}<file_sep>namespace System //Conversor_BIN_DEC_HEX.Functions
{
class ConvertBinDecHex
{
public void ConvertDecHex()
{
int contador = 0;
Console.WriteLine();
Console.Write("Digite um número binário: ");
ConversorDecimal dec = new ConversorDecimal {digito = Console.ReadLine()};
ConversorHexadecimal hex = new ConversorHexadecimal();
char[] s = dec.digito.ToCharArray();
while (contador == 0)
{
foreach (char w in s)
{
if (w != '0' && w != '1') contador = 1;
}
if (contador == 1)
{
Console.WriteLine("FAVOR DIGITAR ALGARISMOS ENTRE 0 OU 1!!!");
Console.WriteLine();
Console.Write("Digite um número binário: ");
dec.digito = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Número digitado foi: " + dec.digito);
s = dec.digito.ToCharArray();
contador = 0;
}
else
{
Console.WriteLine();
Console.Write("Número digitado foi: " + dec.digito);
contador = 1;
}
}
Console.WriteLine();
dec.DeciBin();
hex.digito = dec.y.ToString();
hex.Hexa();
Console.WriteLine();
Console.WriteLine();
}
}
}
<file_sep>using System.Collections.Generic;
namespace System //Conversor_BIN_DEC_HEX.Conversores
{
class ConversorBinario
{
public List<int> list = new List<int>();
public string digito;
public void Bina()
{
int valor = int.Parse(digito);
while (valor != 0)
{
int resultado = valor / 2;
int resto = valor % 2;
int aux = resultado;
valor = aux;
list.Insert(0, resto);
}
Console.Write("Convertido em binário é: ");
foreach (int obj in list)
{
Console.Write(obj);
}
}
}
}<file_sep>namespace System //Conversor_BIN_DEC_HEX.Functions
{
class Decisao
{
public int escolha;
public void Decide()
{
Console.WriteLine("CONVERSOR NUMÉRICO!!!");
Console.Write("Escolha 1 (BINÁRIO / DECIMAL & HEXADECIMAL), 2 (DECIMAL / BINÁRIO & HEXADECIMAL), 3 (HEXADECIMAL / BINÁRIO & DECIMAL) ou 4 (SAIR): ");
int contador = 0;
while (contador == 0)
{
try
{
escolha = int.Parse(Console.ReadLine());
if (escolha < 1 || escolha > 4)
{
Console.Write("FAVOR DIGITAR UM VALOR ENTRE 1 À 4!!! Qual a sua escolha [1 (BINÁRIO / DECIMAL & HEXADECIMAL), 2 (DECIMAL / BINÁRIO & HEXADECIMAL), 3 (HEXADECIMAL / DECIMAL & BINÁRIO) ou 4 (SAIR)]? ");
}
if (escolha == 1)
{
ConvertBinDecHex conDecHex = new ConvertBinDecHex();
conDecHex.ConvertDecHex();
Console.Write("Escolha 1 (BINÁRIO / DECIMAL & HEXADECIMAL), 2 (DECIMAL / BINÁRIO & HEXADECIMAL), 3 (HEXADECIMAL / BINÁRIO & DECIMAL) ou 4 (SAIR): ");
}
if (escolha == 2)
{
ConvertDecBinHex conBinHex = new ConvertDecBinHex();
conBinHex.ConvertBinHex();
Console.Write("Escolha 1 (BINÁRIO / DECIMAL & HEXADECIMAL), 2 (DECIMAL / BINÁRIO & HEXADECIMAL), 3 (HEXADECIMAL / BINÁRIO & DECIMAL) ou 4 (SAIR): ");
}
if (escolha == 3)
{
ConvertHexDecBin conBinDec = new ConvertHexDecBin();
conBinDec.ConvertBinDec();
Console.Write("Escolha 1 (BINÁRIO / DECIMAL & HEXADECIMAL), 2 (DECIMAL / BINÁRIO & HEXADECIMAL), 3 (HEXADECIMAL / BINÁRIO & DECIMAL) ou 4 (SAIR): ");
}
if (escolha == 4)
{
contador = 1;
Console.WriteLine();
Console.WriteLine("ADEUS!!!");
Console.ReadLine();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine();
Console.Write("FAVOR DIGITAR UM VALOR ENTRE 1 À 4!!! Qual a sua escolha [1 (BINÁRIO / DECIMAL & HEXADECIMAL), 2 (DECIMAL / BINÁRIO & HEXADECIMAL), 3 (HEXADECIMAL / BINÁRIO & DECIMAL) ou 4 (SAIR)? ");
contador = 0;
}
}
}
}
} | 6238d563281926ef7a47ce956aa04141563194dc | [
"C#"
] | 6 | C# | nakappa/conversor-git | cc5d21ba5c95b0d6ddf310979052776af252c6f1 | 78b220f2951b1020425e4c7f02460d4363f6747b | |
refs/heads/master | <repo_name>catatonicprime/sacp<file_sep>/README.md
# Simple Apache Config Parser
Welcome to the Simple Apache Config Parser! This package is intended to ease the parsing/analysis of apache config files. This parser uses the Apache Config Lexer provided by the [pygments](http://pygments.org/) project.
This project is still very much in its infancy, but my focus is on providing easy to use/understand object interfaces to analyze and modify apache config files while attempting to minimize the deltas between the original configs and the modified content. If this software is not quite meeting your needs, drop in an Issue and I'll do my best to address/help, but even if that's failing checkout this other neat parser [apacheconfig](https://github.com/etingof/apacheconfig).
# Example usage
Here are some example usages. Note that these examples assume your current working directory properly set to match Include patterns. In the examples below this is for a CentOS installation where the root apache directory tends to be /etc/httpd/.
## Parsing
Parsing a config file is easy!
```python
from sacp import *
cf = ConfigFile(file="conf/httpd.conf")
```
This will automatically parse the httpd.conf from the current directory. Any dependent configs (e.g. those that are listed in an Include or IncludeOptional directive) will also be loaded.
## Walking the nodes
Visiting all the nodes is also easy!
```python
from sacp import *
def visit(node):
print("{}{}".format(node.depth * " ", type(node)))
cf = ConfigFile(file="conf/httpd.conf")
NodeVisitor([cf]).visit(visitor=visit)
```
This visits all of the nodes in the config file, including it's children, and prints each node type with it's relative depth represented as well.
# Contribute
Want to contribute? Awesome! Fork, code, and create a PR.
<file_sep>/tests/tests.py
import unittest
import os
from sacp import *
class TestInclude(unittest.TestCase):
def test_path(self):
# Ensure we have an 'Include' node
parser = Parser(data='Include files/small_vhost.conf')
self.assertTrue(parser)
self.assertEqual(len(parser.nodes), 1, 'Parser returned incorrect number of nodes for Include')
include = parser.nodes[0]
self.assertTrue(isinstance(include, Include))
# Ensure the path matches the expected path above.
self.assertEqual(include.path, 'files/small_vhost.conf', 'Include path does not match expected.')
def test_path_absolute_glob(self):
# Ensure we have an 'Include' node
parser = Parser(data="Include {}/files/glob/*.conf".format(os.getcwd()))
self.assertTrue(parser)
self.assertEqual(len(parser.nodes), 1, 'Parser returned incorrect number of nodes for Include')
include = parser.nodes[0]
self.assertTrue(isinstance(include, Include))
def test_exceptions(self):
with self.assertRaises(IncludeError):
Parser(data='Include')
with self.assertRaises(ValueError):
Parser(data='Include nonexistent.conf')
def test_child_tokens_not_accessed(self):
include = Parser(data='Include files/small_vhost.conf').nodes[0]
self.assertEqual(len(include.tokens), 4)
class TestIncludeOptional(unittest.TestCase):
def test_path(self):
# Ensure we have an 'Include' node
parser = Parser(data='IncludeOptional files/small_vhost.conf')
self.assertTrue(parser)
self.assertEqual(len(parser.nodes), 1, 'Parser returned incorrect number of nodes for IncludeOptional')
include = parser.nodes[0]
self.assertTrue(isinstance(include, IncludeOptional))
# Ensure the path matches the expected path above.
self.assertEqual(include.path, 'files/small_vhost.conf', 'IncludeOptional path does not match expected.')
def test_exceptions(self):
with self.assertRaises(IncludeError):
Parser(data='IncludeOptional')
def test_failed_include(self):
Parser(data='IncludeOptional nonexistent.conf')
class TestParser(unittest.TestCase):
def test_parents(self):
# Ensure we have a known structure.
configFile = ConfigFile(file='files/small_vhost.conf')
self.assertTrue(configFile)
self.assertTrue(isinstance(configFile, ConfigFile))
self.assertTrue(configFile.children)
# Extract the VirtualHost from the structure.
vhost = configFile.children[0]
self.assertTrue(isinstance(vhost, VirtualHost))
self.assertTrue(isinstance(vhost._parent, ConfigFile))
# Extract the first child, which should be a Directive, from the VirtualHost
directive = vhost.children[0]
self.assertTrue(isinstance(directive, Directive))
# Ensure the Directives parent is properly typed to a VirtualHost
self.assertTrue(isinstance(directive._parent, VirtualHost))
def test_parser(self):
nodes = Parser(data="ServerName github.com").nodes
self.assertEqual(len(nodes), 1)
with self.assertRaises(ValueError):
Parser(data="ServerName github.com", nodefactory=0)
with self.assertRaises(ValueError):
Parser(data="ServerName github.com", acl=NodeFactory())
def test_children(self):
configFile = ConfigFile(file='files/small_httpd.conf')
self.assertTrue(configFile)
self.assertTrue(isinstance(configFile, ConfigFile))
self.assertTrue(configFile.children)
self.assertGreaterEqual(len(configFile.children), 3)
comment = configFile.children[0]
self.assertTrue(isinstance(comment, Comment))
directive = configFile.children[1]
self.assertTrue(isinstance(directive, Directive))
multilineComment = configFile.children[2]
self.assertTrue(isinstance(multilineComment, Comment))
self.assertTrue('Multi-line\\\ncomment' in str(multilineComment))
def test_exceptions(self):
with self.assertRaises(ValueError):
configFile = ConfigFile(file='files/lex_errors.conf')
class TestNode(unittest.TestCase):
def test_append_child(self):
# Ensure we have some structure.
configFile = ConfigFile(file='files/small_vhost.conf')
# Ensure we have a new node, it can be blank.
node = Node()
self.assertTrue(node)
# Ensure the node can be successfully appended.
configFile.append_child(node)
self.assertGreaterEqual(configFile.children.index(node), 0)
# Ensure the node has been modified to have the correct parent.
self.assertEqual(node.parent, configFile)
# Test the depth of the node.
self.assertEqual(node.depth-1, node.parent.depth)
def test_append_children(self):
# Ensure we have some structure.
configFile = ConfigFile(file='files/small_vhost.conf')
# Ensure we have a new node, it can be blank.
node = Node()
self.assertTrue(node)
# Ensure the configFile can be successfully appended.
node.append_children([configFile])
self.assertGreaterEqual(node.children.index(configFile), 0)
# Ensure the configFile has been modified to have the correct parent.
self.assertEqual(configFile.parent, node)
# Test the depth of the node.
self.assertEqual(configFile.depth-1, configFile.parent.depth)
def test_node_factory(self):
nf = NodeFactory()
node = Node()
with self.assertRaises(NotImplementedError):
nf.build(node)
class TestDirective(unittest.TestCase):
def test_name(self):
configFile = ConfigFile(file='files/small_vhost.conf')
vhost = configFile.children[0]
self.assertEqual(vhost.name, "VirtualHost")
sn = vhost.children[0]
self.assertEqual(sn.name, "ServerName")
class TestServerName(unittest.TestCase):
def test_server_name(self):
configFile = ConfigFile(file='files/small_vhost.conf')
vhost = configFile.children[0]
sn = vhost.children[0]
self.assertTrue(sn.isValid)
self.assertEqual(sn.arguments[0], "github.com")
self.assertEqual(vhost.server_name.arguments[0], "github.com")
def test_empty_server_name(self):
configFile = ConfigFile(file='files/bad_vhost.conf')
vhost = configFile.children[0]
sn = vhost.children[0]
self.assertFalse(sn.isValid)
def test_bad_servername(self):
nodes = Parser(data='ServerName invalid/domain').nodes
sn = nodes[0]
self.assertFalse(sn.isValid)
class TestServerAlias(unittest.TestCase):
def test_server_alias(self):
configFile = ConfigFile(file='files/small_vhost.conf')
vhost = configFile.children[0]
sa = vhost.children[1]
self.assertTrue(sa.isValid)
self.assertEqual(sa.arguments[0], "www.github.com")
self.assertEqual(vhost.server_alias.arguments[0], "www.github.com")
self.assertEqual(sa.arguments[1], "m.github.com")
self.assertEqual(vhost.server_alias.arguments[1], "m.github.com")
def test_bad_server_alias(self):
nodes = Parser(data='ServerAlias www.github.com bad/alias github.com').nodes
sa = nodes[0]
self.assertFalse(sa.isValid)
def test_empty_server_alias(self):
configFile = ConfigFile(file='files/bad_vhost.conf')
vhost = configFile.children[0]
sa = vhost.children[1]
self.assertFalse(sa.isValid)
class TestConfigFile(unittest.TestCase):
def test_write(self):
testPath = '/tmp/.small_vhost.conf'
configFile = ConfigFile(file='files/small_vhost.conf')
cf_str_left = str(configFile)
self.assertFalse(os.path.exists(testPath))
configFile._file = testPath
configFile.write()
self.assertTrue(os.path.exists(testPath))
configFile = ConfigFile(file=testPath)
cf_str_right = str(configFile)
self.assertEqual(cf_str_left, cf_str_right)
os.remove(testPath)
class TestNodeVisitors(unittest.TestCase):
def __init__(self, methodName="runTest"):
(unittest.TestCase).__init__(self, methodName=methodName)
self._parsed_nodes = ConfigFile(file='files/small_visitors.conf').children
def reset_test_state(self):
self._node_visit_index = 0
self._node_list = []
def visitor(self, node):
self._node_list.append((node, self._node_visit_index))
self._node_visit_index += 1
def test_node_visitor(self):
self.reset_test_state()
NodeVisitor(self._parsed_nodes).visit(visitor=self.visitor)
self.assertEqual(self._node_visit_index, 2)
self.assertEqual(self._node_list[0][1], 0)
self.assertEqual(self._node_list[1][1], 1)
self.assertTrue(isinstance(self._node_list[0][0], VirtualHost))
self.assertTrue(isinstance(self._node_list[1][0], VirtualHost))
def test_dfnode_visitor(self):
self.reset_test_state()
DFNodeVisitor(self._parsed_nodes).visit(visitor=self.visitor)
self.assertEqual(self._node_visit_index, 4)
self.assertEqual(self._node_list[0][1], 0)
self.assertEqual(self._node_list[1][1], 1)
self.assertEqual(self._node_list[2][1], 2)
self.assertEqual(self._node_list[3][1], 3)
self.assertTrue(isinstance(self._node_list[0][0], VirtualHost))
self.assertTrue(isinstance(self._node_list[1][0], ServerName))
self.assertTrue(isinstance(self._node_list[2][0], VirtualHost))
self.assertTrue(isinstance(self._node_list[3][0], ServerName))
def test_bfnode_visitor(self):
self.reset_test_state()
BFNodeVisitor(self._parsed_nodes).visit(visitor=self.visitor)
self.assertEqual(self._node_visit_index, 4)
self.assertEqual(self._node_list[0][1], 0)
self.assertEqual(self._node_list[1][1], 1)
self.assertEqual(self._node_list[2][1], 2)
self.assertEqual(self._node_list[3][1], 3)
self.assertTrue(isinstance(self._node_list[0][0], VirtualHost))
self.assertTrue(isinstance(self._node_list[1][0], VirtualHost))
self.assertTrue(isinstance(self._node_list[2][0], ServerName))
self.assertTrue(isinstance(self._node_list[3][0], ServerName))
class TestDefaultFactory(unittest.TestCase):
def test_factory_builds(self):
configFile = ConfigFile(file='files/factory.conf')
self.assertTrue(isinstance(configFile.children[0], Comment))
self.assertTrue(isinstance(configFile.children[1], Comment))
self.assertTrue(isinstance(configFile.children[2], Directive))
self.assertTrue(isinstance(configFile.children[3], Directive))
self.assertTrue(isinstance(configFile.children[4], ScopedDirective))
self.assertTrue(isinstance(configFile.children[5], Directory))
self.assertTrue(isinstance(configFile.children[6], Directory))
self.assertTrue(isinstance(configFile.children[7], DirectoryMatch))
self.assertTrue(isinstance(configFile.children[8], Files))
self.assertTrue(isinstance(configFile.children[9], Files))
self.assertTrue(isinstance(configFile.children[10], FilesMatch))
self.assertTrue(isinstance(configFile.children[11], Location))
self.assertTrue(isinstance(configFile.children[12], LocationMatch))
self.assertTrue(isinstance(configFile.children[13], Proxy))
self.assertTrue(isinstance(configFile.children[14], ProxyMatch))
class TestScopedDirective(unittest.TestCase):
def test_argument_child_tokens(self):
configFile = ConfigFile(file='files/small_vhost.conf')
self.assertTrue(isinstance(configFile.children[0], ScopedDirective))
sd = configFile.children[0]
self.assertTrue(len(sd.arguments) == 1)
class TestLineEnumerator(unittest.TestCase):
def test_line_numbers(self):
cf = ConfigFile(file='files/factory.conf')
le = LineEnumerator(nodes=[cf])
self.assertTrue(isinstance(le.lines[0][0], Comment))
self.assertTrue(le.lines[0][1] == 1)
self.assertTrue(isinstance(le.lines[1][0], Comment))
self.assertTrue(le.lines[1][1] == 2)
self.assertTrue(isinstance(le.lines[2][0], Directive))
self.assertTrue(le.lines[2][1] == 5)
def test_line_number_recurse_include(self):
parser = Parser(data='Directive simple\nInclude files/factory.conf\nDirective simple')
le = LineEnumerator(nodes=parser.nodes)
self.assertTrue(isinstance(le.lines[0][0], Directive))
self.assertTrue(le.lines[0][1] == 1)
self.assertTrue(isinstance(le.lines[1][0], Include))
self.assertTrue(le.lines[1][1] == 2)
self.assertTrue(isinstance(le.lines[-1][0], Directive))
self.assertTrue(le.lines[2][1] == 3)
def test_line_number_recurse_include_optional(self):
parser = Parser(data='Directive simple\nIncludeOptional files/factory.conf\nDirective simple')
le = LineEnumerator(nodes=parser.nodes)
self.assertTrue(isinstance(le.lines[0][0], Directive))
self.assertTrue(le.lines[0][1] == 1)
self.assertTrue(isinstance(le.lines[1][0], IncludeOptional))
self.assertTrue(le.lines[1][1] == 2)
self.assertTrue(isinstance(le.lines[-1][0], Directive))
self.assertTrue(le.lines[2][1] == 3)
<file_sep>/sacp/base.py
from .node import *
from pygments.lexer import RegexLexer, default, words, bygroups, include, using
from pygments.token import Text, Comment as pygComment, Operator, Keyword, Name, String, \
Number, Punctuation, Whitespace, Literal
import pygments
import glob
class Parser:
def __init__(self, data, nodefactory=None, parent=None, acl=None):
# Use specified node generator to generate nodes or use the default.
if nodefactory is None:
nodefactory = DefaultFactory()
if not isinstance(nodefactory, NodeFactory):
raise ValueError("nodefactory must be of type NodeFactory")
self._nodefactory = nodefactory
# Use specified lexer to generate tokens or use the default.
if acl is None:
acl = ApacheConfLexer(ensurenl=False, stripnl=False)
if not isinstance(acl, ApacheConfLexer):
raise ValueError("acl must be of type ApacheConfLexer")
self._stream = pygments.lex(data, acl)
# Start parsing and tracking nodes
self.nodes = []
node = self.parse(parent=parent)
while node:
self.nodes.append(node)
node = self.parse(parent=parent)
def parse(self, parent=None):
node = Node(parent=parent)
# Flag that indicates we will be exiting a scoped directive after this
# node completes building.
for token in self._stream:
if token[0] is Token.Error:
raise ValueError("Config has errors, bailing.")
node.pretokens.append(token)
# Nodes don't have types until their first non-whitespace token is
# matched, this aggregates all the whitespace tokens to the front
# of the node.
if not node.type_token:
continue
# The node has a type, the lexer will return either a Token.Text
# with an empty OR string comprised only of newlines before the next node info is
# available.
if token[0] is Token.Text and (token[1] == '' or re.search(r'^\n+\s*$', token[1])):
return self._nodefactory.build(node)
# When handling Tag tokens, e.g. nested components, we need to
# know if we're at the start OR end of the Tag. Check for '</'
# first and flag that this node will be the closing tag or not,
# if so and > is encountered then return this node since it is
# complete, this closes the scoped directive.
if token[0] is Token.Name.Tag and token[1][0] == '<' and token[1][1] == '/':
node.closeTag = True
if token[0] is Token.Name.Tag and token[1][0] == '>':
# If we're closing a tag it's time to return this node.
if node.closeTag:
return self._nodefactory.build(node)
# Otherwise, we're starting a Tag instead, begin building out
# the children nodes for this node.
child = self.parse(parent=node)
while child and child.closeTag is False:
node.children.append(child)
child = self.parse(parent=node)
# If the child was a </tag> node it, migrate it's tokens into
# posttokens for this node.
if child and child.closeTag:
for pt in child.tokens:
node.posttokens.append(pt)
return self._nodefactory.build(node)
if len(node.tokens) > 0:
# At the end of files we may sometimes have some white-space stragglers
# this if block captures those into a new node.
return node
return None
class DefaultFactory(NodeFactory):
def __init__(self):
NodeFactory.__init__(self)
pass
def build(self, node):
if node.type_token[0] is Token.Name.Tag:
node = ScopedDirective(node=node)
elif node.type_token[0] is Token.Name.Builtin:
node = Directive(node=node)
elif node.type_token[0] is Token.Comment:
node = Comment(node=node)
if isinstance(node, ScopedDirective):
if node.name.lower() == 'virtualhost':
node = VirtualHost(node=node)
if node.name.lower() == 'directory':
node = Directory(node=node)
if node.name.lower() == 'directorymatch':
node = DirectoryMatch(node=node)
if node.name.lower() == 'files':
node = Files(node=node)
if node.name.lower() == 'filesmatch':
node = FilesMatch(node=node)
if node.name.lower() == 'location':
node = Location(node=node)
if node.name.lower() == 'locationmatch':
node = LocationMatch(node=node)
if node.name.lower() == 'proxy':
node = Proxy(node=node)
if node.name.lower() == 'proxymatch':
node = ProxyMatch(node=node)
if isinstance(node, Directive):
if node.name.lower() == 'servername':
node = ServerName(node=node)
elif node.name.lower() == 'serveralias':
node = ServerAlias(node=node)
elif node.name.lower() == 'include':
node = Include(node=node)
elif node.name.lower() == 'includeoptional':
node = IncludeOptional(node=node)
# Fix up children's parent.
for child in node.children:
child._parent = node
return node
class Directive(Node):
@property
def name(self):
return self.type_token[1]
@property
def arguments(self):
"""
return: Array of arguments following a directive.
example: 'ServerName example.com' returns [u'example.com']
example: 'Deny from all' returns [u'from', u'all']
"""
args = []
directiveIndex = self._pretokens.index(self.type_token)
for token in self._pretokens[directiveIndex+1:]:
if token[0] is Token.Text and (not token[1] or token[1].isspace()):
continue
if token[0] is Token.Name.Tag:
continue
args.append(token[1].strip())
return args
class ScopedDirective(Directive):
@property
def name(self):
return super(ScopedDirective, self).name.split('<')[1]
class Comment(Node):
pass
class ConfigFile(Node):
def __init__(self, node=None, file=None):
Node.__init__(self, node=node)
self._file = file
if file:
with open(file, "r") as f:
data = f.read()
self._parser = Parser(data, parent=self)
self._children = self._parser.nodes
def write(self):
with open(self._file, "w") as self.__fh:
self.__fh.write(str(self))
class VirtualHost(ScopedDirective):
@property
def server_name(self):
for node in self.children:
if isinstance(node, ServerName):
return node
@property
def server_alias(self):
for node in self.children:
if isinstance(node, ServerAlias):
return node
class ServerName(Directive):
@property
def isValid(self):
if len(self.arguments) == 0 or len(self.arguments) > 1:
return False
regex = '^((?P<scheme>[a-zA-Z]+)(://))?(?P<domain>[a-zA-Z_0-9.]+)(:(?P<port>[0-9]+))?\\s*$'
match = re.search(regex, self.arguments[0])
if match:
return True
return False
class ServerAlias(Directive):
@property
def isValid(self):
if len(self.arguments) == 0:
return False
regex = '^(?P<domain>[a-zA-Z_0-9.]+)\\s*$'
for name in self.arguments:
match = re.search(regex, name)
if not match:
return False
return True
class IncludeError(Exception):
pass
class Include(Directive):
def __init__(self, node=None):
Node.__init__(self, node=node)
if not self.path:
raise IncludeError("path cannot be none")
if len(glob.glob(self.path)) == 0:
raise ValueError("Include directive failed to include '{}'".format(self.path))
for path in glob.glob(self.path):
cf = ConfigFile(file=path)
cf._parent = self
self._children.append(cf)
@property
def path(self):
"""
:return: The glob pattern used to load additional configs.
"""
if len(self.arguments) > 0:
return self.arguments[0].strip()
return None
@property
def tokens(self):
"""
:return: List of all the tokens for this node concatenated together, excluding children.
"""
# Process pretokens, skip children, ignore posttokens because Includes will never have them.
tokenList = []
for token in self._pretokens:
tokenList.append(token)
return tokenList
class IncludeOptional(Include):
def __init__(self, node=None):
try:
Include.__init__(self, node=node)
except ValueError:
# Optional means we ignore when no files match the path and the ValueError exception is raised
pass
class Directory(ScopedDirective):
pass
class DirectoryMatch(ScopedDirective):
pass
class Files(ScopedDirective):
pass
class FilesMatch(ScopedDirective):
pass
class Location(ScopedDirective):
pass
class LocationMatch(ScopedDirective):
pass
class Proxy(ScopedDirective):
pass
class ProxyMatch(ScopedDirective):
pass
<file_sep>/sacp/utilities.py
from .base import *
class LineEnumerator(NodeVisitor):
def __init__(self, nodes):
NodeVisitor.__init__(self, nodes=nodes)
self._lineno = 1
self.lines = []
self.visit(visitor=self.visitor)
def visit(self, visitor):
# We need to do depth-first node visit except for into Include or IncludeOptional.
for node in self._nodes:
visitor(node)
if isinstance(node, Include):
continue
if node.children:
nv = LineEnumerator(node.children)
nv.visit(visitor)
def visitor(self, node):
if isinstance(node, ConfigFile):
self._lineno = 1
if node.type_token is None:
return
type_index = node._pretokens.index(node.type_token)
for token in node._pretokens[:type_index]:
self._lineno += token[1].count('\n')
self.lines.append((node, self._lineno))
for token in node._pretokens[type_index:]:
self._lineno += token[1].count('\n')
<file_sep>/sacp/node.py
import re
from pygments.token import Token
class Node:
"""
Node structure:
Node:
/ | \
pre - children - post
When processing tokens, e.g. when rendering, we process pre tokens first,
then the children nodes, then the post tokens.
Example:
<VirtualHost *:80>
ServerName server
</VirtualHost>
[<VirtualHost][ ][*:80][>][\n] -> pretokens
[ServerName][ server][\n] -> children / pretokens
[</VirtualHost][>][\n] -> posttokens
"""
def __init__(self, node=None, close_tag=False, parent=None):
self._parent = parent
self._pretokens = []
self._children = []
self._posttokens = []
self.closeTag = close_tag
if node:
self._parent = node._parent
self._pretokens = node._pretokens or []
self._children = node._children or []
self._posttokens = node._posttokens or []
self.closeTag = node.closeTag
@property
def tokens(self):
"""
:return: List of all the tokens for this node & it's children
concatenated together.
"""
tokenList = []
for token in self._pretokens:
tokenList.append(token)
for child in self._children:
for token in child.tokens:
tokenList.append(token)
for token in self._posttokens:
tokenList.append(token)
return tokenList
@property
def parent(self):
return self._parent
@property
def pretokens(self):
return self._pretokens
@property
def children(self):
return self._children
@property
def posttokens(self):
return self._posttokens
@property
def type_token(self):
"""
:return: returns the first non-whitespace token for the node. This is the first indicator of the type for this node.
"""
for token in self._pretokens:
if token[0] is Token.Text and token[1].isspace():
continue
return token
return None
@property
def depth(self):
depth = 0
node = self._parent
while node:
depth += 1
node = node._parent
return depth
def append_child(self, node):
node._parent = self
self._children.append(node)
def append_children(self, nodes):
for node in nodes:
self.append_child(node)
def __str__(self):
s = ''
for token in self.tokens:
s += "{}".format(token[1])
return s
class NodeFactory:
def __init__(self):
pass
def build(self, node):
"""
Used to build a begin building a new Node, is called as soon as a parser identifies enough information to construct a node.
"""
raise NotImplementedError
class NodeVisitor:
def __init__(self, nodes=None):
self._nodes = nodes
def visit(self, visitor):
for node in self._nodes:
visitor(node)
class DFNodeVisitor(NodeVisitor):
def visit(self, visitor):
for node in self._nodes:
visitor(node)
if node.children:
nv = DFNodeVisitor(node.children)
nv.visit(visitor)
class BFNodeVisitor(NodeVisitor):
def visit(self, visitor):
for node in self._nodes:
visitor(node)
for node in self._nodes:
if node.children:
nv = BFNodeVisitor(node.children)
nv.visit(visitor)
<file_sep>/sacp/__init__.py
from .base import *
from .utilities import *
| 2cb4527a7f7c7b9e6c02b6aeac40137d45879818 | [
"Markdown",
"Python"
] | 6 | Markdown | catatonicprime/sacp | b991704bd4cbe44c5e1aa5cbbd53cd8249df5970 | 0a8e972864adfde0aebb7c38e64d23c2330664bc | |
refs/heads/master | <file_sep>all: build
APP_NAME = puppet
PKGDIR_TMP = ${TMPDIR}golang
.pre-build:
mkdir -p build
deps:
go get -u github.com/golang/dep/...
go get -u golang.org/x/lint/golint
dep ensure -vendor-only -v
clean:
rm -rf build/
rm -rf ${PKGDIR_TMP}_darwin
build: .pre-build
GOOS=darwin go build -i -o build/${APP_NAME}.darwin.ext -pkgdir ${PKGDIR_TMP}
GOOS=windows go build -i -o build/${APP_NAME}.windows.ext.exe -pkgdir ${PKGDIR_TMP}
lastrun:
rm last_run_report.yaml
sudo cp /opt/puppetlabs/puppet/cache/state/last_run_report.yaml last_run_report.yaml
sudo chown graham_gilbert:admin last_run_report.yaml<file_sep>package main
import (
"flag"
"log"
"time"
osquery "github.com/kolide/osquery-go"
"github.com/kolide/osquery-go/plugin/table"
)
func main() {
var (
flSocketPath = flag.String("socket", "", "")
flTimeout = flag.Int("timeout", 0, "")
_ = flag.Int("interval", 0, "")
_ = flag.Bool("verbose", false, "")
)
flag.Parse()
// allow for osqueryd to create the socket path otherwise it will error
time.Sleep(2 * time.Second)
server, err := osquery.NewExtensionManagerServer(
"puppet_state",
*flSocketPath,
osquery.ServerTimeout(time.Duration(*flTimeout)*time.Second),
)
if err != nil {
log.Fatalf("Error creating extension: %s\n", err)
}
// Create and register a new table plugin with the server.
// Adding a new table? Add it to the list and the loop below will handle
// the registration for you.
plugins := []osquery.OsqueryPlugin{
table.NewPlugin("puppet_info", PuppetInfoColumns(), PuppetInfoGenerate),
table.NewPlugin("puppet_logs", PuppetLogsColumns(), PuppetLogsGenerate),
table.NewPlugin("puppet_state", PuppetStateColumns(), PuppetStateGenerate),
}
for _, p := range plugins {
server.RegisterPlugin(p)
}
// Start the server. It will run forever unless an error bubbles up.
if err := server.Run(); err != nil {
log.Fatalln(err)
}
}
<file_sep>package main
import (
"context"
"github.com/kolide/osquery-go/plugin/table"
)
type Log struct {
Level string `yaml:"level"`
Message string `yaml:"message"`
Source string `yaml:"source"`
Tags []string `yaml:"tags"`
Time string `yaml:"time"`
File string `yaml:"file"`
Line string `yaml:"line"`
}
// Columns returns the type hinted columns for the logged in user.
func PuppetLogsColumns() []table.ColumnDefinition {
return []table.ColumnDefinition{
table.TextColumn("level"),
table.TextColumn("message"),
table.TextColumn("source"),
// table.TextColumn("tags"),
table.TextColumn("time"),
table.TextColumn("file"),
table.TextColumn("line"),
}
}
// Generate will be called whenever the table is queried. Since our data in these
// plugins is flat it will return a single row.
func PuppetLogsGenerate(ctx context.Context, queryContext table.QueryContext) ([]map[string]string, error) {
var results []map[string]string
runData, err := GetPuppetYaml()
if err != nil {
return results, err
}
for _, item := range runData.Logs {
results = append(results, map[string]string{
"level": item.Level,
"message": item.Message,
"source": item.Source,
// "tags": parseList(item.Tags),
"time": item.Time,
"file": item.File,
"line": item.Line,
})
}
return results, nil
}
<file_sep>package main
import (
"bytes"
"os"
"runtime"
"strings"
"gopkg.in/yaml.v3"
)
func YamlPath() string {
if runtime.GOOS == "windows" {
return "C:\\ProgramData\\PuppetLabs\\puppet\\cache\\state\\last_run_report.yaml"
}
return "/opt/puppetlabs/puppet/cache/state/last_run_report.yaml"
// This is for when testing with a local report file
// filename, _ := filepath.Abs("./last_run_report.yaml")
// fmt.Print(filename)
// return filename
}
func GetPuppetYaml() (*PuppetInfo, error) {
var yamlData PuppetInfo
yamlFile, err := os.Open(YamlPath())
if err != nil {
// fmt.Print(err)
return &yamlData, err
}
buf := new(bytes.Buffer)
buf.ReadFrom(yamlFile)
yamlString := buf.String()
yamlString = strings.Replace(yamlString, "\r", "\n", -1)
err = yaml.Unmarshal([]byte(yamlString), &yamlData)
if err != nil {
// fmt.Print("Error during unmarshal")
// fmt.Print(err)
return &yamlData, err
}
return &yamlData, nil
}
<file_sep>package main
import (
"context"
"github.com/kolide/osquery-go/plugin/table"
)
// PuppetInfo
type PuppetInfo struct {
CachedCatalogStatus string `yaml:"cached_catalog_status"`
CatalogUUID string `yaml:"catalog_uuid"`
CodeID string `yaml:"code_id"`
ConfigurationVersion string `yaml:"configuration_version"`
CorrectiveChange string `yaml:"corrective_change"`
Environment string `yaml:"environment"`
Host string `yaml:"host"`
Kind string `yaml:"kind"`
MasterUsed string `yaml:"master_used"`
Noop string `yaml:"noop"`
NoopPending string `yaml:"noop_pending"`
PuppetVersion string `yaml:"puppet_version"`
ReportFormat string `yaml:"report_format"`
Status string `yaml:"status"`
Time string `yaml:"time"`
TransactionCompleted string `yaml:"transaction_completed"`
TransactionUUID string `yaml:"transaction_uuid"`
Logs []Log
ResourceStatuses map[string]ResourceStatus `yaml:"resource_statuses"`
// Metrics interface{} `yaml:"metrics"`
}
func PuppetInfoColumns() []table.ColumnDefinition {
return []table.ColumnDefinition{
table.TextColumn("cached_catalog_status"),
table.TextColumn("catalog_uuid"),
table.TextColumn("code_id"),
table.TextColumn("configuration_version"),
table.TextColumn("corrective_change"),
table.TextColumn("environment"),
table.TextColumn("host"),
table.TextColumn("kind"),
table.TextColumn("master_used"),
table.TextColumn("noop"),
table.TextColumn("noop_pending"),
table.TextColumn("puppet_version"),
table.TextColumn("report_format"),
table.TextColumn("status"),
table.TextColumn("time"),
table.TextColumn("transaction_completed"),
table.TextColumn("transaction_uuid"),
}
}
// Generate will be called whenever the table is queried. Since our data in these
// plugins is flat it will return a single row.
func PuppetInfoGenerate(ctx context.Context, queryContext table.QueryContext) ([]map[string]string, error) {
var results []map[string]string
runData, err := GetPuppetYaml()
if err != nil {
// fmt.Print(runData)
// fmt.Println(err)
return results, err
}
// fmt.Println(runData)
results = append(results, map[string]string{
"cached_catalog_status": runData.CachedCatalogStatus,
"catalog_uuid": runData.CatalogUUID,
"code_id": runData.CodeID,
"configuration_version": runData.ConfigurationVersion,
"corrective_change": runData.CorrectiveChange,
"environment": runData.Environment,
"host": runData.Host,
"kind": runData.Kind,
"master_used": runData.MasterUsed,
"noop": runData.Noop,
"noop_pending": runData.NoopPending,
"puppet_version": runData.PuppetVersion,
"report_format": runData.ReportFormat,
"status": runData.Status,
"time": runData.Time,
"transaction_completed": runData.TransactionCompleted,
"transaction_uuid": runData.TransactionUUID,
})
return results, nil
}
<file_sep>package main
import (
"context"
"github.com/kolide/osquery-go/plugin/table"
)
type ResourceStatus struct {
Title string `yaml:"title"`
File string `yaml:"file"`
Line string `yaml:"line"`
Resource string `yaml:"resource"`
ResourceType string `yaml:"resource_type"`
// ContainmentPath []string `yaml:"containment_path"`
EvaulationTime string `yaml:"evaluation_time"`
// Tags interface{} `yaml:"tags"`
// Time string `yaml:"time"`
Failed string `yaml:"failed"`
Changed string `yaml:"changed"`
OutOfSync string `yaml:"out_of_sync"`
Skipped string `yaml:"skipped"`
ChangeCount string `yaml:"change_count"`
OutOfSyncCount string `yaml:"out_of_sync_count"`
// Events []interface{} `yaml:"events"`
CorrectiveChange string `yaml:"corrective_change"`
}
// Columns returns the type hinted columns for the logged in user.
func PuppetStateColumns() []table.ColumnDefinition {
return []table.ColumnDefinition{
table.TextColumn("title"),
table.TextColumn("file"),
table.TextColumn("line"),
table.TextColumn("resource"),
table.TextColumn("resource_type"),
// table.TextColumn("containment_path"),
table.TextColumn("evaluation_time"),
// table.TextColumn("tags"),
// table.TextColumn("time"),
table.TextColumn("failed"),
table.TextColumn("changed"),
table.TextColumn("out_of_sync"),
table.TextColumn("skipped"),
table.TextColumn("change_count"),
table.TextColumn("out_of_sync_count"),
// table.TextColumn("events"),
table.TextColumn("corrective_change"),
}
}
func PuppetStateGenerate(ctx context.Context, queryContext table.QueryContext) ([]map[string]string, error) {
var results []map[string]string
// fmt.Println("Generating info...")
runData, err := GetPuppetYaml()
// fmt.Printf("%s", runData)
if err != nil {
// fmt.Print(err)
return results, err
}
for _, item := range runData.ResourceStatuses {
results = append(results, map[string]string{
"title": item.Title,
"file": item.File,
"line": item.Line,
"resource": item.Resource,
"resource_type": item.ResourceType,
// "containment_path": parseList(item.ContainmentPath),
"evaluation_time": item.EvaulationTime,
// "tags": item.Tags,
// "time": item.Time,
"failed": item.Failed,
"changed": item.Changed,
"out_of_sync": item.OutOfSync,
"skipped": item.Skipped,
"change_count": item.ChangeCount,
"out_of_sync_count": item.OutOfSyncCount,
// "events": item.Events,
"corrective_change": item.CorrectiveChange,
})
}
return results, nil
}
| 6af89ec0bacf827fc6b59182c23bed68fcb7d2a5 | [
"Go",
"Makefile"
] | 6 | Makefile | grahamgilbert/osquery-puppet-ext | 21354fbf98d958bab142b3744249e4b6d81cffa2 | 71d6820533df95b9c85af9523462c700ea9ac87a | |
refs/heads/master | <file_sep>import React, { PureComponent, Suspense, useEffect, useState } from "react";
import { AudioRecorder, AudioRecorderFunction } from "./AudioRecorder";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import allmight from "./allmight.png";
import Button from "./Button";
import { FirebaseAppProvider, useFirestore, useStorage } from "reactfire";
export default class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
accepted: false,
user: "",
};
}
onAccept = () => {
this.setState({ accepted: true });
};
render() {
const firebaseConfig = {
/* Paste your config object from Firebase console here */
apiKey: "<KEY>",
authDomain: "juke-1ad87.firebaseapp.com",
databaseURL: "https://juke-1ad87.firebaseio.com",
projectId: "juke-1ad87",
storageBucket: "juke-1ad87.appspot.com",
messagingSenderId: "826491069739",
appId: "1:826491069739:web:5a2792c9d8a376fd2a916e",
};
return (
<FirebaseAppProvider firebaseConfig={firebaseConfig}>
<Suspense fallback={<div>loading</div>}>
<div>
<Router>
<Switch>
<Route path="/juke">
<Juke></Juke>
</Route>
<Route path="">
<div>
{this.state.accepted ? (
<Switch>
<Route path="/listeA">
<AudioRecorder
audioSource="listeA"
user={this.state.user}
/>
</Route>
<Route path="/pretest">
<AudioRecorder
audioSource="pretest"
user={this.state.user}
/>
</Route>
<Route path="/listeB">
<AudioRecorder
audioSource="listeB"
user={this.state.user}
/>
</Route>
<Links />
</Switch>
) : (
<div style={{ display: "flex", padding: "1rem" }}>
<div
style={{ display: "flex", flexDirection: "column" }}
>
<h1>Note from Zhu</h1>
<p>你好,首先感谢你参与这次实验<span role="img" aria-label="smile">😊</span>!</p>
<p>
这是一个关于注意力的小测试,也可以说是一个小游戏。在接下来的测试中,你将听到小明的两周日记。小明是一个10岁的小男孩,他每天都会写日记,
记下一些有意义,或者无意义的事情,大部分内容都像是简单的流水账,比如吃饭、写作业、睡觉等日常行为。
</p>
<p>
两周的日记一共包含了14篇小日记,每篇日记平均有6到7句话,持续45秒左右,每篇日记间隔5秒,两周之间间隔10秒,整个注意力测试时间约为12分钟。日记中除了小明自己,还会出现他的家人,比如爸爸妈妈、朋友小宇以及其他一些不重要的人或物。日记是第一人称视角,小明即为故事中的“我”。
</p>
<p style={{ fontWeight: "bold" }}>
你的任务是:仔细听小明做了什么,并以一件事为单位,在听到小明做了一件事的时候,用鼠标点击一下按钮。
</p>
<p>
*注意:其他人做了什么并不重要,注意力请放在小明上。
</p>
<p>
在进入正式测试前,请先输入ID,并做一个约为45秒的pretest,以确保你明白了测试的内容及任务。
</p>
<p>
友情提示:测试结束后,请耐心等待数据上传,不要马上关掉网页哦。
</p>
<input
style={{ padding: "1rem" }}
placeholder="Input ID here"
type="text"
value={this.state.user}
onChange={(e) =>
this.setState({ user: e.target.value })
}
/>
<Button
disabled={!this.state.user}
onClick={this.onAccept}
>
Accept
</Button>
</div>
<img
src={allmight}
alt={"all might showing thumbsup"}
style={{ borderRadius: "50%", maxHeight: "90vh" }}
></img>
</div>
)}
</div>
</Route>
</Switch>
</Router>
</div>
</Suspense>
</FirebaseAppProvider>
);
}
}
const Links = () => {
return (
<div
style={{
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
}}
>
<Link
to="listeA"
style={{
fontSize: "4rem",
flex: 1,
color: "white",
textDecoration: "none",
padding: "5%",
border: "1px solid lightgrey",
borderRadius: "10px",
}}
>
listeA
</Link>
<Link
to="listeB"
style={{
fontSize: "4rem",
flex: 1,
color: "white",
textDecoration: "none",
padding: "5%",
border: "1px solid lightgrey",
borderRadius: "10px",
}}
>
listeB
</Link>
<Link
to="pretest"
style={{
fontSize: "4rem",
flex: 1,
color: "white",
textDecoration: "none",
padding: "5%",
border: "1px solid lightgrey",
borderRadius: "10px",
}}
>
pretest
</Link>
<Link
to="juke"
style={{
fontSize: "4rem",
flex: 1,
color: "white",
textDecoration: "none",
padding: "5%",
border: "1px solid lightgrey",
borderRadius: "10px",
}}
>
For Juke
</Link>
</div>
);
};
function getDownloadURL(timestamps){
let downloadUrl = "data:text/csv;charset=utf-8,sep=,\r\n\n" + timestamps?.
map(t => [t.user, ...t.timestamps.map(num => Math.floor(num))].join(",")).
join("\n")
return downloadUrl
}
const Juke = () => {
const [items, setItems] = useState();
const [timestamps, setTimestamps] = useState();
const storage = useStorage().ref();
const timestampsRef = useFirestore().collection("timestamps");
useEffect(() => {
async function getItems() {
const listeA = await storage.child("clips/listeA").listAll();
const listeB = await storage.child("clips/listeB").listAll();
const pretest = await storage.child("clips/pretest").listAll();
const timestampItems = await (await timestampsRef.get()).docs.map(doc => doc.data())
let newTimeStamps = {}
timestampItems.forEach(ts => {
if(!newTimeStamps[ts.audioSource]) newTimeStamps[ts.audioSource] = []
newTimeStamps[ts.audioSource].push(ts)
})
setTimestamps(newTimeStamps)
setItems({ listeA, listeB, pretest });
}
getItems();
}, []);
console.log("items", items);
console.log("timestamps", timestamps);
//let downloadUrl = "data:text/csv;charset=utf-8," + timestamps?.map(t => [t.user, ...t.timestamps.map(num => Math.floor(num))].join(",")).join("\n")
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<div style={{ flex: 2, display: "flex", justifyContent: "space-evenly" }}>
{items &&
Object.keys(items).map((list, i) => (
<div>
<h1>{list}</h1>
<a
href={getDownloadURL(timestamps[list])}
download={list + "timestamps.csv"}
>
Download timestamps
</a>
<div style={{ display: "flex", flexDirection: "column" }}>
{items[list].items.map((item) => (
<ListItem item={item} />
))}
</div>
</div>
))}
</div>
<div style={{ flex: 1, overflowY: "auto", maxHeight: 600 }}>
{timestamps && Object.keys(timestamps).map((key) =>
timestamps[key].map((t) => (
<div style={{margin:'8px 8px', padding:4, background:'#333', borderRadius:4}}>
<div>ID: {t.user}</div>
<div>Audio: {t.audioSource}</div>
<div>Clicks:{t.timestamps.length}</div>
{`${t.timestamps.map(
(num) => " " + Math.floor(num)
)}`}
</div>
))
)}
</div>
</div>
);
};
function ListItem({item}) {
const [link, setLink] = useState("");
useEffect(() => {
item.getDownloadURL().then(url => setLink(url))
// .then((url) => {
// var xhr = new XMLHttpRequest();
// xhr.responseType = 'blob';
// xhr.onload = function(event) {
// var blob = xhr.response;
// setLink(blob)
// };
// xhr.open('GET', url);
// xhr.send();
// })
}, []);
const onClick = () => {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = item.name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
};
xhr.open('GET', link);
xhr.send();
}
return <Button onClick={onClick}>Download {item.name}</Button>
//return <a href={link ? URL.createObjectURL(link) : ''} download={item.name}>{!link ? 'loading' : item.name}</a>;
}
const Lorem = () => `orem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse nec fermentum elit. Sed elementum, dolor vel blandit porttitor, mauris ligula fringilla risus, sit amet interdum justo dui ut sapien. Integer id odio vitae dolor dictum molestie sed consectetur diam. Donec mattis diam id risus mattis ornare. Donec ultrices tincidunt dolor id rhoncus. In dolor augue, egestas non venenatis nec, vestibulum eget nisi. Morbi enim eros, sodales accumsan dolor sit amet, auctor finibus ipsum. Vestibulum imperdiet tincidunt ante a suscipit. Praesent non commodo urna. Duis eleifend metus eu leo efficitur laoreet. Nulla non mauris lectus. Pellentesque viverra risus id nisi efficitur varius.
Donec sed posuere ex. Phasellus pretium mattis augue, vitae malesuada diam ullamcorper nec. Suspendisse egestas dolor eu accumsan vehicula. Nulla facilisi. Vestibulum consectetur malesuada massa at gravida. Fusce tincidunt lacus sed diam scelerisque euismod. Cras egestas, lorem non faucibus venenatis, neque magna lacinia nulla, eget pellentesque mi justo eget sapien.
Sed aliquet neque volutpat arcu rutrum mollis. Nullam ut felis urna. Cras tristique neque eget facilisis lacinia. Vivamus nec facilisis mi. In ac augue laoreet, aliquam tortor sit amet, pulvinar mauris. Nulla vitae mi ac erat bibendum efficitur malesuada eget velit. Nunc congue magna sed quam maximus, id lobortis dolor luctus. Proin nec mattis est. Mauris augue felis, porta a vestibulum et, sollicitudin ut ex. Donec in ultrices velit.
Duis vehicula nisi a quam luctus rutrum. Praesent interdum feugiat suscipit. Ut sed scelerisque sapien, in suscipit mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean quis iaculis eros. Sed imperdiet blandit neque, quis congue leo imperdiet id. Nullam venenatis scelerisque tellus, non blandit ipsum varius ut. Morbi et semper urna. Vivamus fringilla metus eu metus rhoncus euismod. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis fringilla orci vitae massa pharetra, ut porttitor massa facilisis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In in sapien enim. Nam quis lectus commodo, dapibus nunc at, bibendum nisi. In condimentum nisl sit amet suscipit suscipit.`;
| bc11e46d210c417e973ddefa555ad2a1a42b165f | [
"JavaScript"
] | 1 | JavaScript | Spoof14/juke | bc1618da928d8a1ec06549175d6fd9f0d063bd72 | 80f7478121716077ccf13ca81792aec733a16954 | |
refs/heads/main | <repo_name>Variapolis/OpenGL-CW1-CarGame<file_sep>/3DExample1/src/EndGate.h
#pragma once
#include "Rect.h"
#include "PlayerCar.h"
class EndGate :
public Rect //Endgate class used to regenerate a new level when player passes through.
{
public:
EndGate(GLfloat x, GLfloat y, GLfloat width, GLfloat height);
bool CheckCollision(PlayerCar* player, int score, GLfloat startX, GLfloat startY);
};
<file_sep>/3DExample1/src/EndGate.cpp
#include "EndGate.h"
EndGate::EndGate(GLfloat x, GLfloat y, GLfloat width, GLfloat height) :Rect(x, y, width, height)
{
}
bool EndGate::CheckCollision(PlayerCar* player, int score,GLfloat startX, GLfloat startY)
// Checks collision by comparing the aMin x/y and bMin x/y against each other in a AABB format.
{
bool isColliding = false;
GLfloat xMinCar = _posX - (_width);
GLfloat yMinCar = _posY - (_height);
GLfloat xMinObs = player->getPosX() - player->getWidth();
GLfloat yMinObs = player->getPosY() - player->getHeight();
GLfloat widthObs = player->getWidth();
GLfloat heightObs = player->getHeight();
if ((xMinCar + _width * 2) > xMinObs && xMinCar < xMinObs + (widthObs * 2))
{
if (yMinCar + _height * 2 > yMinObs && yMinCar < yMinObs + (heightObs * 2))
//Essentially checks if the gate is inside the range of the player on TWO axes. If it is not within range on both axes, it is not colliding.
{
player->MoveTo(startX,startY);
Log("Player reached End Gate.");
player->AddScore(score);
LogIntValue("Player won and gained: ", score, " points!");
LogIntValue("Current score: ", player->GetScore(), " Points");
return true;
}
}
return false;
}<file_sep>/3DExample1/src/Boundary.h
#pragma once
#include "GameObject.h"
class Boundary :
public GameObject
{
public:
Boundary(GLfloat x, GLfloat y, GLfloat width, GLfloat height);
void Draw(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
};
<file_sep>/3DExample1/src/Obstacle.cpp
#include "Obstacle.h"
Obstacle::Obstacle(GLfloat x, GLfloat y, GLfloat width, GLfloat height):Rect(x,y,width,height)
{
}
Obstacle::Obstacle(GLfloat x, GLfloat y) : Rect(x, y)
{
}
Obstacle::Obstacle():Rect()
{
}
<file_sep>/3DExample1/src/Obstacle.h
#pragma once
#include "Rect.h"
class Obstacle : public Rect //Essentially a copy of Rect, open ended class to allow for more functionality to be given to obstacles at a later date.
{
public:
Obstacle(GLfloat x, GLfloat y, GLfloat width, GLfloat height);
Obstacle(GLfloat x, GLfloat y);
Obstacle();
};
<file_sep>/3DExample1/src/Spawner.cpp
#include "Spawner.h"
Spawner::Spawner(GLfloat x, GLfloat y, GLfloat width, GLfloat height):GameObject(x,y,width,height)
{
}
Spawner::Spawner():GameObject()
{
}
void Spawner::DebugDraw(GLfloat r, GLfloat g, GLfloat b, GLfloat a) // Draw function inside the rectangle class creates a triangle strip with 4 vertices based on the position and size variables.
{
glPushAttrib(GL_CURRENT_BIT);
glBegin(GL_LINE_LOOP);
glColor4f(r, g, b, a);
glVertex2f((_posX - _width), (_posY - _height));
glVertex2f((_posX + _width), (_posY - _height));
glVertex2f((_posX + _width), (_posY + _height));
glVertex2f((_posX - _width), (_posY + _height));
glEnd();
glPopAttrib();
glFlush();
}
void Spawner::Draw() // Draws all of the spawned obstacles.
{
for(int i = 0; i < obstacles.size(); i++)
{
glPushAttrib(GL_CURRENT_BIT);
glPushMatrix();
obstacles[i]->Draw();
glPopMatrix();
glPopAttrib();
glColor3f(1, 1, 1);
}
}
int Spawner::GetRandBounds(int upper) // Generates a number within the range of the bounds of the spawner.
{
int bound = (rand() % (upper*2)) - upper;
return bound;
}
void Spawner::Spawn(int amount, GLfloat width, GLfloat height)
{
int count = 0;
while(count != amount){
bool isBlocked = false;
GLfloat spawnX = GetRandBounds(_width);
GLfloat spawnY = GetRandBounds(_height);
for (int i = 0; i < amount; i++) // Loop spawns the specified amount of Obstacle class instances at specified size.
{
if (!(obstacles.empty()))
{
for (auto i : obstacles)
{
if (CheckSpawn(i, spawnX, spawnY, width, height)) { isBlocked = true; break; }
}
}
if (!isBlocked) { obstacles.push_back(new Obstacle(spawnX, spawnY, width, height)); count++; }
obstacles.back()->SetColor((GLfloat)rand() * (1.0) / (GLfloat)RAND_MAX, (GLfloat)rand() * (1.0 - 0.5) / (GLfloat)RAND_MAX, (GLfloat)rand() * (1.0 - 0.5) / (GLfloat)RAND_MAX);
}
}
}
void Spawner::Spawn(GLfloat width, GLfloat height) // Spawns a single obstacle at the specified size.
{
bool isBlocked = true;
bool hasSpawned = false;
GLfloat spawnX = GetRandBounds(_width);
GLfloat spawnY = GetRandBounds(_height);
while (!hasSpawned)
{
if (!(obstacles.empty()))
{
for (int i = 0; i < obstacles.size(); i++)
{
isBlocked = CheckSpawn(obstacles[i], spawnX, spawnY, width, height);
if (isBlocked) { break; }
}
}
if (!isBlocked) { obstacles.push_back(new Obstacle(spawnX, spawnY, width, height)); hasSpawned = true; }
obstacles.back()->SetColor((GLfloat)rand() * (1.0) / (GLfloat)RAND_MAX + 0.1, (GLfloat)rand() * (1.0 - 0.5) / (GLfloat)RAND_MAX, (GLfloat)rand() * (1.0 - 0.5) / (GLfloat)RAND_MAX);
}
}
bool Spawner::CheckSpawn(GameObject* obstacle, GLfloat posX, GLfloat posY, GLfloat width, GLfloat height) //Checks collision on spawn to see if the area is occupied already.
{
bool isColliding = false;
GLfloat xMinNew = posX - (width);
GLfloat yMinNew = posY - (height);
GLfloat xMinObs = obstacle->getPosX() - obstacle->getWidth();
GLfloat yMinObs = obstacle->getPosY() - obstacle->getHeight();
GLfloat widthObs = obstacle->getWidth();
GLfloat heightObs = obstacle->getHeight();
if (((xMinNew + width * 2) > xMinObs && xMinNew < xMinObs + (widthObs * 2)))
{
if ((yMinNew + height * 2 > yMinObs && yMinNew < yMinObs + (heightObs * 2)))
{
return true; // true means area is taken
}
}
return false;
}
<file_sep>/3DExample1/src/Rect.h
#pragma once
#include "GameObject.h"
class Rect :
public GameObject //Rect class object used as a base and as an individual object for drawing rectangle polygons.
{
GLfloat _red, _green, _blue;
public:
Rect(GLfloat x, GLfloat y, GLfloat width, GLfloat height);
Rect(GLfloat x, GLfloat y);
Rect();
void Draw();
void SetColor(GLfloat red, GLfloat green, GLfloat blue);
};
<file_sep>/3DExample1/src/Spawner.h
#pragma once
#include "GameObject.h"
#include "Obstacle.h"
#include <vector>
class Spawner : public GameObject //Spawner class used to hold and handle a vector of obstacles.
{
public:
std::vector<Obstacle*> obstacles; // Container for all of the obstacles.
Spawner(GLfloat x, GLfloat y, GLfloat width, GLfloat height);
Spawner();
void DebugDraw(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
void Draw();
int GetRandBounds(int upper);
void Spawn(int amount, GLfloat width, GLfloat height);
void Spawn(GLfloat width, GLfloat height);
bool CheckSpawn(GameObject* obstacle, GLfloat posX, GLfloat posY, GLfloat width, GLfloat height);
};
<file_sep>/3DExample1/src/PlayerCar.cpp
#include "PlayerCar.h"
#include <iostream>
PlayerCar::PlayerCar(GLfloat speed, int startScore, GLfloat x, GLfloat y, GLfloat width, GLfloat height)
: Rect(x, y, width, height), _speed(speed), _score(startScore)
{
_hasWon = false;
}
PlayerCar::PlayerCar(GLfloat speed, int startScore) : Rect(), _speed(speed), _score(startScore)
{
_hasWon = false;
}
void PlayerCar::CheckCollision(GameObject* obstacle, int score)
// Checks collision by comparing the aMin x/y and bMin x/y against each other in a AABB format.
{
bool isColliding = false;
GLfloat xMinCar = _posX - (_width);
GLfloat yMinCar = _posY - (_height);
GLfloat xMinObs = obstacle->getPosX() - obstacle->getWidth();
GLfloat yMinObs = obstacle->getPosY() - obstacle->getHeight();
GLfloat widthObs= obstacle->getWidth();
GLfloat heightObs = obstacle->getHeight();
//Essentially checks if the player is inside the range of the obstacle on TWO axes. If it is not within range on both axes, it is not colliding.
if ((xMinCar + _width * 2) > xMinObs && xMinCar < xMinObs + (widthObs * 2))
{
if (yMinCar + _height * 2 > yMinObs && yMinCar < yMinObs + (heightObs * 2))
{
HandleCollision(obstacle);
AddScore(-score);
LogIntValue("Player crashed and lost: ", score, " points!");
LogIntValue("Current score: ", GetScore(), " Points");
}
}
}
void PlayerCar::CheckBoundsCollision(GameObject* obstacle, GLfloat startX, GLfloat startY)
// Checks collision by comparing the aMin x/y and bMin x/y against each other in a REVERSED AABB format.
{
bool isColliding = false;
GLfloat xMinCar = _posX - (_width);
GLfloat yMinCar = _posY - (_height);
GLfloat xMinObs = obstacle->getPosX() - obstacle->getWidth();
GLfloat yMinObs = obstacle->getPosY() - obstacle->getHeight();
GLfloat widthObs = obstacle->getWidth();
GLfloat heightObs = obstacle->getHeight();
if (xMinCar < xMinObs || xMinCar + _width * 2 > xMinObs + widthObs*2 || yMinCar < yMinObs || yMinCar + _height * 2 > yMinObs + (heightObs * 2))
//Essentially checks if the player is outside the range of the border on ANY axis. If it is not within range on atleast one axis, it is colliding.
{
LogIntValue("xMinCar", xMinCar);
LogIntValue("xMinObs", xMinObs);
MoveTo(startX, startY);
Log("Player has been returned within bounds.");
}
}
void PlayerCar::HandleCollision(GameObject* obstacle) // Handles the collision, essentially determines whether the object is above or below, then left or right.
{
bool vertical = (_width < _height); // Top/Side determinant is not flawless and some slipping can be seen.
if (abs((_posX)-obstacle->getPosX()) > abs((_posY)-obstacle->getPosY()))
{
if (_posX > obstacle->getPosX()) { _posX += 6; }
else { _posX -= 6; }
}
else
{
if (_posY > obstacle->getPosY()) { _posY += 6; }
else { _posY -= 6; }
}
Log("Collided with obstacle.");
}
void PlayerCar::Rotate() //Swaps the width and height values to "rotate" by 90 degrees.
{
GLfloat temp = _width;
_width = _height;
_height = temp;
}
void PlayerCar::AddScore(int score) // Adds an amount to the private _score variable.
{
_score += score;
}
int PlayerCar::GetScore(){ return _score; } // Gets player's score
<file_sep>/3DExample1/src/Rect.cpp
#include "Rect.h"
Rect::Rect(GLfloat x, GLfloat y, GLfloat width, GLfloat height) :GameObject(x, y, width, height) // Constructor with all variables.
{
GLfloat red = 1, green = 1, blue = 1;
}
Rect::Rect(GLfloat x, GLfloat y) : GameObject(x, y) // Default constructor for position only.
{
GLfloat _red = 1, _green = 1, _blue = 1;
}
Rect::Rect():GameObject() // Default constructor at position 1.
{
GLfloat _red = 1, _green = 1, _blue = 1;
}
void Rect::Draw() // Draw function inside the rectangle class creates a triangle strip with 4 vertices based on the position and size variables.
{
glPushMatrix();
glBegin(GL_POLYGON); // Creates a polygon with the following vertices specified below.
glColor3f(_red, _green, _blue);
glVertex2f((_posX - _width), (_posY - _height));
glVertex2f((_posX + _width), (_posY - _height));
glVertex2f((_posX + _width), (_posY + _height));
glVertex2f((_posX - _width), (_posY + _height));
glEnd();
glFlush();
glPopMatrix();
}
void Rect::SetColor(GLfloat red, GLfloat green, GLfloat blue) // Sets the colour of the object for draw calls.
{
_red = red;
_green = green;
_blue = blue;
}<file_sep>/3DExample1/src/Boundary.cpp
#include "Boundary.h"
#include "EndGate.h"
Boundary::Boundary(GLfloat x, GLfloat y, GLfloat width, GLfloat height) :GameObject(x, y, width, height)
{
}
void Boundary::Draw(GLfloat r, GLfloat g, GLfloat b, GLfloat a) // Draw function inside the rectangle class creates a triangle strip with 4 vertices based on the position and size variables.
{
glPushAttrib(GL_CURRENT_BIT);
glBegin(GL_LINE_LOOP);
glColor4f(r, g, b, a);
glVertex2f((_posX - _width), (_posY - _height));
glVertex2f((_posX + _width), (_posY - _height));
glVertex2f((_posX + _width), (_posY + _height));
glVertex2f((_posX - _width), (_posY + _height));
glEnd();
glPopAttrib();
glFlush();
}
<file_sep>/3DExample1/src/GameObject.h
#pragma once
#include "freeglut.h"
#include "ConsoleDebug.h"
class GameObject //Base class for every object, used to store position and size information.
{
protected:
GLfloat _posX, _posY, _width, _height;
public:
GameObject(GLfloat x, GLfloat y, GLfloat width, GLfloat height);
GameObject(GLfloat x, GLfloat y);
GameObject();
GLfloat getPosX(); GLfloat getPosY(); GLfloat getWidth(); GLfloat getHeight();
void Move(GLfloat x, GLfloat y);
void MoveTo(GLfloat x, GLfloat y);
void Resize(GLfloat width, GLfloat height);
void ResizeWidth(GLfloat width);
void ResizeHeight(GLfloat height);
};
<file_sep>/3DExample1/src/ConsoleDebug.cpp
#include "ConsoleDebug.h"
// File used to contain Debug functions neatly.
void Log(std::string message){
std::cout<< "Debug Log: " << message << std::endl;
}
void LogIntValue(std::string message, int value, std::string message2)
{
std::cout << "DebugValue Log: "<< message << value << message2 << std::endl;
}
void LogIntValue(std::string message, int value) // Log overload
{
std::cout << "DebugValue Log: " << message << value << std::endl;
}
void LogIntro()
{
std::cout << "Welcome to my Car Game! By <NAME>"<< std::endl;
std::cout << "W - Move Up" << std::endl;
std::cout << "S - Move Down" << std::endl;
std::cout << "A - Move Left" << std::endl;
std::cout << "D - Move Right" << std::endl;
std::cout << "R - Rotate 90" << std::endl;
std::cout << "Reach the red gate and avoid the obstacles!" << std::endl;
}
<file_sep>/3DExample1/src/PlayerCar.h
#pragma once
#include "Rect.h" //Player car used to represent the player, check collisions with the border and obstacles and contain score.
class PlayerCar :
public Rect
{
int _score;
bool _hasWon;
public:
GLfloat _speed;
PlayerCar(GLfloat speed, int startScore, GLfloat x, GLfloat y, GLfloat width, GLfloat height);
PlayerCar(GLfloat speed, int startScore);
void CheckCollision(GameObject* obstacle, int score);
void CheckBoundsCollision(GameObject* obstacle, GLfloat startX, GLfloat startY);
void HandleCollision(GameObject* obstacle);
void Rotate();
void AddScore(int score);
int GetScore();
};
<file_sep>/3DExample1/src/GameObject.cpp
#include "GameObject.h"
GameObject::GameObject(GLfloat x, GLfloat y, GLfloat width, GLfloat height):_posX(x), _posY(y), _width(width), _height(height) // constructor for
{
}
GameObject::GameObject(GLfloat x, GLfloat y): _posX(x), _posY(y), _width(1), _height(1) // constructor for only x and y
{
}
GameObject::GameObject(): _posX(0), _posY(0), _width(1),_height(1) // default constructor
{
}
GLfloat GameObject::getPosX() { return _posX; } // Getters for pos and size
GLfloat GameObject::getPosY() { return _posY; }
GLfloat GameObject::getWidth() { return _width; }
GLfloat GameObject::getHeight() { return _height; }
void GameObject::Move(GLfloat x, GLfloat y) { _posX += x; _posY += y; } // Moves the object by a certain amount
void GameObject::MoveTo(GLfloat x, GLfloat y){ _posX = x; _posY = y; } // Moves the object to a specified coordinate
void GameObject::Resize(GLfloat width, GLfloat height) { _width = width; _height = height; } // Resizes the object
void GameObject::ResizeWidth(GLfloat width) { _width = width; }
void GameObject::ResizeHeight(GLfloat height) {_height = height; }<file_sep>/3DExample1/src/Main.cpp
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include "freeglut.h" // OpenGL toolkit - in the local shared folder
#include "Spawner.h"
#include "PlayerCar.h"
#include "ConsoleDebug.h"
#include "EndGate.h"
#include "Boundary.h"
//Constants
#define X_CENTRE 0.0 // Centre
#define Y_CENTRE 0.0
#define START_X -50.0 // Spawn
#define START_Y -36.0
#define END_X 50.0 // EndGate
#define END_Y 38.0
#define PLAYER_WIDTH 4.0 // Player
#define PLAYER_HEIGHT 2.0
#define PLAYER_SPEED 2
#define DEFAULT_SIZE 4.0 // Obstacle
#define DEFAULT_AMOUNT 6
#define BOUNDARY_WIDTH 60 //Bounds
#define BOUNDARY_HEIGHT 40
#define START_SCORE 50 // Scores
#define WIN_SCORE 30
#define LOSE_SCORE 10
#define GRID_SIZE 4
//Globals
GLfloat rainbowRed = 0, rainbowGreen = 0.8, rainbowBlue = 0;
Spawner* spawner = new Spawner(X_CENTRE, Y_CENTRE, 50, 20); // Creates a spawner instance
EndGate* exitGate = new EndGate(END_X+2, END_Y-2, DEFAULT_SIZE*2, DEFAULT_SIZE); // Creates an End Gate instance
Rect* startGate = new Rect(START_X-2, START_Y, DEFAULT_SIZE*2, DEFAULT_SIZE); // Creates a start gate instance
PlayerCar* player = new PlayerCar(PLAYER_SPEED, START_SCORE, START_X+2, START_Y+2, PLAYER_WIDTH, PLAYER_HEIGHT); // Creates a player class instance
Boundary* border = new Boundary(X_CENTRE, Y_CENTRE, BOUNDARY_WIDTH, BOUNDARY_HEIGHT);
bool rainbowMode = false, grid = false; // Rainbow more global vars
bool redCountUp = false;
bool greenCountUp = false;
std::string scoreStr = "Score: "; // score text var
void* font = GLUT_BITMAP_9_BY_15; // font
// Callback function when the window size is changed.
void reshape(int w, int h)
{
GLfloat aspect = (GLfloat)w / (GLfloat)h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h) // aspect <= 1
glOrtho(-50.0, 50.0, -50.0 / aspect, 50.0 / aspect, -50.0, 50.0);
else // aspect > 1
glOrtho(-50.0*aspect, 50.0*aspect, -50.0, 50.0, -50.0, 50.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void DrawGrid()
{
/*LogIntValue("Width", GLUT_WINDOW_WIDTH);
LogIntValue("Height", GLUT_WINDOW_HEIGHT);*/
glPushMatrix();
for(GLfloat i = START_X*2; i <= END_X*2; i+= GRID_SIZE) // Vertical lines
{
glBegin(GL_LINES);
glColor3f(0.0, 0.2, 0.2);
glVertex2f((i), (START_Y*2));
glVertex2f((i), (END_Y*2));
glEnd();
}
for (GLfloat i = START_Y * 2; i < END_Y * 2; i += GRID_SIZE) // Horizontal lines
{
glBegin(GL_LINES);
glColor3f(0.0, 0.2, 0.2);
glVertex2f((START_X*2), (i));
glVertex2f((END_X*2), (i));
glEnd();
}
glFlush();
glPopMatrix();
}
void DisplayScore(GLfloat x, GLfloat y)
{
std::string scr = std::to_string(player->GetScore()); // Score converted to string
glPushMatrix();
if (player->GetScore() < 0) { glColor3f(1.0, 0.0, 0.0); } // Red
else{ glColor3f(0.0, 1.0, 0.0); } // Green
glRasterPos2i(x, y); // changes the raster position for the text to a specified point.
for (std::string::iterator i = scoreStr.begin(); i != scoreStr.end(); ++i) // Iterates through the string and draws each character.
{
char c = *i;
glutBitmapCharacter(font, c);
}
for(std::string::iterator i = scr.begin(); i != scr.end(); ++i) // Iterator for score.
{
char c = *i;
glutBitmapCharacter(font, c);
}
glPopMatrix();
}
void RateChange(bool &isUp, GLfloat &number, GLfloat rate) //Simple function to make changing the timer value smoothly go up and down
{
if (number > 100) { isUp = true; }
if (number < 0) { isUp = false; }
number += rate + (isUp * (-rate * 2));
}
//Timer callback function
void TimerFunction(int value)
{
glClear(GL_COLOR_BUFFER_BIT);
RateChange(redCountUp, rainbowRed, 0.2); // Rate change for rainbow "GAMER MODE" colours.
RateChange(greenCountUp, rainbowGreen, 0.3);
glutPostRedisplay();
glutTimerFunc(5, TimerFunction, 0); //calls TimerFunction on tick - callback
}
void rightMenu(GLint id) // Right click menu entries
{
switch(id)
{
case 1:
rainbowMode = true;
Log("Rainbow Mode On.");
break;
case 2:
rainbowMode = false;
Log("Rainbow Mode Off.");
break;
case 3:
if (grid) { grid = false; }
else { grid = true; }
LogIntValue("grid toggled: ", grid);
break;
default:
break;
}
glutPostRedisplay();
}
void keyboard(unsigned char key, int x, int y) // Keyboard actions
{
switch (key)
{
case 'w':
player->Move(0, player->_speed);
break;
case 's':
player->Move(0, -player->_speed);
break;
case 'd':
player->Move(player->_speed, 0);
break;
case 'a':
player->Move(-player->_speed, 0);
break;
case 'r':
player->Rotate();
break;
}
glutPostRedisplay();
for(Obstacle* i : spawner->obstacles)
{
player->CheckCollision(i, LOSE_SCORE);
}
}
// Graphics initialization function
void init(void)
{
LogIntro();
glClearColor (0.0, 0.0, 0.0, 0.0); // window will be cleared to black
srand(time(NULL));
spawner->Spawn(DEFAULT_AMOUNT,DEFAULT_SIZE, DEFAULT_SIZE);
player->SetColor(1, 1, 1);
startGate->SetColor(0, 1, 0);
glutCreateMenu(rightMenu);
glutAddMenuEntry("Gamer Mode on", 1);
glutAddMenuEntry("Gamer Mode off", 2);
glutAddMenuEntry("Grid toggle", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
// display callback function called whenever contents of window need to be re-displayed
//this is the all important drawing method - all drawing code goes in here
void display()
{
glClear(GL_COLOR_BUFFER_BIT); /* clear window */
glLoadIdentity();
if (grid) { DrawGrid(); }
border->Draw(1, 1, 1, 1);
player->CheckBoundsCollision(border, START_X, START_Y);
spawner->Draw();
//spawner->DebugDraw(1,0,0,1);
if (rainbowMode) { player->SetColor(rainbowRed/100, rainbowGreen/100, 0.5); }
else { player->SetColor(1, 1, 1); }
exitGate->Draw();
startGate->Draw();
player->Draw();
DisplayScore(START_X, END_Y);
glPushMatrix();
exitGate->SetColor(1.0, 0.0, 0.0);
glPopMatrix();
if(exitGate->CheckCollision(player,WIN_SCORE,START_X,START_Y))
{
spawner->obstacles.clear();
spawner->Spawn(DEFAULT_AMOUNT, DEFAULT_SIZE, DEFAULT_SIZE);
}
glutSwapBuffers();
}
//rename this to main(...) and change example 2 to run this main function
int main(int argc, char** argv)
{
/* window management code ... */
glutInit(&argc, argv); // initialises GLUT and processes any command line arguments
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); // Double Buffered, RGB colour-space
glutInitWindowSize (1024, 720); // window width = 1024 pixels, height = 576 pixels for a 16:9 ascpect ratio
glutInitWindowPosition (600, 100); // Window upper left corner at (100, 100) in Windows space.
glutCreateWindow ("Car Game"); // creates an OpenGL window with command argument in its title bar
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
//needed for animation
glutTimerFunc(5, TimerFunction, 0);
glutMainLoop();
return 0;
}
| ade38d0873666593e3125dea4d56dc802d8c3755 | [
"C++"
] | 16 | C++ | Variapolis/OpenGL-CW1-CarGame | 395ad982743441d6c54293af49912b40daef14a1 | 5f4b6436ee53ecad302faaf42a9deccd1f8b0fb4 | |
refs/heads/master | <repo_name>KaminskayaLyuba/iipu_lr5<file_sep>/Device.h
#pragma once
#define BUFFERL_SIZE 2048
#define REG_PATH "SYSTEM\\CurrentControlSet\\Services\\\0"
#define REG_IMAGE "ImagePath"
#define DISC_DISABLE 2
#define DISC_ENABLE 1
#define PROBLEM_CODE 22
#include <string>
#include <Windows.h>
#include <SetupApi.h>
#include <Cfgmgr32.h>
using namespace std;
#pragma comment(lib, "setupapi.lib")
#pragma comment(lib, "Advapi32.lib")
class Device
{
public:
Device();
static string getDeviceClassDescription(SP_DEVINFO_DATA spDevInfoData); //получить описани класса
static string getDeviceName(HDEVINFO hDevInfo, SP_DEVINFO_DATA spDevInfoData); //получить имя устройства
static string getGUID(HDEVINFO hDevInfo, SP_DEVINFO_DATA spDevInfoData); //получить GUID
static void getDriverInfo(GUID guid, DWORD index, string *hardwareID, string *manufacturer, string *provider, string *driverDescription); //получить информацию из драйвера (hardwareID, производитель, провайдер, описаниедрайвера)
static string getDevicePath(HDEVINFO hDevInfo, SP_DEVINFO_DATA spDevInfoData); //почить путь к устроству
static string getDriverFullName(HDEVINFO hDevInfo, SP_DEVINFO_DATA spDevInfoData); //получить полный путь к драйверу
static bool deviceChangeStatus(HDEVINFO hDevInfo, SP_DEVINFO_DATA spDevInfoData, bool status); //изменить состояние устройства
static bool isEnabled(SP_DEVINFO_DATA spDevInfoData); //получить состояние устройства
~Device();
};
<file_sep>/DeviceEnumerator.h
#pragma once
#include <vector>
#include <string>
#include <set>
#include <Windows.h>
#include <setupapi.h>
#include "Device.h"
using namespace std;
#pragma comment(lib, "setupapi.lib")
typedef struct DEVICE_INFO
{
HDEVINFO hDevInfo; //хендл семейства
SP_DEVINFO_DATA spDevInfoData; //хендл устройства
string classDescription; //описание класса
string deviceName; //имя устройства
string guid_string; //GUID стокой
GUID guid; //GUID
string hardwareID; //hardwareID
string manufacturer; //производитель
string provider; //провайдер
string driverDescription; //описание драйвера
string devicePath; //путь к устройству
string driverFullName; //полнй путь к драйверу
bool isEnabled; //состояне устройства
}DEV_INFO;
class DeviceEnumerator
{
private:
static vector<DEVICE_INFO> vectorDeviceInfo;
public:
static vector<DEVICE_INFO> getDevices();
static set<string> getDeviceTypes();
DeviceEnumerator();
~DeviceEnumerator();
};
| 5ead333429d7afc2acbe07d503d26d4a922d457a | [
"C++"
] | 2 | C++ | KaminskayaLyuba/iipu_lr5 | eabade7f41aedfaceddd3a819bfcd7563f523aa1 | 3c11f4f2daf428847844f78a1e0033f0f2a5a9b5 | |
refs/heads/master | <repo_name>emma58min/CoronaChatbot<file_sep>/README.md
# CoronaChatbot
#### 정부혁신제안 끝장개발대회
##### 서비스 소개
N&A (News&Answer)은 코로나 소식을 알려주는 챗봇 서비스 입니다. 서울 지역의 최근 코로나 확진자정보, 마스크 판매 약국 현황, 코로나 위탁병원 정보를 구별로 제공해줍니다. 처음 사용하는 분이나 기계에 익숙하지 않은 분도 쉽게 사용할 수 있는 버튼형 챗봇으로 제작되었습니다.
##### 못난이 호랭이팀
[문서희](https://github.com/MunSeoHee)
[김재이](https://github.com/KimJaei)
[박상현](https://github.com/BbakSsang)
[최예진](https://github.com/chldppwls12)
[임성준](https://github.com/emma58min)
##### 사용 기술
```
Python, Django
Beutiful soup4
Pandas
AWS EC2, Ubuntu Linux
Nginx
Kakao i Open Builder
```
##### 서비스 소개
https://youtu.be/vs6UAvCv3JE
<file_sep>/project/app/models.py
from django.db import models
# Create your models here.
class User(models.Model):
location = models.CharField(max_length=100)
userId = models.TextField()<file_sep>/project/app/views.py
#-*- coding:utf-8 -*-
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
import json
from .models import User
import pandas as pd
import numpy as np
import requests
from bs4 import BeautifulSoup
# read Seoul Data
# Create your views here.
def keyboard(request):
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": "무엇을 알고싶으신가요?"
}
}
],
"quickReplies": [
{
"messageText": "확진자 정보",
"action": "message",
"label": "확진자 정보"
},
{
"messageText": "마스크 약국 현황",
"action": "message",
"label": "근처 약국 현황"
},
{
"messageText": "위탁병원 정보",
"action": "message",
"label": "위탁 병원 정보"
}
]
}
})
@csrf_exempt
def message(request):
answer = ((request.body).decode('utf-8'))
return_json_str = json.loads(answer)
return_str = return_json_str['userRequest']['utterance']
if return_str == '도봉구' or return_str == '동대문구' or return_str == '동작구' or return_str == '은평구' or return_str == '강북구' or return_str == '강동구' or return_str == '강남구' or return_str == '강서구' or return_str == '금천구' or return_str == '구로구' or return_str == '관악구' or return_str == '광진구' or return_str == '종로구' or return_str == '중구' or return_str == '중랑구' or return_str == '마포구' or return_str == '노원구'or return_str == '서초구' or return_str == '서대문구' or return_str == '성북구' or return_str == '성동구' or return_str == '송파구' or return_str == '양천구' or return_str == '영등포구' or return_str == '용산구':
id = return_json_str["userRequest"]["user"]["id"]
choice = User.objects.get(userId=id)
if choice.location == '확진자 정보':
if return_str == '도봉구':
x = "도봉구 어린이집 2020-06-24 격리 중\n도봉구 어린이집 2020-06-23 격리 중\n도봉구 어린이집 2020-06-23 격리 중\n도봉구 어린이집 2020-06-23 격리 중\n도봉구 어린이집 2020-06-21 격리 중\n도봉구 어린이집 2020-06-20 격리 중\n도봉구 어린이집 2020-06-20 격리 중\n도봉구 어린이집 2020-06-19 격리 중\n도봉구 어린이집 2020-06-19 격리 중\n도봉구 어린이집 2020-06-18 격리 중"
elif return_str == '동대문구':
x = "동대문구 강남 역삼동 모임 2020-06-27 격리 중\n동대문구 강남 역삼동 모임 2020-06-26 격리 중\n동대문구 해외 유입 2020-06-19 격리 중\n동대문구 리치웨이 2020-06-05 격리해제\n동대문구 이태원 클럽 2020-05-14 격리해제\n동대문구 이태원 클럽 2020-05-12 격리해제\n동대문구 이태원 클럽 2020-05-10 격리해제\n동대문구 해외 유입 2020-04-07 격리해제\n동대문구 확진자 접촉 2020-04-04 격리해제\n동대문구 해외 유입 2020-04-04 격리해제"
elif return_str == '강남구':
x = "강남구 강남 역삼동 모임 2020-06-27 격리 중\n강남구 확진자 접촉 2020-06-24 격리 중\n강남구 리치웨이 2020-06-22 격리 중\n강남구 리치웨이 2020-06-17 격리 중\n강남구 리치웨이 2020-06-16 격리 중\n강남구 리치웨이 2020-06-03 격리해제\n강남구 삼성화재 2020-06-03 격리 중\n강남구 확인불가 2020-06-02 격리 중\n강남구 해외 유입 2020-05-31 격리해제\n강남구 구리 집단감염 2020-05-29 격리해제"
elif return_str == '강동구':
x = "강동구 확진자 접촉 2020-06-22 격리 중\n강동구 확인불가 2020-06-22 격리 중\n강동구 확인불가 2020-06-12 격리해제\n강동구 해외 유입 2020-06-11 격리 중\n강동구 리치웨이 2020-06-07 격리 중\n강동구 리치웨이 2020-06-05 격리해제\n강동구 리치웨이 2020-06-05 격리 중\n강동구 리치웨이 2020-06-04 격리해제\n강동구 용인 Brothers 2020-06-04 격리해제\n강동구 해외 유입 2020-06-02 격리해제"
elif return_str == '강북구':
x = "강북구 확인불가 2020-06-18 격리 중\n강북구 리치웨이 2020-06-13 격리해제\n강북구 어린이집 2020-06-12 격리 중\n강북구 어린이집 2020-06-12 격리 중\n강북구 양천 탁구클럽 2020-06-07 격리해제\n강북구 양천 탁구클럽 2020-06-06 격리해제\n강북구 리치웨이 2020-06-05 격리해제\n강북구 확인불가 2020-06-03 격리 중\n강북구 서초 Family 2020-06-02 격리해제\n강북구 KB 생명 2020-06-02 격리해제"
elif return_str == '강서구':
x = "강서구 확진자 접촉 2020-06-25 격리 중\n강서구 리치웨이 2020-06-22 격리 중\n강서구 확인불가 2020-06-21 격리 중\n강서구 대자연 2020-06-20 격리 중\n강서구 금천구 쌀 제조공장 2020-06-19 격리 중\n강서구 금천구 쌀 제조공장 2020-06-18 격리 중\n강서구 확인불가 2020-06-18 격리 중\n강서구 SMR 2020-06-17 격리 중\n강서구 대자연 2020-06-17 격리 중\n강서구 양천 탁구클럽 2020-06-13 격리 중"
elif return_str == '관악구':
x = "관악구 확진자 접촉 2020-06-28 격리 중\n관악구 왕성교회 2020-06-27 격리 중\n관악구 왕성교회 2020-06-27 격리 중\n관악구 확인불가 2020-06-27 격리 중\n관악구 왕성교회 2020-06-27 격리 중\n관악구 왕성교회 2020-06-27 격리 중\n관악구 왕성교회 2020-06-26 격리 중\n관악구 왕성교회 2020-06-26 격리 중\n관악구 왕성교회 2020-06-26 격리 중\n관악구 왕성교회 2020-06-26 격리 중"
elif return_str == '광진구':
x = "광진구 강남 역삼동 모임 2020-06-26 격리 중\n광진구 리치웨이 2020-06-18 격리 중\n광진구 리치웨이 2020-06-10 격리해제\n광진구 이태원 클럽 2020-05-27 격리해제\n광진구 이태원 클럽 2020-05-21 격리해제\n광진구 이태원 클럽 2020-05-14 격리해제\n광진구 이태원 클럽 2020-05-10 격리해제\n광진구 이태원 클럽 2020-05-09 격리해제\n광진구 이태원 클럽 2020-05-09 격리해제\n광진구 해외 유입 2020-04-09 격리해제"
elif return_str == '구로구':
x = "구로구 왕성교회 2020-06-28 격리 중\n구로구 확진자 접촉 2020-06-27 격리 중\n구로구 확진자 접촉 2020-06-26 격리 중\n구로구 확진자 접촉 2020-06-25 격리 중\n구로구 확진자 접촉 2020-06-24 격리 중\n구로구 확인불가 2020-06-23 격리 중\n구로구 리치웨이 2020-06-21 격리 중\n구로구 리치웨이 2020-06-21 격리 중\n구로구 확진자 접촉 2020-06-21 격리 중\n구로구 리치웨이 2020-06-21 격리 중"
elif return_str == '금천구':
x = "금천구 확진자 접촉 2020-06-29 격리 중\n금천구 확인불가 2020-06-24 격리 중\n금천구 리치웨이 2020-06-15 격리 중\n금천구 리치웨이 2020-06-12 격리 중\n금천구 리치웨이 2020-06-13 격리 중\n금천구 양천 탁구클럽 2020-06-11 격리 중\n금천구 리치웨이 2020-06-11 격리해제\n금천구 리치웨이 2020-06-11 격리 중\n금천구 리치웨이 2020-06-10 격리해제\n금천구 리치웨이 2020-06-10 격리 중"
elif return_str == '노원구':
x = "노원구 해외 유입 2020-06-29 격리 중\n노원구 왕성교회 2020-06-28 격리 중\n노원구 왕성교회 2020-06-26 격리 중\n노원구 확진자 접촉 2020-06-25 격리 중\n노원구 리치웨이 2020-06-20 격리 중\n노원구 리치웨이 2020-06-20 격리 중\n노원구 리치웨이 2020-06-12 격리 중\n노원구 리치웨이 2020-06-11 격리 중\n노원구 해외 유입 2020-06-10 격리해제\n노원구 확진자 접촉 2020-06-05 격리 중"
elif return_str == '동작구':
x = "동작구 왕성교회 2020-06-26 격리 중\n동작구 확진자 접촉 2020-06-26 격리 중\n동작구 왕성교회 2020-06-25 격리 중\n동작구 확인불가 2020-06-20 격리 중\n동작구 대전 방문 판매 2020-06-19 격리 중\n동작구 리치웨이 2020-06-16 격리 중\n동작구 확진자 접촉 2020-06-16 격리해제\n동작구 리치웨이 2020-06-15 격리 중\n동작구 리치웨이 2020-06-10 격리해제\n동작구 확인불가 2020-06-09 격리 중"
elif return_str == '마포구':
x = "마포구 리치웨이 2020-06-29 격리 중\n마포구 리치웨이 2020-06-29 격리 중\n마포구 리치웨이 2020-06-27 격리 중\n마포구 리치웨이 2020-06-29 격리 중\n마포구 확인불가 2020-06-19 격리 중\n마포구 확진자 접촉 2020-06-18 격리 중\n마포구 기타 2020-06-16 격리해제\n마포구 리치웨이 2020-06-09 격리해제\n마포구 리치웨이 2020-06-06 격리 중\n마포구 삼성화재 2020-06-04 격리해제"
elif return_str == '서대문구':
x = "서대문구 오렌지 라이프 2020-06-19 격리 중\n서대문구 해외 유입 2020-06-18 격리 중\n서대문구 SMR 2020-06-15 격리해제\n서대문구 해외 유입 2020-06-14 격리 중\n서대문구 확인불가 2020-06-08 deceased\n서대문구 서초 Family 2020-06-02 격리해제\n서대문구 서초 Family 2020-06-02 격리해제\n서대문구 SMR 2020-06-01 격리해제\n서대문구 해외 유입 2020-05-30 격리해제\n서대문구 연아나 뉴스 클래스 2020-05-29 격리해제"
elif return_str == '서초구':
x = "서초구 해외 유입 2020-06-28 격리 중\n서초구 왕성교회 2020-06-26 격리 중\n서초구 의왕 물류 센터 2020-06-20 격리 중\n서초구 리치웨이 2020-06-19 격리 중\n서초구 리치웨이 2020-06-18 격리해제\n서초구 리치웨이 2020-06-16 격리해제\n서초구 확진자 접촉 2020-06-17 격리 중\n서초구 확인불가 2020-06-14 격리해제\n서초구 리치웨이 2020-06-13 격리 중\n서초구 리치웨이 2020-06-11 격리해제"
elif return_str == '성동구':
x = "성동구 금천구 쌀 제조공장 2020-06-20 격리 중\n성동구 금천구 쌀 제조공장 2020-06-20 격리 중\n성동구 확인불가 2020-06-09 격리해제\n성동구 확인불가 2020-06-07 격리해제\n성동구 이태원 클럽 2020-06-07 격리해제\n성동구 이태원 클럽 2020-06-06 격리 중\n성동구 확인불가 2020-06-06 격리해제\n성동구 이태원 클럽 2020-06-05 격리해제\n성동구 해외 유입 2020-06-02 격리해제\n성동구 확인불가 2020-05-29 격리해제"
elif return_str == '성북구':
x = "성북구 해외 유입 2020-06-21 격리 중\n성북구 확인불가 2020-06-18 격리 중\n성북구 리치웨이 2020-06-10 격리해제\n성북구 확인불가 2020-06-12 격리해제\n성북구 확인불가 2020-05-29 격리해제\n성북구 이태원 클럽 2020-05-18 격리해제\n성북구 이태원 클럽 2020-05-10 격리해제\n성북구 이태원 클럽 2020-05-09 격리해제\n성북구 이태원 클럽 2020-05-08 격리해제\n성북구 해외 유입 2020-04-27 격리해제"
elif return_str == '송파구':
x = "송파구 왕성교회 2020-06-28 격리 중\n송파구 강남 역삼동 모임 2020-06-27 격리 중\n송파구 확인불가 2020-06-21 격리 중\n송파구 해외 유입 2020-06-16 격리 중\n송파구 쿠팡 물류센터 2020-06-10 격리해제\n송파구 양천 탁구클럽 2020-06-05 격리해제\n송파구 확인불가 2020-06-01 격리해제\n송파구 성서 연구 모임 2020-05-29 격리해제\n송파구 성서 연구 모임 2020-05-28 격리해제\n송파구 쿠팡 물류센터 2020-05-27 격리 중"
elif return_str == '양천구':
x = "양천구 해외 유입 2020-06-27 격리 중\n양천구 양천 탁구클럽 2020-06-19 격리 중\n양천구 양천 탁구클럽 2020-06-19 격리 중\n양천구 확인불가 2020-06-18 격리 중\n양천구 대자연 2020-06-18 격리 중\n양천구 SMR 2020-06-12 격리 중\n양천구 확인불가 2020-06-12 격리해제\n양천구 리치웨이 2020-06-11 격리 중\n양천구 양천 탁구클럽 2020-06-10 격리해제\n양천구 리치웨이 2020-06-10 격리 중"
elif return_str == '영등포구':
x = "영등포구 왕성교회 2020-06-27 격리 중\n영등포구 확인불가 2020-06-27 격리 중\n영등포구 해외 유입 2020-06-23 격리 중\n영등포구 시청역 안전요원 2020-06-20 격리 중\n영등포구 시청역 안전요원 2020-06-20 격리 중\n영등포구 의왕 물류 센터 2020-06-20 격리 중\n영등포구 시청역 안전요원 2020-06-19 격리 중\n영등포구 확진자 접촉 2020-06-19 격리 중\n영등포구 리치웨이 2020-06-18 격리 중\n영등포구 리치웨이 2020-06-17 격리 중"
elif return_str == '용산구':
x = "용산구 확진자 접촉 2020-06-28 격리 중\n용산구 확인불가 2020-06-27 격리 중\n용산구 리치웨이 2020-06-15 격리 중\n용산구 리치웨이 2020-06-15 격리 중\n용산구 리치웨이 2020-06-14 격리 중\n용산구 리치웨이 2020-06-06 격리 중\n용산구 리치웨이 2020-06-12 격리해제\n용산구 리치웨이 2020-06-06 격리해제\n용산구 리치웨이 2020-06-05 격리 중\n용산구 리치웨이 2020-06-05 격리 중"
elif return_str == '은평구':
x = "은평구 확인불가 2020-06-29 격리 중\n은평구 해외 유입 2020-06-26 격리 중\n은평구 확진자 접촉 2020-06-19 격리 중\n은평구 리치웨이 2020-06-18 격리 중\n은평구 확인불가 2020-06-17 격리 중\n은평구 양천 탁구클럽 2020-06-17 격리 중\n은평구 확인불가 2020-06-16 격리해제\n은평구 확인불가 2020-06-16 격리해제\n은평구 양천 탁구클럽 2020-06-16 격리 중\n은평구 확인불가 2020-06-15 격리 중"
elif return_str == '종로구':
x = "종로구 해외 유입 2020-06-24 격리 중\n종로구 확인불가 2020-06-13 격리 중\n종로구 한국 캠퍼스 십자군 2020-06-12 격리해제\n종로구 한국 캠퍼스 십자군 2020-05-29 격리해제\n종로구 해외 유입 2020-05-17 격리해제\n종로구 이태원 클럽 2020-05-08 격리해제\n종로구 해외 유입 2020-04-02 격리해제\n종로구 해외 유입 2020-03-31 격리해제\n종로구 해외 유입 2020-03-31 격리해제\n종로구 확진자 접촉 2020-03-24 격리해제"
elif return_str == '중구':
x = "중구 해외 유입 2020-06-26 격리 중\n중구 리치웨이 2020-06-18 격리 중\n중구 양천 탁구클럽 2020-06-09 격리 중\n중구 KB 생명 2020-05-28 격리해제\n중구 이태원 클럽 2020-05-11 격리해제\n중구 이태원 클럽 2020-05-08 격리해제\n중구 확진자 접촉 2020-04-15 격리해제\n중구 확진자 접촉 2020-03-31 격리해제\n중구 확진자 접촉 2020-03-30 격리해제\n중구 해외 유입 2020-03-28 격리해제"
elif return_str == '중랑구':
x = "중랑구 강남 역삼동 모임 2020-06-26 격리 중\n중랑구 해외 유입 2020-06-25 격리 중\n중랑구 확인불가 2020-06-19 격리 중\n중랑구 리치웨이 2020-06-23 격리 중\n중랑구 어린이집 2020-06-18 격리 중\n중랑구 양천 탁구클럽 2020-06-16 격리 중\n중랑구 리치웨이 2020-06-13 격리해제\n중랑구 확인불가 2020-06-12 격리 중\n중랑구 확인불가 2020-06-12 격리 중\n중랑구 리치웨이 2020-06-12 격리해제"
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text":x
}
}
],
"quickReplies": [
{
"messageText": "확진자 정보",
"action": "message",
"label": "확진자 정보"
},
{
"messageText": "마스크 약국 현황",
"action": "message",
"label": "근처 약국 현황"
},
{
"messageText": "위탁병원 정보",
"action": "message",
"label": "위탁 병원 정보"
}
]
}
})
elif choice.location == '마스크 약국 현황':
#sadasd
addr = []
name =[]
open_url='http://apis.data.go.kr/B552657/ErmctInsttInfoInqireService/getParmacyListInfoInqire?serviceKey=<KEY>2<KEY>2%2Fg%3D%3D&Q0=서울특별&Q1='+return_str+'&ORD=NAME&pageNo=1&numOfRows=10'
res= requests.get(open_url)
yak= BeautifulSoup(res.content,'html.parser')
data=yak.find_all('item')
for item in data:
addr.append(item.find('dutytel1').get_text())
name.append(item.find('dutyname').get_text())
#추가
#추가
#sdaasdasd
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"carousel": {
"type": "basicCard",
"items": [
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[0]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[1]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[2]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[3]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[4]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[5]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[6]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[7]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[8]
}
]
},
{
"title": "약국",
"description": "근처약국을 알려드려요",
"buttons": [
{
"action": "webLink",
"label": "지도보기",
"webLinkUrl": "https://map.naver.com/v5/search/"+addr[9]
}
]
}
]
}
}
],
"quickReplies": [
{
"messageText": "확진자 정보",
"action": "message",
"label": "확진자 정보"
},
{
"messageText": "마스크 약국 현황",
"action": "message",
"label": "근처 약국 현황"
},
{
"messageText": "위탁병원 정보",
"action": "message",
"label": "위탁 병원 정보"
}
]
}
})
elif choice.location == '위탁병원 정보':
if return_str == '도봉구':
x = "도봉병원 02)3492-3250 서울특별시 도봉구 도봉로 720 (방학동)"
elif return_str == '동대문구':
x = "서울나은병원 1544-6003 서울특별시 동대문구 왕산로 137(제기동)\n현대중앙의원 02)2244-9600 서울특별시 동대문구 사가정로 110 (전농동)"
elif return_str == '강남구':
x = "강남베드로병원 02-1544-7522 남부순환로 2633(도곡동 914-2)"
elif return_str == '강동구':
x = "강동성모요양병원 02)488-0020 서울특별시 강동구 올림픽로80길31"
elif return_str == '강북구':
x = "신일병원 02)903-5121 서울특별시 강북구 덕릉로 73 (수유동)"
elif return_str == '강서구':
x = "강서연세병원 02)2658-5114 서울특별시 강서구 양천로 712 (염창동)\n강서힘찬병원 1899-2228 서울시 강서구 강서로56길 38(등촌동)"
elif return_str == '관악구':
x = "사랑의병원 02)880-0114 서울특별시 관악구 남부순환로 1860 (봉천동)"
elif return_str == '광진구':
x = "김종웅내과의원 02)455-4038 서울시 광진구 용마산로 44"
elif return_str == '구로구':
x = "권내과의원 02)2685-6612 서울시 구로구 경안로40길 34(개봉동)"
elif return_str == '금천구':
x = "연세조내과 02)803-2134 서울특별시 금천구 시흥대로58길 5 (시흥동)\n서울으뜸정형외과의원 02)807-0111 서울시 금천구 독산로 210, 2층"
elif return_str == '노원구':
x = "밝은미래안과 02)939-3075 서울특별시 노원구 동일로 1548, 세일빌딩 4층 (상계동)\n삼성드림이비인후과 02)935-1365 서울특별시 노원구 노해로 482, 덕영빌딩 4층 (상계동)\n새서울병원 02)930-5858 서울특별시 노원구 동일로 1678 (상계동)\n어비뇨기과 02)930-013 서울특별시 노원구 동일로 1401 (상계동)"
elif return_str == '동작구':
x = "의료법인성석의료재단 동작경희병원 02)822-8112 서울특별시 동작구 상도로 146"
elif return_str == '마포구':
x = "박상수내과의원 02)332-5460 서울특별시 마포구 독막로 22 (합정동)\n예담정형외과의원 02-335-2500 서울 마포구 독막로 22(합정동 청명빌딩 3층)\n서울본내과의원 02)3143-2220 서울특별시 마포구 양화로133"
elif return_str == '서대문구':
x = "한양그린내과의원 02)379-3377 서울특별시 서대문구 통일로 413, 화인빌딩 2층 (홍제동)"
elif return_str == '서초구':
x = "김일중내과 02)3473-1356 서울특별시 서초구 효령로 396 (서초동)"
elif return_str == '성동구':
x = "9988병원 02)2297-9988 서울특별시 성동구 왕십리로269"
elif return_str == '성북구':
x = "서울척병원 1599-0033 서울특별시 성북구 동소문로 47길 8\n의료법인 유라의료재단 온누리요양병원 02)919-2700 서울특별시 성북구 화랑로 271 (장위동)"
elif return_str == '송파구':
x = "서울수내과의원 02)414-9919 서울특별시 송파구 송파대로 389, 2층 (석촌동)"
elif return_str == '양천구':
x = "메디힐병원 02)2604-7551 서울특별시 양천구 남부순환로 331 (신월동)"
elif return_str == '영등포구':
x = "jc빛소망 안과 02)785-1068 서울특별시 영등포구 국제금융로 6길 33, 6층(여의도동)\n아이비이비인후과 02)784-7533 서울 영등포구 여의도동 43-4\n윤문수비뇨기과 02)2069-0221 서울특별시 영등포구 영중로 46, 4층 (영등포동5가)\n의료법인 영등포병원 02)2632-0013 서울 영등포구 당산로 31길 10\n김종률내과의원 02)831-1585 서울 영등포구 신길로 28"
elif return_str == '용산구':
x = "김내과의원 02)703-2226 서울특별시 용산구 백범로 281 (효창동)"
elif return_str == '은평구':
x = "본서부병원 02)3156-5020 서울특별시 은평구 은평로133"
elif return_str == '종로구':
x = "서울적십자병원 02)2002-8000 서울특별시 종로구 새문안로 9 (평동)"
elif return_str == '중구':
x = "삼성푸른의원 02)2231-4154 서울특별시 중구 다산로42길 80 (신당동)"
elif return_str == '중랑구':
x = "팔팔(88)병원 1899-8875 서울특별시 중랑구 동일로 679\n건강한 성심의원 02-437-6152 서울특별시 중랑구 용마산로 503"
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": x
}
}
],
"quickReplies": [
{
"messageText": "확진자 정보",
"action": "message",
"label": "확진자 정보"
},
{
"messageText": "마스크 약국 현황",
"action": "message",
"label": "근처 약국 현황"
},
{
"messageText": "위탁병원 정보",
"action": "message",
"label": "위탁 병원 정보"
}
]
}
})
elif return_str == '확진자 정보' or return_str == '지역선택' or return_str=='마스크 약국 현황' or return_str =='위탁병원 정보' :
if return_str == '확진자 정보':
x = '확진자 정보'
elif return_str == '마스크 약국 현황':
x = '마스크 약국 현황'
elif return_str == '위탁병원 정보':
x = '위탁병원 정보'
elif return_str == '지역선택':
x = '지역선택'
id = return_json_str["userRequest"]["user"]["id"]
obj, create = User.objects.get_or_create(userId = id)
obj.location = x
obj.save()
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": "지역을 선택해주세요"
}
}
],
"quickReplies": [
{
"messageText": "강남구",
"action": "message",
"label": "강남구"
},
{
"messageText": "강동구",
"action": "message",
"label": "강동구"
},
{
"messageText": "강북구",
"action": "message",
"label": "강북구"
},
{
"messageText": "강서구",
"action": "message",
"label": "강서구"
},
{
"messageText": "관악구",
"action": "message",
"label": "관악구"
},
{
"messageText": "광진구",
"action": "message",
"label": "광진구"
},
{
"messageText": "구로구",
"action": "message",
"label": "구로구"
},
{
"messageText": "금천구",
"action": "message",
"label": "금천구"
},
{
"messageText": "노원구",
"action": "message",
"label": "노원구"
},
{
"messageText": "그 외",
"action": "message",
"label": "그 외"
}
]
}
})
elif return_str == '그 외' :
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": "지역을 선택해주세요"
}
}
],
"quickReplies": [
{
"messageText": "도봉구",
"action": "message",
"label": "도봉구"
},
{
"messageText": "동대문구",
"action": "message",
"label": "동대문구"
},
{
"messageText": "동작구",
"action": "message",
"label": "동작구"
},
{
"messageText": "마포구",
"action": "message",
"label": "마포구"
},
{
"messageText": "서대문구",
"action": "message",
"label": "서대문구"
},
{
"messageText": "서초구",
"action": "message",
"label": "서초구"
},
{
"messageText": "성동구",
"action": "message",
"label": "성동구"
},
{
"messageText": "성북구",
"action": "message",
"label": "성북구"
},
{
"messageText": "송파구",
"action": "message",
"label": "송파구"
},
{
"messageText": "다른 지역",
"action": "message",
"label": "다른 지역"
}
]
}
})
elif return_str == '다른 지역' :
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": "지역을 선택해주세요"
}
}
],
"quickReplies": [
{
"messageText": "양천구",
"action": "message",
"label": "양천구"
},
{
"messageText": "영등포구",
"action": "message",
"label": "영등포구"
},
{
"messageText": "용산구",
"action": "message",
"label": "용산구"
},
{
"messageText": "은평구",
"action": "message",
"label": "은평구"
},
{
"messageText": "종로구",
"action": "message",
"label": "종로구"
},
{
"messageText": "중구",
"action": "message",
"label": "중구"
},
{
"messageText": "중랑구",
"action": "message",
"label": "중랑구"
},
{
"messageText": "지역선택",
"action": "message",
"label": "지역선택"
}
]
}
})
else:
return JsonResponse({
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": "무엇을 알고싶으신가요?"
}
}
],
"quickReplies": [
{
"messageText": "확진자 정보",
"action": "message",
"label": "확진자 정보"
},
{
"messageText": "마스크 약국 현황",
"action": "message",
"label": "근처 약국 현황"
},
{
"messageText": "위탁병원 정보",
"action": "message",
"label": "위탁 병원 정보"
}
]
}
})
| f1af803a852733139c8e6cdc0876fbacc8dd93e6 | [
"Markdown",
"Python"
] | 3 | Markdown | emma58min/CoronaChatbot | f5a600af6d8670a45b4c345654fb93f5d1d5d65c | b4c6253bd2a6f91c4276eb5cd3631293b46c251b | |
refs/heads/master | <file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#forum-thread-functions
require_once('app/forum-thread-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
//session variables
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<section class="main-container">
<?php
#show all the forums
forum_overview($con, $session_tz);
?>
</section>
</body>
</html>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(2);
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])){
#password to generate a new password and email link to activate it
list($indicator, $data) = forgot_password($con, $_POST['username'], $_POST['email']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle()?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body class="body-center">
<div class="login-container">
<?php
if(isset($indicator) && $indicator === TRUE){
foreach($data as $msg)
echo '
<section class="message-container">
<div class="message-area green">'.$msg.'</div>
</section>
';
die();
}
if(isset($indicator) && $indicator === FALSE){
foreach($data as $msg){
echo '
<section class="message-container red-border">
<div class="message-area red">'.$msg.'</div>
</section>
';
}
}
?>
<h2>Reset your password</h2>
<form action="forgot_password.php" method="POST">
<label for="username">Enter your username:</label>
<input type="text" name="username" value="<?php if (isset($_POST['username'])) echo e($_POST['username']);?>" maxlength="" class="login-input">
<label for="email">Enter your account email:</label>
<input type="email" name="email" value="<?php if (isset($_POST['email'])) echo e($_POST['email']);?>" maxlength="" class="login-input">
<div class="submit-con">
<input type="submit" value="Reset Password" class="login-submit" name="change_password">
</div><a href="login.php">Login</a>
</form>
<div class="login-links"></div>
</div>
</body>
</html>
<file_sep><?php
session_start();
/**
* verify and activate account
*/
#includes
#sql connection
require_once('_dependancies/sql.php');
#functions
#navigation
require_once('app/navigation-functions.php');
#login functions
require_once('app/register-functions.php');
#security
require_once('app/security-functions.php');
if(isset($_GET['verify1']) && isset($_GET['verify2'])){
$url_email = $_GET['verify1'];
$url_key = $_GET['verify2'];
activate_account($con, $url_email, $url_key) === TRUE ? header('Location: profile.php') : header('Location: login.php');
}else{
#else redirect user
header('Location: login.php');
}
?>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#functions
#navigation
require_once('app/navigation-functions.php');
#login functions
require_once('app/register-functions.php');
#security
require_once('app/security-functions.php');
//start session
#check the users login
check_login(2);
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register'])){
//verify registration data
list($flag, $errors) = verify_registration_data($con, $_POST['username'], $_POST['email'], $_POST['password'], $_POST['password2']);
if($flag === TRUE ){
activation_email($con, $_SESSION['username'], $_SESSION['email'], $_SESSION['key']) ? header('Location: register_activate.php') : header('Location: register_activate.php') ;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pagetitle()?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body class="body-center">
<div class="login-container">
<h2>Register:</h2>
<form action="register.php" method="POST">
<?php
#any erros during registration
if(!empty($errors)){
foreach($errors as $msg){
echo "- $msg<br>";
}
}
?>
<label for="username">Choose your username:</label>
<input type="text" name="username" value="<?php if(isset($_POST['username'])) echo e($_POST['username'])?>" maxlength="" class="login-input">
<label for="email">Email:</label>
<input type="email" name="email" value="<?php if(isset($_POST['email'])) echo e($_POST['email'])?>" maxlength="" class="login-input">
<label for="password">Password:</label>
<input type="<PASSWORD>" name="password" value="<?php if(isset($_POST['password'])) echo e($_POST['password'])?>" maxlength="" class="login-input">
<label for="password2">Verify Password:</label>
<input type="password" name="password2" value="<?php if(isset($_POST['password2'])) echo e($_POST['password2'])?>" maxlength="" class="login-input">
<div class="submit-con">
<input type="submit" value="Register" class="login-submit" name="register">
</div><a href="">Login</a>
</form>
<div class="login-links"></div>
</div>
</body>
</html>
<file_sep><?php
/**
* function to verify all the registration data
* also calls the registration function
*/
function verify_registration_data($con, $username = '', $email='', $pass1 = '', $pass2 = ''){
trim($username);
trim($email);
trim($pass1);
trim($pass2);
#initialize errors array
$errors = array();
#initialize key array
$key = array();
#username validation
if(empty($username)){
$errors[] = 'Please choose a username';
}
if(strlen($username > 20)){
$errors[] = 'Max username size is 20 characters';
}
#email validation
if(!empty($email)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email;
}else{
$errors[] = 'Please ente your valid email address';
}
}else{
$errors[] = 'Please enter your email address';
}
if(strlen($email > 100)){
$errors[] = 'Max email size is 100 characters';
}
#passwords validation
if(empty($pass1)){
$errors[] = 'Please enter your chosen password';
}
if(empty($pass2)){
$errors[] = 'Please confirm your password';
}
if(($pass1 === $pass2) === FALSE){
$errors[] = 'Passwords do not match';
}else{
$pass1;
}
#if errors is empty check if the username of email is taken
if(empty($errors)){
#see if username is already taken(in users table and limbo table)
$sql = "SELECT (SELECT COUNT(id_users) FROM users WHERE username=?) + (SELECT COUNT(id_limbo) FROM limbo WHERE username=?) AS total";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $username, $username);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $sum);
while(mysqli_stmt_fetch($stmt)){
$sum;
}
mysqli_stmt_free_result($stmt);
if($sum > 0){
$errors[] = 'Username Taken';
return array(FALSE, $errors);
}
#see if email is already taken
$sql = "SELECT (SELECT COUNT(id_users) FROM users WHERE email=?) + (SELECT COUNT(id_limbo) FROM limbo WHERE email=?) AS total";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $email, $email);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $sum);
while(mysqli_stmt_fetch($stmt)){
$sum;
}
mysqli_stmt_free_result($stmt);
if($sum > 0){
$errors[] = 'Email Taken';
return array(FALSE, $errors);
}
#register the user
list($flag, $errors, $key) = register($con, $username, $email, $pass1);
#set super global variables for later use
if(empty($errors) && isset($key) && !empty($key)){
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['key'] = $key[0];
$_SESSION['resent'] = 0;
return array(TRUE, $errors);
}else{
return array(FALSE, $errors);
}
}else{
return array(FALSE, $errors);
}
}
/**
* function to register the user
* this function is called in the verify_registration_data function
* inserts the user registration data in the limbo table in the database
* returns error if there was a problem and a activation key if everything went according to plan
*/
function register($con, $username, $email, $password){
#initilizee errors array
$errors = array();
#initialize key array
$key = array();
#sha1 version of email
$sha1_email = sha1($email);
#generate a unique random activation key
$activation_key = sha1(uniqid(rand()));
$sql = "INSERT INTO limbo(username, email, email_sha1, password, activation_code, date) VALUES(?,?,SHA1(?),?, UTC_TIMESTAMP())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'sssss', $username, $email, $sha1_email, $password, $activation_key);
mysqli_execute($stmt);
if(mysqli_stmt_affected_rows($stmt) === 1){
mysqli_stmt_free_result($stmt);
$key[] = $activation_key;
return array(TRUE, $errors, $key);
}else{
$errors[] = 'There was a problem Please try again';
return array(FALSE, $errors);
}
}
/**
* function sends the email for account activation
* verify1 = email
* verify2 = activation keycode
*/
function activation_email($con, $username, $email, $key){
#intialize errors array
$errors = array();
$link = 'activate.php?verify1='. sha1(urlencode($email)) .'&verify2='. urlencode($key) .' ';
$to = $email;
$subject = "Activate your account";
$body = '
<a href="' . $link . '>Activate your acount</a>"
';
$headers = 'no-reply';
if(@mail($to, $subject, $body, $headers)){
return TRUE;
}else{
return FALSE;
}
}
/**
* function to activate users account
* validates the data from the url and moves users account from limbo table to users table
* also logs the user in after activation of account
*/
function activate_account($con, $url_email = '', $url_key = ''){
#if strigns are empty redirect user
if(empty($url_email) && empty($url_key)){
isset($_SESSION['user_id']) ? header('Location: forum_overview.php') : header('Location: login.php');
}
/**
* section will use a mysql transaction to move users information from limbos table to the users table
*/
#start transaction
mysqli_autocommit($con, FALSE);
//default image
$image = addslashes(file_get_contents($image = '_dependancies/profiles/default.png'));
$sql = "SELECT username, email, password FROM limbo WHERE email_sha1=? AND activation_code=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $url_email, $url_key);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$username = $row['username'];
$email = $row['email'];
$password = $row['<PASSWORD>'];
$rand = sha1(uniqid(rand()));
$sql = "INSERT INTO users(id_users_sha1, username, password, email, profile, activation_date) VALUES(?,?,?,?,?, UTC_TIMESTAMP())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'sssss', $rand, $username, $password, $email, $image);
mysqli_execute($stmt);
$sql = "DELETE FROM limbo WHERE email_sha1=? AND activation_code=? LIMIT 1";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $url_email, $url_key);
mysqli_execute($stmt);
#commit transaction
if(mysqli_commit($con)){
#if commited logged the user in
$sql =
"SELECT users.id_users, users.id_users_sha1 AS id_sha1, time_zones.name_time_zones AS tz
FROM users
JOIN time_zones ON time_zones.id_time_zones = users.time_zone
WHERE username=? AND email=? AND password=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'sss', $username, $email, $password);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user_id = mysqli_fetch_array($result, MYSQLI_ASSOC);
#set the user id
$_SESSION['user_id'] = $user_id['id_users'];
$_SESSION['secure'] = $user_id['id_sha1'];
$_SESSION['timezone'] = $user_id['tz'];
#return the function as true if the user is logged in
return TRUE;
}else{
return FALSE;
}
}
<file_sep><?php
session_start();
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-3600);
header('Location: login.php');
?>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(2);
if(isset($_GET['reset1']) && isset($_GET['reset2'])){
#call the reset password function to reset it in do transaction on database to update
reset_password($con, $_GET['reset1'], $_GET['reset2']);
}else{
header('Location: login.php');
}
?>
<file_sep><?php
#initialize flag
$flag = '';
/**
* Function handles the login of the user
* returns error messages if criteria is not met
* sets the user session with the user id
* $con = the connection of the database
* $email is the user email
* $password is the user password
*/
function login($con, $email = '', $password = ''){
trim($email);
trim($password);
#initialize errors array
$errors = array();
#email validation
if(!empty($email)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email;
}else{
$errors[] = 'Please enter your valid email address';
}
}else{
$errors[] = 'Please enter your email address';
}
#password validation
if(!empty($password)){
$password;
}else{
$errors[] = 'Please enter your password';
}
#if errors is empty check the password and email
if(empty($errors)){
$sql =
"SELECT users.id_users, users.id_users_sha1 AS secure, time_zones.name_time_zones AS tz
FROM users
JOIN time_zones ON time_zones.id_time_zones = users.time_zone
WHERE email=? AND password=<PASSWORD>(?)";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $email, $password);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $user_id, $secure, $tz);
mysqli_stmt_store_result($stmt);
$num = mysqli_stmt_num_rows($stmt);
if(mysqli_stmt_num_rows($stmt) === 1){
#check first the the user hasent request that there password must be changed
while(mysqli_stmt_fetch($stmt)){
$sql_check = "SELECT id_user FROM forgot_password WHERE id_user=?";
$stmt_check = mysqli_prepare($con, $sql_check);
mysqli_stmt_bind_param($stmt_check, 'i', $user_id);
mysqli_execute($stmt_check);
mysqli_stmt_store_result($stmt_check);
if(mysqli_stmt_num_rows($stmt_check) === 1){
$errors[] = 'Please check your email you have requested that your password be changed';
return array(FALSE, $errors);
}
#set the user session upon successful login
$_SESSION['user_id'] = $user_id;
$_SESSION['secure'] = $secure;
$_SESSION['timezone'] = $tz;
break;
}
require_once ('additional-functionality-functions.php');
user_logs($con, $_SESSION['user_id']);
return array(TRUE, $errors);
}else{
$errors[] = 'Wrong email password combination';
return array(FALSE, $errors);
}
}else{
return array(FALSE, $errors);
}
}
<file_sep><?php
#start session
session_start();
#includes
#sql connection
require_once('sql.php');
#navigation
require_once('../_public/app/navigation-functions.php');
#security
require_once('../_public/app/security-functions.php');
#check the users login
check_login(1);
$id = $_GET['id'];
$sql = "SELECT profile from users WHERE id_users_sha1=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $id);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$image = stripslashes($row['profile']);
/*
can use this section if you want to do a more advance proxy
you'll need save the content type in the database and run a query to run the
required content-type
header("Content-type: image/png");
header("Content-type: image/jpg");
*/
echo $image;
?>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#functions
#navigation
require_once('app/navigation-functions.php');
#login functions
require_once('app/register-functions.php');
#security
require_once('app/security-functions.php');
#start session
#check the users login
check_login(2);
if($_SERVER['REQUEST_METHOD'] === 'POST' AND isset($_POST['resend'])){
activation_email($con, $_SESSION['username'], $_SESSION['email'], $_SESSION['key']);
#spam delayer
$_SESSION['resent'] = $_SESSION['resent'] + 1;
($_SESSION['resent'] > 0 && $_SESSION['resent'] <= 4) ? sleep($_SESSION['resent'] * 5) : NULL ;
#if user has requested to many resends, destroy there session and redirect to login
if($_SESSION['resent'] >= 5){
$_SESSION = array();
session_destroy();
header('Location: login.php');
}
}else{
#else redirect user to login
header('Location: login.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle() ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body class="body-center">
<div class="login-container">
<h3 class="activate-h3">Activate your account with the link in your email</h3>
<?php
if($_SESSION['resent'] > 0){
echo '<p class="sent">We have resent you the email, check your spam box</p>';
}
?>
<div class="register-activate-container">
<form action="register_activate.php" method="POST">
<p class="activate-p">Did not get it?</p>
<input type="submit" value="Resend email" class="resend" name="resend">
</form>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#functions
#navigation
require_once('app/navigation-functions.php');
#login functions
require_once('app/login-functions.php');
#security
require_once('app/security-functions.php');
#check the users login
check_login(2);
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])){
#use the login function if the form was activated
list($flag, $errors) = login($con, $_POST['email'], $_POST['password']);
#redirect login function logs user in
$flag === TRUE ? header('Location: forum_overview.php') : NULL;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle()?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body class="body-center">
<div class="login-container">
<?php
#output errors if any
if($flag === FALSE){
foreach($errors as $msg){
echo "- $msg<br>";
}
}
?>
<h2>Login:</h2>
<form action="login.php" method="POST">
<label for="email">Email:</label>
<input type="email" name="email" value=" <?php if(isset($_POST['email'])) echo e($_POST['email'])?>" maxlength="" class="login-input">
<label for="password">Password:</label>
<input type="password" name="password" value="<?php if(isset($_POST['password'])) echo e($_POST['password'])?>" maxlength="" class="login-input">
<div class="submit-con">
<input type="submit" value="Login" class="login-submit" name="login">
</div>
</form>
<div class="login-links"><a href="forgot_password.php">Forgot-password</a><a href="register.php">Register</a></div>
</div>
</body>
</html>
<file_sep><?php
/**
* function to validate file types and insert them into the database
*/
function verify_file(){
#initialize errors array
$errors = array();
#array of allowed file types (MIME TYPES)
$allowed_filetypes =
array('image/png',
'image/x-png',
'image/jpg',
'image/jpeg',
'image/pjeg'
);
#allowed extensions
$allowed_extensions =
array('png',
'x-png',
'jpg',
'jpeg',
'pjeg'
);
$max_size = 5242880; #5MB
#file superglobals
#get pics original name
$pic_orig_name = strtolower($_FILES['profile']['name']);
#get the images name on the server
$pic_name = strtolower($_FILES['profile']['tmp_name']);
#get the images size
$pic_size = $_FILES['profile']['size'];
#get the images extension
$pic_type = strtolower($_FILES['profile']['type']);
#check the images size
if($pic_size > $max_size){
$errors[] = 'Max file upload is 5MB';
return array(FALSE, $errors);
}
#check if file type is an image
if(!getimagesize($pic_name)){
$errors[] = 'Only image files allowed(png and jpg)';
return array(FALSE, $errors);
}
#check magic bytes
#handler( finfo extension )
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
#check the actual magic bytes
if(!in_array(finfo_file($fileinfo, $pic_name), $allowed_filetypes)){
$errors[] = 'Only png and jpg files allowed';
return array(FALSE, $errors);
}
#check mime type ( mime_content_type )
if(!in_array(mime_content_type($pic_name), $allowed_filetypes)){
$errors[] = 'Only png and jpg files allowed';
return array(FALSE, $errors);
}
#check mime with ( $_FILES )
if(!in_array($pic_type, $allowed_filetypes)){
$errors[] = 'Only png and jpg files allowed';
return array(FALSE, $errors);
}
#check file extensions(that the files extenstions are what is allowed)
if(!in_array(pathinfo($pic_orig_name, PATHINFO_EXTENSION), $allowed_extensions)){
$errors[] = 'Only png and jpg files allowed';
return array(FALSE, $errors);
}
if(empty($errors)){
return array(TRUE, $errors);
}
}
/**
* function to sanitize output
*/
function e($value){
return htmlspecialchars($value, ENT_QUOTES, 'utf-8');
}
/**
* check if require session variables are set
*/
function check_login($flag){
$pagename = basename(e($_SERVER['PHP_SELF']));
#flag 1
if($flag === 1){
#pagenames that need user_id, secure, timezone session variables
$pages = array(
'Change Password',
'Create Thread',
'Forums',
'Threads',
'Viewing Thread',
'Your Profile',
'Threads you created',
'Your Posts',
'Viewing image'
);
#if page is in array and certain variables are not set redirect the user to the login
if(in_array(pagename($pagename), $pages) && (!isset($_SESSION['user_id']) || !isset($_SESSION['secure']) || !isset($_SESSION['timezone']))){
#delete any redudant session data beforeredirecting user
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-3600);
header('Location: login.php');
}
}
#flag2
if($flag === 2){
#pagenames that need user_id, secure, timezone session variables
$pages = array(
'Forgot Password',
'Login',
'Activate your account',
'Register',
'Reset password'
);
#if page is in array and certain variables are not set redirect the user to the login
if(in_array(pagename($pagename), $pages) && (isset($_SESSION['user_id']) || isset($_SESSION['secure']) || isset($_SESSION['timezone']))){
#redirect the user to forum_overview
header('Location: forum_overview.php');
}
}
}
/**
* function to validate url data
*/
function validate_url($flag, $con, $id1 = '', $id2 = ''){
#pages that require id 1
if($flag === 1){
#id 1 empty redirect user
if(empty($id1)){
header('Location: forum_overview.php');
}
#make sure that id1 is correct data tpye and correct length
if(!ctype_alnum($id1) || strlen($id1) != 40){
header('Location: forum_overview.php');
}
#validate id1
$sql = "SELECT COUNT(id_forum_sha1) FROM forum_overview WHERE id_forum_sha1=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $id1);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
if($row[0] != 1){
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
header('Location: forum_overview.php');
}
}
#pages the require id1 and id2
if($flag === 2){
#validate
if(empty($id1) || empty($id2)){
header('Location: forum_overview.php');
}
if(!ctype_alnum($id1) || !ctype_alnum($id2) || strlen($id1) != 40 || strlen($id2) != 40){
header('Location: forum_overview.php');
}
#check database
$sql =
"SELECT forum_overview.id_forum_sha1, threads.id_thread_sha1
FROM forum_overview
JOIN threads ON forum_overview.id_forum = threads.id_forum
WHERE forum_overview.id_forum_sha1=? AND threads.id_thread_sha1=?
";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $id1, $id2);
mysqli_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) === 0){
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
header('Location: forum_overview.php');
}
}
}
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#forum-thread
require_once('app/forum-thread-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
#validate url
validate_url(1, $con, $_GET['id1']);
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
#get forum hash from url
$forum_id = $_GET['id1'];
#check if the form to create the thread has been submitted
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_thread'])){
$forum_to_create = $_POST['list_of_threads'];
$subject = $_POST['subject'];
$body = $_POST['body'];
list($indicator, $data) = create_thread($con, $forum_to_create, $subject, $body, $session_id, $forum_id);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<?php
if(isset($indicator) && $indicator === FALSE){
foreach($data as $msg){
echo '
<section class="message-container red-border">
<div class="message-area red">'.$msg.'</div>
</section>
';
}
}
?>
<section class="main-container">
<div class="create-thread-container">
<div class="form-container">
<h1>Create your Thread</h1>
<form action="<?php echo create_thread_urlaction($_SERVER['PHP_SELF'], $forum_id); ?>" method="POST">
<div class="thread-head">
<label for="thread-dropdown" class="thread-label-select">Create thread in forum:</label>
<?php
#get forum id from url to remember in drop down seletion(sticky form)
get_forum_id($con, $forum_id);
?>
</div>
<div class="create-thread-subject">
<label for="subject" class="thread-label">Thread: subject</label>
<input name="subject" class="thread-subject" value="<?php if(isset($_POST['subject'])) echo e($_POST['subject']);?>">
</div>
<div class="create-thread-body">
<label for="body" class="thread-label">Thread: body(message)</label>
<textarea name="body"><?php if (isset($_POST['body'])) echo e($_POST['body']);?></textarea>
</div>
<input type="submit" value="Create Thread" class="thread-submit" name="create_thread">
</form>
</div>
</div>
</section>
</body>
</html>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#forum-thread
require_once('app/forum-thread-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
#validate url
validate_url(2, $con, $_GET['id1'], $_GET['id2']);
//session variables
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
#flag for which pagniation page
$p_flag = 2;
//log thread view
thread_view_log($con, $_GET['id1'], $_GET['id2'], $session_id);
if(isset($_GET['id1']) && strlen($_GET['id1']) === 40 && isset($_GET['id2']) && strlen($_GET['id2']) === 40){
#set url values to variables
$forum_id = $_GET['id1'];
$thread_id = $_GET['id2'];
$y = 10;
//see if pages has been set
if(isset($_GET['pages']) && is_numeric($_GET['pages'])){
$total_pages = $_GET['pages'];
}else{
$sql =
"SELECT COUNT(posts.id_thread)
FROM posts
JOIN threads ON threads.id_thread = posts.id_thread
WHERE threads.id_thread_sha1=?";
$cstmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($cstmt, 's', $thread_id);
mysqli_execute($cstmt);
$result = mysqli_stmt_get_result($cstmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$total_records = $row[0];
if($total_records > $y){
$total_pages = ceil($total_records / $y);
}else{
$total_pages = 1;
}
mysqli_stmt_free_result($cstmt);
}
// databse start point
if(isset($_GET['x']) && is_numeric($_GET['x'])){
$x = $_GET['x'];
}else{
$x = 0;
}
}
#section for posting a reply
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['post-in-thread'])){
list($indicator, $data) = reply($con, $session_id, $_POST['message'], $forum_id, $thread_id);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<?php
if($indicator === TRUE){
foreach($data as $msg)
echo '
<section class="message-container">
<div class="message-area green">'.$msg.'</div>
</section>
';
}
if($indicator === FALSE){
foreach($data as $msg){
echo '
<section class="message-container red-border">
<div class="message-area red">'.$msg.'</div>
</section>
';
}
}
?>
<section class="main-container orange-border">
<?php
thread_post($con, $session_tz, $thread_id, $x, $y);
?>
</section>
<div class="pagination-container">
<div class="pagination">
<div class="pagination-links">
<div class="tree">
<?php navigation_modal($con, $forum_id);?>
</div>
<div class="links-contain">
<?php
pagination($p_flag, $total_pages, $forum_id, $thread_id , $x, $y);
?>
</div>
</div>
</div>
</div>
<section class="main-container">
<?php
thread_replies($con, $session_tz, $thread_id, $x, $y);
?>
</section>
<section class="main-container blue-border">
<div class="post-reply-container">
<h2>Post a Reply<a name="reply"></a></h2>
<div class="post-group">
<div class="post-left">
<div class="post-img"><?php echo "<img class=\"post-img1\" src=../_dependancies/image_proxy.php?id=$session_secure>"; ?></div>
</div>
<div class="post-right">
<form action="<?php echo action_url($_SERVER['PHP_SELF'], $_GET['id1'], $_GET['id2']); ?>" method="POST">
<textarea placeholder="Post a reply" name="message"><?php if(isset($_POST['message'])) echo e($_POST['message'])?></textarea>
<input name="post-in-thread" type="submit" value="Post a Reply" class="post-in-thread">
</form>
</div>
</div>
</div>
</section>
<div class="pagination-container">
<div class="pagination">
<div class="pagination-links">
<div class="tree">
<?php navigation_modal($con, $forum_id);?>
</div>
<div class="links-contain">
<?php
pagination($p_flag, $total_pages, $forum_id, $thread_id , $x, $y);
?>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep># Retro forum
### Installation instructions:
##### For viewing purposes:
_dependacies/_db contains the database files, you can use **dummy-data.sql** if you want to view the site with data, after importing the database you will have to set up a username and password manually within the database client-in the **users** table, to bypass email activation
<file_sep><?php
/**
* function to get users profile information
*/
function get_profile($con, $user_id, $session_timezone){
#get the current users profile information
$sql = "SELECT id_users_sha1, username, email, time_zone, signature, CONVERT_TZ(activation_date, 'UTC', ?) FROM users WHERE id_users=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'si', $session_timezone, $user_id );
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_sha1, $username, $email, $user_timezone, $signature, $activation_date);
mysqli_stmt_store_result($stmt);
#get the timezon information
$sql_tz = "SELECT id_time_zones, name_time_zones FROM time_zones";
$stmt_tz = mysqli_prepare($con, $sql_tz);
mysqli_execute($stmt_tz);
mysqli_stmt_bind_result($stmt_tz, $id_tz, $name_tz);
mysqli_stmt_store_result($stmt_tz);
while(mysqli_stmt_fetch($stmt)){
echo '
<img class="profile-img" img src="_dependancies/image_proxy.php?id='. e($id_sha1) .'">
</div>
<div class="profile-details-contain">
<div class="profile-header">
<h1>Viewing Your Profile</h1><a href="change_password.php">Change password</a>
</div>
<h3>Account activate on: '.e($activation_date).'</h3>
<h3>Username:</h3>
<input type="text" placeholder="'.e($username).'" class="text-grey-input" readonly >
<h3>Email:</h3>
<input type="text" placeholder="'.e($email).'" class="text-grey-input" readonly >
<h3>Signature:</h3>
<textarea name="signature">'.e($signature).'</textarea>
';
$user_timezone;
}
echo '
<h3>Your Timezone</h3>
<select name="timezone" class="timezone">
';
while(mysqli_stmt_fetch($stmt_tz)){
echo'
<option value="'.e($id_tz).'"';
if($id_tz === $user_timezone){
echo ' SELECTED>';
}else{
echo '>';
}
echo ''.e($name_tz).'</option>';
}
echo '
</select>
';
mysqli_stmt_free_result($stmt);
mysqli_stmt_free_result($stmt_tz);
}
/**
* function to update users profile
* also uses the verify file function to validate profile picture information
*/
function update_profile($con, $profile_pic = '', $timezone, $signature, $session_id, $session_secure, $session_tz){
if(strlen($signature) > 250){
$errors[] = 'Max signature length is 250 characters';
return array(FALSE, $errors);
}
#initilize success array
$success = array();
if(!empty($profile_pic)){
list($data, $errors) = verify_file();
if($data === TRUE){
$image = addslashes(file_get_contents($profile_pic));
$sql_image = "UPDATE users SET time_zone=?, profile=?, signature=? WHERE id_users=?";
$stmt_image = mysqli_prepare($con, $sql_image);
mysqli_stmt_bind_param($stmt_image, 'issi', $timezone, $image, $signature, $session_id);
mysqli_execute($stmt_image);
if(mysqli_stmt_affected_rows($stmt_image) === 1){
#remove the uplaoded image from the server after it has been succesfully inserted into the database
unlink($profile_pic);
$success[] = 'Your profile has been updated';
#update session info
$sql_up_tz =
"SELECT users.id_users, users.id_users_sha1 AS secure, time_zones.name_time_zones AS tz
FROM users
JOIN time_zones ON time_zones.id_time_zones = users.time_zone
WHERE users.id_users=?";
$stmt_up_tz = mysqli_prepare($con, $sql_up_tz);
mysqli_stmt_bind_param($stmt_up_tz, 'i', $session_id);
mysqli_execute($stmt_up_tz);
mysqli_stmt_bind_result($stmt_up_tz, $user_id, $secure, $tz);
mysqli_stmt_store_result($stmt_up_tz);
//echo $num = mysqli_stmt_num_rows($stmt);
if(mysqli_stmt_num_rows($stmt_up_tz) === 1){
#set the user session upon successful login
while(mysqli_stmt_fetch($stmt_up_tz)){
$_SESSION['timezone'] = $tz;
break;
}
mysqli_stmt_free_result($stmt_up_tz);
#echo to user profile has been updated
return array(TRUE, $success);
}
}
mysqli_stmt_free_result($stmt_image);
}else{
return array(FALSE, $errors);
}
}#end of not empty profile picture if
if(empty($profile_pic)){
#update information in database
$sql_no_image = "UPDATE users SET time_zone=?, signature=? WHERE id_users=? LIMIT 1";
$stmt_no_image = mysqli_prepare($con, $sql_no_image);
mysqli_stmt_bind_param($stmt_no_image, 'isi', $timezone, $signature, $session_id);
mysqli_execute($stmt_no_image);
if(mysqli_stmt_affected_rows($stmt_no_image) === 1){
$success[] = 'Your profile has been updated';
#update session info
$sql_up_tz =
"SELECT users.id_users, users.id_users_sha1 AS secure, time_zones.name_time_zones AS tz
FROM users
JOIN time_zones ON time_zones.id_time_zones = users.time_zone
WHERE users.id_users=?";
$stmt_up_tz = mysqli_prepare($con, $sql_up_tz);
mysqli_stmt_bind_param($stmt_up_tz, 'i', $session_id);
mysqli_execute($stmt_up_tz);
mysqli_stmt_bind_result($stmt_up_tz, $user_id, $secure, $tz);
mysqli_stmt_store_result($stmt_up_tz);
//echo $num = mysqli_stmt_num_rows($stmt);
if(mysqli_stmt_num_rows($stmt_up_tz) === 1){
#set the user session upon successful login
while(mysqli_stmt_fetch($stmt_up_tz)){
$_SESSION['timezone'] = $tz;
break;
}
mysqli_stmt_free_result($stmt_up_tz);
return array(TRUE, $success);
}
}
mysqli_stmt_free_result($stmt_no_image);
}#end of empty profile picture if
}#end of function
/**
* function to ge your posts or you threads pages data
*/
function your_posts_threads($flag, $con, $x, $y, $session_id, $session_tz){
#your_posts
if($flag === 1){
#view only where thread is distinct
$sql =
"SELECT posts.id_posts, MIN(posts.date_posted) as firstReplied, posts.message_post, threads.title_thread, threads.id_user, threads.id_thread_sha1, users.username, forum_overview.id_forum_sha1
FROM posts
JOIN threads ON threads.id_thread = posts.id_thread
JOIN forum_overview ON forum_overview.id_forum = threads.id_forum
JOIN users ON users.id_users = threads.id_user WHERE posts.id_user = ?
GROUP BY threads.id_thread
LIMIT ?,?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'iii', $session_id, $x, $y);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_post, $firstreplied, $message, $title_thread, $threads_id_user, $id_thread_sha1, $username, $id_forum_sha1);
mysqli_stmt_store_result($stmt);
while(mysqli_stmt_fetch($stmt)){
#modify data for better display pusposes
$title_thread = strlen($title_thread) > 50 ? substr($title_thread, 0, 50).'...' : $title_thread;
$message = strlen($message) > 250 ? substr($message, 0, 250).'...' : $message;
#check if thread was created by the user
$username = $threads_id_user === $session_id ? 'You created this thread' : $username;
echo '
<div class="your-threads-container">
<div class="go-to-thread">
<div class="modal-forum">
<div class="modal-text1">Thread:</div>
<div class="modal-text2">'.e($title_thread).'</div>
</div><a class="go-to-thread-btn" href="view_thread.php?id1='.e($id_forum_sha1).'&id2='.e($id_thread_sha1).'">Go to this thread</a>
</div>
<div class="your-threads-main">
<div class="your-threads-left">
<div class="combo-your-threads">
<div class="combo-your-threads-heading">Thread Created by:</div>
<div class="combo-your-threads-data">'.e($username).'</div>
</div>
<div class="combo-your-threads">
<div class="combo-your-threads-heading">Date posted a reply: </div>
<div class="combo-your-threads-data">'.e($firstreplied).'</div>
</div>
</div>
<div class="your-threads-right">
<div class="h2-right">Your post:</div>
<p>'.e($message).'</p>
</div>
</div>
</div>
';
}
mysqli_stmt_free_result($stmt);
}
#your_threads
if($flag === 2){
#the query data
$sql =
"SELECT threads.id_thread, threads.id_thread_sha1, threads.title_thread, threads.body_thread, DATE_FORMAT(threads.created_on, '%d-%b-%y %h:%i %p') AS created, count(posts.id_thread) AS totalposts, IFNULL(DATE_FORMAT(CONVERT_TZ(max(posts.date_posted), 'UTC', ?), '%d-%b-%y %h:%i %p'), 'No replies') AS lastposted, forum_overview.name_forum, forum_overview.id_forum_sha1, users.username
FROM threads
LEFT JOIN posts ON threads.id_thread = posts.id_thread
JOIN forum_overview ON forum_overview.id_forum = threads.id_forum
JOIN users ON users.id_users = threads.id_user
WHERE threads.id_user=?
GROUP BY threads.id_thread
ORDER BY totalposts DESC, created DESC
LIMIT ?,? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'siii', $session_tz, $session_id, $x, $y);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_thread, $id_thread_sha1, $thread_title, $thread_body, $created, $totalposts, $lastposted, $name_forum, $id_forum_sha1, $username);
mysqli_stmt_store_result($stmt);
while(mysqli_stmt_fetch($stmt)){
#modify data for better display pusposes
$thread_title = strlen($thread_title) > 75 ? substr($thread_title, 0, 75).'...' : $thread_title;
$thread_body = strlen($thread_body) > 250 ? substr($thread_body, 0, 250).'...' : $thread_body ;
echo '
<div class="your-threads-container">
<div class="go-to-thread">
<div class="modal-forum">
<div class="modal-text1">Created in forum:</div>
<div class="modal-text2">'.e($name_forum).'</div>
</div><a class="go-to-thread-btn" href="view_thread.php?id1='.e($id_forum_sha1).'&id2='.e($id_thread_sha1).'">Go to this thread</a>
</div>
<div class="your-threads-main">
<div class="your-threads-left">
<div class="combo-your-threads">
<div class="combo-your-threads-heading">You created this thread on:</div>
<div class="combo-your-threads-data">'.e($created).'</div>
</div>
<div class="combo-your-threads">
<div class="combo-your-threads-heading">Last reply to thread: </div>
<div class="combo-your-threads-data">'.e($lastposted).'</div>
</div>
<div class="combo-your-threads">
<div class="combo-your-threads-heading">Number of posts in thread:</div>
<div class="combo-your-threads-data">'.e($totalposts).'</div>
</div>
</div>
<div class="your-threads-right">
<div class="h2-right">'.e($thread_title).'</div>
<p>'.e($thread_body).'</p>
</div>
</div>
</div>
';
}
mysqli_stmt_free_result($stmt);
}
}
/**
* function to change users password
*/
function change_password($con, $password = '', $new_<PASSWORD>1 = '', $new_<PASSWORD>2, $session_id){
#errors array
$errors = array();
#succss array
$succes = array();
#validate input
if(empty($password)){
$errors[] = 'Please enter your password';
}
if(empty($new_password1)){
$errors[] = 'Please enter your new password';
}
if(empty($new_password2)){
$errors[] = 'Please confirm your new password';
}
if(!empty($errors)){
return array(FALSE, $errors);
}
$password = <PASSWORD>($password);
$new_password1 = <PASSWORD>($<PASSWORD>);
$new_password2 = <PASSWORD>($<PASSWORD>);
if($new_password1 != $new_password2){
$errors[] = 'New passwords do not match';
return array(FALSE, $errors);
}
if(empty($errors)){
#check pass1 in database
$sql = "SELECT id_users FROM users WHERE password=? AND id_users=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'si', $password, $session_id);
mysqli_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) != 1){
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
$errors[] = 'Your password is incorrect';
return array(FALSE, $errors);
}
if(mysqli_stmt_num_rows($stmt) === 1){
$sql = "UPDATE users SET password=? WHERE id_users=? Limit 1";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'si', $new_password1, $session_id);
mysqli_execute($stmt);
if(mysqli_stmt_affected_rows($stmt) === 1){
$success[] = 'Your password has been updated';
return array(TRUE, $success);
}else{
$errors[] = 'An error occured please try again';
return array(FALSE, $errors);
}
}
}else{
return array(FALSE, $errors);
}
}
/**
* function for forgot_password
*/
function forgot_password($con, $username, $email){
#initialize arrays
$errors = array();
$success = array();
if(empty($username)){
$errors[] = 'Please enter your username';
}
if(empty($email)){
$errors[] = 'Please enter you email';
}
if(!empty($errors)){
return array(FALSE, $errors);
}
#check if user name and email is real user
$sql = "SELECT id_users, id_users_sha1, username, email FROM users WHERE username=? AND email=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_user, $id_secure, $username_db, $email_db);
mysqli_stmt_store_result($stmt);
$num = mysqli_stmt_num_rows($stmt);
if($num === 0){
$errors[] = 'No such user';
return array(FALSE, $errors);
}else{
while(mysqli_stmt_fetch($stmt)){
$id_user;
$id_secure;
$username_db;
$email_db;
break;
}
}
#destroy $num to free memory reset the memory associated with $stmt
unset($num);
mysqli_stmt_free_result($stmt);
#check if there is already a request pending
$sql = "SELECT request_date FROM forgot_password WHERE id_user=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'i', $id_user);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $request_date);
mysqli_stmt_store_result($stmt);
$num = mysqli_stmt_num_rows($stmt);
if($num === 1){
while(mysqli_stmt_fetch($stmt)){
$errors[] = 'A request was made on: '.$request_date.' please check your email';
return array(FALSE, $errors);
}
}
unset($num);
mysqli_stmt_free_result($stmt);
#generate a new password, add details to forgot_password table
$new_password = <PASSWORD>(<PASSWORD>(<PASSWORD>()));
$sql = "INSERT INTO forgot_password(id_user, id_secure, new_password, request_date) VALUES(?,?,?, UTC_TIMESTAMP())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'iss', $id_user, $id_secure, $new_password);
mysqli_stmt_execute($stmt);
if(mysqli_stmt_affected_rows($stmt) === 1){
if(newPasword_email($con, $id_secure, $email_db, $new_password) === TRUE){
$success[] = 'Check your email your password was changed';
return array(TRUE, $success);
}else{
$success[] = 'Check your email your password was changed';
return array(TRUE, $success);
}
}else{
$errors[] = 'An error occured please try again';
return array(FALSE. $errors);
}
}
/**
* function to send link to change password
*/
function newPasword_email($con, $id_secure, $email_db, $new_password){
$link = 'reset_password.php?reset1='. urlencode($id_secure) .'&reset2='. urlencode($new_password) .' ';
$to = $email_db;
$subject = "Reset your password";
$body = '
<a href="' . $link . '>Reset your password</a>"
';
$headers = 'no-reply';
if(@mail($to, $subject, $body, $headers)){
return TRUE;
}else{
return FALSE;
}
}
/**
* function activate the changed password
*/
function reset_password($con, $id_secure, $new_password_hashed){
if(!ctype_alnum($id_secure) || !ctype_alnum($new_password_hashed) || strlen($id_secure) != 40 || strlen($new_password_hashed) != 40){
header("Location: login.php");
}else{
#start transaction
mysqli_autocommit($con, FALSE);
$sql = "SELECT id_user, new_password FROM forgot_password WHERE id_secure=? AND new_password=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $id_secure, $new_password_hashed);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$id_user = $row['id_user'];
$new_password = $row['<PASSWORD>'];
$sql = "UPDATE users SET password=? WHERE id_users=? LIMIT 1";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'si', $new_password, $id_user);
mysqli_execute($stmt);
$sql= "DELETE FROM forgot_password WHERE id_user=? AND new_password=? LIMIT 1";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'is', $id_user, $new_password_hashed);
mysqli_execute($stmt);
if(mysqli_commit($con)){
#if commited logged the user in
if(!isset($_SESSION['user_id']) || !isset($_SESSION['secure']) || !isset($_SESSION['timezone'])) {
$sql =
"SELECT users.id_users, users.id_users_sha1 AS id_sha1, time_zones.name_time_zones AS tz
FROM users
JOIN time_zones ON time_zones.id_time_zones = users.time_zone
WHERE id_users=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'i', $id_user);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user_id = mysqli_fetch_array($result, MYSQLI_ASSOC);
#set the user id
$_SESSION['user_id'] = $user_id['id_users'];
$_SESSION['secure'] = $user_id['id_sha1'];
$_SESSION['timezone'] = $user_id['tz'];
#redirect the mto change password page so that they must change there password
header('Location: change_password.php');
}
}else{
header('Location: login.php');
}
}
}
/**
* collect user data
*/
function user_logs($con, $session_id){
$agent = $_SERVER['HTTP_USER_AGENT'];
#get ip
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip = addslahes($_SERVER['HTTP_CLIENT_IP']);
$method = 'client_ip';
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$method = 'x_forward';
}
elseif(!empty($_SERVER['REMOTE_ADDR'])){
$ip = $_SERVER['REMOTE_ADDR'];
$method = 'remote';
}else{
$ip = 0;
$method = 0;
}
#host name
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
#session cookie id
$phpsess = session_id();
#pagename
$pagename = htmlspecialchars(basename($_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8');
$sql = "INSERT INTO user_logs(user_id, ip, ip_method, hostaddr, phpsess, agent, page_name, datetime) VALUES(?,?,?,?,?,?,?, UTC_TIMESTAMP())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'issssss', $session_id, $ip, $method, $hostname, $phpsess, $agent, $pagename);
mysqli_execute($stmt);
mysqli_stmt_free_result($stmt);
}
<file_sep><?php
/**
* function for the forum overview page
* get all necaseery information from database and builds the page
*/
function forum_overview($con, $timezone){
$sql =
"SELECT forum_overview.id_forum_sha1, forum_overview.name_forum, forum_overview.details_forum, COUNT(threads.id_forum), IFNULL(DATE_FORMAT(CONVERT_TZ(MAX(threads.created_on), 'UTC', ?), '%d %b '), '0')
FROM forum_overview
LEFT JOIN threads ON forum_overview.id_forum = threads.id_forum
GROUP BY forum_overview.id_forum";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $timezone);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_forum, $name_forum, $details_forum, $number_threads, $last_thread);
mysqli_stmt_store_result($stmt);
$sql_posts =
"SELECT forum_overview.id_forum, COUNT(posts.id_forum) as sum
FROM forum_overview
LEFT JOIN posts ON forum_overview.id_forum = posts.id_forum
GROUP BY forum_overview.id_forum";
$stmt_posts = mysqli_prepare($con, $sql_posts);
mysqli_execute($stmt_posts);
$result = mysqli_stmt_get_result($stmt_posts);
$i = 1;
while (mysqli_stmt_fetch($stmt)){
echo '
<div class="thread">
<div class="counter">
<div class="counter-inner">
<div class="counter-inner-inner">
'.$i.'</1>
</div>
</div>
</div>
<div class="thread-combo"><a href="threads.php?id1='.$id_forum.'">
<h3>' .$name_forum. '</h3></a>
<div class="description">
'. $details_forum .'
</div>
</div>
<div class="thread-stats">
<ul>
<div class="stats-heading">Forum Stats
<li>
<div class="details">Threads:</div>
<div class="value">'.$number_threads.'</div>
</li>
<li>
';
while($number = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo '
<div class="details">Posts:</div>
<div class="value">'.$number['sum'].'</div>
';
break;
}
echo'
</li>
<li>
<div class="details">Latest:</div>
<div class="value">'.$last_thread.'</div>
</li>
</div>
</ul>
</div>
</div>
';
$i++;
}
mysqli_stmt_free_result($stmt);
mysqli_stmt_free_result($stmt_posts);
}
#pagination
function pagination($p_flag, $total_pages, $forum_id, $thread_id='', $x,$y){
#create this page variable to add appropriate styles
$this_page = ($x / $y) + 1;
if($p_flag === 1){
#pagination links
if ($total_pages > 1){
if($this_page !=1){
echo '<a href="threads.php?id1='.$forum_id.'&x='.($x - $y).'&pages='.$total_pages.'">Previous</a>';
}
for($i =1; $i <=$total_pages; $i++){
if($i != $this_page){
echo '<a href="threads.php?id1='.$forum_id.'&x='.(($y *($i-1))).'&pages='.$total_pages.'">'.$i.'</a>';
}else{
echo '<a class="active">'.$i .'</a>';
}
}
if($this_page != $total_pages){
echo '<a href="threads.php?id1='.$forum_id.'&x='.($x + $y).'&pages='.$total_pages.'">Next</a>';
}
}
}
if($p_flag === 2){
#pagination links
if ($total_pages > 1){
if($this_page !=1){
echo '<a href="view_thread.php?id1='.$forum_id.'&id2='.$thread_id.'&x='.($x - $y).'&pages='.$total_pages.'">Previous</a>';
}
for($i =1; $i <=$total_pages; $i++){
if($i != $this_page){
echo '<a href="view_thread.php?id1='.$forum_id.'&id2='.$thread_id.'&x='.(($y *($i-1))).'&pages='.$total_pages.'">'.$i.'</a>';
}else{
echo '<a class="active">'.$i .'</a>';
}
}
if($this_page != $total_pages){
echo '<a href="view_thread.php?id1='.$forum_id.'&id2='.$thread_id.'&x='.($x + $y).'&pages='.$total_pages.'">Next</a>';
}
}
}
}
/**
* modal function to transverse back and fourth through forums and and threads
*/
function navigation_modal($con, $forum_id){
$pageName = htmlspecialchars(basename($_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8');
if(pagename($pageName) === 'Viewing Thread'){
$modal_sql = "SELECT name_forum FROM forum_overview WHERE id_forum_sha1=?";
$modal_stmt = mysqli_prepare($con, $modal_sql);
mysqli_stmt_bind_param($modal_stmt, 's', $forum_id);
mysqli_execute($modal_stmt);
$result = mysqli_stmt_get_result($modal_stmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
echo '<h3>Viewing a thread in: <a href="threads.php?id1='.$forum_id.'">'.$row[0].'</a> forum</h3>';
mysqli_stmt_free_result($modal_stmt);
mysqli_stmt_close($modal_stmt);
}
if(pagename($pageName) === 'Threads'){
$modal_sql = "SELECT name_forum FROM forum_overview WHERE id_forum_sha1=?";
$modal_stmt = mysqli_prepare($con, $modal_sql);
mysqli_stmt_bind_param($modal_stmt, 's', $forum_id);
mysqli_execute($modal_stmt);
$result = mysqli_stmt_get_result($modal_stmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
echo '<h3>Viewing all threads in: <a href="forum_overview.php">'.$row[0].'</a></h3>';
mysqli_stmt_free_result($modal_stmt);
mysqli_stmt_close($modal_stmt);
}
}
#build submit butron url
function action_url($url, $id1, $id2){
$page = strip_tags(htmlspecialchars(basename($url), ENT_QUOTES, 'utf-8'));
#check if its the right page
if(pageName($page) != 'Viewing Thread'){
return $action = '#';
}
#id values must consist of only alphanumeric characters
return $action = (ctype_alnum($id1) AND ctype_alnum($id2)) ? ''.$page.'?id1='.urlencode($id1).'&id2='.urlencode($id2).'' : '#' ;
}
/**
* function for posting a message to a thread
*/
$indicator = '';
function reply($con, $user_id, $message, $id1, $id2){
#initialize errros array
$errors = array();
#initialize success array
$success = array();
if(empty($message)){
$errors[] = 'Please enter your message';
}
if(empty($errors)){
$get_sql=
"SELECT forum_overview.id_forum, threads.id_thread
FROM forum_overview
JOIN threads ON forum_overview.id_forum = threads.id_forum
WHERE forum_overview.id_forum_sha1=? AND threads.id_thread_sha1=?";
$get_stmt = mysqli_prepare($con ,$get_sql);
mysqli_stmt_bind_param($get_stmt, 'ss', $id1, $id2);
mysqli_execute($get_stmt);
mysqli_stmt_bind_result($get_stmt, $id_forum, $id_thread);
mysqli_stmt_store_result($get_stmt);
while(mysqli_stmt_fetch($get_stmt)){
$id_forum;
$id_thread;
break;
}
$num = mysqli_stmt_num_rows($get_stmt);
#if forum id and thread id are valid
if($num === 1){
$in_sql = "INSERT INTO posts(id_thread, id_forum, message_post, id_user, date_posted) VALUES (?,?,?,?, UTC_TIMESTAMP())";
$in_stmt = mysqli_prepare($con, $in_sql);
mysqli_stmt_bind_param($in_stmt, 'ssss', $id_thread, $id_forum, $message, $user_id);
mysqli_execute($in_stmt);
if(mysqli_stmt_affected_rows($in_stmt) === 1){
$success[] = "Your message was posted!";
return array(TRUE, $success);
}else{
$errors[] = "There was an error trying to post your message";
return array(FALSE, $errors);
}
}
}else{
return array(FALSE, $errors);
}
}
/**
* function to remember chose thread for create thread
*/
function get_forum_id($con, $forum_id){
#get the current forum to post in from url
$sql =
"SELECT id_forum FROM forum_overview WHERE id_forum_sha1=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $forum_id);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $current_forum);
mysqli_stmt_store_result($stmt);
while(mysqli_stmt_fetch($stmt)){
$current_forum;
break;
}
mysqli_stmt_free_result($stmt);
#get list of all current forums
$sql_forums = "SELECT id_forum, name_forum FROM forum_overview";
$stmt_forums = mysqli_prepare($con, $sql_forums);
mysqli_execute($stmt_forums);
mysqli_stmt_bind_result($stmt_forums, $id_forum, $name_forum);
mysqli_stmt_store_result($stmt_forums);
#start drop down selection
echo '<select name="list_of_threads">';
while(mysqli_stmt_fetch($stmt_forums)){
echo '<option value="'.$id_forum.'"';
if($current_forum === $id_forum){
echo ' SELECTED >';
}else{
echo '>';
}
echo ''.$name_forum.'</option>';
}
echo '</select>';
mysqli_stmt_free_result($stmt_forums);
}
/**
* function to create a thread
*/
function create_thread($con, $forum_to_create, $subject = '', $body = '', $session_id, $forum_id){
#initialize errors array
$errors = array();
#validation checking
if(strlen($subject) > 100){
$errors[] = 'Forum subject can not be longer that 100 charaters';
}
if(empty($subject)){
$errors[] = 'You forgot the subject of your post';
}
if(empty($body)){
$errors[] = 'You forgot the body of your post';
}
if(empty($errors)){
#create random sha1 key
$id_thread_sha1 = sha1(uniqid(rand()));
#lookup forum sha1
$sql_lookup =
"SELECT id_forum_sha1 FROM forum_overview WHERE id_forum=?";
$stmt_lookup = mysqli_prepare($con, $sql_lookup);
mysqli_stmt_bind_param($stmt_lookup, 'i', $forum_to_create);
mysqli_stmt_execute($stmt_lookup);
mysqli_stmt_bind_result($stmt_lookup, $id_out);
mysqli_stmt_store_result($stmt_lookup);
while(mysqli_stmt_fetch($stmt_lookup)){
$id_out;
break;
}
#create the thread
$sql_create =
"INSERT INTO threads(id_thread_sha1, id_forum, title_thread, body_thread, id_user, created_on) VALUES(?,?,?,?,?,UTC_TIMESTAMP()) ";
$stmt_create = mysqli_prepare($con, $sql_create);
mysqli_stmt_bind_param($stmt_create, 'sissi', $id_thread_sha1, $forum_to_create, $subject, $body, $session_id);
mysqli_execute($stmt_create);
if(mysqli_stmt_affected_rows($stmt_create) === 1){
#if there where no problems and thread was created redirect user to their created thread
header('Location: view_thread.php?id1='.$id_out.'&id2='.$id_thread_sha1.'');
mysqli_stmt_free_result($stmt_lookup);
mysqli_stmt_free_result($stmt_create);
return array(TRUE, $errors);
}else{
$errors[] = 'An error occured please try again';
return array(FALSE, $errors);
}
}else{
return array(FALSE, $errors);
}
}
#build submit butron url
function create_thread_urlaction($url, $id1){
$page = strip_tags(htmlspecialchars(basename($url), ENT_QUOTES, 'utf-8'));
#check if its the right page
if(pageName($page) != 'Create Thread'){
return $action = '#';
}
#id values must consist of only alphanumeric characters
return $action = (ctype_alnum($id1)) ? ''.$page.'?id1='.urlencode($id1).'' : '#' ;
}
/**
* get ops thread
*/
function thread_post($con, $session_tz, $thread_id, $x='', $y=''){
#thread post by OP
$sql_poster =
"SELECT users.username, users.id_users_sha1, DATE_FORMAT(CONVERT_TZ(users.activation_date, 'UTC', ?), '%d %b %y'), users.signature, threads.title_thread, threads.body_thread, DATE_FORMAT(CONVERT_TZ(threads.created_on, 'UTC', ?), '%d-%b-%Y %h:%i %p'), user_groups.name_user_group
FROM users
JOIN threads ON users.id_users = threads.id_user
JOIN user_groups ON user_groups.id_user_group = users.user_group
WHERE threads.id_thread_sha1=?";
$stmt_poster = mysqli_prepare($con, $sql_poster);
mysqli_stmt_bind_param($stmt_poster, 'sss', $session_tz, $session_tz, $thread_id);
mysqli_execute($stmt_poster);
mysqli_stmt_bind_result($stmt_poster,$p_username, $p_id_sha1, $p_account_date, $p_signature, $p_title, $p_body, $p_created_on, $p_user_group);
mysqli_stmt_store_result($stmt_poster);
while(mysqli_stmt_fetch($stmt_poster)){
echo '
<div class="op-main-container">
<div class="time-container">
<div class="post-number orange-text">#0 - OP</div>
<div class="post-time orange-text">'.e($p_created_on).'</div>
</div>
<div class="post">
<div class="left">
<div class="img"><img class="img1" src="_dependancies/image_proxy.php?id='.e($p_id_sha1).'"></div>
<ul>
<li class="orange-text">Username: '.e($p_username).'</li>
<li class="orange-text">Join Date: '.e($p_account_date).'</li>
<li class="orange-text">Rank: '.e($p_user_group).'</li>
<li>
<div class="send-message"><a class="orange-text">Message
<svg id="Layer_1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewbox="0 0 50 50" enable-background="new 0 0 50 50" xml:space="preserve">
<path d="M41.798,33.763v-18c0-0.513-0.39-0.919-0.887-0.977c-0.009-0.002-0.017-0.004-0.025-0.005 c-0.03-0.003-0.057-0.018-0.088-0.018h-30c-0.032,0-0.06,0.015-0.091,0.018c-0.065,0.006-0.126,0.019-0.189,0.038 c-0.065,0.019-0.125,0.041-0.183,0.072c-0.053,0.028-0.1,0.062-0.147,0.099c-0.056,0.044-0.105,0.09-0.151,0.145 c-0.019,0.023-0.045,0.035-0.062,0.06c-0.019,0.027-0.022,0.06-0.038,0.088c-0.034,0.06-0.059,0.12-0.08,0.187 c-0.02,0.065-0.033,0.129-0.039,0.196c-0.003,0.033-0.019,0.062-0.019,0.096v18c0,0.553,0.447,1,1,1h30 C41.351,34.763,41.798,34.315,41.798,33.763z M37.502,16.763l-11.745,8.092l-11.745-8.092H37.502z M11.798,32.763V17.666 l13.392,9.227c0.171,0.118,0.369,0.177,0.567,0.177s0.396-0.059,0.567-0.177l13.474-9.283v15.153H11.798z"></path>
</svg></a></div>
</li>
</ul>
</div>
<div class="right">
<div class="post-heading">
<h2 class="post-h2">'.$p_title.'</h2>
</div>
<div class="post-body">
<p>'.$p_body.'</p>
</div>
<div class="signature">
<div class="signature-heading">Signature:</div>
<div class="signature-body">'.e($p_signature).'</div>
</div>
</div>
</div>
</div>
';
}
mysqli_stmt_free_result($stmt_poster);
}
/**
* function to get the threads replies
*/
function thread_replies($con, $session_tz, $thread_id, $x='', $y=''){
#thread replies
$sql_reply =
"SELECT users.username, users.id_users_sha1, users.signature, DATE_FORMAT(CONVERT_TZ(users.activation_date, 'UTC', ?), '%d %b %y'),threads.id_thread, posts.id_posts, posts.message_post, DATE_FORMAT(CONVERT_TZ(posts.date_posted, 'UTC', ?), '%d-%b-%Y %h:%i %p'), user_groups.name_user_group
FROM users
JOIN posts ON users.id_users = posts.id_user
JOIN threads ON threads.id_thread = posts.id_thread
JOIN user_groups ON users.user_group = user_groups.id_user_group
WHERE threads.id_thread_sha1=? LIMIT ?,?
";
$stmt_reply = mysqli_prepare($con, $sql_reply);
mysqli_stmt_bind_param($stmt_reply, 'sssss', $session_tz, $session_tz, $thread_id, $x, $y );
mysqli_execute($stmt_reply);
mysqli_stmt_bind_result($stmt_reply, $username, $id_sha1, $signature, $account_date, $id_thread, $id_posts, $message, $date_posted, $user_group);
mysqli_stmt_store_result($stmt_reply);
while(mysqli_stmt_fetch($stmt_reply)){
echo '
<div class="reply-main-container">
<div class="reply-time-container">
<div class="reply-post-number orange-text">#'.e($id_posts).'</div>
<div class="reply-post-time">'.e($date_posted).'</div>
</div>
<div class="reply-post">
<div class="reply-left">
<div class="reply-img"><img class="reply-img1" src="_dependancies/image_proxy.php?id='.e($id_sha1).'"></div>
<ul>
<li>Username: '.e($username).'</li>
<li>Join date: '.e($account_date).'</li>
<li>Rank: '.e($user_group).' </li>
<li>
<div class="send-message"><a>Message
<svg id="Layer_1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewbox="0 0 50 50" enable-background="new 0 0 50 50" xml:space="preserve">
<path d="M41.798,33.763v-18c0-0.513-0.39-0.919-0.887-0.977c-0.009-0.002-0.017-0.004-0.025-0.005 c-0.03-0.003-0.057-0.018-0.088-0.018h-30c-0.032,0-0.06,0.015-0.091,0.018c-0.065,0.006-0.126,0.019-0.189,0.038 c-0.065,0.019-0.125,0.041-0.183,0.072c-0.053,0.028-0.1,0.062-0.147,0.099c-0.056,0.044-0.105,0.09-0.151,0.145 c-0.019,0.023-0.045,0.035-0.062,0.06c-0.019,0.027-0.022,0.06-0.038,0.088c-0.034,0.06-0.059,0.12-0.08,0.187 c-0.02,0.065-0.033,0.129-0.039,0.196c-0.003,0.033-0.019,0.062-0.019,0.096v18c0,0.553,0.447,1,1,1h30 C41.351,34.763,41.798,34.315,41.798,33.763z M37.502,16.763l-11.745,8.092l-11.745-8.092H37.502z M11.798,32.763V17.666 l13.392,9.227c0.171,0.118,0.369,0.177,0.567,0.177s0.396-0.059,0.567-0.177l13.474-9.283v15.153H11.798z"></path>
</svg></a></div>
</li>
</ul>
</div>
<div class="reply-right">
<div class="reply-post-body">
<p>'.e($message).'</p>
</div>
<div class="signature2">
<div class="signature-heading2">Signature:</div>
<div class="signature-body2">'.e($signature).'</div>
</div>
</div>
</div>
</div>
';
}
mysqli_stmt_free_result($stmt_reply);
}
/**
* function to show all the threads
*/
function show_threads($con, $session_tz, $forum_id, $x, $y){
#get threads
$sql =
"SELECT threads.id_thread, threads.id_thread_sha1, threads.title_thread, threads.body_thread, threads.created_on AS created, count(posts.id_thread) AS totalposts, ifnull(DATE_FORMAT(CONVERT_TZ(max(posts.date_posted), 'UTC', ?), '%d-%b %h:%i %p'), 'No reply yet') AS lastposted, forum_overview.id_forum_sha1, users.username
FROM threads
LEFT JOIN posts ON threads.id_thread = posts.id_thread
JOIN forum_overview ON forum_overview.id_forum = threads.id_forum
JOIN users ON users.id_users = threads.id_user
WHERE forum_overview.id_forum_sha1=?
GROUP BY threads.id_thread
ORDER BY totalposts DESC, created DESC LIMIT ?,?
";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ssss', $session_tz, $forum_id, $x, $y );
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_thread, $id_thread_sha1, $title_thread, $body_thread, $created, $totalposts, $last_posted, $id_forum, $username);
mysqli_stmt_store_result($stmt);
while(mysqli_stmt_fetch($stmt)){
$body_thread = strlen($body_thread) > 40 ? substr($body_thread, 0, 300) .'...' : $body_thread;
$totalposts = $totalposts === 0 ? 'No reply yet' : $totalposts;
echo '
<div class="thread">
<div class="thread-combo"><a href="view_thread.php?id1='.urlencode($id_forum).'&id2='.urlencode($id_thread_sha1).'">
<h3>'.e($title_thread).'</h3></a>
<div class="description">'.e($body_thread).'</div>
</div>
<div class="thread-stats-additional">
<ul>
<div class="stats-heading">Thread Stats
<li>
<div class="details">Created by:</div>
<div class="value">'.e($username).'</div>
</li>
<li>
<div class="details">Replies:</div>
<div class="value">'.e($totalposts).'</div>
</li>
<li>
<div class="details">last-reply:</div>
<div class="value">'.e($last_posted).'</div>
</li>
</div>
</ul>
</div>
</div>
';
}
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
/**
* function inserts thread view in database
*/
function thread_view_log($con, $id1, $id2, $session_id){
$sql = "SELECT idt, idf FROM view_all_thread_info WHERE idtsecure=? AND idfsecure=?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $id2, $id1);
mysqli_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$id_thread = $row[0];
$id_forum = $row[1];
mysqli_stmt_free_result($stmt);
$sql = "INSERT INTO thread_views(id_forum, id_thread, id_user, timestamp) VALUES(?,?,?, UTC_TIMESTAMP())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'iii', $id_forum, $id_thread, $session_id);
mysqli_execute($stmt);
mysqli_stmt_free_result($stmt);
}
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#forum-thread
require_once('app/forum-thread-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
//session variables
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
#pagination requirements NB change the query to what is needed
$y = 10;
//see if pages has been set
if(isset($_GET['pages']) && is_numeric($_GET['pages'])){
$total_pages = $_GET['pages'];
}else{
$csql =
"SELECT COUNT(id_user) FROM posts WHERE id_user = ?";
$cstmt = mysqli_prepare($con, $csql);
mysqli_stmt_bind_param($cstmt, 'i', $session_id);
mysqli_execute($cstmt);
$result = mysqli_stmt_get_result($cstmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$total_records = $row[0];
if($total_records > $y){
$total_pages = ceil($total_records / $y);
}else{
$total_pages = 1;
}
mysqli_stmt_free_result($cstmt);
}
// databse start point
if(isset($_GET['x']) && is_numeric($_GET['x'])){
$x = $_GET['x'];
}else{
$x = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<section class="main-container">
<?php
#show all the users specific posts
your_posts_threads(1, $con, $x, $y, $session_id, $session_tz);
?>
</section>
</body>
</html>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#security functions
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])){
list($indicator, $data) = change_password($con, $_POST['password'], $_POST['new_password'], $_POST['<PASSWORD>'], $session_id);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<?php
if(isset($indicator) && $indicator === TRUE){
foreach($data as $msg)
echo '
<section class="message-container">
<div class="message-area green">'.$msg.'</div>
</section>
';
die();
}
if(isset($indicator) && $indicator === FALSE){
foreach($data as $msg){
echo '
<section class="message-container red-border">
<div class="message-area red">'.$msg.'</div>
</section>
';
}
}
?>
<div class="section main-container no-border">
<div class="profile-container cpw-align">
<form action="change_password.php" method="POST">
<div class="profile-details-contain">
<div class="profile-header">
<h1>Change your password</h1>
</div>
<h3>Current Password:</h3>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" class="text-input" value="<?php if(isset($_POST['password'])) echo e($_POST['password']);?>">
<h3>New Password:</h3>
<input type="<PASSWORD>" name="new_password" placeholder="<PASSWORD>" class="text-input" value="<?php if(isset($_POST['new_password'])) echo e($_POST['new_password']);?>">
<h3>Confirm new Password:</h3>
<input type="<PASSWORD>" name="new_password2" placeholder="<PASSWORD>" class="text-input" value="<?php if(isset($_POST['new_password2'])) echo e($_POST['new_password2']);?>">
<input type="submit" value="Change Password" class="profile-update" name="change_password">
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
if($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['update']){
#get server name of picture
$profile_pic = $_FILES['profile']['tmp_name'];
$timezone = $_POST['timezone'];
$signature = $_POST['signature'];
list($indicator, $data) = update_profile($con, $profile_pic, $timezone, $signature, $session_id, $session_secure, $session_tz);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<?php
if(isset($indicator) && $indicator === TRUE){
foreach($data as $msg)
echo '
<section class="message-container">
<div class="message-area green">'.$msg.'</div>
</section>
';
}
if(isset($indicator) && $indicator === FALSE){
foreach($data as $msg){
echo '
<section class="message-container red-border">
<div class="message-area red">'.$msg.'</div>
</section>
';
}
}
?>
<div class="section main-container no-border">
<div class="profile-container">
<form action="profile.php" method="POST" enctype="multipart/form-data">
<div class="profile-image-contain">
<?php
get_profile($con, $session_id, $session_tz);
?>
<h3>Change profile picture</h3>
<input type="file" class="file" name="profile" id="profile">
<input type="submit" value="Update Profile" class="profile-update" name="update">
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
#includes
#sql connection
require_once('_dependancies/sql.php');
#navigation
require_once('app/navigation-functions.php');
#forum-thread
require_once('app/forum-thread-functions.php');
#security
require_once('app/security-functions.php');
#additional functionality
require_once('app/additional-functionality-functions.php');
#check the users login
check_login(1);
#validate url
validate_url(1, $con, $_GET['id1']);
//session variables
$session_id = $_SESSION['user_id'];
$session_secure = $_SESSION['secure'];
$session_tz = $_SESSION['timezone'];
#user logs
user_logs($con, $session_id);
#flag for which pagniation page
$p_flag = 1;
if(isset($_GET['id1']) && strlen($_GET['id1']) === 40){
#set url values to variables
$forum_id = $_GET['id1'];
$y = 10;
//see if pages has been set
if(isset($_GET['pages']) && is_numeric($_GET['pages'])){
$total_pages = $_GET['pages'];
}else{
$sql =
"SELECT COUNT(threads.id_forum)
FROM threads
JOIN forum_overview ON forum_overview.id_forum = threads.id_forum
WHERE forum_overview.id_forum_sha1=?";
$cstmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($cstmt, 's', $forum_id);
mysqli_execute($cstmt);
$result = mysqli_stmt_get_result($cstmt);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$total_records = $row[0];
if($total_records > $y){
$total_pages = ceil($total_records / $y);
}else{
$total_pages = 1;
}
mysqli_stmt_free_result($cstmt);
}
// databse start point
if(isset($_GET['x']) && is_numeric($_GET['x'])){
$x = $_GET['x'];
}else{
$x = 0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php pageTitle();?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta description="the description">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<?php navigation();?>
<div class="pagination-container">
<div class="pagination">
<div class="pagination-links">
<div class="tree">
<?php navigation_modal($con, $_GET['id1']);?>
</div>
<div class="links-contain">
<?php
#pagination to transverse through the different threads
pagination($p_flag, $total_pages, $forum_id, '' , $x, $y);
?>
</div>
</div>
</div>
</div>
<section class="main-container">
<?php
#show all the threads in the specific forum
show_threads($con, $session_tz, $forum_id, $x, $y);
?>
</section>
<div class="pagination-container">
<div class="pagination">
<div class="pagination-links">
<div class="tree">
<?php navigation_modal($con, $_GET['id1']);?>
</div>
<div class="links-contain">
<?php
#pagination to transverse through the different threads
pagination($p_flag, $total_pages, $forum_id, '' , $x, $y);
?>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Nov 20, 2016 at 01:41 AM
-- Server version: 10.1.16-MariaDB
-- PHP Version: 5.6.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `retro`
--
-- --------------------------------------------------------
--
-- Table structure for table `forgot_password`
--
CREATE TABLE `forgot_password` (
`id_change_password` int(10) UNSIGNED NOT NULL,
`id_user` int(10) UNSIGNED NOT NULL,
`id_secure` char(40) NOT NULL,
`new_password` char(40) NOT NULL,
`request_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `forum_overview`
--
CREATE TABLE `forum_overview` (
`id_forum` int(11) UNSIGNED NOT NULL,
`id_forum_sha1` char(40) NOT NULL,
`name_forum` varchar(100) NOT NULL,
`details_forum` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `limbo`
--
CREATE TABLE `limbo` (
`id_limbo` int(10) UNSIGNED NOT NULL,
`username` varchar(20) NOT NULL,
`email` varchar(100) NOT NULL,
`email_sha1` char(40) NOT NULL,
`password` char(40) NOT NULL,
`activation_code` char(40) NOT NULL,
`date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`id_posts` int(11) NOT NULL,
`id_thread` int(10) UNSIGNED NOT NULL,
`id_forum` int(11) UNSIGNED NOT NULL,
`message_post` text NOT NULL,
`id_user` int(10) UNSIGNED NOT NULL,
`date_posted` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `threads`
--
CREATE TABLE `threads` (
`id_thread` int(11) UNSIGNED NOT NULL,
`id_thread_sha1` char(40) NOT NULL,
`id_forum` int(11) UNSIGNED NOT NULL,
`title_thread` varchar(100) NOT NULL,
`body_thread` text NOT NULL,
`id_user` int(10) UNSIGNED NOT NULL,
`created_on` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `thread_views`
--
CREATE TABLE `thread_views` (
`id_thread_views` int(10) UNSIGNED NOT NULL,
`id_forum` int(10) UNSIGNED NOT NULL,
`id_thread` int(10) UNSIGNED NOT NULL,
`id_user` int(10) UNSIGNED NOT NULL,
`timestamp` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=ucs2;
-- --------------------------------------------------------
--
-- Table structure for table `time_zones`
--
CREATE TABLE `time_zones` (
`id_time_zones` int(10) UNSIGNED NOT NULL,
`name_time_zones` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id_users` int(10) UNSIGNED NOT NULL,
`id_users_sha1` char(40) NOT NULL,
`username` varchar(20) NOT NULL,
`password` char(40) NOT NULL,
`email` varchar(100) NOT NULL,
`profile` blob NOT NULL,
`time_zone` int(10) UNSIGNED NOT NULL DEFAULT '1',
`signature` varchar(250) NOT NULL,
`user_group` int(11) NOT NULL DEFAULT '5',
`activation_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `user_groups`
--
CREATE TABLE `user_groups` (
`id_user_group` int(10) UNSIGNED NOT NULL,
`name_user_group` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `user_logs`
--
CREATE TABLE `user_logs` (
`id_user_logs` int(10) UNSIGNED NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`ip` varchar(50) NOT NULL,
`ip_method` enum('client_ip','x_forward','remote','') NOT NULL,
`hostaddr` varchar(50) NOT NULL,
`phpsess` varchar(50) NOT NULL,
`agent` varchar(250) NOT NULL,
`page_name` varchar(25) NOT NULL,
`datetime` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=ucs2;
-- --------------------------------------------------------
--
-- Stand-in structure for view `view_all_forum_info`
--
CREATE TABLE `view_all_forum_info` (
`idf` int(11) unsigned
,`idfsecure` char(40)
,`fname` varchar(100)
,`fdetails` varchar(250)
,`totalthreads` varchar(21)
,`newestthread` varchar(19)
,`totalposts` varchar(21)
);
-- --------------------------------------------------------
--
-- Stand-in structure for view `view_all_thread_info`
--
CREATE TABLE `view_all_thread_info` (
`idt` int(11) unsigned
,`idtsecure` char(40)
,`title` varchar(100)
,`body` text
,`createdon` datetime
,`createbyuserid` int(10) unsigned
,`idf` int(11) unsigned
,`idfsecure` char(40)
,`createdby` varchar(20)
,`totalposts` varchar(21)
,`lastpostdate` varchar(19)
);
-- --------------------------------------------------------
--
-- Stand-in structure for view `view_forum_stats`
--
CREATE TABLE `view_forum_stats` (
`id_forum` int(11) unsigned
,`totalthreads` bigint(21)
,`newestthread` varchar(19)
,`totalposts` bigint(21)
);
-- --------------------------------------------------------
--
-- Stand-in structure for view `view_thread_stats`
--
CREATE TABLE `view_thread_stats` (
`id_thread` int(11) unsigned
,`totalposts` bigint(21)
,`lastpostdate` varchar(19)
);
-- --------------------------------------------------------
--
-- Structure for view `view_all_forum_info`
--
DROP TABLE IF EXISTS `view_all_forum_info`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_all_forum_info` AS select `forum_overview`.`id_forum` AS `idf`,`forum_overview`.`id_forum_sha1` AS `idfsecure`,`forum_overview`.`name_forum` AS `fname`,`forum_overview`.`details_forum` AS `fdetails`,if((`view_forum_stats`.`totalthreads` = 0),'no-threads-yet',`view_forum_stats`.`totalthreads`) AS `totalthreads`,`view_forum_stats`.`newestthread` AS `newestthread`,if((`view_forum_stats`.`totalposts` = 0),'no-posts-yet',`view_forum_stats`.`totalposts`) AS `totalposts` from (`forum_overview` join `view_forum_stats` on((`forum_overview`.`id_forum` = `view_forum_stats`.`id_forum`))) ;
-- --------------------------------------------------------
--
-- Structure for view `view_all_thread_info`
--
DROP TABLE IF EXISTS `view_all_thread_info`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_all_thread_info` AS select `threads`.`id_thread` AS `idt`,`threads`.`id_thread_sha1` AS `idtsecure`,`threads`.`title_thread` AS `title`,`threads`.`body_thread` AS `body`,`threads`.`created_on` AS `createdon`,`threads`.`id_user` AS `createbyuserid`,`forum_overview`.`id_forum` AS `idf`,`forum_overview`.`id_forum_sha1` AS `idfsecure`,`users`.`username` AS `createdby`,if((`view_thread_stats`.`totalposts` = 0),'no-reply-yet',`view_thread_stats`.`totalposts`) AS `totalposts`,`view_thread_stats`.`lastpostdate` AS `lastpostdate` from ((((`threads` left join `posts` on((`threads`.`id_thread` = `posts`.`id_thread`))) join `forum_overview` on((`forum_overview`.`id_forum` = `threads`.`id_forum`))) join `users` on((`users`.`id_users` = `threads`.`id_user`))) join `view_thread_stats` on((`threads`.`id_thread` = `view_thread_stats`.`id_thread`))) group by `threads`.`id_thread` ;
-- --------------------------------------------------------
--
-- Structure for view `view_forum_stats`
--
DROP TABLE IF EXISTS `view_forum_stats`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_forum_stats` AS select `forum_overview`.`id_forum` AS `id_forum`,count(distinct `threads`.`id_thread`) AS `totalthreads`,ifnull(max(`threads`.`created_on`),'no-threads-yet') AS `newestthread`,count(distinct `posts`.`id_posts`) AS `totalposts` from ((`forum_overview` left join `threads` on((`forum_overview`.`id_forum` = `threads`.`id_forum`))) left join `posts` on((`forum_overview`.`id_forum` = `posts`.`id_forum`))) group by `forum_overview`.`id_forum` ;
-- --------------------------------------------------------
--
-- Structure for view `view_thread_stats`
--
DROP TABLE IF EXISTS `view_thread_stats`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_thread_stats` AS select `threads`.`id_thread` AS `id_thread`,count(`posts`.`id_thread`) AS `totalposts`,ifnull(max(`posts`.`date_posted`),'No reply yet') AS `lastpostdate` from ((`threads` left join `posts` on((`threads`.`id_thread` = `posts`.`id_thread`))) join `forum_overview` on((`forum_overview`.`id_forum` = `threads`.`id_forum`))) group by `threads`.`id_thread` ;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `forgot_password`
--
ALTER TABLE `forgot_password`
ADD PRIMARY KEY (`id_change_password`),
ADD UNIQUE KEY `id_secure` (`id_secure`);
--
-- Indexes for table `forum_overview`
--
ALTER TABLE `forum_overview`
ADD PRIMARY KEY (`id_forum`);
--
-- Indexes for table `limbo`
--
ALTER TABLE `limbo`
ADD PRIMARY KEY (`id_limbo`),
ADD UNIQUE KEY `username` (`username`),
ADD UNIQUE KEY `email` (`email`);
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`id_posts`),
ADD KEY `id_thread` (`id_thread`),
ADD KEY `id_user` (`id_user`),
ADD KEY `date_posted` (`date_posted`),
ADD KEY `id_user_2` (`id_user`);
--
-- Indexes for table `threads`
--
ALTER TABLE `threads`
ADD PRIMARY KEY (`id_thread`);
--
-- Indexes for table `thread_views`
--
ALTER TABLE `thread_views`
ADD PRIMARY KEY (`id_thread_views`);
--
-- Indexes for table `time_zones`
--
ALTER TABLE `time_zones`
ADD PRIMARY KEY (`id_time_zones`),
ADD UNIQUE KEY `name_time_zones` (`name_time_zones`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id_users`),
ADD UNIQUE KEY `username` (`username`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `id_users_sha1` (`id_users_sha1`);
--
-- Indexes for table `user_groups`
--
ALTER TABLE `user_groups`
ADD PRIMARY KEY (`id_user_group`),
ADD UNIQUE KEY `name_user_group` (`name_user_group`);
--
-- Indexes for table `user_logs`
--
ALTER TABLE `user_logs`
ADD PRIMARY KEY (`id_user_logs`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `forgot_password`
--
ALTER TABLE `forgot_password`
MODIFY `id_change_password` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `forum_overview`
--
ALTER TABLE `forum_overview`
MODIFY `id_forum` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `limbo`
--
ALTER TABLE `limbo`
MODIFY `id_limbo` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
MODIFY `id_posts` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `threads`
--
ALTER TABLE `threads`
MODIFY `id_thread` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `thread_views`
--
ALTER TABLE `thread_views`
MODIFY `id_thread_views` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `time_zones`
--
ALTER TABLE `time_zones`
MODIFY `id_time_zones` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id_users` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user_groups`
--
ALTER TABLE `user_groups`
MODIFY `id_user_group` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user_logs`
--
ALTER TABLE `user_logs`
MODIFY `id_user_logs` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| db40938eabb98b178abf3c8d090dad098162bd0c | [
"Markdown",
"SQL",
"PHP"
] | 22 | PHP | lorenzothedev/retro-forum | 2fb102ca05f7273cc934c2e157f72b4d60c78586 | b8782bdcf5ea4e3871a362ecfd06b1790efc9e30 | |
refs/heads/master | <repo_name>Sophia10/Sophia10.github.io<file_sep>/projekt/js/map.js
window.onload = function () {
// WMTS-Layer
L.TileLayer.Common = L.TileLayer.extend({
initialize: function (options) {
L.TileLayer.prototype.initialize.call(this, this.url, options);
}
});
var layers = {
osm: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
subdomains: ['a', 'b', 'c'],
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}),
/*ortophoto: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping,
Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}),*/
laender_topo: OpenMapSurfer_Roads = L.tileLayer('http://korona.geog.uni-heidelberg.de/tiles/roads/x={x}&y={y}&z={z}', {
maxZoom: 20,
attribution: 'Imagery from ' +
'<a href="http://giscience.uni-hd.de/">GIScience Research Group @ University of Heidelberg</a> ' +
'— Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}),
NASA: new L.GIBSLayer('BlueMarble_ShadedRelief', {
date: new Date('currentDate'),
transparent: true
}),
night: new L.GIBSLayer('VIIRS_CityLights_2012', {
date: new Date('currentDate'),
transparent: true
}),
opentopo: new L.tileLayer('http://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
maxZoom: 17,
attribution: 'Map data: © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>,' +
' <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: © ' +
'<a href="https://opentopomap.org">OpenTopoMap</a> ' +
'(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
})
};
// define map
var map = L.map('map', {
layers: [layers.NASA],
center: [25.8, 7.4],
zoom: 2
});
// Maßstab hinzufügen
L.control.scale({
maxWidth: 200,
metric: true,
imperial: false
}).addTo(map);
// WMTS-Layer Auswahl hinzufügen
var layerControl = L.control.layers({
//"Orthophoto": layers.ortophoto,
"Blue Marble": layers.NASA,
"Länder-Topographie": layers.laender_topo,
"OpenTopoMap": layers.opentopo,
"World at night": layers.night,
"OpenStreetMap": layers.osm
}).addTo(map);
// leaflet-hash aktivieren
var hash = new L.Hash(map);
// Marker cluster
var cluster_group = L.markerClusterGroup();
//load image data and make marker and popup
var allImages = document.getElementsByClassName("pictures");
console.log(allImages);
var pictureIcon = L.icon({
iconUrl: 'icons/picture.png',
iconAnchor: [16, 37],
popupAnchor: [1, -34]
});
var markerGroup = L.featureGroup().addTo(map);
for (var i = 0; i < allImages.length; i += 1) {
console.log(allImages[i]);
EXIF.getData(allImages[i], function () {
var author = EXIF.getTag(this, "Copyright");
var lat_arr = EXIF.getTag(this, "GPSLatitude");
var lng_arr = EXIF.getTag(this, "GPSLongitude");
var lat = lat_arr[0] + (lat_arr[1] / 60);
var lng = lng_arr[0] + (lng_arr[1] / 60);
var latRef = EXIF.getTag(this, "GPSLatitudeRef");
var lngRef = EXIF.getTag(this, "GPSLongitudeRef");
if (latRef === "S") {
lat = lat * -1
}
if (lngRef === "W") {
lng = lng * -1
}
var mrk = L.marker([lat, lng], {icon: pictureIcon});
var popup = "<a href=" + this.src + "><img src='" + this.src + "' class='thumbnail'/></a>" +
'<br/>Picture by <a href="photographers.html">' + author + '<a/>' +
'<br/>Latitude: ' + lat + " " + latRef +
'<br/>Longitude: ' + lng + " " + lngRef;
mrk.bindPopup(popup).addTo(cluster_group);
cluster_group.addTo(map);
});
}
};<file_sep>/projekt/js/gibs-metadata/GIBSMetadata.js
L.GIBS_LAYERS = {
"AMSR2_Snow_Water_Equivalent": {
"title": "AMSR2_Snow_Water_Equivalent",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Snow_Water_Equivalent/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Cloud_Liquid_Water_Day": {
"title": "AMSR2_Cloud_Liquid_Water_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Cloud_Liquid_Water_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Cloud_Liquid_Water_Night": {
"title": "AMSR2_Cloud_Liquid_Water_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Cloud_Liquid_Water_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Surface_Precipitation_Rate_Day": {
"title": "AMSR2_Surface_Precipitation_Rate_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Surface_Precipitation_Rate_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Surface_Precipitation_Rate_Night": {
"title": "AMSR2_Surface_Precipitation_Rate_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Surface_Precipitation_Rate_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Surface_Rain_Rate_Day": {
"title": "AMSR2_Surface_Rain_Rate_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Surface_Rain_Rate_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Surface_Rain_Rate_Night": {
"title": "AMSR2_Surface_Rain_Rate_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Surface_Rain_Rate_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Wind_Speed_Day": {
"title": "AMSR2_Wind_Speed_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Wind_Speed_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Wind_Speed_Night": {
"title": "AMSR2_Wind_Speed_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Wind_Speed_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Columnar_Water_Vapor_Day": {
"title": "AMSR2_Columnar_Water_Vapor_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Columnar_Water_Vapor_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Columnar_Water_Vapor_Night": {
"title": "AMSR2_Columnar_Water_Vapor_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Columnar_Water_Vapor_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Sea_Ice_Concentration_12km": {
"title": "AMSR2_Sea_Ice_Concentration_12km",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Sea_Ice_Concentration_12km/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Sea_Ice_Concentration_25km": {
"title": "AMSR2_Sea_Ice_Concentration_25km",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Sea_Ice_Concentration_25km/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Sea_Ice_Brightness_Temp_6km_89H": {
"title": "AMSR2_Sea_Ice_Brightness_Temp_6km_89H",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Sea_Ice_Brightness_Temp_6km_89H/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSR2_Sea_Ice_Brightness_Temp_6km_89V": {
"title": "AMSR2_Sea_Ice_Brightness_Temp_6km_89V",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSR2_Sea_Ice_Brightness_Temp_6km_89V/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Brightness_Temp_89H_Day": {
"title": "AMSRE_Brightness_Temp_89H_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Brightness_Temp_89H_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Brightness_Temp_89H_Night": {
"title": "AMSRE_Brightness_Temp_89H_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Brightness_Temp_89H_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Brightness_Temp_89V_Day": {
"title": "AMSRE_Brightness_Temp_89V_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Brightness_Temp_89V_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Brightness_Temp_89V_Night": {
"title": "AMSRE_Brightness_Temp_89V_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Brightness_Temp_89V_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Surface_Precipitation_Rate_Day": {
"title": "AMSRE_Surface_Precipitation_Rate_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Surface_Precipitation_Rate_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Surface_Precipitation_Rate_Night": {
"title": "AMSRE_Surface_Precipitation_Rate_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Surface_Precipitation_Rate_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Surface_Rain_Rate_Day": {
"title": "AMSRE_Surface_Rain_Rate_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Surface_Rain_Rate_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Surface_Rain_Rate_Night": {
"title": "AMSRE_Surface_Rain_Rate_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Surface_Rain_Rate_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Sea_Ice_Concentration_12km": {
"title": "AMSRE_Sea_Ice_Concentration_12km",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Sea_Ice_Concentration_12km/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Snow_Depth_Over_Ice": {
"title": "AMSRE_Snow_Depth_Over_Ice",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Snow_Depth_Over_Ice/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Sea_Ice_Concentration_25km": {
"title": "AMSRE_Sea_Ice_Concentration_25km",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Sea_Ice_Concentration_25km/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Sea_Ice_Brightness_Temp_89H": {
"title": "AMSRE_Sea_Ice_Brightness_Temp_89H",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Sea_Ice_Brightness_Temp_89H/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AMSRE_Sea_Ice_Brightness_Temp_89V": {
"title": "AMSRE_Sea_Ice_Brightness_Temp_89V",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AMSRE_Sea_Ice_Brightness_Temp_89V/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_CO_Total_Column_Day": {
"title": "AIRS_CO_Total_Column_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_CO_Total_Column_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_CO_Total_Column_Night": {
"title": "AIRS_CO_Total_Column_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_CO_Total_Column_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Dust_Score_Ocean_Day": {
"title": "AIRS_Dust_Score_Ocean_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Dust_Score_Ocean_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Dust_Score_Ocean_Night": {
"title": "AIRS_Dust_Score_Ocean_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Dust_Score_Ocean_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Prata_SO2_Index_Day": {
"title": "AIRS_Prata_SO2_Index_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Prata_SO2_Index_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Prata_SO2_Index_Night": {
"title": "AIRS_Prata_SO2_Index_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Prata_SO2_Index_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Precipitation_Day": {
"title": "AIRS_Precipitation_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Precipitation_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Precipitation_Night": {
"title": "AIRS_Precipitation_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Precipitation_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_400hPa_Day": {
"title": "AIRS_RelativeHumidity_400hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_400hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_400hPa_Night": {
"title": "AIRS_RelativeHumidity_400hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_400hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_500hPa_Day": {
"title": "AIRS_RelativeHumidity_500hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_500hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_500hPa_Night": {
"title": "AIRS_RelativeHumidity_500hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_500hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_600hPa_Day": {
"title": "AIRS_RelativeHumidity_600hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_600hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_600hPa_Night": {
"title": "AIRS_RelativeHumidity_600hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_600hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_700hPa_Day": {
"title": "AIRS_RelativeHumidity_700hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_700hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_700hPa_Night": {
"title": "AIRS_RelativeHumidity_700hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_700hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_850hPa_Day": {
"title": "AIRS_RelativeHumidity_850hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_850hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_RelativeHumidity_850hPa_Night": {
"title": "AIRS_RelativeHumidity_850hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_RelativeHumidity_850hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_400hPa_Day": {
"title": "AIRS_Temperature_400hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_400hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_400hPa_Night": {
"title": "AIRS_Temperature_400hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_400hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_500hPa_Day": {
"title": "AIRS_Temperature_500hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_500hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_500hPa_Night": {
"title": "AIRS_Temperature_500hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_500hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_600hPa_Day": {
"title": "AIRS_Temperature_600hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_600hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_600hPa_Night": {
"title": "AIRS_Temperature_600hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_600hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_700hPa_Day": {
"title": "AIRS_Temperature_700hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_700hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_700hPa_Night": {
"title": "AIRS_Temperature_700hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_700hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_850hPa_Day": {
"title": "AIRS_Temperature_850hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_850hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"AIRS_Temperature_850hPa_Night": {
"title": "AIRS_Temperature_850hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/AIRS_Temperature_850hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"BlueMarble_NextGeneration": {
"title": "BlueMarble_NextGeneration",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_NextGeneration/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": false
},
"BlueMarble_ShadedRelief": {
"title": "BlueMarble_ShadedRelief",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_ShadedRelief/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": false
},
"BlueMarble_ShadedRelief_Bathymetry": {
"title": "BlueMarble_ShadedRelief_Bathymetry",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_ShadedRelief_Bathymetry/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": false
},
"CERES_Combined_TOA_Longwave_Flux_All_Sky_Monthly": {
"title": "CERES_Combined_TOA_Longwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Combined_TOA_Longwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Combined_TOA_Longwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_Combined_TOA_Longwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Combined_TOA_Longwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Combined_TOA_Shortwave_Flux_All_Sky_Monthly": {
"title": "CERES_Combined_TOA_Shortwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Combined_TOA_Shortwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Combined_TOA_Shortwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_Combined_TOA_Shortwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Combined_TOA_Shortwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Combined_TOA_Window_Region_Flux_All_Sky_Monthly": {
"title": "CERES_Combined_TOA_Window_Region_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Combined_TOA_Window_Region_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Combined_TOA_Window_Region_Flux_Clear_Sky_Monthly": {
"title": "CERES_Combined_TOA_Window_Region_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Combined_TOA_Window_Region_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_CRE_Net_Longwave_Flux_Monthly": {
"title": "CERES_EBAF_Surface_CRE_Net_Longwave_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_CRE_Net_Longwave_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_CRE_Net_Shortwave_Flux_Monthly": {
"title": "CERES_EBAF_Surface_CRE_Net_Shortwave_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_CRE_Net_Shortwave_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_CRE_Net_Total_Flux_Monthly": {
"title": "CERES_EBAF_Surface_CRE_Net_Total_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_CRE_Net_Total_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Longwave_Flux_Down_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Longwave_Flux_Down_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Longwave_Flux_Down_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Longwave_Flux_Up_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Longwave_Flux_Up_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Longwave_Flux_Up_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Longwave_Flux_Down_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Longwave_Flux_Down_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Longwave_Flux_Down_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Longwave_Flux_Up_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Longwave_Flux_Up_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Longwave_Flux_Up_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Net_Longwave_Flux_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Net_Longwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Net_Longwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Net_Longwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Net_Longwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Net_Longwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Net_Shortwave_Flux_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Net_Shortwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Net_Shortwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Net_Shortwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Net_Shortwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Net_Shortwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Net_Total_Flux_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Net_Total_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Net_Total_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Net_Total_Flux_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Net_Total_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Net_Total_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Shortwave_Flux_Down_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Shortwave_Flux_Down_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Shortwave_Flux_Down_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Shortwave_Flux_Up_All_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Shortwave_Flux_Up_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Shortwave_Flux_Up_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Shortwave_Flux_Down_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Shortwave_Flux_Down_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Shortwave_Flux_Down_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_Surface_Shortwave_Flux_Up_Clear_Sky_Monthly": {
"title": "CERES_EBAF_Surface_Shortwave_Flux_Up_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_Surface_Shortwave_Flux_Up_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_CRE_Longwave_Flux_Monthly": {
"title": "CERES_EBAF_TOA_CRE_Longwave_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_CRE_Longwave_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_CRE_Net_Flux_Monthly": {
"title": "CERES_EBAF_TOA_CRE_Net_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_CRE_Net_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_CRE_Shortwave_Flux_Monthly": {
"title": "CERES_EBAF_TOA_CRE_Shortwave_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_CRE_Shortwave_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Longwave_Flux_All_Sky_Monthly": {
"title": "CERES_EBAF_TOA_Longwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Longwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Longwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_EBAF_TOA_Longwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Longwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Net_Flux_All_Sky_Monthly": {
"title": "CERES_EBAF_TOA_Net_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Net_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Net_Flux_Clear_Sky_Monthly": {
"title": "CERES_EBAF_TOA_Net_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Net_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Incoming_Solar_Flux_Monthly": {
"title": "CERES_EBAF_TOA_Incoming_Solar_Flux_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Incoming_Solar_Flux_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly": {
"title": "CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_EBAF_TOA_Shortwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_EBAF_TOA_Shortwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_EBAF_TOA_Shortwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Terra_TOA_Longwave_Flux_All_Sky_Monthly": {
"title": "CERES_Terra_TOA_Longwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Terra_TOA_Longwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Terra_TOA_Longwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_Terra_TOA_Longwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Terra_TOA_Longwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Terra_TOA_Shortwave_Flux_All_Sky_Monthly": {
"title": "CERES_Terra_TOA_Shortwave_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Terra_TOA_Shortwave_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Terra_TOA_Shortwave_Flux_Clear_Sky_Monthly": {
"title": "CERES_Terra_TOA_Shortwave_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Terra_TOA_Shortwave_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Terra_TOA_Window_Region_Flux_All_Sky_Monthly": {
"title": "CERES_Terra_TOA_Window_Region_Flux_All_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Terra_TOA_Window_Region_Flux_All_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"CERES_Terra_TOA_Window_Region_Flux_Clear_Sky_Monthly": {
"title": "CERES_Terra_TOA_Window_Region_Flux_Clear_Sky_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/CERES_Terra_TOA_Window_Region_Flux_Clear_Sky_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"Coastlines": {
"title": "Coastlines",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/Coastlines/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 9,
"date": false
},
"GHRSST_L4_G1SST_Sea_Surface_Temperature": {
"title": "GHRSST_L4_G1SST_Sea_Surface_Temperature",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GHRSST_L4_G1SST_Sea_Surface_Temperature/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"GHRSST_L4_MUR_Sea_Surface_Temperature": {
"title": "GHRSST_L4_MUR_Sea_Surface_Temperature",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GHRSST_L4_MUR_Sea_Surface_Temperature/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"GMI_Rain_Rate_Asc": {
"title": "GMI_Rain_Rate_Asc",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GMI_Rain_Rate_Asc/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"GMI_Rain_Rate_Dsc": {
"title": "GMI_Rain_Rate_Dsc",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GMI_Rain_Rate_Dsc/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"GMI_Brightness_Temp_Asc": {
"title": "GMI_Brightness_Temp_Asc",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GMI_Brightness_Temp_Asc/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"GMI_Brightness_Temp_Dsc": {
"title": "GMI_Brightness_Temp_Dsc",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GMI_Brightness_Temp_Dsc/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"GMI_Snow_Rate_Asc": {
"title": "GMI_Snow_Rate_Asc",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GMI_Snow_Rate_Asc/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"GMI_Snow_Rate_Dsc": {
"title": "GMI_Snow_Rate_Dsc",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GMI_Snow_Rate_Dsc/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Combined_Value_Added_AOD": {
"title": "MODIS_Combined_Value_Added_AOD",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Combined_Value_Added_AOD/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MEaSUREs_Daily_Landscape_Freeze_Thaw_AMSRE": {
"title": "MEaSUREs_Daily_Landscape_Freeze_Thaw_AMSRE",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MEaSUREs_Daily_Landscape_Freeze_Thaw_AMSRE/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MEaSUREs_Daily_Landscape_Freeze_Thaw_SSMI": {
"title": "MEaSUREs_Daily_Landscape_Freeze_Thaw_SSMI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MEaSUREs_Daily_Landscape_Freeze_Thaw_SSMI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MISR_Directional_Hemispherical_Reflectance_Average_Natural_Color_Monthly": {
"title": "MISR_Directional_Hemispherical_Reflectance_Average_Natural_Color_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MISR_Directional_Hemispherical_Reflectance_Average_Natural_Color_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MISR_Radiance_Average_Infrared_Color_Monthly": {
"title": "MISR_Radiance_Average_Infrared_Color_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MISR_Radiance_Average_Infrared_Color_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MISR_Radiance_Average_Natural_Color_Monthly": {
"title": "MISR_Radiance_Average_Natural_Color_Monthly",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MISR_Radiance_Average_Natural_Color_Monthly/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_CO_215hPa_Day": {
"title": "MLS_CO_215hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_CO_215hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_CO_215hPa_Night": {
"title": "MLS_CO_215hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_CO_215hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_H2O_46hPa_Day": {
"title": "MLS_H2O_46hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_H2O_46hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_H2O_46hPa_Night": {
"title": "MLS_H2O_46hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_H2O_46hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_HNO3_46hPa_Day": {
"title": "MLS_HNO3_46hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_HNO3_46hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_HNO3_46hPa_Night": {
"title": "MLS_HNO3_46hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_HNO3_46hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_N2O_46hPa_Day": {
"title": "MLS_N2O_46hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_N2O_46hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_N2O_46hPa_Night": {
"title": "MLS_N2O_46hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_N2O_46hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_O3_46hPa_Day": {
"title": "MLS_O3_46hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_O3_46hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_O3_46hPa_Night": {
"title": "MLS_O3_46hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_O3_46hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_SO2_147hPa_Day": {
"title": "MLS_SO2_147hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_SO2_147hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_SO2_147hPa_Night": {
"title": "MLS_SO2_147hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_SO2_147hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_Temperature_46hPa_Day": {
"title": "MLS_Temperature_46hPa_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_Temperature_46hPa_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MLS_Temperature_46hPa_Night": {
"title": "MLS_Temperature_46hPa_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MLS_Temperature_46hPa_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Chlorophyll_A": {
"title": "MODIS_Terra_Chlorophyll_A",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Chlorophyll_A/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Water_Mask": {
"title": "MODIS_Water_Mask",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Water_Mask/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 9,
"date": false
},
"MODIS_Terra_Brightness_Temp_Band31_Day": {
"title": "MODIS_Terra_Brightness_Temp_Band31_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Brightness_Temp_Band31_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Brightness_Temp_Band31_Night": {
"title": "MODIS_Terra_Brightness_Temp_Band31_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Brightness_Temp_Band31_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Aerosol_Optical_Depth_3km": {
"title": "MODIS_Terra_Aerosol_Optical_Depth_3km",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Aerosol_Optical_Depth_3km/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Angstrom_Exponent_Land": {
"title": "MODIS_Terra_Angstrom_Exponent_Land",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Angstrom_Exponent_Land/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Angstrom_Exponent_Ocean": {
"title": "MODIS_Terra_Angstrom_Exponent_Ocean",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Angstrom_Exponent_Ocean/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_AOD_Deep_Blue_Land": {
"title": "MODIS_Terra_AOD_Deep_Blue_Land",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_AOD_Deep_Blue_Land/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_AOD_Deep_Blue_Combined": {
"title": "MODIS_Terra_AOD_Deep_Blue_Combined",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_AOD_Deep_Blue_Combined/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Aerosol": {
"title": "MODIS_Terra_Aerosol",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Aerosol/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Water_Vapor_5km_Day": {
"title": "MODIS_Terra_Water_Vapor_5km_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Water_Vapor_5km_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Water_Vapor_5km_Night": {
"title": "MODIS_Terra_Water_Vapor_5km_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Water_Vapor_5km_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Effective_Radius_37_PCL": {
"title": "MODIS_Terra_Cloud_Effective_Radius_37_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Effective_Radius_37_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Effective_Radius_37": {
"title": "MODIS_Terra_Cloud_Effective_Radius_37",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Effective_Radius_37/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Effective_Radius": {
"title": "MODIS_Terra_Cloud_Effective_Radius",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Effective_Radius/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Effective_Radius_PCL": {
"title": "MODIS_Terra_Cloud_Effective_Radius_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Effective_Radius_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Multi_Layer_Flag": {
"title": "MODIS_Terra_Cloud_Multi_Layer_Flag",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Multi_Layer_Flag/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Optical_Thickness": {
"title": "MODIS_Terra_Cloud_Optical_Thickness",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Optical_Thickness/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Optical_Thickness_PCL": {
"title": "MODIS_Terra_Cloud_Optical_Thickness_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Optical_Thickness_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Phase_Optical_Properties": {
"title": "MODIS_Terra_Cloud_Phase_Optical_Properties",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Phase_Optical_Properties/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Water_Path": {
"title": "MODIS_Terra_Cloud_Water_Path",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Water_Path/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Water_Path_PCL": {
"title": "MODIS_Terra_Cloud_Water_Path_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Water_Path_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Cloud_Fraction_Day": {
"title": "MODIS_Terra_Cloud_Fraction_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Fraction_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Phase_Infrared_Day": {
"title": "MODIS_Terra_Cloud_Phase_Infrared_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Phase_Infrared_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Top_Height_Day": {
"title": "MODIS_Terra_Cloud_Top_Height_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Top_Height_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Top_Pressure_Day": {
"title": "MODIS_Terra_Cloud_Top_Pressure_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Top_Pressure_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Top_Temp_Day": {
"title": "MODIS_Terra_Cloud_Top_Temp_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Top_Temp_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Fraction_Night": {
"title": "MODIS_Terra_Cloud_Fraction_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Fraction_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Phase_Infrared_Night": {
"title": "MODIS_Terra_Cloud_Phase_Infrared_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Phase_Infrared_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Top_Height_Night": {
"title": "MODIS_Terra_Cloud_Top_Height_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Top_Height_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Top_Pressure_Night": {
"title": "MODIS_Terra_Cloud_Top_Pressure_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Top_Pressure_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_Cloud_Top_Temp_Night": {
"title": "MODIS_Terra_Cloud_Top_Temp_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Cloud_Top_Temp_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Terra_SurfaceReflectance_Bands143": {
"title": "MODIS_Terra_SurfaceReflectance_Bands143",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_SurfaceReflectance_Bands143/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": true
},
"MODIS_Terra_SurfaceReflectance_Bands721": {
"title": "MODIS_Terra_SurfaceReflectance_Bands721",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_SurfaceReflectance_Bands721/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": true
},
"MODIS_Terra_SurfaceReflectance_Bands121": {
"title": "MODIS_Terra_SurfaceReflectance_Bands121",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_SurfaceReflectance_Bands121/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"MODIS_Terra_Snow_Cover": {
"title": "MODIS_Terra_Snow_Cover",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Snow_Cover/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 8,
"date": true
},
"MODIS_Terra_Land_Surface_Temp_Day": {
"title": "MODIS_Terra_Land_Surface_Temp_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Land_Surface_Temp_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Land_Surface_Temp_Night": {
"title": "MODIS_Terra_Land_Surface_Temp_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Land_Surface_Temp_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_Sea_Ice": {
"title": "MODIS_Terra_Sea_Ice",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Sea_Ice/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Terra_CorrectedReflectance_TrueColor": {
"title": "MODIS_Terra_CorrectedReflectance_TrueColor",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"MODIS_Terra_CorrectedReflectance_Bands367": {
"title": "MODIS_Terra_CorrectedReflectance_Bands367",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_CorrectedReflectance_Bands367/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"MODIS_Terra_CorrectedReflectance_Bands721": {
"title": "MODIS_Terra_CorrectedReflectance_Bands721",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_CorrectedReflectance_Bands721/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"MOPITT_CO_Daily_Surface_Mixing_Ratio_Night": {
"title": "MOPITT_CO_Daily_Surface_Mixing_Ratio_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Daily_Surface_Mixing_Ratio_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Daily_Surface_Mixing_Ratio_Day": {
"title": "MOPITT_CO_Daily_Surface_Mixing_Ratio_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Daily_Surface_Mixing_Ratio_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Daily_Total_Column_Night": {
"title": "MOPITT_CO_Daily_Total_Column_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Daily_Total_Column_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Daily_Total_Column_Day": {
"title": "MOPITT_CO_Daily_Total_Column_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Daily_Total_Column_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Monthly_Surface_Mixing_Ratio_Night": {
"title": "MOPITT_CO_Monthly_Surface_Mixing_Ratio_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Monthly_Surface_Mixing_Ratio_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Monthly_Surface_Mixing_Ratio_Day": {
"title": "MOPITT_CO_Monthly_Surface_Mixing_Ratio_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Monthly_Surface_Mixing_Ratio_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Monthly_Total_Column_Night": {
"title": "MOPITT_CO_Monthly_Total_Column_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Monthly_Total_Column_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MOPITT_CO_Monthly_Total_Column_Day": {
"title": "MOPITT_CO_Monthly_Total_Column_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MOPITT_CO_Monthly_Total_Column_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Chlorophyll_A": {
"title": "MODIS_Aqua_Chlorophyll_A",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Chlorophyll_A/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Brightness_Temp_Band31_Day": {
"title": "MODIS_Aqua_Brightness_Temp_Band31_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Brightness_Temp_Band31_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Brightness_Temp_Band31_Night": {
"title": "MODIS_Aqua_Brightness_Temp_Band31_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Brightness_Temp_Band31_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Aerosol_Optical_Depth_3km": {
"title": "MODIS_Aqua_Aerosol_Optical_Depth_3km",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Aerosol_Optical_Depth_3km/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Angstrom_Exponent_Land": {
"title": "MODIS_Aqua_Angstrom_Exponent_Land",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Angstrom_Exponent_Land/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Angstrom_Exponent_Ocean": {
"title": "MODIS_Aqua_Angstrom_Exponent_Ocean",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Angstrom_Exponent_Ocean/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_AOD_Deep_Blue_Land": {
"title": "MODIS_Aqua_AOD_Deep_Blue_Land",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_AOD_Deep_Blue_Land/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_AOD_Deep_Blue_Combined": {
"title": "MODIS_Aqua_AOD_Deep_Blue_Combined",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_AOD_Deep_Blue_Combined/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Aerosol": {
"title": "MODIS_Aqua_Aerosol",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Aerosol/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Water_Vapor_5km_Day": {
"title": "MODIS_Aqua_Water_Vapor_5km_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Water_Vapor_5km_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Water_Vapor_5km_Night": {
"title": "MODIS_Aqua_Water_Vapor_5km_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Water_Vapor_5km_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Effective_Radius_37_PCL": {
"title": "MODIS_Aqua_Cloud_Effective_Radius_37_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Effective_Radius_37_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Effective_Radius_37": {
"title": "MODIS_Aqua_Cloud_Effective_Radius_37",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Effective_Radius_37/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Effective_Radius": {
"title": "MODIS_Aqua_Cloud_Effective_Radius",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Effective_Radius/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Effective_Radius_PCL": {
"title": "MODIS_Aqua_Cloud_Effective_Radius_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Effective_Radius_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Multi_Layer_Flag": {
"title": "MODIS_Aqua_Cloud_Multi_Layer_Flag",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Multi_Layer_Flag/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Optical_Thickness": {
"title": "MODIS_Aqua_Cloud_Optical_Thickness",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Optical_Thickness/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Optical_Thickness_PCL": {
"title": "MODIS_Aqua_Cloud_Optical_Thickness_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Optical_Thickness_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Phase_Optical_Properties": {
"title": "MODIS_Aqua_Cloud_Phase_Optical_Properties",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Phase_Optical_Properties/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Water_Path": {
"title": "MODIS_Aqua_Cloud_Water_Path",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Water_Path/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Water_Path_PCL": {
"title": "MODIS_Aqua_Cloud_Water_Path_PCL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Water_Path_PCL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Cloud_Fraction_Day": {
"title": "MODIS_Aqua_Cloud_Fraction_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Fraction_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Phase_Infrared_Day": {
"title": "MODIS_Aqua_Cloud_Phase_Infrared_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Phase_Infrared_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Top_Height_Day": {
"title": "MODIS_Aqua_Cloud_Top_Height_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Top_Height_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Top_Pressure_Day": {
"title": "MODIS_Aqua_Cloud_Top_Pressure_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Top_Pressure_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Top_Temp_Day": {
"title": "MODIS_Aqua_Cloud_Top_Temp_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Top_Temp_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Fraction_Night": {
"title": "MODIS_Aqua_Cloud_Fraction_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Fraction_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Phase_Infrared_Night": {
"title": "MODIS_Aqua_Cloud_Phase_Infrared_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Phase_Infrared_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Top_Height_Night": {
"title": "MODIS_Aqua_Cloud_Top_Height_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Top_Height_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Top_Pressure_Night": {
"title": "MODIS_Aqua_Cloud_Top_Pressure_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Top_Pressure_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_Cloud_Top_Temp_Night": {
"title": "MODIS_Aqua_Cloud_Top_Temp_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Cloud_Top_Temp_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"MODIS_Aqua_SurfaceReflectance_Bands143": {
"title": "MODIS_Aqua_SurfaceReflectance_Bands143",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_SurfaceReflectance_Bands143/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": true
},
"MODIS_Aqua_SurfaceReflectance_Bands721": {
"title": "MODIS_Aqua_SurfaceReflectance_Bands721",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_SurfaceReflectance_Bands721/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": true
},
"MODIS_Aqua_SurfaceReflectance_Bands121": {
"title": "MODIS_Aqua_SurfaceReflectance_Bands121",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_SurfaceReflectance_Bands121/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"MODIS_Aqua_Snow_Cover": {
"title": "MODIS_Aqua_Snow_Cover",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Snow_Cover/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 8,
"date": true
},
"MODIS_Aqua_Land_Surface_Temp_Day": {
"title": "MODIS_Aqua_Land_Surface_Temp_Day",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Land_Surface_Temp_Day/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Land_Surface_Temp_Night": {
"title": "MODIS_Aqua_Land_Surface_Temp_Night",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Land_Surface_Temp_Night/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_Sea_Ice": {
"title": "MODIS_Aqua_Sea_Ice",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Sea_Ice/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 7,
"date": true
},
"MODIS_Aqua_CorrectedReflectance_TrueColor": {
"title": "MODIS_Aqua_CorrectedReflectance_TrueColor",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_CorrectedReflectance_TrueColor/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"MODIS_Aqua_CorrectedReflectance_Bands721": {
"title": "MODIS_Aqua_CorrectedReflectance_Bands721",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_CorrectedReflectance_Bands721/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"OMI_Absorbing_Aerosol_Optical_Depth": {
"title": "OMI_Absorbing_Aerosol_Optical_Depth",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_Absorbing_Aerosol_Optical_Depth/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"OMI_Aerosol_Index": {
"title": "OMI_Aerosol_Index",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_Aerosol_Index/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"OMI_Aerosol_Optical_Depth": {
"title": "OMI_Aerosol_Optical_Depth",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_Aerosol_Optical_Depth/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"OMI_Cloud_Pressure": {
"title": "OMI_Cloud_Pressure",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_Cloud_Pressure/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"OMI_SO2_Upper_Troposphere_and_Stratosphere": {
"title": "OMI_SO2_Upper_Troposphere_and_Stratosphere",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_SO2_Upper_Troposphere_and_Stratosphere/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"OMI_SO2_Lower_Troposphere": {
"title": "OMI_SO2_Lower_Troposphere",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_SO2_Lower_Troposphere/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"OMI_SO2_Middle_Troposphere": {
"title": "OMI_SO2_Middle_Troposphere",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/OMI_SO2_Middle_Troposphere/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"Reference_Features": {
"title": "Reference_Features",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/Reference_Features/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 9,
"date": false
},
"Reference_Labels": {
"title": "Reference_Labels",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/Reference_Labels/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 9,
"date": false
},
"SMAP_L1_Passive_Faraday_Rotation_Aft": {
"title": "SMAP_L1_Passive_Faraday_Rotation_Aft",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Faraday_Rotation_Aft/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Faraday_Rotation_Fore": {
"title": "SMAP_L1_Passive_Faraday_Rotation_Fore",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Faraday_Rotation_Fore/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Aft_H_QA": {
"title": "SMAP_L1_Passive_Brightness_Temp_Aft_H_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Aft_H_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Aft_H_RFI": {
"title": "SMAP_L1_Passive_Brightness_Temp_Aft_H_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Aft_H_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Aft_H": {
"title": "SMAP_L1_Passive_Brightness_Temp_Aft_H",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Aft_H/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Fore_H_QA": {
"title": "SMAP_L1_Passive_Brightness_Temp_Fore_H_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Fore_H_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Fore_H_RFI": {
"title": "SMAP_L1_Passive_Brightness_Temp_Fore_H_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Fore_H_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Fore_H": {
"title": "SMAP_L1_Passive_Brightness_Temp_Fore_H",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Fore_H/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Aft_V_QA": {
"title": "SMAP_L1_Passive_Brightness_Temp_Aft_V_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Aft_V_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Aft_V_RFI": {
"title": "SMAP_L1_Passive_Brightness_Temp_Aft_V_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Aft_V_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Aft_V": {
"title": "SMAP_L1_Passive_Brightness_Temp_Aft_V",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Aft_V/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Fore_V_QA": {
"title": "SMAP_L1_Passive_Brightness_Temp_Fore_V_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Fore_V_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Fore_V_RFI": {
"title": "SMAP_L1_Passive_Brightness_Temp_Fore_V_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Fore_V_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L1_Passive_Brightness_Temp_Fore_V": {
"title": "SMAP_L1_Passive_Brightness_Temp_Fore_V",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L1_Passive_Brightness_Temp_Fore_V/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L2_Passive_Soil_Moisture_Option1": {
"title": "SMAP_L2_Passive_Soil_Moisture_Option1",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L2_Passive_Soil_Moisture_Option1/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L2_Passive_Soil_Moisture_Option2": {
"title": "SMAP_L2_Passive_Soil_Moisture_Option2",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L2_Passive_Soil_Moisture_Option2/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L2_Passive_Soil_Moisture_Option3": {
"title": "SMAP_L2_Passive_Soil_Moisture_Option3",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L2_Passive_Soil_Moisture_Option3/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_HH_QA": {
"title": "SMAP_L3_Active_Sigma0_HH_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_HH_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_HH_RFI": {
"title": "SMAP_L3_Active_Sigma0_HH_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_HH_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_HH": {
"title": "SMAP_L3_Active_Sigma0_HH",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_HH/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_VV_QA": {
"title": "SMAP_L3_Active_Sigma0_VV_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_VV_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_VV_RFI": {
"title": "SMAP_L3_Active_Sigma0_VV_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_VV_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_VV": {
"title": "SMAP_L3_Active_Sigma0_VV",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_VV/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_XPOL_QA": {
"title": "SMAP_L3_Active_Sigma0_XPOL_QA",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_XPOL_QA/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_XPOL_RFI": {
"title": "SMAP_L3_Active_Sigma0_XPOL_RFI",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_XPOL_RFI/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Sigma0_XPOL": {
"title": "SMAP_L3_Active_Sigma0_XPOL",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Sigma0_XPOL/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Soil_Moisture": {
"title": "SMAP_L3_Active_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Passive_Soil_Moisture": {
"title": "SMAP_L3_Active_Passive_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Passive_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Passive_Soil_Moisture": {
"title": "SMAP_L3_Passive_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Passive_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Passive_Brightness_Temp_H": {
"title": "SMAP_L3_Active_Passive_Brightness_Temp_H",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Passive_Brightness_Temp_H/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Passive_Brightness_Temp_H": {
"title": "SMAP_L3_Passive_Brightness_Temp_H",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Passive_Brightness_Temp_H/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Active_Passive_Brightness_Temp_V": {
"title": "SMAP_L3_Active_Passive_Brightness_Temp_V",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Active_Passive_Brightness_Temp_V/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L3_Passive_Brightness_Temp_V": {
"title": "SMAP_L3_Passive_Brightness_Temp_V",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L3_Passive_Brightness_Temp_V/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Analyzed_Root_Zone_Soil_Moisture": {
"title": "SMAP_L4_Analyzed_Root_Zone_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Analyzed_Root_Zone_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Analyzed_Surface_Soil_Moisture": {
"title": "SMAP_L4_Analyzed_Surface_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Analyzed_Surface_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Emult_Average": {
"title": "SMAP_L4_Emult_Average",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Emult_Average/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Frozen_Area": {
"title": "SMAP_L4_Frozen_Area",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Frozen_Area/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Mean_Gross_Primary_Productivity": {
"title": "SMAP_L4_Mean_Gross_Primary_Productivity",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Mean_Gross_Primary_Productivity/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Mean_Net_Ecosystem_Exchange": {
"title": "SMAP_L4_Mean_Net_Ecosystem_Exchange",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Mean_Net_Ecosystem_Exchange/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Mean_Heterotrophic_Respiration": {
"title": "SMAP_L4_Mean_Heterotrophic_Respiration",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Mean_Heterotrophic_Respiration/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Snow_Mass": {
"title": "SMAP_L4_Snow_Mass",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Snow_Mass/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Soil_Temperature_Layer_1": {
"title": "SMAP_L4_Soil_Temperature_Layer_1",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Soil_Temperature_Layer_1/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Uncertainty_Analyzed_Root_Zone_Soil_Moisture": {
"title": "SMAP_L4_Uncertainty_Analyzed_Root_Zone_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Uncertainty_Analyzed_Root_Zone_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Uncertainty_Analyzed_Surface_Soil_Moisture": {
"title": "SMAP_L4_Uncertainty_Analyzed_Surface_Soil_Moisture",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Uncertainty_Analyzed_Surface_Soil_Moisture/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": true
},
"SMAP_L4_Uncertainty_Mean_Net_Ecosystem_Exchange": {
"title": "SMAP_L4_Uncertainty_Mean_Net_Ecosystem_Exchange",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/SMAP_L4_Uncertainty_Mean_Net_Ecosystem_Exchange/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 6,
"date": false
},
"VIIRS_CityLights_2012": {
"title": "VIIRS_CityLights_2012",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_CityLights_2012/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 8,
"date": false
},
"VIIRS_SNPP_DayNightBand_ENCC": {
"title": "VIIRS_SNPP_DayNightBand_ENCC",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_DayNightBand_ENCC/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 8,
"date": true
},
"VIIRS_SNPP_CorrectedReflectance_TrueColor": {
"title": "VIIRS_SNPP_CorrectedReflectance_TrueColor",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1": {
"title": "VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
},
"VIIRS_SNPP_CorrectedReflectance_BandsM3-I3-M11": {
"title": "VIIRS_SNPP_CorrectedReflectance_BandsM3-I3-M11",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_BandsM3-I3-M11/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg",
"zoom": 9,
"date": true
}
};
L.GIBS_MASKS = {
"MODIS_Terra_Data_No_Data": {
"title": "MODIS_Terra_Data_No_Data",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_Data_No_Data/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 9,
"date": true
},
"MODIS_Aqua_Data_No_Data": {
"title": "MODIS_Aqua_Data_No_Data",
"template": "http://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Aqua_Data_No_Data/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
"zoom": 9,
"date": true
}
};<file_sep>/README.md
# Sophia10.github.io
some content
| 9f9862f39128d26549c582c370ea135d17ed2657 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Sophia10/Sophia10.github.io | 083ca7819a361aae996858c00ad7f590c7cd9a44 | 74c99e095fdc14b90905bfc7f43b065b8e2937ef | |
refs/heads/master | <file_sep>package com.letsrace.game.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.letsrace.game.FRConstants;
import com.letsrace.game.LetsRace;
public class FRWaitScreen extends ScreenAdapter{
private LetsRace gameRef;
private final static float ROTATION = 40;
private final static float DURATION = 0.65f;
public FRWaitScreen(LetsRace letsRace) {
Gdx.app.log(FRConstants.TAG, "Wait: Constructor");
gameRef = letsRace;
gameRef.stage.clear();
Gdx.input.setInputProcessor(gameRef.stage);
Image image = new Image(gameRef.skin.getDrawable("background"));
image.setWidth(Gdx.graphics.getWidth());
image.setHeight(Gdx.graphics.getHeight());
image.setZIndex(1);
gameRef.stage.addActor(image);
Image steering = new Image(gameRef.skin.getDrawable("wait-screen-steer"));
steering.setWidth(210 * FRConstants.GUI_SCALE_WIDTH);
steering.setHeight(210 * FRConstants.GUI_SCALE_WIDTH);
steering.setPosition(Gdx.graphics.getWidth()/2 - steering.getWidth()/2, Gdx.graphics.getHeight()/2 - steering.getHeight()/2);
steering.setOrigin(steering.getWidth()/2,steering.getHeight()/2);
steering.addAction(Actions.forever(Actions.sequence(Actions.rotateBy(ROTATION,DURATION),Actions.rotateBy(-2*ROTATION,DURATION*2),Actions.rotateBy(ROTATION,DURATION),Actions.rotateBy(ROTATION*4,DURATION),Actions.rotateBy(-ROTATION*4,DURATION))));
gameRef.stage.addActor(steering);
}
public void show(){
Gdx.app.log(FRConstants.TAG, "Wait: show()");
// Throwing stuff in constructor as loading stuff in show() causes black screen
}
@Override
public void render(float delta) {
GL20 gl = Gdx.gl;
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameRef.stage.act(delta);
gameRef.stage.draw();
}
public void dispose() {
Gdx.app.log(FRConstants.TAG, "Wait: dispose()");
}
}
<file_sep>package com.letsrace.game.screen;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.letsrace.game.CameraTweenAccessor;
import com.letsrace.game.FRConstants;
import com.letsrace.game.LetsRace;
import com.letsrace.game.Message;
import com.letsrace.game.FRConstants.GameState;
import com.letsrace.game.network.FRMessageCodes;
import com.letsrace.game.unused.FRAssets;
public class FRArenaSelectScreen extends ScreenAdapter implements
GestureListener {
LetsRace gameRef;
SpriteBatch batch;
Camera camera;
Vector3 touchPoint;
ArrayList<String> arenaNames;
int currentPosition = 1;
Sprite logo;
Sprite heading;
Sprite trackOverview;
Sprite arrow;
Sprite background;
Sprite endHint;
TweenManager tweenMgr;
GestureDetector gesture;
float camHalfWidth;
float camHalfHeight;
enum State {
WAITING_FOR_SERVER, IS_SERVER_SELECT_ARENA
}
private boolean isAnimating = false;
private boolean showLeft = false, showRight = false;
private State screenState;
public FRArenaSelectScreen(LetsRace letsRace) {
Gdx.app.log(FRConstants.TAG, "ArenaSelect: Constructor");
gameRef = letsRace;
gameRef.stage.clear();
batch = new SpriteBatch();
camera = new OrthographicCamera(6, 10);
camHalfWidth = camera.viewportWidth / 2f;
camHalfHeight = camera.viewportHeight / 2f;
camera.position.set(currentPosition * camHalfWidth, camHalfHeight, 0);
camera.update();
batch.setProjectionMatrix(camera.combined);
touchPoint = new Vector3();
if (gameRef.isServer()) {
screenState = State.IS_SERVER_SELECT_ARENA;
tweenMgr = new TweenManager();
gesture = new GestureDetector(this);
Gdx.input.setInputProcessor(gesture);
Tween.registerAccessor(Camera.class, new CameraTweenAccessor());
loadNames();
} else {
screenState = State.WAITING_FOR_SERVER;
}
}
private void loadNames() {
arenaNames = new ArrayList<String>();
FileHandle handle = Gdx.files.internal("arenaNames.txt");
if (handle.exists()) {
BufferedReader input = new BufferedReader(new InputStreamReader(
handle.read()));
String name;
try {
while ((name = input.readLine()) != null) {
arenaNames.add(name);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void render(float delta) {
GL20 gl = Gdx.gl;
gl.glClearColor(0.8f, 0.8f, 0.8f, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
switch (screenState) {
case IS_SERVER_SELECT_ARENA:
updateSelect(delta);
renderSelect(delta);
break;
case WAITING_FOR_SERVER:
updateWaiting(delta);
renderWaiting(delta);
break;
}
}
private void renderWaiting(float delta) {
batch.begin();
background = FRAssets.background;
background.setSize(camHalfWidth * 2, camHalfHeight * 2);
background.setPosition(0, 0);
background.draw(batch);
batch.end();
}
private void updateWaiting(float delta) {
Message msg;
while ((msg = gameRef.network.readFromClientQueue()) != null) {
if (msg.msg[0] == FRMessageCodes.ARENA_SELECTED) {
gameRef.setUpArena((int) msg.msg[1]);
gameRef.moveToScreen(GameState.SELECT_CAR);
}
}
}
private void renderSelect(float delta) {
tweenMgr.update(delta);
batch.begin();
endHint = FRAssets.arenaScreenAtlas.createSprite("endHint");
renderTile(currentPosition);
renderTile(currentPosition - 1);
renderTile(currentPosition + 1);
endHint.setSize(camHalfWidth * 2, camHalfHeight * 2);
endHint.setPosition((currentPosition - 1) * camHalfWidth * 2, 0);
if (showLeft) {
endHint.draw(batch);
}
if (showRight) {
endHint.flip(true, false);
endHint.draw(batch);
}
batch.end();
}
private void updateSelect(float delta) {
Message msg;
while ((msg = gameRef.network.readFromClientQueue()) != null) {
if (msg.msg[0] == FRMessageCodes.ARENA_SELECTED) {
gameRef.setUpArena((int) msg.msg[1]);
gameRef.moveToScreen(GameState.SELECT_CAR);
}
}
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean tap(float x, float y, int count, int button) {
byte message[] = new byte[2];
message[0] = FRMessageCodes.ARENA_SELECTED;
message[1] = (byte) currentPosition;
gameRef.network.sendToClient(new Message(message, ""));
return true;
}
@Override
public boolean longPress(float x, float y) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
if (velocityX > 5f) {
moveLeft();
} else if (velocityX < -5f) {
moveRight();
}
return false;
}
private void moveLeft() {
Gdx.app.log(FRConstants.TAG, "Move Left !");
if (currentPosition > 1) {
currentPosition = currentPosition - 1;
Tween.to(camera, CameraTweenAccessor.POSITION, 1.0f)
.target((currentPosition - 1) * camHalfWidth * 2
+ camHalfWidth, camHalfHeight)
.setCallback(myCallBack)
.setCallbackTriggers(TweenCallback.END).start(tweenMgr);
isAnimating = true;
} else {
showLeft = true;
Timer.schedule(new Task() {
public void run() {
showLeft = false;
}
}, 0.3f);
}
}
private void moveRight() {
Gdx.app.log(FRConstants.TAG, "Move Right !");
if (currentPosition < arenaNames.size()) {
currentPosition = currentPosition + 1;
Tween.to(camera, CameraTweenAccessor.POSITION, 1.0f)
.target((currentPosition - 1) * camHalfWidth * 2
+ camHalfWidth, camHalfHeight)
.setCallback(myCallBack)
.setCallbackTriggers(TweenCallback.END).start(tweenMgr);
isAnimating = true;
} else {
showRight = true;
Timer.schedule(new Task() {
public void run() {
showRight = false;
}
}, 0.3f);
}
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
return false;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
Vector2 pointer1, Vector2 pointer2) {
return false;
}
private void renderTile(int pos) {
if (pos < 1 || pos > arenaNames.size()) {
return;
} else {
batch.setProjectionMatrix(camera.combined);
String name = arenaNames.get(pos - 1);
logo = FRAssets.arenaScreenAtlas.createSprite(name + "Logo");
heading = FRAssets.arenaScreenAtlas.createSprite(name + "Heading");
trackOverview = FRAssets.arenaScreenAtlas.createSprite(name
+ "Track");
float xOffset = (pos - 1) * camHalfWidth * 2;
background = FRAssets.background;
background.setSize(camHalfWidth * 2, camHalfHeight * 2);
background.setPosition(xOffset, 0);
arrow = FRAssets.arenaScreenAtlas.createSprite("nextArrow");
heading.setSize(5, 1);
heading.setPosition(0.5f + xOffset, 8);
logo.setSize(5, 4);
logo.setPosition(1 + xOffset, 3.5f);
trackOverview.setSize(3.5f, 2.0f);
trackOverview.setPosition(xOffset + 1.25f, 1.0f);
background.draw(batch);
heading.draw(batch);
logo.draw(batch);
trackOverview.draw(batch);
if (!isAnimating) {
arrow.setSize(0.5f, 1.2f);
if (currentPosition > 1) {
arrow.setPosition(xOffset + 0.2f, camHalfHeight);
arrow.draw(batch);
}
if (currentPosition < arenaNames.size()) {
arrow.flip(true, false);
arrow.setPosition(xOffset + 0.2f + 5f, camHalfHeight);
arrow.draw(batch);
}
}
}
}
TweenCallback myCallBack = new TweenCallback() {
public void onEvent(int type, BaseTween<?> source) {
isAnimating = false;
}
};
}<file_sep>package com.letsrace.game;
import com.badlogic.gdx.Gdx;
public class FRConstants {
public final static int PIXELS_PER_UNIT = 16;
public enum GameState {
SPLASH,SPLASH_SIGN_IN, MENU, WAIT, SELECT_CAR, GAME_SCREEN, CAR_SELECT,MULTIPLAYER_MENU,ARENA_SELECT,PLAYER_WAITING};
public final static int GUI_WIDTH = 480;
public final static int GUI_HIEGHT = 800;
public static float GUI_SCALE_WIDTH;
public static final String TAG = "Lets-Race!";
public static void initializeDynamicConstants(){
GUI_SCALE_WIDTH = ((float)Gdx.graphics.getWidth()/GUI_WIDTH);
}
}
<file_sep>package com.letsrace.game.network;
public interface FRMessageListener {
public void onMessageRecieved(byte[] buffer, String participantId);
}
<file_sep>package com.letsrace.game.network;
import com.letsrace.game.GameWorld;
import com.letsrace.game.LetsRace;
public class Server {
GameWorld world;
LetsRace gameRef;
enum ServerState {
WAITING_FOR_ARENA_SELECT,
CAR_SELECT,
}
}
<file_sep>package com.letsrace.game;
import java.util.HashMap;
import java.util.Set;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.letsrace.game.car.Car;
import com.letsrace.game.map.FRMapHandler;
public class GameWorld {
public World physicalWorld;
public HashMap<String, Player> players;
public String arenaName;
public FRMapHandler mapHandler;
public int numberOfPlayers;
int arenaNumber;
public GameWorld() {
this.physicalWorld = new World(new Vector2(0.0f, 0.0f), true);
this.players = new HashMap<String, Player>();
this.numberOfPlayers = 0;
}
public void setUpArena(String arenaName) {
mapHandler = new FRMapHandler(physicalWorld,
"beach_track_draft_two.tmx");
}
public void addPlayer(String id, String name, int playerType) {
if (!players.containsKey(id)) {
Player newPlayer = new Player();
newPlayer.name = name;
newPlayer.playerType = playerType;
players.put(id, new Player());
numberOfPlayers += 1;
}
}
public void setUpCars() {
Set keySet = players.keySet();
int index = 0;
for (Object key : keySet) {
Player player = players.get(key);
Vector2 initialPosition = mapHandler
.getInitialPositionForNumber(index);
player.car = new Car(physicalWorld, 3, 4, initialPosition, 0.0f,
40, 20, 60, "hummer");
index += 1;
}
}
}
<file_sep>package com.letsrace.game.network;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Set;
import com.letsrace.game.GameWorld;
import com.letsrace.game.Player;
import com.letsrace.game.car.Car;
public class ServerUtils {
public static boolean isCarSelected(GameWorld world, int number) {
Set keySet = world.players.keySet();
for (Object key : keySet) {
Player player = world.players.get(key);
if (player.playerType == number) {
return true;
}
}
return false;
}
public static void updateCars(GameWorld world, float delta){
Set keySet = world.players.keySet();
for (Object key : keySet) {
Car car = world.players.get(key).car;
car.update(delta);
}
}
public static byte[] generateCarSyncMessage(GameWorld gameWorld,
ArrayList<String> participantIds) {
int ctr = 0;
byte playerNumber = 0;
byte[] message = new byte[1 + participantIds.size() * 21];
message[ctr++] = FRMessageCodes.SYNC_CARS;
for (String participantId : participantIds) {
Car c = gameWorld.players.get(participantId).car;
message[ctr++] = playerNumber++;
byte[] posX = ByteBuffer.allocate(4)
.putFloat(c.getWorldPosition().x).array();
for (int i = 0; i < 4; i++)
message[ctr++] = posX[i];
byte[] posY = ByteBuffer.allocate(4)
.putFloat(c.getWorldPosition().y).array();
for (int i = 0; i < 4; i++)
message[ctr++] = posY[i];
byte[] wAngle = ByteBuffer.allocate(4).putFloat(c.wheelAngle)
.array();
for (int i = 0; i < 4; i++)
message[ctr++] = wAngle[i];
byte[] cBodyAngle = ByteBuffer.allocate(4)
.putFloat(c.getBodyAngle()).array();
for (int i = 0; i < 4; i++)
message[ctr++] = cBodyAngle[i];
byte[] cSpeed = ByteBuffer.allocate(4).putFloat(c.getSpeedKMH())
.array();
for (int i = 0; i < 4; i++)
message[ctr++] = cSpeed[i];
}
return message;
}
}
<file_sep>Lets-Race
=========
New repo for versus-racer - multiplayer racing game based on libgdx
<file_sep>package com.letsrace.game.map;
import static com.letsrace.game.FRConstants.PIXELS_PER_UNIT;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
public class FRMapHandler{
public MapBodyManager manager;
public TiledMap tiledMap;
public World physicalWorldRef;
public Vector2[] initialPositionMarkers;
public FRAngleMonitor angleMon=new FRAngleMonitor(0.5f);
public Body mainCarBody;
public FRMapHandler(World physicalWorld,String arenaName){
this.physicalWorldRef = physicalWorld;
tiledMap = new TmxMapLoader().load(arenaName);
manager = new MapBodyManager(physicalWorld, PIXELS_PER_UNIT, null, 0);
manager.createPhysics(tiledMap);
initialPositionMarkers = manager.getInitialPosition(tiledMap);
}
public void setupContactListener(Body mainCarBody){
this.mainCarBody = mainCarBody;
physicalWorldRef.setContactListener(new ContactListener() {
public Vector2 lastBodyVector= new Vector2(0,0);
public void preSolve(Contact contact, Manifold oldManifold) {}
public void postSolve(Contact contact, ContactImpulse impulse) {}
public void endContact(Contact contact) {}
public void beginContact(Contact contact) {
if(contact.getFixtureA().getBody() == FRMapHandler.this.mainCarBody||contact.getFixtureB().getBody() == FRMapHandler.this.mainCarBody){
MarkerBody mb = manager.fetchMarkerBody(contact.getFixtureB().getBody());
if(mb != null || (mb=manager.fetchMarkerBody(contact.getFixtureA().getBody()))!=null){
angleMon.setTurnAngle(mb.direction.angle(lastBodyVector));
lastBodyVector = mb.direction;
}
}
}
});
}
public Vector2 getInitialPositionForNumber(int index){
return initialPositionMarkers[index];
}
}
<file_sep>package com.letsrace.game.network;
import java.util.ArrayList;
public interface FRGoogleServices {
void initiateSignIn();
void startQuickGame();
public ArrayList<String> getParticipantIds();
public String getMyId();
public void setServerListener(FRMessageListener listener);
public void setClientListener(FRMessageListener listener);
public void sendReliableMessage(byte[] message, String participantID);
public void broadcastMessage(byte[] message);
public void broadcastReliableMessage(byte[] message);
public boolean isSignedIn();
public String getSinglePlayerIds();
}
<file_sep>package com.letsrace.game;
import static com.letsrace.game.FRConstants.PIXELS_PER_UNIT;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.letsrace.game.car.Car;
import com.letsrace.game.map.OrthogonalTiledMapRenderer;
public class GameRenderer {
GameWorld worldRef;
Box2DDebugRenderer debugRenderer;
OrthographicCamera cam;
SpriteBatch batch;
TiledMapRenderer tiledMapRenderer;
Car myCar;
public GameRenderer(GameWorld world, Batch batch, Car myCar) {
worldRef = world;
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
this.cam = new OrthographicCamera(PIXELS_PER_UNIT * 20, PIXELS_PER_UNIT
* 20 * h / w);
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
debugRenderer = new Box2DDebugRenderer();
tiledMapRenderer = new OrthogonalTiledMapRenderer(world.mapHandler.tiledMap, batch);
this.myCar = myCar;
}
public void render() {
cam.update();
cam.rotate(worldRef.mapHandler.angleMon.getTurnAngle());
cam.position.set(myCar.getWorldPosition().x * PIXELS_PER_UNIT,myCar.getWorldPosition().y * PIXELS_PER_UNIT, 0);
tiledMapRenderer.setView(cam);
tiledMapRenderer.render();
Matrix4 debugMat = new Matrix4(cam.combined);
debugMat.scale(PIXELS_PER_UNIT, PIXELS_PER_UNIT, 1f);
debugRenderer.render(worldRef.physicalWorld, debugMat);
}
}
<file_sep>package com.letsrace.game.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.letsrace.game.FRConstants;
import com.letsrace.game.FRConstants.GameState;
import com.letsrace.game.LetsRace;
public class FRSplashScreen extends ScreenAdapter {
private LetsRace gameRef;
public FRSplashScreen(LetsRace game) {
Gdx.app.log(FRConstants.TAG, "FRSplash: Constructor");
gameRef = game;
Gdx.input.setInputProcessor(gameRef.stage);
Image image = new Image(gameRef.skin.getDrawable("fr."));
image.setSize(image.getWidth()*FRConstants.GUI_SCALE_WIDTH,image.getHeight()*FRConstants.GUI_SCALE_WIDTH);
image.setPosition((Gdx.graphics.getWidth()-image.getWidth())/2, (Gdx.graphics.getHeight()-image.getHeight())/2);
gameRef.stage.addActor(image);
}
public void show() {
Gdx.app.log(FRConstants.TAG, "FRSplash: Show()");
Timer.schedule(new Task() {
@Override
public void run() {
gameRef.moveToScreen(GameState.MENU);
}
}, 3);
}
@Override
public void render(float delta) {
GL20 gl = Gdx.gl;
gl.glClearColor(0, 0, 0, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameRef.stage.draw();
}
public void dispose() {
Gdx.app.log(FRConstants.TAG, "Splash: Dispose()");
}
}
<file_sep>package com.letsrace.game.unused;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.letsrace.game.Animation;
public class FRAssets {
public static TextureAtlas uiButtonsAtlas;
public static Sprite singleplayerButton;
public static Sprite multiplayerButton;
public static Sprite quickraceButton;
public static Sprite invitefriendsButton;
public static Sprite checkInvitesButton;
public static Sprite settingsIcon;
public static Sprite frIcon;
public static Sprite background;
public static Sprite signIn;
public static Sprite signInPressed;
public static TextureAtlas arenaScreenAtlas;
public static TextureAtlas playerAsset;
public static TextureAtlas carScreenAtlas;
public static Animation explosion;
public static Sprite cannister;
public static Sprite vaderFullCar;
public static Sprite firedMissile;
public static Sprite vaderCarBody;
public static Animation wheel;
public static Sprite powerBar;
public static Sprite accnBar;
public static Sprite steeringBar;
public static void load() {
uiButtonsAtlas = new TextureAtlas("ui/ui_icons.pack");
playerAsset = new TextureAtlas("ui/playerAssetsAtlas.txt");
carScreenAtlas = new TextureAtlas("ui/carScreenAtlas.txt");
powerBar = carScreenAtlas.createSprite("powerBar");
steeringBar=carScreenAtlas.createSprite("steeringBar");
accnBar=carScreenAtlas.createSprite("accelerationBar");
explosion = new Animation(false, 1 / 60f, playerAsset, "explosion", 41);
cannister = playerAsset.createSprite("cannister", 1);
vaderFullCar = playerAsset.createSprite("vaderCar_NoWeapon");
firedMissile = playerAsset.createSprite("missileFired");
vaderCarBody = playerAsset.createSprite("vaderCarBody");
wheel = new Animation(true, 1 / 7f, playerAsset, "wheel", 2);
/*
* singleplayerButton =
* uiButtonsAtlas.createSprite("singlePlayerButton"); multiplayerButton
* = uiButtonsAtlas.createSprite("multiplayerButton"); quickraceButton =
* uiButtonsAtlas.createSprite("quickRaceButton"); invitefriendsButton =
* uiButtonsAtlas .createSprite("inviteFriendsButton");
* checkInvitesButton =
* uiButtonsAtlas.createSprite("checkInvitesButton"); settingsIcon =
* uiButtonsAtlas.createSprite("settingsIcon"); frIcon =
* uiButtonsAtlas.createSprite("fr."); background =
* uiButtonsAtlas.createSprite("background"); signIn
* =uiButtonsAtlas.createSprite("signIn"); signInPressed =
* uiButtonsAtlas.createSprite("signInPressed");
*/
background = uiButtonsAtlas.createSprite("background");
arenaScreenAtlas = new TextureAtlas("ui/arenaScreenUI.txt");
}
public static void dispose() {
if (uiButtonsAtlas != null)
uiButtonsAtlas.dispose();
}
}
<file_sep>package com.letsrace.game.car;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.letsrace.game.car.Wheel.WheelType;
public class Car {
public Body body;
public float width, length, angle, maxSteerAngle, maxSpeed, maxRevSpeed, power;
public float wheelAngle;
public Steer steer;
public Accel accelerate;
public List<Wheel> wheels;
Vector2 origin;
public enum Steer {
NONE, LEFT, RIGHT
};
public enum Accel {
NONE, ACCELERATE, BRAKE
};
public Car(World world, float width, float length, Vector2 position,
float angle, float power, float maxSteerAngle, float maxSpeed,
String jsonFilePrefix) {
super();
this.steer = Steer.NONE;
this.accelerate = Accel.NONE;
this.width = width;
this.length = length;
this.angle = angle;
this.maxSteerAngle = maxSteerAngle;
this.maxSpeed = maxSpeed;
this.maxRevSpeed = maxSpeed / 2;
this.power = power;
this.wheelAngle = 0;
BodyEditorLoader loader = new BodyEditorLoader(
Gdx.files.internal(jsonFilePrefix + "-normal.json"));
// init body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(position);
bodyDef.angle = angle;
this.body = world.createBody(bodyDef);
origin = loader.getOrigin("Name", width);
// init shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.6f; // friction when rubbing against other
// shapes
fixtureDef.restitution = 0.4f; // amount of force feedback when hitting
// something. >0 makes the car bounce
// off, it's fun!
loader.attachFixture(this.body, "Name", fixtureDef, this.width);
// initialize wheels
this.wheels = new ArrayList<Wheel>();
this.wheels.add(new Wheel(world, this, this.width, false, false,
jsonFilePrefix, WheelType.BOTTOM_LEFT)); // top left
this.wheels.add(new Wheel(world, this, this.width, false, false,
jsonFilePrefix, WheelType.BOTTOM_RIGHT)); // top right
this.wheels.add(new Wheel(world, this, this.width, true, true,
jsonFilePrefix, WheelType.TOP_LEFT)); // back left
this.wheels.add(new Wheel(world, this, this.width, true, true,
jsonFilePrefix, WheelType.TOP_RIGHT)); // back right
}
public List<Wheel> getPoweredWheels() {
List<Wheel> poweredWheels = new ArrayList<Wheel>();
for (Wheel wheel : this.wheels) {
if (wheel.powered)
poweredWheels.add(wheel);
}
return poweredWheels;
}
public Vector2 getLocalVelocity() {
/*
* returns car's velocity vector relative to the car
*/
return this.body.getLocalVector(this.body
.getLinearVelocityFromLocalPoint(new Vector2(0, 0)));
}
public Vector2 getWorldPosition() {
return this.body.getPosition();
}
public float getRotation() {
return this.body.getAngle();
}
public List<Wheel> getRevolvingWheels() {
List<Wheel> revolvingWheels = new ArrayList<Wheel>();
for (Wheel wheel : this.wheels) {
if (wheel.revolving)
revolvingWheels.add(wheel);
}
return revolvingWheels;
}
public float getSpeedKMH() {
Vector2 velocity = this.body.getLinearVelocity();
float len = velocity.len();
return (len / 1000) * 3600;
}
public float getBodyAngle(){
return this.body.getAngle();
}
public void setSpeed(float speed) {
/*
* speed - speed in kilometers per hour
*/
Vector2 velocity = this.body.getLinearVelocity();
velocity = velocity.nor();
velocity = new Vector2(velocity.x * ((speed * 1000.0f) / 3600.0f),
velocity.y * ((speed * 1000.0f) / 3600.0f));
this.body.setLinearVelocity(velocity);
}
public void update(float deltaTime) {
// 1. KILL SIDEWAYS VELOCITY
for (Wheel wheel : wheels) {
wheel.killSidewaysVelocity();
}
// 2. SET WHEEL ANGLE
// calculate the change in wheel's angle for this update
float incr = (this.maxSteerAngle) * deltaTime * 5;
if (this.steer == Steer.LEFT) {
this.wheelAngle = Math.min(Math.max(this.wheelAngle, 0) + incr,
this.maxSteerAngle); // increment angle without going over
// max steer
} else if (this.steer == Steer.RIGHT) {
this.wheelAngle = Math.max(Math.min(this.wheelAngle, 0) - incr,
-this.maxSteerAngle); // decrement angle without going over
// max steer
} else {
this.wheelAngle = 0;
}
// update revolving wheels
for (Wheel wheel : this.getRevolvingWheels()) {
wheel.setAngle(this.wheelAngle);
}
// 3. APPLY FORCE TO WHEELS
Vector2 baseVector = new Vector2(0, 0); // vector pointing in the
// direction force will be
// applied to a wheel ; relative to the wheel.
// if accelerator is pressed down and speed limit has not been reached,
// go forwards
if ((this.accelerate == Accel.ACCELERATE)
&& (this.getSpeedKMH() < this.maxSpeed)) {
baseVector = new Vector2(0, 1);
} else if (this.accelerate == Accel.BRAKE) {
// braking, but still moving forwards - increased force
if (this.getLocalVelocity().y > 0) {
baseVector = new Vector2(0f, -1.3f);
}
// going in reverse - less force
else if ((this.getSpeedKMH() < this.maxRevSpeed))
baseVector = new Vector2(0f, -0.7f);
} else if (this.accelerate == Accel.NONE) {
// slow down if not accelerating
baseVector = new Vector2(0, 0);
if (this.getSpeedKMH() < 7)
this.setSpeed(0);
else if (this.getLocalVelocity().y > 0)
baseVector = new Vector2(0, -0.7f);
else if (this.getLocalVelocity().y < 0)
baseVector = new Vector2(0, +0.7f);
} else
baseVector = new Vector2(0, 0);
// multiply by engine power, which gives us a force vector relative to
// the wheel
Vector2 forceVector = new Vector2(this.power * baseVector.x, this.power
* baseVector.y);
// apply force to each wheel
for (Wheel wheel : this.getPoweredWheels()) {
Vector2 position = wheel.body.getWorldCenter();
wheel.body.applyForce(wheel.body.getWorldVector(new Vector2(
forceVector.x, forceVector.y)), position, true);
}
}
public void setTransform(float posX, float posY, float cBodyAngle) {
this.body.setTransform(posX, posY, cBodyAngle);
}
}
<file_sep>package com.letsrace.game;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.letsrace.game.FRConstants.GameState;
import com.letsrace.game.network.FRGameClient;
import com.letsrace.game.network.FRGameServer;
import com.letsrace.game.network.FRGoogleServices;
import com.letsrace.game.network.FRNetwork;
import com.letsrace.game.screen.CarSelectScreen;
import com.letsrace.game.screen.FRArenaSelectScreen;
import com.letsrace.game.screen.FRGameScreen;
import com.letsrace.game.screen.FRMenuScreen;
import com.letsrace.game.screen.FRMultiplayerMenuScreen;
import com.letsrace.game.screen.FRSplashScreen;
import com.letsrace.game.screen.FRWaitScreen;
import com.letsrace.game.screen.FRWaitingForPlayerScreen;
import com.letsrace.game.screen.GameScreen;
import com.letsrace.game.unused.FRAssets;
public class LetsRace extends Game {
public GameState gameState;
public BitmapFont font;
public FRGoogleServices googleServices;
public Stage stage;
public Camera guicam;
public SpriteBatch batch;
public Skin skin;
public HashMap<String, Integer> playerNumber;
public int myPlayerNo;
public FRGameClient client;
public boolean multiplayer;
public FRNetwork network;
public String serverId;
public String myId;
public String arenaName;
public GameWorld serverWorld;
public GameWorld clientWorld;
public void setServerId(String serverId) {
this.serverId = serverId;
}
public void setMyId(String myId) {
this.myId = myId;
}
public void setArenaName(String arenaName) {
this.arenaName = arenaName;
}
public boolean isServer() {
if (serverId == null || myId == null) {
return false;
}
return myId.equals(serverId);
}
public LetsRace(FRGoogleServices services) {
googleServices = services;
playerNumber = new HashMap<String, Integer>();
network = new FRNetwork(this);
}
public void setUpWorlds() {
if (isServer()) {
serverWorld = new GameWorld();
clientWorld = new GameWorld();
for (String id : this.googleServices.getParticipantIds()) {
serverWorld.addPlayer(id, id, -1);
clientWorld.addPlayer(id, id, -1);
}
} else {
clientWorld = new GameWorld();
for (String id : googleServices.getParticipantIds()) {
clientWorld.addPlayer(id, id, -1);
}
}
}
public void setUpArena(int arenaNumber) {
if (isServer()) {
this.serverWorld.arenaNumber = arenaNumber;
this.serverWorld.setUpArena(arenaName);
this.clientWorld.arenaNumber = arenaNumber;
this.clientWorld.setUpArena(arenaName);
} else {
this.clientWorld.arenaNumber = arenaNumber;
this.clientWorld.setUpArena(arenaName);
}
}
public void setUpCars() {
if (isServer()) {
this.serverWorld.setUpCars();
this.clientWorld.setUpCars();
} else {
this.clientWorld.setUpCars();
}
}
public void decideOnServerAndStart() {
ArrayList<String> list = googleServices.getParticipantIds();
String[] participants = list.toArray(new String[list.size()]);
Arrays.sort(participants);
if (participants[0] == googleServices.getMyId()) {
Gdx.app.log(FRConstants.TAG, "I am the server");
FRGameServer server = new FRGameServer(this, participants);
googleServices.setServerListener(server);
}
int ctr = 0;
for (String s : participants) {
playerNumber.put(s, ctr++);
}
myPlayerNo = playerNumber.get(googleServices.getMyId());
Gdx.app.log(FRConstants.TAG, "I am the client - P" + myPlayerNo);
client = new FRGameClient(this, participants[0]);
Gdx.app.log(FRConstants.TAG, "Setting Client Listener");
googleServices.setClientListener(client);
Gdx.app.log(FRConstants.TAG, "Moving to car-select screen");
moveToScreen(GameState.SELECT_CAR);
}
@Override
public void create() {
font = new BitmapFont();
skin = new Skin(new TextureAtlas("ui/ui_icons.pack"));
stage = new Stage();
guicam = new OrthographicCamera();
batch = new SpriteBatch();
FRConstants.initializeDynamicConstants();
FRAssets.load();
moveToScreen(GameState.SPLASH);
}
@Override
public void render() {
super.render();
}
public void dispose() {
stage.dispose();
font.dispose();
}
public void moveToScreen(GameState screen) {
switch (screen) {
case GAME_SCREEN:
gameState = GameState.GAME_SCREEN;
setScreen(new GameScreen(this));
break;
case MENU:
gameState = GameState.MENU;
setScreen(new FRMenuScreen(this));
break;
case WAIT:
gameState = GameState.WAIT;
setScreen(new FRWaitScreen(this));
break;
case SELECT_CAR:
gameState = GameState.SELECT_CAR;
setScreen(new CarSelectScreen(this));
break;
case SPLASH:
gameState = GameState.SPLASH;
setScreen(new FRSplashScreen(this));
break;
case MULTIPLAYER_MENU:
gameState = GameState.MULTIPLAYER_MENU;
setScreen(new FRMultiplayerMenuScreen(this));
break;
case ARENA_SELECT:
gameState = GameState.ARENA_SELECT;
setScreen(new FRArenaSelectScreen(this));
break;
case PLAYER_WAITING:
gameState = GameState.PLAYER_WAITING;
setScreen(new FRWaitingForPlayerScreen(this));
break;
default:
break;
}
}
}
<file_sep>package com.letsrace.game.unused;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.letsrace.game.FRConstants;
import com.letsrace.game.LetsRace;
public class FROldSplashScreen extends ScreenAdapter{
private LetsRace gameRef;
public FROldSplashScreen(LetsRace game){
Gdx.app.log(FRConstants.TAG, "Splash: Constructor");
gameRef = game;
gameRef.stage.clear();
Gdx.input.setInputProcessor(gameRef.stage);
Image image = new Image(gameRef.skin.getDrawable("wait-screen-back"));
image.setWidth(Gdx.graphics.getWidth());
image.setHeight(Gdx.graphics.getHeight());
LabelStyle style = new LabelStyle(gameRef.font, Color.WHITE);
Label label = new Label("Signing in ...", style);
label.setPosition((Gdx.graphics.getWidth()-label.getWidth())/2,(Gdx.graphics.getHeight())/2+label.getHeight());
gameRef.stage.addActor(image);
gameRef.stage.addActor(label);
}
public void show(){
Gdx.app.log(FRConstants.TAG, "Splash: Show()");
// Throwing stuff in constructor as loading stuff in show() causes black screen
gameRef.googleServices.initiateSignIn();
}
@Override
public void render(float delta) {
GL20 gl = Gdx.gl;
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameRef.stage.draw();
}
public void dispose() {
Gdx.app.log(FRConstants.TAG, "Splash: Dispose()");
}
}
<file_sep>package com.letsrace.game.android;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesActivityResultCodes;
import com.google.android.gms.games.GamesStatusCodes;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.Multiplayer;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.Participant;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
import com.google.android.gms.games.multiplayer.realtime.Room;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateListener;
import com.google.android.gms.games.multiplayer.realtime.RoomUpdateListener;
import com.google.android.gms.plus.Plus;
import com.google.example.games.basegameutils.BaseGameUtils;
import com.letsrace.game.FRConstants.GameState;
import com.letsrace.game.LetsRace;
import com.letsrace.game.network.FRGoogleServices;
import com.letsrace.game.network.FRMessageListener;
import com.letsrace.game.screen.FRMultiplayerMenuScreen;
import com.letsrace.game.unused.FRAssets;
public class AndroidLauncher extends AndroidApplication implements
FRGoogleServices, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, RoomStatusUpdateListener,
RoomUpdateListener, OnInvitationReceivedListener {
/*
* API INTEGRATION SECTION. This section contains the code that integrates
* the game with the Google Play game services API.
*/
final static String TAG = "Lets-Race!";
// Request codes for the UIs that we show with startActivityForResult:
final static int RC_SELECT_PLAYERS = 10000;
final static int RC_INVITATION_INBOX = 10001;
final static int RC_WAITING_ROOM = 10002;
// Request code used to invoke sign in user interactions.
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
// Are we currently resolving a connection failure?
private boolean mResolvingConnectionFailure = false;
// Has the user clicked the sign-in button?
private boolean mSignInClicked = false;
// Set to true to automatically start the sign in flow when the Activity
// starts.
// Set to false to require the user to click the button in order to sign in.
private boolean mAutoStartSignInFlow = true;
// Room ID where the currently active game is taking place; null if we're
// not playing.
Room room;
// Are we playing in multiplayer mode?
boolean mMultiplayer = false;
// The participants in the currently active game
ArrayList<Participant> mParticipants = null;
// My participant ID in the currently active game
String mMyId = null;
// If non-null, this is the id of the invitation we received via the
// invitation listener
String mIncomingInvitationId = null;
// Message handler
FRMessageHandler messageHandler;
LetsRace game;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Google Api Client with access to Plus and Games
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).addApi(Games.API)
.addScope(Games.SCOPE_GAMES).build();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useAccelerometer = true;
config.useCompass = true;
game = new LetsRace(this);
messageHandler = new FRMessageHandler(game.network);
initialize(game, config);
}
public ArrayList<Participant> getmParticipants() {
return mParticipants;
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
public void initiateSignIn() {
// start the sign-in flow
Log.d(TAG, "Sign-in button clicked");
mSignInClicked = true;
mGoogleApiClient.connect();
}
public void invitePlayers() {
// show list of invitable players
Intent intent = Games.RealTimeMultiplayer.getSelectOpponentsIntent(
mGoogleApiClient, 1, 3);
game.moveToScreen(GameState.WAIT);
startActivityForResult(intent, RC_SELECT_PLAYERS);
}
public void showInvites() {
Intent intent = Games.Invitations
.getInvitationInboxIntent(mGoogleApiClient);
game.moveToScreen(GameState.WAIT);
startActivityForResult(intent, RC_INVITATION_INBOX);
}
public void startQuickGame() {
// quick-start a game with 1 randomly selected opponent
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
MIN_OPPONENTS, MAX_OPPONENTS, 0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(messageHandler);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
game.moveToScreen(GameState.WAIT);
Games.RealTimeMultiplayer.create(mGoogleApiClient,
rtmConfigBuilder.build());
}
@Override
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
Gdx.app.log(TAG, "On activity result: " + requestCode);
switch (requestCode) {
case RC_SELECT_PLAYERS:
// we got the result from the "select players" UI -- ready to create
// the room
handleSelectPlayersResult(responseCode, intent);
break;
case RC_INVITATION_INBOX:
// we got the result from the "select invitation" UI (invitation
// inbox). We're
// ready to accept the selected invitation:
handleInvitationInboxResult(responseCode, intent);
break;
case RC_WAITING_ROOM:
// we got the result from the "waiting room" UI.
if (responseCode == Activity.RESULT_OK) {
// ready to start playing
Log.d(TAG, "Starting game (waiting room returned OK).");
game.moveToScreen(GameState.GAME_SCREEN);
} else if (responseCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
// player indicated that they want to leave the room
leaveRoom();
game.moveToScreen(GameState.MENU);
} else if (responseCode == Activity.RESULT_CANCELED) {
// Dialog was cancelled (user pressed back key, for instance).
// In our game,
// this means leaving the room too. In more elaborate games,
// this could mean
// something else (like minimizing the waiting room UI).
leaveRoom();
game.moveToScreen(GameState.MENU);
}
break;
case RC_SIGN_IN:
Log.d(TAG,
"onActivityResult with requestCode == RC_SIGN_IN, responseCode="
+ responseCode + ", intent=" + intent);
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (responseCode == RESULT_OK) {
mGoogleApiClient.connect();
} else {
OnClickListener listener = new OnClickListener() {
Activity parentActivity = AndroidLauncher.this;
@Override
public void onClick(DialogInterface dialog, int which) {
parentActivity.finish();
}
};
BaseGameUtils.showActivityResultError(this, listener,
requestCode, responseCode, R.string.sign_in_error,
responseCode);
}
break;
}
super.onActivityResult(requestCode, responseCode, intent);
}
// Handle the result of the "Select players UI" we launched when the user
// clicked the
// "Invite friends" button. We react by creating a room with those players.
private void handleSelectPlayersResult(int response, Intent data) {
if (response != Activity.RESULT_OK) {
Log.w(TAG, "*** select players UI cancelled, " + response);
game.moveToScreen(GameState.MENU);
return;
}
Log.d(TAG, "Select players UI succeeded.");
// get the invitee list
final ArrayList<String> invitees = data
.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
Log.d(TAG, "Invitee count: " + invitees.size());
// get the automatch criteria
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0 || maxAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
Log.d(TAG, "Automatch criteria: " + autoMatchCriteria);
}
// create the room
Log.d(TAG, "Creating room...");
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.addPlayersToInvite(invitees);
rtmConfigBuilder.setMessageReceivedListener(messageHandler);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
if (autoMatchCriteria != null) {
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
}
game.moveToScreen(GameState.WAIT);
Games.RealTimeMultiplayer.create(mGoogleApiClient,
rtmConfigBuilder.build());
Log.d(TAG, "Room created, waiting for it to be ready...");
}
// Handle the result of the invitation inbox UI, where the player can pick
// an invitation
// to accept. We react by accepting the selected invitation, if any.
private void handleInvitationInboxResult(int response, Intent data) {
if (response != Activity.RESULT_OK) {
Log.w(TAG, "*** invitation inbox UI cancelled, " + response);
game.moveToScreen(GameState.MENU);
return;
}
Log.d(TAG, "Invitation inbox UI succeeded.");
Invitation inv = data.getExtras().getParcelable(
Multiplayer.EXTRA_INVITATION);
// accept invitation
acceptInviteToRoom(inv.getInvitationId());
}
// Accept the given invitation.
void acceptInviteToRoom(String invId) {
// accept the invitation
Log.d(TAG, "Accepting invitation: " + invId);
RoomConfig.Builder roomConfigBuilder = RoomConfig.builder(this);
roomConfigBuilder.setInvitationIdToAccept(invId)
.setMessageReceivedListener(messageHandler)
.setRoomStatusUpdateListener(this);
game.moveToScreen(GameState.WAIT);
Games.RealTimeMultiplayer.join(mGoogleApiClient,
roomConfigBuilder.build());
}
// Activity is going to the background. We have to leave the current room.
@Override
public void onStop() {
Log.d(TAG, "**** got onStop");
// if we're in a room, leave it.
leaveRoom();
super.onStop();
FRAssets.dispose();
}
// Activity just got to the foreground. We switch to the wait screen because
// we will now
// go through the sign-in flow (remember that, yes, every time the Activity
// comes back to the
// foreground we go through the sign-in flow -- but if the user is already
// authenticated,
// this flow simply succeeds and is imperceptible).
@Override
public void onStart() {
// TODO: Implement logic
// game.goToWaitScreen();
// if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
// Log.w(TAG, "GameHelper: client was already connected on onStart()");
// } else {
// Log.d(TAG, "Connecting client.");
// mGoogleApiClient.connect();
// }
super.onStart();
}
// Handle back key to make sure we cleanly leave a game if we are in the
// middle of one
@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& game.gameState == GameState.GAME_SCREEN) {
leaveRoom();
return true;
}
return super.onKeyDown(keyCode, e);
}
// Leave the room.
void leaveRoom() {
Log.d(TAG, "Leaving room.");
if (room != null) {
Games.RealTimeMultiplayer.leave(mGoogleApiClient, this,
room.getRoomId());
room = null;
}
}
// Show the waiting room UI to track the progress of other players as they
// enter the
// room and get connected.
void showWaitingRoom(Room room) {
// minimum number of players required for our game
// For simplicity, we require everyone to join the game before we start
// it
// (this is signaled by Integer.MAX_VALUE).
final int MIN_PLAYERS = Integer.MAX_VALUE;
Intent i = Games.RealTimeMultiplayer.getWaitingRoomIntent(
mGoogleApiClient, room, MIN_PLAYERS);
// show waiting room UI
startActivityForResult(i, RC_WAITING_ROOM);
}
// Called when we get an invitation to play a game. We react by showing that
// to the user.
@Override
public void onInvitationReceived(Invitation invitation) {
// We got an invitation to play a game! So, store it in
// mIncomingInvitationId
// and show the popup on the screen.
// TODO: implement this
}
@Override
public void onInvitationRemoved(String invitationId) {
if (mIncomingInvitationId.equals(invitationId)) {
mIncomingInvitationId = null;
}
// TODO: implement this
}
/*
* CALLBACKS SECTION. This section shows how we implement the several games
* API callbacks.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected() called. Sign in successful!");
Log.d(TAG, "Sign-in succeeded.");
// register listener so we are notified if we receive an invitation to
// play
// while we are in the game
Games.Invitations.registerInvitationListener(mGoogleApiClient, this);
if (connectionHint != null) {
Log.d(TAG,
"onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint
.getParcelable(Multiplayer.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// retrieve and cache the invitation ID
Log.d(TAG, "onConnected: connection hint has a room invite!");
acceptInviteToRoom(inv.getInvitationId());
return;
}
}
// TODO: Pop up already signed in
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
if (game.gameState == GameState.MULTIPLAYER_MENU) {
((FRMultiplayerMenuScreen) game.getScreen())
.enableSignedInButtons();
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended() called. Trying to reconnect.");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed() called, result: " + connectionResult);
if (mResolvingConnectionFailure) {
Log.d(TAG,
"onConnectionFailed() ignoring connection failure; already resolving.");
return;
}
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = BaseGameUtils
.resolveConnectionFailure(this, mGoogleApiClient,
connectionResult, RC_SIGN_IN,
getString(R.string.other_error));
}
// TODO: Quit game
}
// Called when we are connected to the room. We're not ready to play yet!
// (maybe not everybody
// is connected yet).
@Override
public void onConnectedToRoom(Room room) {
Log.d(TAG, "onConnectedToRoom.");
// get room ID, participants and my ID:
this.room = room;
mParticipants = room.getParticipants();
mMyId = room.getParticipantId(Games.Players
.getCurrentPlayerId(mGoogleApiClient));
// print out the list of participants (for debug purposes)
Log.d(TAG, "Room ID: " + room.getRoomId());
Log.d(TAG, "My ID " + mMyId);
Log.d(TAG, "<< CONNECTED TO ROOM >>");
}
// Called when we've successfully left the room (this happens a result of
// voluntarily leaving
// via a call to leaveRoom(). If we get disconnected, we get
// onDisconnectedFromRoom()).
@Override
public void onLeftRoom(int statusCode, String roomId) {
// we have left the room; return to main screen.
Log.d(TAG, "onLeftRoom, code " + statusCode);
game.moveToScreen(GameState.MENU);
}
// Called when we get disconnected from the room. We return to the main
// screen.
@Override
public void onDisconnectedFromRoom(Room room) {
room = null;
showGameError();
}
// Show error message about game being cancelled and return to main screen.
void showGameError() {
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
};
BaseGameUtils.makeSimpleDialog(this, getString(R.string.other_error),
listener).show();
}
// Called when room has been created
@Override
public void onRoomCreated(int statusCode, Room room) {
Log.d(TAG, "onRoomCreated(" + statusCode + ", " + room + ")");
if (statusCode != GamesStatusCodes.STATUS_OK) {
Log.e(TAG, "*** Error: onRoomCreated, status " + statusCode);
showGameError();
return;
}
// show the waiting room UI
showWaitingRoom(room);
}
// Called when room is fully connected.
@Override
public void onRoomConnected(int statusCode, Room room) {
Log.d(TAG, "onRoomConnected(" + statusCode + ", " + room + ")");
if (statusCode != GamesStatusCodes.STATUS_OK) {
Log.e(TAG, "*** Error: onRoomConnected, status " + statusCode);
showGameError();
return;
}
updateRoom(room);
}
@Override
public void onJoinedRoom(int statusCode, Room room) {
Log.d(TAG, "onJoinedRoom(" + statusCode + ", " + room + ")");
if (statusCode != GamesStatusCodes.STATUS_OK) {
Log.e(TAG, "*** Error: onRoomConnected, status " + statusCode);
showGameError();
return;
}
// show the waiting room UI
showWaitingRoom(room);
}
// We treat most of the room update callbacks in the same way: we update our
// list of
// participants and update the display. In a real game we would also have to
// check if that
// change requires some action like removing the corresponding player avatar
// from the screen,
// etc.
@Override
public void onPeerDeclined(Room room, List<String> arg1) {
updateRoom(room);
}
@Override
public void onPeerInvitedToRoom(Room room, List<String> arg1) {
updateRoom(room);
}
@Override
public void onP2PDisconnected(String participant) {
}
@Override
public void onP2PConnected(String participant) {
}
@Override
public void onPeerJoined(Room room, List<String> arg1) {
updateRoom(room);
}
@Override
public void onPeerLeft(Room room, List<String> peersWhoLeft) {
updateRoom(room);
}
@Override
public void onRoomAutoMatching(Room room) {
updateRoom(room);
}
@Override
public void onRoomConnecting(Room room) {
updateRoom(room);
}
@Override
public void onPeersConnected(Room room, List<String> peers) {
updateRoom(room);
}
@Override
public void onPeersDisconnected(Room room, List<String> peers) {
updateRoom(room);
}
void updateRoom(Room room) {
if (room != null) {
mParticipants = room.getParticipants();
}
}
public ArrayList<String> getParticipantIds() {
if (!game.multiplayer) {
ArrayList<String> local = new ArrayList<String>();
local.add("local");
return local;
} else {
ArrayList<String> participants = room.getParticipantIds();
participants.sort(new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
return participants;
}
}
public String getMyId() {
return mMyId;
}
public void sendReliableMessage(byte[] message, String participantID) {
if (participantID.equals(mMyId)) {
Gdx.app.log(TAG, "Manual trigger onRealTimeMessageRecieved()");
triggerMessageRecieveWithDelay(message);
} else
Games.RealTimeMultiplayer.sendReliableMessage(mGoogleApiClient,
null, message, room.getRoomId(), participantID);
}
public void broadcastMessage(byte[] message) {
for (Participant p : mParticipants) {
if (p.getParticipantId().equals(mMyId)) {
Gdx.app.log(TAG, "Manual trigger onRealTimeMessageRecieved()");
triggerMessageRecieveWithDelay(message);
} else
Games.RealTimeMultiplayer.sendUnreliableMessage(
mGoogleApiClient, message, room.getRoomId(),
p.getParticipantId());
}
}
@Override
public void broadcastReliableMessage(byte[] message) {
for (Participant p : mParticipants) {
if (p.getParticipantId().equals(mMyId)) {
Gdx.app.log(TAG, "Manual trigger onRealTimeMessageRecieved()");
triggerMessageRecieveWithDelay(message);
} else
Games.RealTimeMultiplayer.sendReliableMessage(mGoogleApiClient,
null, message, room.getRoomId(), p.getParticipantId());
}
}
public void triggerMessageRecieveWithDelay(final byte[] message) {
Timer.schedule(new Task() {
@Override
public void run() {
messageHandler.onRealTimeMessageReceived(new RealTimeMessage(
mMyId, message, RealTimeMessage.RELIABLE));
}
}, 0.1f);
}
@Override
public void setServerListener(FRMessageListener listener) {
messageHandler.setServerMessageListener(listener);
}
@Override
public void setClientListener(FRMessageListener listener) {
messageHandler.setClientMessageListener(listener);
}
@Override
public boolean isSignedIn() {
return mGoogleApiClient != null && mGoogleApiClient.isConnected();
}
@Override
public String getSinglePlayerIds() {
return "local";
}
}
<file_sep>package com.letsrace.game.network;
public class FRPlayerData {
int carCode;
int ping;
public FRPlayerData() {
carCode = Integer.MIN_VALUE;
ping = Integer.MIN_VALUE;
}
}
<file_sep>package com.letsrace.game.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.letsrace.game.FRConstants;
import com.letsrace.game.FRGameRenderer;
import com.letsrace.game.FRGameWorld;
import com.letsrace.game.GameWorld;
import com.letsrace.game.LetsRace;
import com.letsrace.game.input.FRCarKeyboardInputHandler;
import com.letsrace.game.input.FRInputAdapter;
import com.letsrace.game.input.FRNetworkInputHandler;
public class FRGameScreen extends ScreenAdapter{
public LetsRace gameRef;
public FRGameRenderer renderer;
public FRGameWorld gameWorldRef;
public FRInputAdapter adapter;
public FRGameScreen(LetsRace letsRace, boolean multiplayer) {
if(multiplayer){
Gdx.app.log(FRConstants.TAG, "GameScreen(): Constructor");
this.gameRef = letsRace;
gameWorldRef = gameRef.client.gameWorld;
gameRef.stage.clear();
renderer = new FRGameRenderer(gameRef.myPlayerNo, gameWorldRef, gameRef.stage.getBatch());
adapter = new FRNetworkInputHandler(gameRef.googleServices, gameRef.client.serverID);
Gdx.input.setInputProcessor(adapter);
}else{
Gdx.app.log(FRConstants.TAG, "GameScreen(): Constructor");
this.gameRef = letsRace;
gameWorldRef = new FRGameWorld();
gameWorldRef.carHandler.addCar(0, 0);
renderer = new FRGameRenderer(0, gameWorldRef, gameRef.batch);
adapter = new FRCarKeyboardInputHandler(gameWorldRef.carHandler.cars.get(0));
Gdx.input.setInputProcessor(adapter);
}
}
@Override
public void render(float delta){
adapter.handleAccelerometer();
update(delta);
draw();
}
private void draw() {
GL20 gl = Gdx.gl;
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
}
private void update(float delta) {
gameWorldRef.update(delta);
}
}
<file_sep>package com.letsrace.game.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.letsrace.game.FRConstants;
import com.letsrace.game.FRConstants.GameState;
import com.letsrace.game.LetsRace;
import com.letsrace.game.network.FRMessageCodes;
public class FRCarSelectScreen extends ScreenAdapter {
private LetsRace gameRef;
public FRCarSelectScreen(LetsRace game){
Gdx.app.log(FRConstants.TAG, "Car-Select: Constructor");
gameRef = game;
gameRef.stage.clear();
Gdx.input.setInputProcessor(gameRef.stage);
Image image = new Image(gameRef.skin.getDrawable("background"));
image.setWidth(Gdx.graphics.getWidth());
image.setHeight(Gdx.graphics.getHeight());
Image name = new Image(gameRef.skin.getDrawable("car-selection-name"));
name.setWidth(400*FRConstants.GUI_SCALE_WIDTH);
name.setHeight(50*FRConstants.GUI_SCALE_WIDTH);
name.setPosition(36*FRConstants.GUI_SCALE_WIDTH, (FRConstants.GUI_HIEGHT-30-50)*FRConstants.GUI_SCALE_WIDTH);
Image character = new Image(gameRef.skin.getDrawable("car-selection-char"));
character.setWidth(230*FRConstants.GUI_SCALE_WIDTH);
character.setHeight(250*FRConstants.GUI_SCALE_WIDTH);
character.setPosition(36*FRConstants.GUI_SCALE_WIDTH, (FRConstants.GUI_HIEGHT-96-250)*FRConstants.GUI_SCALE_WIDTH);
Image stats = new Image(gameRef.skin.getDrawable("car-selection-stats"));
stats.setWidth(150*FRConstants.GUI_SCALE_WIDTH);
stats.setHeight(250*FRConstants.GUI_SCALE_WIDTH);
stats.setPosition(286*FRConstants.GUI_SCALE_WIDTH, (FRConstants.GUI_HIEGHT-96-250)*FRConstants.GUI_SCALE_WIDTH);
Image car = new Image(gameRef.skin.getDrawable("car-selection-car"));
car.setWidth(400*FRConstants.GUI_SCALE_WIDTH);
car.setHeight(400*FRConstants.GUI_SCALE_WIDTH);
car.setPosition(36*FRConstants.GUI_SCALE_WIDTH, (FRConstants.GUI_HIEGHT-364-400)*FRConstants.GUI_SCALE_WIDTH);
car.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
byte[] msg = new byte[1];
if (gameRef.myPlayerNo == 0)
msg[0] = FRMessageCodes.SELECTED_CAR_0;
else if (gameRef.myPlayerNo == 1)
msg[0] = FRMessageCodes.SELECTED_CAR_1;
gameRef.googleServices.sendReliableMessage(msg, gameRef.client.serverID);
gameRef.moveToScreen(GameState.WAIT);
}
});
gameRef.stage.addActor(image);
gameRef.stage.addActor(name);
gameRef.stage.addActor(character);
gameRef.stage.addActor(stats);
gameRef.stage.addActor(car);
}
public void show() {
Gdx.app.log(FRConstants.TAG, "Car-Select: Show()");
// Throwing stuff in constructor as loading stuff in show() causes black
// screen
}
@Override
public void render(float delta) {
GL20 gl = Gdx.gl;
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameRef.stage.draw();
}
public void dispose() {
Gdx.app.log(FRConstants.TAG, "Car-Select: Dispose()");
}
}
| 4c2431e648e52179666713e4d0078f959ebb12d6 | [
"Markdown",
"Java"
] | 20 | Java | nihalsid/Lets-Race | a1a02621199220b222d6ef74ab2b759aacabed28 | a2a63cddb3c5f89bb09c4fed885ba14a890c38e7 | |
refs/heads/master | <repo_name>kacpercierpiak/SensorTagPython<file_sep>/SensorTagPython/main.py
import asyncio
import threading
import time
import curses
from os import name, system
from bleak import discover,BleakClient
from sensor_calcs import *
stdscr = curses.initscr()
curses.noecho()
class gatt_set:
def __init__(self, data, config, extra = ''):
self.data = data
self.config = config
self.extra = extra
global sensor_data
sensor_data = {}
sensor_data['sensor_tag'] = ''
sensor_data['key'] = 'None'
sensor_data['temp'] = 0
sensor_data['humid'] = 0
sensor_data['bar'] = 0
sensor_data['accel'] = [0.0,0.0,0.0]
sensor_data['gyro'] = [0.0,0.0,0.0]
sensor_data['magn'] = [0.0,0.0,0.0]
gatt_services = dict({
'Temp': gatt_set('f000aa01-0451-4000-b000-000000000000','f000aa02-0451-4000-b000-000000000000'),
'Accel': gatt_set('f000aa11-0451-4000-b000-000000000000','f000aa12-0451-4000-b000-000000000000','f000aa13-0451-4000-b000-000000000000'),
'Humid': gatt_set('f000aa21-0451-4000-b000-000000000000','f000aa22-0451-4000-b000-000000000000'),
'Mag': gatt_set('f000aa31-0451-4000-b000-000000000000','f000aa32-0451-4000-b000-000000000000','f000aa33-0451-4000-b000-000000000000'),
'Barometer': gatt_set('f000aa41-0451-4000-b000-000000000000','f000aa42-0451-4000-b000-000000000000','f000aa43-0451-4000-b000-000000000000'),
'Gyro': gatt_set('f000aa51-0451-4000-b000-000000000000','f000aa52-0451-4000-b000-000000000000'),
'Key': gatt_set('0<KEY>','')
})
def print_info(info):
stdscr.clear()
stdscr.addstr(str(info))
stdscr.refresh()
def draw():
while True:
info = "SensorTag: " + sensor_data['sensor_tag'] + '\n'
info += "Key status: " + sensor_data['key'] + '\n'
info += "Temp: %.2f" % sensor_data['temp'] + '\n'
info += "Humid: %.2f" % sensor_data['humid'] + '\n'
info += "Accell: [%.2f, %.2f, %.2f]" % (sensor_data['accel'][0],sensor_data['accel'][1],sensor_data['accel'][2]) + '\n'
info += "Gyro: [%.2f, %.2f, %.2f]" % (sensor_data['gyro'][0],sensor_data['gyro'][1],sensor_data['gyro'][2]) + '\n'
info += "Magn: [%.2f, %.2f, %.2f]" % (sensor_data['magn'][0],sensor_data['magn'][1],sensor_data['magn'][2]) + '\n'
print_info(info)
time.sleep(0.1)
def notification_handler(sender, data):
if sender == 36: # Temp
sensor_data['temp'] = temp_calc(data)
elif sender == 44: # Accel
sensor_data['accel'] = accel_calc(data)
elif sender == 55: # Humid
sensor_data['humid'] = humid_calc(data)
elif sender == 63: # Magn
sensor_data['magn'] = magn_calc(data)
elif sender == 74: # Barometer
sensor_data['bar'] = bar_calc(data)
elif sender == 86: # Gyro
sensor_data['gyro'] = gyro_calc(data)
elif sender == 94: # Key
sensor_data['key'] = key_calc(data)
async def main():
sensor_data['sensor_tag'] = 'Discover devices'
devices = await discover()
for d in devices:
if d.name == 'SensorTag':
sensor_data['sensor_tag'] = d.address
async with BleakClient(d.address) as client:
client.pair()
for service in gatt_services:
if service == 'Gyro':
await client.write_gatt_char(gatt_services[service].config,[0x07])
else:
char_conf = gatt_services[service].config
if char_conf != '':
await client.write_gatt_char(char_conf,[0x01])
await client.start_notify(gatt_services[service].data, notification_handler)
while(True):
await asyncio.sleep(1.0)
if __name__ == "__main__":
x = threading.Thread(target=draw)
x.start()
asyncio.run(main()) <file_sep>/SensorTagPython/sensor_calcs.py
from os import name, system
tosigned = lambda n: float(n-0x10000) if n>0x7fff else float(n)
tosignedbyte = lambda n: float(n-0x100) if n>0x7f else float(n)
def calcTmpTarget(objT, ambT):
objT = tosigned(objT)
ambT = tosigned(ambT)
m_tmpAmb = ambT/128.0
Vobj2 = objT * 0.00000015625
Tdie2 = m_tmpAmb + 273.15
S0 = 6.4E-14 # Calibration factor
a1 = 1.75E-3
a2 = -1.678E-5
b0 = -2.94E-5
b1 = -5.7E-7
b2 = 4.63E-9
c2 = 13.4
Tref = 298.15
S = S0*(1+a1*(Tdie2 - Tref)+a2*pow((Tdie2 - Tref),2))
Vos = b0 + b1*(Tdie2 - Tref) + b2*pow((Tdie2 - Tref),2)
fObj = (Vobj2 - Vos) + c2*pow((Vobj2 - Vos),2)
tObj = pow(pow(Tdie2,4) + (fObj/S),.25)
tObj = (tObj - 273.15)
return tObj
def temp_calc(data):
objT = (data[1]<<8)+data[0]
ambT = (data[3]<<8)+data[2]
return calcTmpTarget(objT, ambT)
def accel_calc(data):
acc = lambda v: tosignedbyte(v) / 64.0
return [acc(data[0]), acc(data[1]), acc(data[2]) * -1]
def humid_calc(data):
rawH = (data[3]<<8)+data[2]
rawH = float(int(rawH) & ~0x0003)
return -6.0 + 125.0/65536.0 * rawH
def magn_calc(data):
x = (data[1] & 0xFF <<8)+data[0] & 0xFF
y = (data[3] & 0xFF <<8)+data[2] & 0xFF
z = (data[5] & 0xFF <<8)+data[4] & 0xFF
magforce = lambda v: (tosigned(v) * 1.0) / (65536.0/2000.0)
return [magforce(x),magforce(y),magforce(z)]
def bar_calc(data):
m_raw_temp = tosigned((data[1]<<8)+data[0])
m_raw_pres = (data[3]<<8)+data[2]
return 1000.0
def gyro_calc(data):
x = (data[1]<<8)+data[0]
y = (data[3]<<8)+data[2]
z = (data[5]<<8)+data[4]
result = lambda v: (tosigned(v) * 1.0) / (65536.0/500.0)
return [result(x),result(y) ,result(z)]
def key_calc(data):
i = int.from_bytes(data, "big")
result =''
if i == 1:
result = 'Right'
elif i == 2:
result = 'Left'
elif i == 3:
result = 'Left and Right'
else:
result = 'None'
return result | d14860f6b7c50744c74f4579ed3f3c245c11332a | [
"Python"
] | 2 | Python | kacpercierpiak/SensorTagPython | 548e4fcf65f4638111ddd6d58d395a932a598524 | 8745eed2d3ed3c7b6fe980c57a89d5a0d6278511 | |
refs/heads/master | <file_sep>from flask import Flask
from flask import request
from dbHelper import *
from Urfu_api import *
import time
from strings import *
app = Flask(name)
schedules_commands = ['скажи расписание', 'сегодняшнее расписание']
schedules_commands_tomorrow = ['скажи расписание на завтра', 'завтрашнее расписание', 'расписание на завтра']
brs_commands = ['какие у меня баллы', 'сколько у меня баллов', 'что у меня в брс', 'брс']
@app.route('/Alice', methods=['POST'])
def main():
response = {
'session': request.json['session'],
'version': request.json['version'],
'response': {
'end_session': False
}
}
handle_dialog(response, request.json)
return json.dumps(response)
def handle_dialog(res, req):
command = req['request']['command']
user_id = req['session']['user']['user_id']
if command == 'авторизация':
authorization_answer(res)
elif command.startswith('login'):
login = req['request']['original_utterance'][6:]
add_user(user_id, login)
res['response']['text'] = login_saves
elif command.startswith('password'):
password = req['request']['original_utterance'][9:]
update_user_password(user_id, password)
res['response']['text'] = password_saved
elif command in schedules_commands:
schedule_answer(res, user_id, time.time())
elif command in schedules_commands_tomorrow:
schedule_answer(res, user_id, time.time() + 86399)
elif command == 'спасибо':
res['response']['text'] = have_a_good_day
res['response']['end_session'] = True
elif command in brs_commands:
brs_answer(res, user_id)
else:
if check_user(user_id):
res['response']['text'] = info
else:
inf = info + ', но для начала необходимо авторизоваться, чтобы узнать, как это сделать скажи "авторизация"'
res['response']['text'] = inf
def authorization_answer(res):
res['response']['text'] = autorization_answer
def schedule_answer(res, user_id, data):
login, password = get_user(user_id)
cookies = authorization(login, password)
schedule = get_current_schedule(cookies, data)
if time.time() - data > 0:
answer = 'Сегодня у тебя '
else:
answer = 'Завтра у тебя '
if len(schedule) == 0:
answer = answer + ' нет пар'
else:
answer = answer + ', '.join(schedule)
res['response']['text'] = answer
def brs_answer(res, user_id):
login, password = get_user(user_id)
cookies = authorization(login, password)
brs = get_current_brs(cookies)
if brs is not None:
str = 'Твои баллы: \n'
for name in brs:
if float(brs[name]) > 0:
r = f'{name} {brs[name]}, \n'
str = str + r
res['response']['text'] = str
else:
res['response']['text'] = 'В БРС пусто'
if __name__ == '__main__':
app.run(host='0.0.0.0')
<file_sep>import re
import flask
import pymorphy2
from werkzeug.local import LocalProxy
__all__ = ['Request', 'request']
morph = pymorphy2.MorphAnalyzer()
class Request(dict):
def __init__(self, dictionary):
super().__init__(dictionary)
self._command = self['request']['command'].rstrip('.')
self._words = re.findall(r'[\w-]+', self._command, flags=re.UNICODE)
self._lemmas = [morph.parse(word)[0].normal_form
for word in self._words]
@property
def command(self):
return self._command
@property
def words(self):
return self._words
def matches(self, pattern, flags=0):
return re.fullmatch(pattern, self._command, flags) is not None
@property
def lemmas(self):
return self._lemmas
@property
def session_id(self):
return self['session']['session_id']
@property
def user_id(self):
return self['session']['user_id']
def has_lemmas(self, *lemmas):
return any(morph.parse(item)[0].normal_form in self._lemmas
for item in lemmas)
request = LocalProxy(lambda: flask.g.request)
<file_sep># This code parses date/times, so please
#
# pip install python-dateutil
#
# To use this code, make sure you
#
# import json
#
# and then, to convert JSON from a string, do
#
# result = welcome_from_dict(json.loads(json_string))
from typing import Optional, Any, Dict, TypeVar, Type, Callable, cast
from datetime import datetime
import dateutil.parser
T = TypeVar("T")
def from_none(x: Any) -> Any:
assert x is None
return x
def from_str(x: Any) -> str:
assert isinstance(x, str)
return x
def from_union(fs, x):
for f in fs:
try:
return f(x)
except:
pass
assert False
def from_datetime(x: Any) -> datetime:
return dateutil.parser.parse(x)
def is_type(t: Type[T], x: Any) -> T:
assert isinstance(x, t)
return x
def from_bool(x: Any) -> bool:
assert isinstance(x, bool)
return x
def from_int(x: Any) -> int:
assert isinstance(x, int) and not isinstance(x, bool)
return x
def from_dict(f: Callable[[Any], T], x: Any) -> Dict[str, T]:
assert isinstance(x, dict)
return { k: f(v) for (k, v) in x.items() }
def to_class(c: Type[T], x: Any) -> dict:
assert isinstance(x, c)
return cast(Any, x).to_dict()
class GroupInfo:
sgroup_id: Optional[int]
sgroup_external_id: None
sgroup_uuid: Optional[str]
sgroup_name: Optional[str]
sgroup_course: Optional[int]
sgroup_division: None
sgroup_eduyear: None
sgroup_pkey: None
sspec_id: Optional[int]
sgroup_start_education_year: Optional[int]
sgroup_date_add: Optional[datetime]
sgroup_date_modified: Optional[datetime]
sgroup_its_group_id: None
sgroup_its_group_type_id: None
sgroup_its_group_key: None
sspec_code_okso: Optional[str]
sspec_title: Optional[str]
def __init__(self, sgroup_id: Optional[int], sgroup_external_id: None, sgroup_uuid: Optional[str], sgroup_name: Optional[str], sgroup_course: Optional[int], sgroup_division: None, sgroup_eduyear: None, sgroup_pkey: None, sspec_id: Optional[int], sgroup_start_education_year: Optional[int], sgroup_date_add: Optional[datetime], sgroup_date_modified: Optional[datetime], sgroup_its_group_id: None, sgroup_its_group_type_id: None, sgroup_its_group_key: None, sspec_code_okso: Optional[str], sspec_title: Optional[str]) -> None:
self.sgroup_id = sgroup_id
self.sgroup_external_id = sgroup_external_id
self.sgroup_uuid = sgroup_uuid
self.sgroup_name = sgroup_name
self.sgroup_course = sgroup_course
self.sgroup_division = sgroup_division
self.sgroup_eduyear = sgroup_eduyear
self.sgroup_pkey = sgroup_pkey
self.sspec_id = sspec_id
self.sgroup_start_education_year = sgroup_start_education_year
self.sgroup_date_add = sgroup_date_add
self.sgroup_date_modified = sgroup_date_modified
self.sgroup_its_group_id = sgroup_its_group_id
self.sgroup_its_group_type_id = sgroup_its_group_type_id
self.sgroup_its_group_key = sgroup_its_group_key
self.sspec_code_okso = sspec_code_okso
self.sspec_title = sspec_title
@staticmethod
def from_dict(obj: Any) -> 'GroupInfo':
assert isinstance(obj, dict)
sgroup_id = from_union([from_none, lambda x: int(from_str(x))], obj.get("sgroup_id"))
sgroup_external_id = from_none(obj.get("sgroup_external_id"))
sgroup_uuid = from_union([from_str, from_none], obj.get("sgroup_uuid"))
sgroup_name = from_union([from_str, from_none], obj.get("sgroup_name"))
sgroup_course = from_union([from_none, lambda x: int(from_str(x))], obj.get("sgroup_course"))
sgroup_division = from_none(obj.get("sgroup_division"))
sgroup_eduyear = from_none(obj.get("sgroup_eduyear"))
sgroup_pkey = from_none(obj.get("sgroup_pkey"))
sspec_id = from_union([from_none, lambda x: int(from_str(x))], obj.get("sspec_id"))
sgroup_start_education_year = from_union([from_none, lambda x: int(from_str(x))], obj.get("sgroup_start_education_year"))
sgroup_date_add = from_union([from_datetime, from_none], obj.get("sgroup_date_add"))
sgroup_date_modified = from_union([from_datetime, from_none], obj.get("sgroup_date_modified"))
sgroup_its_group_id = from_none(obj.get("sgroup_its_group_id"))
sgroup_its_group_type_id = from_none(obj.get("sgroup_its_group_type_id"))
sgroup_its_group_key = from_none(obj.get("sgroup_its_group_key"))
sspec_code_okso = from_union([from_str, from_none], obj.get("sspec_code_okso"))
sspec_title = from_union([from_str, from_none], obj.get("sspec_title"))
return GroupInfo(sgroup_id, sgroup_external_id, sgroup_uuid, sgroup_name, sgroup_course, sgroup_division, sgroup_eduyear, sgroup_pkey, sspec_id, sgroup_start_education_year, sgroup_date_add, sgroup_date_modified, sgroup_its_group_id, sgroup_its_group_type_id, sgroup_its_group_key, sspec_code_okso, sspec_title)
def to_dict(self) -> dict:
result: dict = {}
result["sgroup_id"] = from_union([lambda x: from_none((lambda x: is_type(type(None), x))(x)), lambda x: from_str((lambda x: str((lambda x: is_type(int, x))(x)))(x))], self.sgroup_id)
result["sgroup_external_id"] = from_none(self.sgroup_external_id)
result["sgroup_uuid"] = from_union([from_str, from_none], self.sgroup_uuid)
result["sgroup_name"] = from_union([from_str, from_none], self.sgroup_name)
result["sgroup_course"] = from_union([lambda x: from_none((lambda x: is_type(type(None), x))(x)), lambda x: from_str((lambda x: str((lambda x: is_type(int, x))(x)))(x))], self.sgroup_course)
result["sgroup_division"] = from_none(self.sgroup_division)
result["sgroup_eduyear"] = from_none(self.sgroup_eduyear)
result["sgroup_pkey"] = from_none(self.sgroup_pkey)
result["sspec_id"] = from_union([lambda x: from_none((lambda x: is_type(type(None), x))(x)), lambda x: from_str((lambda x: str((lambda x: is_type(int, x))(x)))(x))], self.sspec_id)
result["sgroup_start_education_year"] = from_union([lambda x: from_none((lambda x: is_type(type(None), x))(x)), lambda x: from_str((lambda x: str((lambda x: is_type(int, x))(x)))(x))], self.sgroup_start_education_year)
result["sgroup_date_add"] = from_union([lambda x: x.isoformat(), from_none], self.sgroup_date_add)
result["sgroup_date_modified"] = from_union([lambda x: x.isoformat(), from_none], self.sgroup_date_modified)
result["sgroup_its_group_id"] = from_none(self.sgroup_its_group_id)
result["sgroup_its_group_type_id"] = from_none(self.sgroup_its_group_type_id)
result["sgroup_its_group_key"] = from_none(self.sgroup_its_group_key)
result["sspec_code_okso"] = from_union([from_str, from_none], self.sspec_code_okso)
result["sspec_title"] = from_union([from_str, from_none], self.sspec_title)
return result
class Event:
ntk: Optional[bool]
loadcase: Optional[str]
retake: Optional[bool]
event_date: Optional[int]
begin_time: Optional[str]
end_time: Optional[str]
npair: Optional[int]
nday: None
teacher: Optional[str]
teacher_auditory: None
teacher_auditory_location: None
teacher_auditory_capacity: None
auditory: Optional[str]
auditory_location: Optional[str]
auditory_capacity: Optional[int]
comment: Optional[str]
distations: Optional[bool]
ntk_retake: Optional[bool]
teachers_comment: None
teachers_link: None
auditory_location_is_link: Optional[int]
teacher_auditory_location_is_link: Optional[int]
loadtype: Optional[str]
discipline: Optional[str]
state: Optional[str]
teachers_comment_exists: Optional[bool]
def __init__(self, ntk: Optional[bool], loadcase: Optional[str], retake: Optional[bool], event_date: Optional[int], begin_time: Optional[str], end_time: Optional[str], npair: Optional[int], nday: None, teacher: Optional[str], teacher_auditory: None, teacher_auditory_location: None, teacher_auditory_capacity: None, auditory: Optional[str], auditory_location: Optional[str], auditory_capacity: Optional[int], comment: Optional[str], distations: Optional[bool], ntk_retake: Optional[bool], teachers_comment: None, teachers_link: None, auditory_location_is_link: Optional[int], teacher_auditory_location_is_link: Optional[int], loadtype: Optional[str], discipline: Optional[str], state: Optional[str], teachers_comment_exists: Optional[bool]) -> None:
self.ntk = ntk
self.loadcase = loadcase
self.retake = retake
self.event_date = event_date
self.begin_time = begin_time
self.end_time = end_time
self.npair = npair
self.nday = nday
self.teacher = teacher
self.teacher_auditory = teacher_auditory
self.teacher_auditory_location = teacher_auditory_location
self.teacher_auditory_capacity = teacher_auditory_capacity
self.auditory = auditory
self.auditory_location = auditory_location
self.auditory_capacity = auditory_capacity
self.comment = comment
self.distations = distations
self.ntk_retake = ntk_retake
self.teachers_comment = teachers_comment
self.teachers_link = teachers_link
self.auditory_location_is_link = auditory_location_is_link
self.teacher_auditory_location_is_link = teacher_auditory_location_is_link
self.loadtype = loadtype
self.discipline = discipline
self.state = state
self.teachers_comment_exists = teachers_comment_exists
@staticmethod
def from_dict(obj: Any) -> 'Event':
assert isinstance(obj, dict)
ntk = from_union([from_bool, from_none], obj.get("ntk"))
loadcase = from_union([from_none, from_str], obj.get("loadcase"))
retake = from_union([from_bool, from_none], obj.get("retake"))
event_date = from_union([from_int, from_none], obj.get("event_date"))
begin_time = from_union([from_str, from_none], obj.get("begin_time"))
end_time = from_union([from_str, from_none], obj.get("end_time"))
npair = from_union([from_int, from_none], obj.get("npair"))
nday = from_none(obj.get("nday"))
teacher = from_union([from_none, from_str], obj.get("teacher"))
teacher_auditory = from_none(obj.get("teacher_auditory"))
teacher_auditory_location = from_none(obj.get("teacher_auditory_location"))
teacher_auditory_capacity = from_none(obj.get("teacher_auditory_capacity"))
auditory = from_union([from_none, from_str], obj.get("auditory"))
auditory_location = from_union([from_none, from_str], obj.get("auditory_location"))
auditory_capacity = from_union([from_int, from_none], obj.get("auditory_capacity"))
comment = from_union([from_str, from_none], obj.get("comment"))
distations = from_union([from_bool, from_none], obj.get("distations"))
ntk_retake = from_union([from_bool, from_none], obj.get("ntk_retake"))
teachers_comment = from_none(obj.get("teachers_comment"))
teachers_link = from_none(obj.get("teachers_link"))
auditory_location_is_link = from_union([from_int, from_none], obj.get("auditory_location_is_link"))
teacher_auditory_location_is_link = from_union([from_int, from_none], obj.get("teacher_auditory_location_is_link"))
loadtype = from_union([from_str, from_none], obj.get("loadtype"))
discipline = from_union([from_str, from_none], obj.get("discipline"))
state = from_union([from_str, from_none], obj.get("state"))
teachers_comment_exists = from_union([from_bool, from_none], obj.get("teachers_comment_exists"))
return Event(ntk, loadcase, retake, event_date, begin_time, end_time, npair, nday, teacher, teacher_auditory, teacher_auditory_location, teacher_auditory_capacity, auditory, auditory_location, auditory_capacity, comment, distations, ntk_retake, teachers_comment, teachers_link, auditory_location_is_link, teacher_auditory_location_is_link, loadtype, discipline, state, teachers_comment_exists)
def to_dict(self) -> dict:
result: dict = {}
result["ntk"] = from_union([from_bool, from_none], self.ntk)
result["loadcase"] = from_union([from_none, from_str], self.loadcase)
result["retake"] = from_union([from_bool, from_none], self.retake)
result["event_date"] = from_union([from_int, from_none], self.event_date)
result["begin_time"] = from_union([from_str, from_none], self.begin_time)
result["end_time"] = from_union([from_str, from_none], self.end_time)
result["npair"] = from_union([from_int, from_none], self.npair)
result["nday"] = from_none(self.nday)
result["teacher"] = from_union([from_none, from_str], self.teacher)
result["teacher_auditory"] = from_none(self.teacher_auditory)
result["teacher_auditory_location"] = from_none(self.teacher_auditory_location)
result["teacher_auditory_capacity"] = from_none(self.teacher_auditory_capacity)
result["auditory"] = from_union([from_none, from_str], self.auditory)
result["auditory_location"] = from_union([from_none, from_str], self.auditory_location)
result["auditory_capacity"] = from_union([from_int, from_none], self.auditory_capacity)
result["comment"] = from_union([from_str, from_none], self.comment)
result["distations"] = from_union([from_bool, from_none], self.distations)
result["ntk_retake"] = from_union([from_bool, from_none], self.ntk_retake)
result["teachers_comment"] = from_none(self.teachers_comment)
result["teachers_link"] = from_none(self.teachers_link)
result["auditory_location_is_link"] = from_union([from_int, from_none], self.auditory_location_is_link)
result["teacher_auditory_location_is_link"] = from_union([from_int, from_none], self.teacher_auditory_location_is_link)
result["loadtype"] = from_union([from_str, from_none], self.loadtype)
result["discipline"] = from_union([from_str, from_none], self.discipline)
result["state"] = from_union([from_str, from_none], self.state)
result["teachers_comment_exists"] = from_union([from_bool, from_none], self.teachers_comment_exists)
return result
class Schedule:
event_date: Optional[int]
events: Optional[Dict[str, Event]]
def __init__(self, event_date: Optional[int], events: Optional[Dict[str, Event]]) -> None:
self.event_date = event_date
self.events = events
@staticmethod
def from_dict(obj: Any) -> 'Schedule':
assert isinstance(obj, dict)
event_date = from_union([from_int, from_none], obj.get("event_date"))
events = from_union([lambda x: from_dict(Event.from_dict, x), from_none], obj.get("events"))
return Schedule(event_date, events)
def to_dict(self) -> dict:
result: dict = {}
result["event_date"] = from_union([from_int, from_none], self.event_date)
result["events"] = from_union([lambda x: from_dict(lambda x: to_class(Event, x), x), from_none], self.events)
return result
class Welcome:
schedule: Optional[Dict[str, Schedule]]
i_cal: Optional[str]
group_info: Optional[GroupInfo]
today: Optional[int]
start_date: Optional[int]
end_date: Optional[int]
prev_start_date: Optional[int]
next_start_date: Optional[int]
def __init__(self, schedule: Optional[Dict[str, Schedule]], i_cal: Optional[str], group_info: Optional[GroupInfo], today: Optional[int], start_date: Optional[int], end_date: Optional[int], prev_start_date: Optional[int], next_start_date: Optional[int]) -> None:
self.schedule = schedule
self.i_cal = i_cal
self.group_info = group_info
self.today = today
self.start_date = start_date
self.end_date = end_date
self.prev_start_date = prev_start_date
self.next_start_date = next_start_date
@staticmethod
def from_dict(obj: Any) -> 'Welcome':
assert isinstance(obj, dict)
schedule = from_union([lambda x: from_dict(Schedule.from_dict, x), from_none], obj.get("schedule"))
i_cal = from_union([from_str, from_none], obj.get("iCal"))
group_info = from_union([GroupInfo.from_dict, from_none], obj.get("groupInfo"))
today = from_union([from_int, from_none], obj.get("today"))
start_date = from_union([from_int, from_none], obj.get("start_date"))
end_date = from_union([from_int, from_none], obj.get("end_date"))
prev_start_date = from_union([from_int, from_none], obj.get("prev_start_date"))
next_start_date = from_union([from_int, from_none], obj.get("next_start_date"))
return Welcome(schedule, i_cal, group_info, today, start_date, end_date, prev_start_date, next_start_date)
def to_dict(self) -> dict:
result: dict = {}
result["schedule"] = from_union([lambda x: from_dict(lambda x: to_class(Schedule, x), x), from_none], self.schedule)
result["iCal"] = from_union([from_str, from_none], self.i_cal)
result["groupInfo"] = from_union([lambda x: to_class(GroupInfo, x), from_none], self.group_info)
result["today"] = from_union([from_int, from_none], self.today)
result["start_date"] = from_union([from_int, from_none], self.start_date)
result["end_date"] = from_union([from_int, from_none], self.end_date)
result["prev_start_date"] = from_union([from_int, from_none], self.prev_start_date)
result["next_start_date"] = from_union([from_int, from_none], self.next_start_date)
return result
def welcome_from_dict(s: Any) -> Welcome:
return Welcome.from_dict(s)
def welcome_to_dict(x: Welcome) -> Any:
return to_class(Welcome, x)
<file_sep>from bs4 import BeautifulSoup
import json
from data import *
import requests
def authorization(login, password):
response = requests.post(
'https://sts.urfu.ru/adfs/OAuth2/authorize?resource=https%3A%2F%2Fistudent.urfu.ru&type=web_server&client_id'
'=https%3A%2F%2Fistudent.urfu.ru&redirect_uri=https%3A%2F%2Fistudent.urfu.ru%3Fauth&response_type=code&scope=',
data={'UserName': login,
'Password': <PASSWORD>,
'AuthMethod': 'FormsAuthentication'})
return response.cookies
def get_current_schedule(cookies, time):
schedule = requests.post('https://istudent.urfu.ru/itribe/schedule_its/?access-token=',
data={'schedule_its[start_date]': time},
cookies=cookies)
result = welcome_from_dict(json.loads(schedule.text))
data = []
for days in result.schedule.values():
if days.event_date < time <= days.event_date + 86399:
for i in days.events.values():
data.append(i.discipline)
break
return data
def get_current_brs(cookies):
brs_data = requests.post('https://istudent.urfu.ru/s/http-urfu-ru-ru-students-study-brs/',
cookies=cookies)
soup = BeautifulSoup(brs_data.text, 'html.parser')
data = []
brs = {}
for i in soup.find_all('td')[3:]:
data.append(i.text)
for i, j in enumerate(data):
if i % 3 == 0:
brs[j] = data[i + 1]
return brs
<file_sep>from peewee import *
db = SqliteDatabase('myDB.db')
class Data(Model):
name = TextField()
login = TextField()
password = TextField()
class Meta:
database = db
def add_user(name, login):
Data.create(name=name, login=login, password='')
def update_user_password(name, password):
user = Data.select().where(Data.name == name).get()
user.password = <PASSWORD>
user.save()
def get_user(name):
login = Data.select().where(Data.name == name).get().login
password = Data.select().where(Data.name == name).get().password
return login, password
def check_user(name):
if Data.select().where(Data.name == name):
return True
return False
<file_sep>name = 'Alice'
password_saved = '<PASSWORD>'
login_saves = 'Логин сохранён'
have_a_good_day = 'Хорошего дня!'
info = 'Бот для студентов УрФУ, чтобы узнать сегодняшнее расписание, скажи "сегодняшнее расписание", чтобы узнать ' \
'расписание пар на завтра, скажи "завтрашнее расписание", чтобы узнать свои баллы БРС, спроси "сколько у меня ' \
'баллов"'
autorization_answer = 'Для авторизации необходимо отправить логин и пароль от учётной записи УрФУ \n' \
'Отправляй в формате\n' \
'login <EMAIL>\n' \
'password <PASSWORD>'
no_lessons = 'Сегодня у тебя нет пар, можешь отдыхать'
<file_sep>import logging
import threading
import flask
from .requests import Request
__all__ = ['Skill']
class Skill(flask.Flask):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._sessions = {}
self._session_lock = threading.RLock()
def script(self, generator):
@self.route("/", methods=['POST'])
def handle_post():
flask.g.request = Request(flask.request.get_json())
logging.debug('Request: %r', flask.g.request)
content = self._switch_state(generator)
response = {
'version': flask.g.request['version'],
'session': flask.g.request['session'],
'response': content,
}
logging.debug('Response: %r', response)
return flask.jsonify(response)
return generator
def _switch_state(self, generator):
session_id = flask.g.request['session']['session_id']
with self._session_lock:
if session_id not in self._sessions:
state = self._sessions[session_id] = generator()
else:
state = self._sessions[session_id]
content = next(state)
if content['end_session']:
with self._session_lock:
del self._sessions[session_id]
return content
<file_sep>import random
__all__ = ['say']
def say(*args, **kwargs):
if not all(isinstance(item, str) or callable(item)
for item in args):
raise ValueError('Each argument of say(...) must be str or callable')
response = kwargs.copy()
phrases = [item for item in args if isinstance(item, str)]
if phrases:
response['text'] = random.choice(phrases)
if 'end_session' not in response:
response['end_session'] = False
for item in args:
if callable(item):
item(response)
return response
<file_sep># UrfuAlice
Навык для Алисы
<br/>
<br/>
Навык позволяет получить расписание на ближайшие дни и текущие баллы БРС

<file_sep>__all__ = ['suggest']
def suggest(*options):
def modifier(response):
if 'buttons' not in response:
response['buttons'] = []
response['buttons'] += [{'title': item, 'hide': True}
for item in options]
return modifier
<file_sep>from .modifiers import *
from .requests import *
from .say import *
from .skill import *
__version__ = '0.2.post1'
| b663c09c1d4c2b3c041cb4a0f23026cad38016cb | [
"Markdown",
"Python"
] | 11 | Python | BuroRoll/UrfuAlice | 9b73efa6eb8f4328f3eea529fb7505c69a58ff84 | 804b2493cd64450e69e1fc263459ea1c59f29448 | |
refs/heads/master | <repo_name>Ligerlilly/triangle_js<file_sep>/spec/triangle_spec.js
var assert = require('assert');
var triangle = function(side_a, side_b, side_c){
var isTriangle, isEquilateral, isIsosceles, isScalene;
isTriangle = function(){
var sides_a_b;
var sides_a_c;
var sides_c_b;
var sides;
console.log(side_c);
sides_a_b = (side_a + side_b) >= side_c ? true : false;
sides_b_c = (side_a + side_b) >= side_a ? true : false;
sides_c_a = (side_c + side_a) >= side_b ? true : false;
sides = (side_a !== 0 && side_b !== 0 && side_c !== 0) ? true : false;
if(sides && sides_a_b && sides_b_c && sides_c_a) {
return true;
}
else {
return false;
}
};
isEquilateral = function(){
if (side_a === side_b && side_c === side_b){
return true;
}
else {
return false;
}
};
isIsosceles = function(){
var sides2 = (side_a == side_b || side_a == side_c || side_c == side_b);
if (sides2 && !this.isEquilateral()){
return true;
}
else {
return false;
}
};
isScalene = function(){
if (!this.isEquilateral() && !this.isIsosceles()){
return true;
}
else {
return false;
}
};
return { isTriangle : isTriangle,
isEquilateral : isEquilateral,
isIsosceles : isIsosceles,
isScalene : isScalene };
};
describe('Triangle#isTriangle', function() {
it('has three sides and returns true', function() {
assert.equal(triangle(3, 3, 3).isTriangle(), true);
});
it('doesnt have three sides returns false', function(){
assert.equal(triangle(3, 3, 0).isTriangle(), false);
});
it('the sum of any two sides are greater than the third side, return false',function(){
assert.equal(triangle(2, 2, 7).isTriangle(), false);
});
});
describe('Triangle#isEquilateral', function(){
it('returns true if all the sides are equal', function(){
assert.equal(triangle(3, 3, 3).isEquilateral(), true);
});
it('returns false if all the sides are not equal',function() {
assert.equal(triangle(3, 3, 5).isEquilateral(), false);
});
});
describe('Triangle#isIsosceles', function(){
it('returns true if exactly 2 sides are equal', function(){
assert.equal(triangle(3, 3, 5).isIsosceles(), true);
});
it('returns false all sides are equal', function(){
assert.equal(triangle(3, 3, 3).isIsosceles(), false);
});
it('returns false if no sides are equal', function(){
assert.equal(triangle(3, 4, 5).isIsosceles(), false);
});
});
describe('Triangle#isScalene', function(){
it('returns true if no sides are equal', function(){
assert.equal(triangle(1, 2, 5).isScalene(), true);
});
it('returns false if any sides are equal', function(){
assert.equal(triangle(8,8,3).isScalene(), false);
});
});
<file_sep>/lib/triangle.js
var triangle = function(side_a, side_b, side_c){
var isTriangle, isEquilateral, isIsosceles, isScalene;
isTriangle = function(){
var sides_a_b;
var sides_a_c;
var sides_c_b;
var sides;
console.log(side_c);
sides_a_b = (side_a + side_b) >= side_c ? true : false;
sides_b_c = (side_a + side_b) >= side_a ? true : false;
sides_c_a = (side_c + side_a) >= side_b ? true : false;
sides = (side_a !== 0 && side_b !== 0 && side_c !== 0) ? true : false;
if(sides && sides_a_b && sides_b_c && sides_c_a) {
return true;
}
else {
return false;
}
};
isEquilateral = function(){
if (side_a === side_b && side_c === side_b){
return true;
}
else {
return false;
}
};
isIsosceles = function(){
var sides2 = (side_a == side_b || side_a == side_c || side_c == side_b);
if (sides2 && !this.isEquilateral()){
return true;
}
else {
return false;
}
};
isScalene = function(){
if (!this.isEquilateral() && !this.isIsosceles()){
return true;
}
else {
return false;
}
};
return { isTriangle : isTriangle,
isEquilateral : isEquilateral,
isIsosceles : isIsosceles,
isScalene : isScalene };
};
| 142f2c0edee3483b83521b1dde0b0a4b55a63821 | [
"JavaScript"
] | 2 | JavaScript | Ligerlilly/triangle_js | 400ffcd55c6bd143bfb76f6920ca80a50f47701f | cfe92ecd8df3f37ed20809b35af8a430b3cf58bc | |
refs/heads/master | <repo_name>riiswa/orchalang-server<file_sep>/orchalang-orchacompiler/src/main/kotlin/orcha/lang/compiler/DemoApplication.kt
package orcha.lang.compiler
import orcha.lang.compiler.OrchaCompiler
import orcha.lang.compiler.syntax.ReceiveInstruction
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import java.io.File
@SpringBootApplication
class DemoApplication{
@Bean
fun init(orchaCompiler: OrchaCompiler) = CommandLineRunner {
orchaCompiler . compile(File("src/main/orcha/source").list()[0])
}
}
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/OutputGenerationToSpringIntegration.kt
package orcha.lang.compiler.referenceimpl.springIntegration
import orcha.lang.compiler.IntegrationNode
import orcha.lang.compiler.OrchaMetadata
import orcha.lang.compiler.OrchaProgram
import orcha.lang.compiler.OutputGeneration
import orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.Aggregator
import orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.MessageFilter
import orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.ServiceActivator
import orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.impl.AggregatorImpl
import orcha.lang.compiler.syntax.ComputeInstruction
import orcha.lang.compiler.syntax.ReceiveInstruction
import orcha.lang.compiler.syntax.WhenInstruction
import org.jdom2.Document
import org.jdom2.Element
import org.jdom2.input.SAXBuilder
import org.jdom2.output.Format
import org.jdom2.output.XMLOutputter
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileWriter
import java.io.StringWriter
class OutputGenerationToSpringIntegration : OutputGeneration, MessageFilter(), Aggregator {
internal var aggregator: AggregatorImpl = AggregatorImpl()
override fun aggregate(releaseExpression: String): Element {
return aggregator.aggregate(releaseExpression)
}
/* internal lateinit var sourceCodeDirectory: File
init {
try {
val directories = pathToBinaryCode.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var pathToBinCode = "."
for (directory in directories) {
pathToBinCode = pathToBinCode + File.separator + directory
}
binaryCodeDirectory = File(pathToBinCode)
val pathToBinary = binaryCodeDirectory.canonicalPath + File.separator + "orcha" + File.separator + "lang" + File.separator + "generated"
var files = File(pathToBinary).listFiles()
if (files != null) {
for (file in files) {
log.info("Delete existing generated file: " + file.canonicalPath)
file.delete()
}
}
val pathToSouresCode = "." + File.separator + "src" + File.separator + "main"
sourceCodeDirectory = File(pathToSouresCode)
var pathToSource = sourceCodeDirectory.canonicalPath + File.separator + "groovy" + File.separator + "orcha" + File.separator + "lang" + File.separator + "generated"
files = File(pathToSource).listFiles()
if (files != null) {
for (file in files) {
log.info("Delete existing generated file: " + file.canonicalPath)
file.delete()
}
}
pathToSource = sourceCodeDirectory.canonicalPath + File.separator + "java" + File.separator + "orcha" + File.separator + "lang" + File.separator + "generated"
files = File(pathToSource).listFiles()
if (files != null) {
for (file in files) {
log.info("Delete existing generated file: " + file.canonicalPath)
file.delete()
}
}
} catch (e: IOException) {
log.error(e.message)
}
}*/
override fun generation(orchaProgram: OrchaProgram) {
val orchaMetadata = orchaProgram.orchaMetadata
log.info("Generation of the output (Spring Integration) for the orcha program \"" + orchaMetadata.title + "\" begins.")
/*val xmlSpringContextFileName = orchaMetadata.title!! + ".xml"
val xmlSpringContent = sourceCodeDirectory.absolutePath + File.separator + "resources" + File.separator + xmlSpringContextFileName
val xmlSpringContextFile = File(xmlSpringContent)
val xmlSpringContextQoSFileName = orchaMetadata.title!! + "QoS.xml"
val xmlQoSSpringContent = sourceCodeDirectory.absolutePath + File.separator + "resources" + File.separator + xmlSpringContextQoSFileName
val xmlQoSSpringContextFile = File(xmlQoSSpringContent)*/
val stringWriter = StringWriter()
stringWriter.write("<beans xmlns=\"http://www.springframework.org/schema/beans\">")
stringWriter.write("</beans>")
stringWriter.flush()
val s = stringWriter.toString()
val inputStream = ByteArrayInputStream(s.toByteArray())
val builder = SAXBuilder()
val document = builder. build (inputStream)
val graphOfInstructions = orchaProgram.integrationGraph
this.transpile(document, orchaMetadata, graphOfInstructions)
val pathToResources = "." + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + orchaMetadata.title + ".xml"
val file = File(pathToResources)
val xml = XMLOutputter()
xml.format = Format.getPrettyFormat()
val xmlProcessor = xml.xmlOutputProcessor
val fw = FileWriter(file)
xmlProcessor.process(fw, Format.getPrettyFormat(), document)
fw.close()
log.info("XML configuration file for Spring Integration has been generated: " + file.canonicalPath)
log.info("Generation of the output (Spring Integration) for the orcha program \"" + orchaMetadata.title + "\" complete successfully.")
}
private fun transpile(document: Document, orchaMetadata: OrchaMetadata, graphOfInstructions: List<IntegrationNode>) {
val rootElement = document.rootElement
var channelName: String = "input"
var channelNumber: Int = 1
for (node in graphOfInstructions) {
log.info("Generation of XML code for the node: " + node)
log.info("Generation of XML code for the instruction: " + node.instruction!!.instruction)
when(node.integrationPattern) {
IntegrationNode.IntegrationPattern.CHANNEL_ADAPTER -> {
}
IntegrationNode.IntegrationPattern.MESSAGE_FILTER -> {
when(node.instruction){
is ReceiveInstruction -> {
val receive: ReceiveInstruction = node.instruction as ReceiveInstruction
val element = filter(receive.condition)
element.setAttribute("input-channel", channelName)
channelName = "OutputFilter" + channelNumber
channelNumber++
element.setAttribute("output-channel", channelName)
rootElement.addContent(element)
}
}
}
IntegrationNode.IntegrationPattern.SERVICE_ACTIVATOR -> {
when(node.instruction){
is ComputeInstruction -> {
}
}
}
IntegrationNode.IntegrationPattern.AGGREGATOR -> {
when(node.instruction){
is WhenInstruction -> {
val whenInstruction: WhenInstruction = node.instruction as WhenInstruction
val element = aggregate(whenInstruction.aggregationExpression)
element.setAttribute("input-channel", channelName)
channelName = "OutputFilter" + channelNumber
channelNumber++
element.setAttribute("output-channel", channelName)
rootElement.addContent(element)
}
}
}
else -> {
}
}
val adjacentNodes = node.nextIntegrationNodes
this.transpile(document, orchaMetadata, adjacentNodes)
}
}
companion object {
private val log = LoggerFactory.getLogger(OutputGenerationToSpringIntegration::class.java)
}
}
<file_sep>/orchalang-spring-boot-autoconfigure/settings.gradle
includeFlat 'orchalang'
// includeFlat 'orchalang-spring-integration-eventhandler'
includeFlat 'orchalang-spring-integration-implementation'<file_sep>/orchalang/src/main/kotlin/orcha/lang/compiler/OrchaCompiler.kt
package orcha.lang.compiler
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.WebApplicationType
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
class OrchaCompiler {
@Autowired
internal var preprocessing: Preprocessing? = null
@Autowired
@Qualifier("lexicalAnalysisForOrchaCompiler")
internal var lexicalAnalysis: LexicalAnalysis? = null
@Autowired
internal var syntaxAnalysis: SyntaxAnalysis? = null
@Autowired
internal var semanticAnalysis: SemanticAnalysis? = null
@Autowired
internal var postprocessing: Postprocessing? = null
@Autowired
internal var linkEditor: LinkEditor? = null
@Autowired
internal var outputGeneration: OutputGeneration? = null
@Throws(OrchaCompilationException::class)
fun compile(orchaFileName: String) {
val linesOfCode = preprocessing!!.process(orchaFileName)
var orchaProgram = lexicalAnalysis!!.analysis(linesOfCode)
orchaProgram = syntaxAnalysis!!.analysis(orchaProgram)
orchaProgram = semanticAnalysis!!.analysis(orchaProgram)
orchaProgram = postprocessing!!.process(orchaProgram)
orchaProgram = linkEditor!!.link(orchaProgram)
outputGeneration!!.generation(orchaProgram)
}
companion object {
private val log = LoggerFactory.getLogger(OrchaCompiler::class.java)
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/xmlgenerator/ServiceActivator.kt
package orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator
import org.jdom2.Element
import org.jdom2.Namespace
open class ServiceActivator {
fun serviceActivator(expression: String): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
val element = Element("service-activator", namespace)
element.setAttribute("expression", expression)
return element
}
}<file_sep>/orchalang-spring-boot-sample-app/src/main/orcha/service/transport/Bill.java
package service.transport;
public class Bill {
}
<file_sep>/orchalang/src/main/java/orcha/lang/compiler/OrchaProgram.java
package orcha.lang.compiler;
import java.util.List;
public class OrchaProgram {
List<IntegrationNode> integrationGraph;
OrchaMetadata orchaMetadata;
public OrchaProgram(){
}
public OrchaProgram(List<IntegrationNode> integrationGraph, OrchaMetadata orchaMetadata) {
this.integrationGraph = integrationGraph;
this.orchaMetadata = orchaMetadata;
}
public List<IntegrationNode> getIntegrationGraph() {
return integrationGraph;
}
public void setIntegrationGraph(List<IntegrationNode> integrationGraph) {
this.integrationGraph = integrationGraph;
}
public OrchaMetadata getOrchaMetadata() {
return orchaMetadata;
}
public void setOrchaMetadata(OrchaMetadata orchaMetadata) {
this.orchaMetadata = orchaMetadata;
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/OutputGenerationToSpringIntegrationJavaDSL.kt
package orcha.lang.compiler.referenceimpl.springIntegration
import com.fasterxml.jackson.databind.ObjectMapper
import orcha.lang.compiler.IntegrationNode
import orcha.lang.compiler.OrchaMetadata
import orcha.lang.compiler.OrchaProgram
import orcha.lang.compiler.OutputGeneration
import orcha.lang.compiler.syntax.ComputeInstruction
import orcha.lang.compiler.syntax.ReceiveInstruction
import orcha.lang.compiler.syntax.WhenInstruction
import org.slf4j.LoggerFactory
import java.io.File
class OutputGenerationToSpringIntegrationJavaDSL : OutputGeneration {
override fun generation(orchaProgram: OrchaProgram) {
val orchaMetadata = orchaProgram.orchaMetadata
log.info("Generation of the output (Spring Integration Java DSL) for the orcha program \"" + orchaMetadata.title + "\" begins.")
val graphOfInstructions = orchaProgram.integrationGraph
this.export(orchaMetadata, graphOfInstructions)
val pathToResources = "." + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + orchaMetadata.title + ".json"
val file = File(pathToResources)
val objectMapper = ObjectMapper()
val jsonInString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphOfInstructions);
file.writeText(jsonInString)
log.info("XML configuration file for Spring Integration has been generated: " + file.canonicalPath)
log.info("Generation of the output (Spring Integration Java DSL) for the orcha program \"" + orchaMetadata.title + "\" complete successfully.")
}
private fun export(orchaMetadata: OrchaMetadata, graphOfInstructions: List<IntegrationNode>) {
for (node in graphOfInstructions) {
log.info("Generation of Java DSL code for the node: " + node)
log.info("Generation of Java DSL code for the instruction: " + node.instruction!!.instruction)
when(node.integrationPattern) {
IntegrationNode.IntegrationPattern.CHANNEL_ADAPTER -> {
}
IntegrationNode.IntegrationPattern.MESSAGE_FILTER -> {
when(node.instruction){
is ReceiveInstruction -> {
val receive: ReceiveInstruction = node.instruction as ReceiveInstruction
}
}
}
IntegrationNode.IntegrationPattern.SERVICE_ACTIVATOR -> {
when(node.instruction){
is ComputeInstruction -> {
}
}
}
IntegrationNode.IntegrationPattern.AGGREGATOR -> {
when(node.instruction){
is WhenInstruction -> {
val whenInstruction: WhenInstruction = node.instruction as WhenInstruction
}
}
}
else -> {
}
}
val adjacentNodes = node.nextIntegrationNodes
this.export(orchaMetadata, adjacentNodes)
}
}
companion object {
private val log = LoggerFactory.getLogger(OutputGenerationToSpringIntegrationJavaDSL::class.java)
}
}
<file_sep>/orchalang-spring-integration-implementation/src/test/kotlin/orcha/lang/compiler/referenceimpl/LexicalAnalysisTest.kt
package orcha.lang.compiler.referenceimpl
import orcha.lang.compiler.LexicalAnalysis
import orcha.lang.compiler.OrchaCompilationException
import orcha.lang.compiler.referenceimpl.springIntegration.SendInstructionForSpringIntegration
import orcha.lang.compiler.referenceimpl.springIntegration.WhenInstructionForSpringIntegration
import orcha.lang.compiler.syntax.TitleInstruction
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
import java.util.*
@RunWith(SpringRunner::class)
@SpringBootTest
class LexicalAnalysisTest {
@Autowired
internal var lexicalAnalysisForTest: LexicalAnalysis? = null
@Test
fun test() {
try {
Assert.assertTrue(lexicalAnalysisForTest != null)
val linesOfCode = ArrayList(
Arrays.asList(
"title: title",
"",
"receive order from customer",
"when \"order terminates\"",
"send order.number to customer"))
val orchaProgram = lexicalAnalysisForTest!!.analysis(linesOfCode)
Assert.assertNotNull(orchaProgram)
Assert.assertNotNull(orchaProgram.integrationGraph)
Assert.assertNotNull(orchaProgram.orchaMetadata)
val orchaMetadata = orchaProgram.orchaMetadata
val metadata = orchaMetadata.metadata
Assert.assertNotNull(metadata)
Assert.assertEquals(metadata.size.toLong(), 1)
val instruction = metadata[0]
Assert.assertTrue(instruction is TitleInstruction)
val graphOfInstructions = orchaProgram.integrationGraph
Assert.assertTrue(graphOfInstructions.size == 3)
var integrationNode = graphOfInstructions[1]
Assert.assertNotNull(integrationNode)
var inst = integrationNode.instruction
inst.analysis()
Assert.assertNotNull(inst)
Assert.assertTrue(inst is WhenInstructionForSpringIntegration)
val whenInstruction = inst as WhenInstructionForSpringIntegration
Assert.assertEquals(whenInstruction.getLineNumber(), 4)
Assert.assertTrue(whenInstruction.getCommand().equals("when"))
integrationNode = graphOfInstructions[2]
Assert.assertNotNull(integrationNode)
inst = integrationNode.instruction
Assert.assertNotNull(inst)
inst.analysis()
Assert.assertTrue(inst is SendInstructionForSpringIntegration)
val sendInstruction = inst as SendInstructionForSpringIntegration
Assert.assertEquals(sendInstruction.getLineNumber(), 5)
Assert.assertTrue(sendInstruction.getCommand().equals("send"))
Assert.assertEquals(sendInstruction.getVariables(), "payload.number")
} catch (e: OrchaCompilationException) {
Assert.fail(e.message)
}
}
}
<file_sep>/README.md
# orchalang
## orcha language
* [documentation](http://www.orchalang.com/)
* [reference implementation](https://github.com/orchaland/orchalang/tree/master/orchalang)
## Spring integration implementation
* [reference implementation](https://github.com/orchaland/orchalang/tree/master/orchalang-spring-integration-implementation)
<file_sep>/orchalang-orchacompiler/src/main/kotlin/orcha/lang/compiler/OrchaCompilerConfiguration.kt
package orcha.lang.compiler
import orcha.lang.configuration.*
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class OrchaCompilerConfiguration {
@Bean
fun orchaProgramSource(): EventHandler {
val eventHandler = EventHandler("orchaProgramSource")
return eventHandler;
}
@Bean
fun preprocessing(): Application {
val application = Application("preprocessing", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.PreprocessingImpl", "process")
application.input = Input(javaAdapter, "java.lang.String")
application.output = Output(javaAdapter, "java.util.List<java.lang.String>")
return application
}
@Bean
fun lexicalAnalysis(): Application {
val application = Application("lexicalAnalysis", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.LexicalAnalysisImpl", "analysis")
application.input = Input(javaAdapter, "java.util.List<java.lang.String>")
application.output = Output(javaAdapter, "orcha.lang.compiler.OrchaProgram")
return application
}
@Bean
fun syntaxAnalysis(): Application {
val application = Application("syntaxAnalysis", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.SyntaxAnalysisImpl", "analysis")
application.input = Input(javaAdapter,"orcha.lang.compiler.OrchaProgram")
application.output = Output(javaAdapter, "orcha.lang.compiler.OrchaProgram")
return application
}
@Bean
fun semanticAnalysis(): Application {
val application = Application("semanticAnalysis", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.SemanticAnalysisImpl", "analysis")
application.input = Input(javaAdapter,"orcha.lang.compiler.OrchaProgram")
application.output = Output(javaAdapter,"orcha.lang.compiler.OrchaProgram")
return application
}
@Bean
fun postprocessing(): Application {
val application = Application("postprocessing", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.PostprocessingImpl", "process")
application.input = Input(javaAdapter,"orcha.lang.compiler.OrchaProgram")
application.output = Output(javaAdapter, "orcha.lang.compiler.OrchaProgram")
return application
}
@Bean
fun linkEditor(): Application {
val application = Application("linkEditor", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.springIntegration.LinkEditorImpl", "link")
application.input = Input(javaAdapter,"orcha.lang.compiler.OrchaProgram")
application.output = Output(javaAdapter, "orcha.lang.compiler.OrchaProgram")
return application
}
@Bean
fun outputGeneration(): Application {
val application = Application("outputGeneration", "Kotlin")
val javaAdapter = JavaServiceAdapter("orcha.lang.compiler.referenceimpl.springIntegration.OutputGenerationToSpringIntegration", "generation")
application.input = Input(javaAdapter, "orcha.lang.compiler.OrchaProgram")
return application
}
@Bean
fun orchaProgramDestination(): EventHandler {
val eventHandler = EventHandler("orchaProgramDestination")
val fileAdapter = OutputFileAdapter("data/output", "orchaCompiler.xml")
eventHandler.output = Output(fileAdapter, "application/xml")
return eventHandler
}
}<file_sep>/orchalang-orchacompiler/src/main/kotlin/orcha/lang/compiler/OrchaCompilerConfig.kt
package orcha.lang.compiler
import orcha.lang.compiler.referenceimpl.LexicalAnalysisImpl
import orcha.lang.compiler.referenceimpl.PreprocessingImpl
import orcha.lang.compiler.referenceimpl.SemanticAnalysisImpl
import orcha.lang.compiler.referenceimpl.SyntaxAnalysisImpl
import orcha.lang.compiler.referenceimpl.springIntegration.LinkEditorImpl
import orcha.lang.compiler.referenceimpl.springIntegration.OutputGenerationToSpringIntegration
import orcha.lang.compiler.referenceimpl.springIntegration.OutputGenerationToSpringIntegrationJavaDSL
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
@Configuration
class OrchaCompilerConfig{
@Bean
fun orchaCompiler(): OrchaCompiler{
return OrchaCompiler()
}
/*@Bean(name = ["whenInstruction"])
fun whenInstructionFactory(): WhenInstructionFactory {
return WhenInstructionFactory()
}
@Bean
@Throws(Exception::class)
fun whenInstruction(): WhenInstruction? {
return whenInstructionFactory().getObject()
}*/
@Value("\${orcha.pathToBinaryCode:build/resources/main}")
internal var pathToBinaryCode: String? = null
@Bean
internal fun preprocessing(): Preprocessing {
return PreprocessingImpl()
}
@Bean
@DependsOn("whenInstruction", "sendInstruction")
@Qualifier("lexicalAnalysisForOrchaCompiler")
internal fun lexicalAnalysis(): LexicalAnalysis {
return LexicalAnalysisImpl()
}
@Bean
internal fun syntaxAnalysis(): SyntaxAnalysis {
return SyntaxAnalysisImpl()
}
@Bean
internal fun semanticAnalysis(): SemanticAnalysis {
return SemanticAnalysisImpl()
}
@Bean
internal fun linkEditor(): LinkEditor {
return LinkEditorImpl()
}
/*@Bean
internal fun outputGeneration(): OutputGeneration {
return OutputGenerationToSpringIntegration()
}*/
@Bean
internal fun outputGeneration(): OutputGeneration {
return OutputGenerationToSpringIntegrationJavaDSL()
}
}<file_sep>/orchalang-spring-boot-sample-app/src/main/orcha/service/transport/ProductDesignation.java
package service.transport;
public class ProductDesignation {
CategoryOfProduct categoryOfProduct;
String brand;
String model;
int quantity;
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/xmlgenerator/MessageTranslator.kt
package orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator
import org.jdom2.Element
import org.jdom2.Namespace
import java.util.HashMap
open class MessageTranslator : Bean() {
fun translate(translationExpression: String): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
val transformer = Element("transformer", namespace)
//transformer.setAttribute("id", "transformer-"+instructionNode.inputName+"-id")
//transformer.setAttribute("input-channel", instructionNode.inputName + "Transformer")
//transformer.setAttribute("output-channel", outputChannel)
transformer.setAttribute("expression", translationExpression)
return transformer
}
fun objectToString(): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
return Element("object-to-string-transformer", namespace)
}
fun objectToJson(): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
return Element("object-to-json-transformer", namespace)
}
fun jsonToObject(type: String): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
val element = Element("json-to-object-transformer", namespace)
element.setAttribute("type", type)
return element
}
/*fun objectToApplicationTransformer(integrationNode: IntegrationNode): Element {
val instruction = integrationNode.instruction
//val applicationName = instruction.springBean.name
//val outputServiceChannel = applicationName + "ServiceAcivatorOutput"
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
val transformer = Element("transformer", namespace)
//transformer.setAttribute("id", "transformer-$outputServiceChannel-id")
//transformer.setAttribute("input-channel", outputServiceChannel)
//transformer.setAttribute("output-channel", integrationNode.outputName)
transformer.setAttribute("method", "transform")
val properties = object : HashMap<String, String>() {
init {
put("application", "applicationName")
}
}
val beanElement = beanWithRef("orcha.lang.compiler.referenceimpl.xmlgenerator.impl.ObjectToApplicationTransformer", properties)
transformer.addContent(beanElement)
/*if (integrationNode.options != null && integrationNode.options.eventSourcing != null) {
if (integrationNode.options.eventSourcing.joinPoint === JoinPoint.after || integrationNode.options.eventSourcing.joinPoint === JoinPoint.beforeAndAfter) {
val adviceChain = Element("request-handler-advice-chain", namespace)
transformer.addContent(adviceChain)
val eventSourcingElement = eventSourcing(integrationNode.options.eventSourcing)
adviceChain.addContent(eventSourcingElement)
}
}*/
return transformer
}
fun applicationsListToObjectsListTransformer(integrationNode: IntegrationNode): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
//val outputChannel = integrationNode.inputName + "AggregatorOutput"
val transformer = Element("transformer", namespace)
//transformer.setAttribute("id", "transformer-$outputChannel-id")
//transformer.setAttribute("input-channel", outputChannel)
//transformer.setAttribute("output-channel", integrationNode.outputName)
transformer.setAttribute("method", "transform")
val properties = HashMap<String, String>()
val beanElement = beanWithValue("orcha.lang.compiler.referenceimpl.xmlgenerator.impl.ApplicationsListToObjectsListTransformer", properties)
transformer.addContent(beanElement)
return transformer
}
fun applicationToObjectTransformer(integrationNode: IntegrationNode): Element {
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
//val outputChannel = integrationNode.inputName + "AggregatorOutput"
val transformer = Element("transformer", namespace)
//transformer.setAttribute("id", "transformer-$outputChannel-id")
//transformer.setAttribute("input-channel", outputChannel)
//transformer.setAttribute("output-channel", integrationNode.outputName)
transformer.setAttribute("method", "transform")
val properties = HashMap<String, String>()
val beanElement = beanWithValue("orcha.lang.compiler.referenceimpl.xmlgenerator.impl.ApplicationToObjectTransformer", properties)
transformer.addContent(beanElement)
return transformer
}*/
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/SpringIntegrationAutoConfiguration.kt
package orcha.lang.compiler.referenceimpl.springIntegration
import orcha.lang.compiler.Postprocessing
import orcha.lang.compiler.referenceimpl.PostprocessingImpl
import orcha.lang.compiler.syntax.SendInstruction
import orcha.lang.compiler.syntax.WhenInstruction
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@ConditionalOnClass(WhenInstructionForSpringIntegration::class, SendInstructionForSpringIntegration::class)
class SpringIntegrationAutoConfiguration {
@Bean(name = ["whenInstruction"])
fun whenInstructionFactory(): WhenInstructionFactory {
return WhenInstructionFactory()
}
@Bean
@Throws(Exception::class)
fun whenInstruction(): WhenInstruction? {
return whenInstructionFactory().getObject()
}
@Bean(name = ["sendInstruction"])
fun sendInstructionFactory(): SendInstructionFactory {
return SendInstructionFactory()
}
@Bean
@Throws(Exception::class)
fun sendInstruction(): SendInstruction? {
return sendInstructionFactory().getObject()
}
@Bean
internal fun postprocessing(): Postprocessing {
return PostprocessingImpl()
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/xmlgenerator/impl/AggregatorImpl.kt
package orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.impl
import orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.Aggregator
import orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator.MessageTranslator
import org.jdom2.Element
import org.jdom2.Namespace
class AggregatorImpl : MessageTranslator(), Aggregator{
override fun aggregate(releaseExpression: String): Element {
//val rootElement = document!!.getRootElement()
val namespace = Namespace.getNamespace("int", "http://www.springframework.org/schema/integration")
//val sameEvent = integrationNode.options.sameEvent
val sameEvent = false
//val instruction = integrationNode.instruction
//val outputChannel = integrationNode.inputName + "AggregatorOutput"
/*if (integrationNode.options == null) {
integrationNode.options = QualityOfServicesOptions(false)
}*/
val aggregatorElement = Element("aggregator", namespace)
//aggregatorElement.setAttribute("id", "aggregator-" + integrationNode.inputName + "-id")
//aggregatorElement.setAttribute("input-channel", integrationNode.inputName)
//aggregatorElement.setAttribute("output-channel", integrationNode.inputName + "Transformer")
aggregatorElement.setAttribute("release-strategy-expression", releaseExpression)
if (sameEvent == true) {
aggregatorElement.setAttribute("correlation-strategy-expression", "headers['messageID']")
} else {
aggregatorElement.setAttribute("correlation-strategy-expression", "0")
}
//rootElement.addContent(aggregatorElement)
/*val transformer = Element("transformer", namespace)
transformer.setAttribute("id", "transformer-" + integrationNode.inputName + "-id")
transformer.setAttribute("input-channel", integrationNode.inputName + "Transformer")
transformer.setAttribute("output-channel", outputChannel)
transformer.setAttribute("expression", transformerExpression)
rootElement.addContent(transformer)*/
/*if (isMultipleArgumentsInExpression == true) {
val applicationsListToObjectsListElement = applicationsListToObjectsListTransformer(integrationNode)
rootElement.addContent(applicationsListToObjectsListElement)
} else {
val applicationToObjectElement = applicationToObjectTransformer(integrationNode)
rootElement.addContent(applicationToObjectElement)
}*/
/*if (integrationNode.options != null && integrationNode.options.queue != null) {
val queueElement = queue(integrationNode.outputName, integrationNode.options.queue)
rootElement.addContent(queueElement)
}*/
return aggregatorElement
}
}
<file_sep>/orchalang-spring-boot-autoconfigure/build.gradle
apply plugin: 'org.springframework.boot'
sourceSets {
main {
java {
srcDirs = [ 'src/main/java' ]
srcDir 'src/main/orcha'
}
}
test {
java {
srcDirs = [ 'src/test/java' ]
srcDir 'src/test/orcha'
}
resources {
srcDirs = ["src/test/resources"]
}
}
}
springBoot {
mainClassName = "orcha.lang.compiler.OrchaCompiler"
}
dependencies {
compile project(':orchalang')
compile "org.springframework.boot:spring-boot-autoconfigure"
annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor"
}
<file_sep>/orchalang-spring-integration-implementation/src/test/kotlin/orcha/lang/compiler/referenceimpl/CompilerReferenceImplTestConfiguration.kt
package orcha.lang.compiler.referenceimpl
import orcha.lang.compiler.LexicalAnalysis
import orcha.lang.compiler.SyntaxAnalysis
import orcha.lang.compiler.referenceimpl.springIntegration.SendInstructionFactory
import orcha.lang.compiler.referenceimpl.springIntegration.WhenInstructionFactory
import orcha.lang.compiler.syntax.SendInstruction
import orcha.lang.compiler.syntax.WhenInstruction
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.SpringBootConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
@SpringBootConfiguration
@Configuration
class CompilerReferenceImplTestConfiguration {
@Value("\${orcha.pathToBinaryCode:build/resources/main}")
internal var pathToBinaryCode: String? = null
@Bean
@DependsOn("whenInstruction", "sendInstruction")
internal fun lexicalAnalysisForTest(): LexicalAnalysis {
return LexicalAnalysisImpl()
}
@Bean(name = ["whenInstruction"])
fun whenInstructionFactory(): WhenInstructionFactory {
return WhenInstructionFactory()
}
@Bean
@Throws(Exception::class)
fun whenInstruction(): WhenInstruction? {
return whenInstructionFactory().getObject()
}
@Bean(name = ["sendInstruction"])
fun sendInstructionFactory(): SendInstructionFactory {
return SendInstructionFactory()
}
@Bean
@Throws(Exception::class)
fun sendInstruction(): SendInstruction? {
return sendInstructionFactory().getObject()
}
@Bean
internal fun syntaxAnalysisForTest(): SyntaxAnalysis {
return SyntaxAnalysisImpl()
}
}
<file_sep>/orchalang-spring-integration-implementation/build.gradle
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.2.71'
id 'org.jetbrains.kotlin.plugin.spring' version '1.2.71'
}
dependencies {
compile project(':orchalang')
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
compile group: 'org.jdom', name: 'jdom2', version: '2.0.6'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
compile 'com.fasterxml.jackson.core:jackson-core:2.10.0'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile 'com.fasterxml.jackson.core:jackson-databind:2.10.0'
implementation 'org.jetbrains.kotlin:kotlin-reflect'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
compileTestKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
<file_sep>/orchalang-spring-boot-sample-app/src/main/orcha/service/transport/ProfileUser.kt
package service.transport
import java.util.Calendar
class ProfileUser {
internal fun check(request: Request): Request {
request.date = Calendar.getInstance().time
request.identifier = 123
request.customer = Customer()
return request
}
}
<file_sep>/orchalang-spring-boot-sample-app/src/main/orcha/service/transport/Request.kt
package service.transport
import java.util.ArrayList
import java.util.Date
class Request {
var identifier: Int = 0
val products = ArrayList<ProductDesignation>()
val deliveryTime: DeliveryTime? = null
var date: Date? = null
val placeOfDelivery: PlaceOfDelivery? = null
var customer: Customer? = null
val bill: Bill? = null
enum class DeliveryTime private constructor(val numberOfDays: Int) {
URGENT(1),
FAST(3),
NORMAL(5)
}
enum class PlaceOfDelivery {
AT_HOME,
DELIVERY_CENTER
}
}
<file_sep>/orchalang-spring-boot-sample-app/src/main/orcha/configuration/transport/ProductOrderConfiguration.kt
package configuration.transport
import orcha.lang.configuration.*
import org.springframework.context.annotation.Bean
import service.transport.ProfileUser
class ProductOrderConfiguration {
@Bean
fun user(): EventHandler {
val eventHandler = EventHandler("user")
val inputFileAdapter = InputFileAdapter("data/input", "request.json")
eventHandler.input = Input("application/json", "service.transport.Request", inputFileAdapter)
val outputFileAdapter = OutputFileAdapter("data/output", true, "securityAlert.json", true, OutputFileAdapter.WritingMode.REPLACE)
eventHandler.output = Output("application/json", "service.airport.SecurityAlert", outputFileAdapter)
return eventHandler
}
@Bean
fun profileUser(): ProfileUser {
return ProfileUser()
}
@Bean
fun authenticateUsersRequest(): Application {
val application = Application("authenticateUsersRequest", "Java")
val javaAdapter = JavaServiceAdapter("service.transport.ProfileUser", "check")
application.input = Input("service.transport.Request", javaAdapter)
application.output = Output("service.transport.Request", javaAdapter)
return application
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/xmlgenerator/MessageRouting.kt
package orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator
<file_sep>/orchalang-spring-boot-sample-app/src/main/orcha/service/transport/Customer.java
package service.transport;
public class Customer {
}
<file_sep>/orchalang-orchacompiler/src/main/kotlin/orcha/lang/compiler/Server.kt
package orcha.lang.compiler
import com.sun.net.httpserver.HttpServer
import org.springframework.boot.runApplication
import java.io.*
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.stream.Collectors
fun inputStreamToString(inputStream: InputStream): String {
val isReader = InputStreamReader(inputStream)
val reader = BufferedReader(isReader)
return reader.lines().collect(Collectors.joining())
}
fun decodeURL(url: String): String {
return java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name())
}
fun getQueryMap(query: String): Map<String, String> {
val params = query.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val map = HashMap<String, String>()
for (param in params) {
val name = param.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
val value = param.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]
map[name] = value
}
return map
}
fun cleanDirectory(dir: File) {
for (file in dir.listFiles()) file.delete()
}
fun main(args: Array<String>) {
HttpServer.create(InetSocketAddress(8080), 0).apply {
createContext("/api/orcha") { http ->
http.responseHeaders.add("Access-Control-Allow-Origin", "*")
http.responseHeaders.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, reponseType");
http.responseHeaders.add("Access-Control-Allow-Credentials", "true")
http.responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,HEAD")
val directory = "src/main/orcha/source/"
val decodedRequest = decodeURL(inputStreamToString(http.requestBody))
val params = getQueryMap(decodedRequest)
if (params.containsKey("fileName") && params.containsKey("fileContent")) {
cleanDirectory(File(directory))
val out = PrintWriter(directory + params["fileName"])
out.println(params["fileContent"])
out.close()
val baos = ByteArrayOutputStream()
val ps = PrintStream(baos)
val old = System.out
System.setOut(ps)
try {
runApplication<DemoApplication>(*args)
} catch (e: Exception) {
println(e.message)
} finally {
System.out.flush()
System.setOut(old)
}
http.sendResponseHeaders(200, 0)
PrintWriter(http.responseBody).use { out ->
out.println(baos.toString())
}
} else {
http.responseHeaders.add("Content-type", "text/plain")
http.sendResponseHeaders(420, 0)
}
}
start()
}
}<file_sep>/orchalang/build.gradle
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.2.71'
id 'org.jetbrains.kotlin.plugin.spring' version '1.2.71'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
//compile group: 'org.jdom', name: 'jdom2', version: '2.0.6'
implementation 'org.jetbrains.kotlin:kotlin-reflect'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
compileTestKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
/*sourceSets {
main {
java {
srcDirs = [ 'src/main/java' ]
srcDir 'src/main/orcha'
}
}
test {
java {
srcDirs = [ 'src/test/java' ]
srcDir 'src/test/orcha'
}
resources {
srcDirs = ["src/test/resources"]
}
}
}*/
/*task fatJar(type: Jar) {
manifest {
attributes 'Main-Class': 'orcha.lang.compiler.OrchaCompiler'
}
baseName = 'orchalanguage'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
springBoot {
mainClassName = "orcha.lang.compiler.OrchaCompiler"
}*/
/*dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
compile 'org.codehaus.groovy:groovy-all:2.4.5'
compile group: 'org.jdom', name: 'jdom2', version: '2.0.6'
}*/
<file_sep>/orchalang-spring-integration-implementation/README.md
# Spring integration implementation
<file_sep>/orchalang-spring-integration-implementation/src/test/kotlin/orcha/lang/compiler/referenceimpl/OutputGenerationTest.kt
package orcha.lang.compiler.referenceimpl
import orcha.lang.compiler.OrchaProgram
import orcha.lang.compiler.OutputGeneration
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class OutputGenerationTest {
@Autowired
internal var outputGeneration: OutputGeneration? = null
@Test
fun test() {
val orchaProgram = OrchaProgram()
//transpiler.transpile(orchaProgram);
}
}
<file_sep>/orchalang-orchacompiler/build.gradle
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.2.71'
id 'org.jetbrains.kotlin.plugin.spring' version '1.2.71'
}
/*sourceSets {
main {
java {
srcDirs = [ 'src/main/kotlin' ]
srcDir 'src/main/orcha'
}
}
test {
java {
srcDirs = [ 'src/test/kotlin' ]
srcDir 'src/test/orcha'
}
resources {
srcDirs = ["src/test/resources"]
}
}
}*/
dependencies {
compile project(':orchalang')
compile project(':orchalang-spring-integration-implementation')
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.jetbrains.kotlin:kotlin-reflect'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
compileTestKotlin {
kotlinOptions {
freeCompilerArgs = ['-Xjsr305=strict']
jvmTarget = '1.8'
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/LinkEditorImpl.kt
package orcha.lang.compiler.referenceimpl.springIntegration
import orcha.lang.compiler.IntegrationNode
import orcha.lang.compiler.LinkEditor
import orcha.lang.compiler.OrchaCompilationException
import orcha.lang.compiler.OrchaProgram
import orcha.lang.compiler.syntax.ComputeInstruction
import orcha.lang.configuration.Application
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.getBean
import org.springframework.context.ApplicationContext
class LinkEditorImpl : LinkEditor {
@Autowired
internal var springApplicationContext: ApplicationContext? = null
@Throws(OrchaCompilationException::class)
override fun link(orchaProgram: OrchaProgram): OrchaProgram {
log.info("Link edition of the orcha program \"" + orchaProgram.orchaMetadata.title + "\" begins. ")
for (node in orchaProgram.integrationGraph) {
log.info("Link edition for the node: " + node)
log.info("Link edition for the instruction: " + node.instruction!!.instruction)
when (node.integrationPattern) {
IntegrationNode.IntegrationPattern.SERVICE_ACTIVATOR -> {
when(node.instruction){
is ComputeInstruction -> {
val compute: ComputeInstruction = node.instruction as ComputeInstruction
val configuration = springApplicationContext!!.getBean(compute.application)
val application: Application = configuration as Application
compute.configuration = application
}
}
}
}
}
log.info("Linf edition of the orcha program \"" + orchaProgram.orchaMetadata.title + "\" complete successfuly.")
return orchaProgram
}
companion object {
private val log = LoggerFactory.getLogger(LinkEditorImpl::class.java)
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/xmlgenerator/Bean.kt
package orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator
import org.jdom2.Element
import org.jdom2.Namespace
import java.util.HashMap
open class Bean {
fun bean(fullClassName: String): Element {
val properties = HashMap<String, String>()
return beanWithValue(fullClassName, properties)
}
fun bean(id: String, fullClassName: String): Element {
val properties = HashMap<String, String>()
return beanWithValue(id, fullClassName, properties)
}
fun beanWithValue(fullClassName: String, properties: Map<String, String>): Element {
val namespace = Namespace.getNamespace("", "http://www.springframework.org/schema/beans")
val bean = Element("bean", namespace)
bean.setAttribute("class", fullClassName)
properties.forEach { (k, v) ->
val property = Element("property", namespace)
property.setAttribute("name", k)
property.setAttribute("value", v)
bean.addContent(property)
}
return bean
}
fun beanWithValue(id: String, fullClassName: String, properties: Map<String, String>): Element {
val namespace = Namespace.getNamespace("", "http://www.springframework.org/schema/beans")
val bean = this.beanWithValue(fullClassName, properties)
bean.setAttribute("id", id)
return bean
}
fun beanWithRef(fullClassName: String, properties: Map<String, String>): Element {
val namespace = Namespace.getNamespace("", "http://www.springframework.org/schema/beans")
val bean = Element("bean", namespace)
bean.setAttribute("class", fullClassName)
properties.forEach { (k, v) ->
val property = Element("property", namespace)
property.setAttribute("name", k)
property.setAttribute("ref", v)
bean.addContent(property)
}
return bean
}
}
<file_sep>/orchalang-spring-integration-implementation/src/main/kotlin/orcha/lang/compiler/referenceimpl/springIntegration/xmlgenerator/Aggregator.kt
package orcha.lang.compiler.referenceimpl.springIntegration.xmlgenerator
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
interface Aggregator {
fun aggregate(releaseExpression: String): Element
}
| 17fabe19256db43fabf652fb1accacbad5a609cc | [
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 32 | Kotlin | riiswa/orchalang-server | dd836d18bd5017e9ad4b3f52463063ca6331f2b2 | d27772c4e1c0b525016530d038cd37ed19b88321 | |
refs/heads/master | <file_sep><?php
session_start();
if(!$_SESSION['validUser'] == true){
header('Location: ../html/login.php');
}
require 'selectProduct.php';
$inProductImage = "";
$inProductName = "";
$inProductPrice = "";
$inProductDescription = "";
$inProductBuyNowButton = "";
$inProductBuyNowButton2 = "";
$inProductAddToCartButton = "";
$inProductViewCart= "";
$inProductImageErrMsg = "";
$inProductNameErrMsg = "";
$inProductPriceErrMsg = "";
$inProductDescriptionErrMsg = "";
$inProductBuyNowButtonErrMsg= "";
$inProductBuyNowButton2ErrMsg= "";
$inProductAddToCartErrMsg= "";
$inProductViewCartErrMsg= "";
if(isset($_POST["submit"]))
{
// capturing the values of the form inputs
$inProductImage= $_FILES['productImage']['name'];
$inProductName = $_POST["productName"];
$inProductPrice = $_POST["productPrice"];
$inProductDescription = $_POST["productDescription"];
$inProductBuyNowButton = $_POST["productBuyNow"];
$inProductAddToCart= $_POST["addToCart"];
$inProductBuyNowButton2=$_POST["productBuyNow2"];
$inProductViewCart= $_POST["viewCart"];
$target = "../images/".basename($_FILES['productImage']['name']);
require 'PDOconnection.php';
require 'insertProduct.php';
if(move_uploaded_file($_FILES['productImage']['tmp_name'], $target)){
$msg = 'Success';
}else{
$msg = 'Fail';
}
$validForm = true; // sets a flag/switch to make sure data is valid
// PHP validation goes here
if($validForm){
require('PDOconnection.php');
//echo '<script>alert("valid")</script>';
} else{
// BAD BAD Data - Display error message, display form to user
// 1. bad name
// put data on the form
// put error messege on the form
$inProductPriceErrMsg = "Invalid Product Price";
$inProductNameErrMsg = "Invalid Product Name";
$inProductPriceErrMsg = "Invalid Product Price";
$inProductDescriptionErrMsg = "Invalid Product Description";
$inProductBuyNowButtonErrMsg = "Invalid button code";
$inProductAddToCartErrMsg = "Invalid Add to cart code";
$inProductViewCartErrMsg = "invalid view card code";
$inProductBuyNowButton2ErrMsg = "invalid buy now button code";
}
}else{
}
?>
<!doctype html>
<html>
<head>
<!-- Meta Data -->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME> photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Form</title>
<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../js/userNav.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- CSS -->
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div id="userNav"></div>
<div id="container" class="p-3 col-9 m-auto">
<form method="POST" action="addProduct.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<h1>Add Product:</h1>
<div class="form-group">
<label for="productImage">Product Image</label>
<input type="file" class="form-control" id="productImage" name="productImage">
</div>
<div class="form-group">
<label for="productName">Product Name</label>
<input type="text" class="form-control" id="productName" name="productName" placeholder="Enter Product Name" value="<?php echo $inProductName; ?>" required><span><?php echo $inProductNameErrMsg; ?> </span>
</div>
<div class="form-group">
<label for="productPrice">Product Price</label>
<input type="text" class="form-control" id="productPrice" name="productPrice" placeholder="Enter Product Price" value="<?php echo $inProductPrice; ?>" required><span><?php echo $inProductPriceErrMsg; ?> </span>
</div>
<div class="form-group">
<label for="productDescription">Product Description</label>
<textarea class="form-control" id="productDescription" name="productDescription" placeholder="What is the picture?" value="<?php echo $inProductDescription; ?>" required></textarea><span><?php echo $inProductDescriptionErrMsg; ?>
</div>
<div class="form-group">
<label for="productBuyNow">Buy Now Online </label>
<textarea class="form-control" id="productBuyNow" name="productBuyNow" placeholder="buy now button code" value="<?php echo $inProductBuyNowButton; ?>"></textarea><span><?php echo $inProductBuyNowButtonErrMsg; ?>
</div>
<div class="form-group">
<label for="productBuyNow2">Buy Now Paper print</label>
<textarea class="form-control" id="productBuyNow2" name="productBuyNow2" placeholder="buy now physical print button code" value="<?php echo $inProductBuyNowButton2; ?>"></textarea><span><?php echo $inProductBuyNowButton2ErrMsg; ?>
</div>
<div class="form-group">
<label for="addToCart">online Add To Cart</label>
<textarea class="form-control" id="addToCart" name="addToCart" placeholder="add to cart button code" value="<?php echo $inProductAddToCart; ?>" required></textarea><span><?php echo $inProductAddToCartErrMsg; ?>
</div>
<div class="form-group">
<label for="viewCart">Paper print add to cart</label>
<textarea class="form-control" id="viewCart" name="viewCart" placeholder="view cart button code" value="<?php echo $inProductViewCart; ?>" required></textarea><span><?php echo $inProductViewCartErrMsg; ?>
</div>
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</form>
</div>
<div id="logout">
<a href="logout.php">Logout</a>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<!-- Css files -->
<link src="../css/index.css" type="text/css" rel="stylesheet">
<!-- javascript files -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../js/nav.js"></script>
<script src="../js/store.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Bootsrap CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Meta Data-->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME> photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title -->
<?php
require '../php/selectProduct.php';
require '../php/PDOconnection.php';
?>
<!doctype html>
<html>
<head>
<!-- Css files -->
<link src="../css/product.css" type="text/css" rel="stylesheet">
<!-- javascript files -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../js/Nav.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Bootsrap CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Meta Data-->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME> photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title -->
<title>Products</title>
</head>
<body>
<div id="Nav"></div>
<?php
while( $row=$stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="m-auto" style="width: 400px;">
<div class="card h-90">
<p> * NOTE: ALL PAPER PRINTS COME WITH A DIGITAL COPY </p>
<img src="../images/<?php echo $row['product_image']; ?>" name="productImage" id="productImage" class="card-img-top">
<div class="card-body m-auto">
<h2 class="card-title text-center">
<?php echo $row['product_Name'];?>
</h2>
<h5 class="text-center">$ <?php echo $row['product_Price'];?></h5>
<h5 class="card-text"> <?php echo $row['product_Description'];?></h5>
<center>
<h5>Buy Now Online Print</h5>
<p><?php echo $row['product_BuyNow'];?></p>
<h5>Buy Now Paper Print</h5>
<p><?php echo $row['product_BuyNow2'];?></p>
<h5>Add To Cart Online Print</h5>
<p><?php echo $row['product_AddToCart'];?></p>
<!--
<h5>Add To Cart Paper Print</h5>
<p><?php //echo $row['product_ViewCart'];?></p>
-->
<h5>View Cart</h5>
<p>
<form target="paypal" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" >
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="encrypted" value="-----<KEY>END <KEY>">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_viewcart_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</p>
</center>
</div>
</div>
<!-- Temporary filler for gap between cards -->
<p></p>
<?php
};
?>
</body>
</html>
<title>Gallary</title>
</head>
<body>
<!-- NavBar -->
<header></header>
<!-- Footer -->
<footer></footer>
</body>
</html><file_sep><?php
session_start();
// assign a defalt value to input fields and error messages
$inLoginUsername = "";
$inLoginPassword = "";
// error messages
$inLoginUsernameErrMsg = "";
$inLoginPasswordErrMsg = "";
if(isset($_POST["submit"]))
{
// capturing the values of the form inputs
$inLoginUsername = $_POST["username"];
$inLoginPassword = $_POST["<PASSWORD>"];
$validForm = true; // sets a flag/switch to make sure data is valid
// PHP validation goes here
if($validForm && $inLoginUsername == 'dhuck' && $inLoginPassword == '<PASSWORD>!'){
//require('validUser.php');
echo '<script>alert("valid")</script>';
$_SESSION["validUser"] = "true";
if($_SESSION["validUser"] == true){
header("Location: ../php/addProduct.php");
}
} else{
// BAD BAD Data - Display error message, display form to user
// 1. bad name
// put data on the form
// put error messege on the form
$inLoginUsernameErrMsg = " Invalid Username";
$inLoginPasswordErrMsg = " <PASSWORD>";
$_SESSION['validUser'] = false;
}
}else{
echo "<h1>Please enter your information</h1>";
}
?>
<!doctype html>
<html>
<head>
<!-- Css files -->
<link src="../css/product.css" type="text/css" rel="stylesheet">
<!-- javascript files -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../js/userNav.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Bootsrap CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Meta Data-->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME> photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title -->
<title>Login</title>
</head>
<body>
<div id="userNav"></div>
<form method="post" action="login.php" class="col-lg-6 col-sm-10 m-auto" >
<div class="form-group">
<label for="username">Username:</label>
<input type="text" name="username" id="username" class="form-control" value="<?php echo $inLoginUsername; ?>"><span><?php echo $inLoginUsernameErrMsg; ?> </span>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="text" name="password" id="password" class="form-control" value="<?php echo $inLoginPassword; ?>"><span><?php echo $inLoginPasswordErrMsg; ?></span>
</div>
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
<button type="reset" class="btn" name="submit">Reset</button>
</form>
</body>
</html><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Css files -->
<link src="../css/index.css" type="text/css" rel="stylesheet">
<!-- javascript files -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../js/nav.js"></script>
<script src="../js/about.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Bootsrap CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Meta Date -->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME> photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Valkenburg</title>
</head>
<body class="p-2 border">
<h1>Product Purchased! Valkenburg Print</h1>
<h2>Thank you for supporting David Huck Photography</h1>
<h2>*Please allow for two weeks if you purchased the Paper Print*</h2>
<div>
<ul>
<li><a href="../images/valkenburg/valkenburg.jpg" download>Valkenburg JPG</a></li>
<li><a href="../images/valkenburg/valkenburg.png" download>Valkenburg PNG</a></li>
<p>If your download has not started within 10 seconds, click the link(s) above</p>
</ul>
</div>
<h2><a href="../html/gallery.html">Click Here To Return To David Huck Photography</a></h2>
<!-- Footer -->
<footer></footer>
</body>
</html><file_sep>
$(document).ready(function(){
$('#store').html(`
<div class="container">
<div class="row">
<div class="col-sm">
<div class="card h-100">
<a href="#"><img class="card-img-top" src="../images/ferrari.jpg" alt="ferrari"></a>
<div class="card-body">
<h4 class="card-title">
<a href="#">Ferrari Side Print</a>
</h4>
<h5>$5.00 - $30.00</h5>
<p class="card-text">Spice up your collection with this beautiful Ferrari Print!</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
</div>
</div
`);
});<file_sep><?php
session_start();
if(!$_SESSION['validUser'] == true){
header('Location: ../html/login.php');
}
try {
require 'PDOconnection.php';
require 'selectProduct.php'; //CONNECT to the database
$sql = "DELETE FROM dhp WHERE product_ID='$_GET[id]'";
//PREPARE the SQL statement
$stmt = $conn->prepare($sql);
//EXECUTE the prepared statement
$stmt->execute();
//Prepared statement result will deliver an associative array
$stmt->setFetchMode(PDO::FETCH_ASSOC);
header("refresh:1; url=deleteProduct.php");
}
catch(PDOException $e)
{
$message = "There has been a problem . Please try again later.";
echo $message;
error_log($e->getMessage()); //Delivers a developer defined error message to the PHP log file at c:\xampp/php\logs\php_error_log
error_log($e->getLine());
error_log(var_dump(debug_backtrace()));
//Clean up any variables or connections that have been left hanging by this error.
header('Location: files/505_error_response_page.php'); //sends control to a User friendly page
}
?><file_sep><?php
// PHP PDO Connection File.
// This file used to connect to a database.
// Include this file into your application as needed.
$serverName = 'localhost'; // the usual default name
$username = 'dnhuck_photography'; //username of database
$password = '<PASSWORD>!'; //password of database
$database = 'dnhuck_photography'; // name of database you will be accessing
try {
$conn = new PDO("mysql:host=$serverName;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Submission Success! Redirecting you now";
//header('Refresh:3; url="eventsForm.php", true, 303');
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?><file_sep>
$(document).ready(function(){
$('#gallary').html(`
<div class="p-2">
<img src="../images/banner.jpg" alt="david huck banner" class="img-fluid">
<center style="width: 80%;" class="m-auto">
<h1 class="d-flex justify-content-center">Gallary</h1>
<div id="pixlee_container"></div><script type="text/javascript">window.PixleeAsyncInit = function() {Pixlee.init({apiKey:'<KEY>'});Pixlee.addSimpleWidget({widgetId:'30371'});};</script><script src="//instafeed.assets.pxlecdn.com/assets/pixlee_widget_1_0_0.js"></script>
</center>
</div>
`);
});<file_sep><?php
if(isset($_POST['submit'])){
$firstName = $_POST['fName'];
$lastName = $_POST['lName'];
$FromEmail = $_POST['email'];
$message = $_POST['message'];
$mailTo = '<EMAIL>';
$headers = "From: " . $FromEmail;
$txt = "You have recieved an email from " . $firstName. ".\n\n".$message;
mail($mailTo, $message, $txt, $headers);
echo "<script>alert('Sent Success!';)</script>";
header('Location: ../html/contact.html');
}
?><file_sep>
$(document).ready(function(){
$('#homepage').html(`
<div>
<a href="gallery.html"><img src="../images/home.png" alt="biker chick" class="img-fluid"></a>
</div>
`);
});<file_sep>
$(document).ready(function(){
$('#userNav').html(`
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand">DAVID HUCK PRODUCTS</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="../html/gallery.html">Back To Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="addProduct.php">Add New Product</a>
</li>
<li class="nav-item">
<a class="nav-link" href="updateProduct.php">Update Product</a>
</li>
<li class="nav-item">
<a class="nav-link" href="deleteProduct.php">Delete Product</a>
</li>
<li class="nav-item">
<a class="nav-link" href="viewProduct.php">View Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../html/logout.php">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
`);
});<file_sep><?php
session_start();
if(!$_SESSION['validUser'] == true){
header('Location: ../html/login.php');
}
require 'PDOconnection.php'; // access and run this external file
try{
$picImage = $_FILES['productImage']['name'];
$picName = $_POST["productName"];
$picPrice = $_POST["productPrice"];
$picDescription = $_POST["productDescription"];
$picBuyNow = $_POST["productBuyNow"];
$picBuyNow2=$_POST['productBuyNow2'];
$picAddToCart = $_POST["addToCart"];
$picViewCart = $_POST["viewCart"];
//$eventTime = $_POST["eventTime"];
//$image = $_FILES['image']['name'];
// PDO Prepare statements
// prepare the SQL statements
// 1. Create the SQL statements with name placeholders
$sql = "INSERT INTO dhp(product_image, product_Name, product_Price, product_Description, product_BuyNow, product_BuyNow2, product_AddToCart, product_ViewCart)
VALUES (:productImage, :productName, :productPrice, :productDescription, :productBuyNow, :productBuyNow2, :addToCart, :viewCart)";
// 2. Create the prepared statement object
$stmt = $conn->prepare($sql); // creates the prepared statement object
// Bind parameters to the prepared statement object. One for each parameter
$stmt->bindParam(':productImage', $picImage);
$stmt->bindParam(':productName', $picName);
$stmt->bindParam(':productPrice', $picPrice);
$stmt->bindParam(':productDescription', $picDescription);
$stmt->bindParam(':productBuyNow', $picBuyNow);
$stmt->bindParam(':productBuyNow2', $picBuyNow2);
$stmt->bindParam(':addToCart', $picAddToCart);
$stmt->bindParam(':viewCart', $picViewCart);
//Execute the prepared statement
$stmt->execute();
}
catch(PDOException $e){
echo "Failure. Please try again";
}
$conn = null; // close your connection object
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Insert Events</title>
</head>
<body>
</body>
</html><file_sep><?php
session_start();
if(!$_SESSION['validUser'] == true){
header('Location: login.php');
}
require 'selectProduct.php';
require 'PDOconnection.php';
?>
<!doctype html>
<html>
<head>
<!-- Css files -->
<link src="../css/product.css" type="text/css" rel="stylesheet">
<!-- javascript files -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../js/userNav.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Bootsrap CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Meta Data-->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME>uck photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title -->
<title>Products</title>
</head>
<body>
<div id="userNav"></div>
<?php
while( $row=$stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="m-auto" style="width: 400px;">
<div class="card h-90">
<p> * NOTE: ALL PAPER PRINTS COME WITH A DIGITAL COPY </p>
<img src="../images/<?php echo $row['product_image']; ?>" name="productImage" id="productImage" class="card-img-top">
<div class="card-body m-auto">
<h2 class="card-title text-center">
<?php echo $row['product_Name'];?>
</h2>
<h5 class="text-center">$ <?php echo $row['product_Price'];?></h5>
<h5 class="card-text"> <?php echo $row['product_Description'];?></h5>
<center>
<h5>Buy Now Online Print</h5>
<p><?php echo $row['product_BuyNow'];?></p>
<h5>Add To Cart Paper Print</h5>
<p><?php echo $row['product_BuyNow2'];?></p>
<h5>Buy Now Online Print</h5>
<p><?php echo $row['product_AddToCart'];?></p>
<!--
<h5>Add To Cart Paper Print</h5>
<p><?php //echo $row['product_ViewCart'];?></p>
-->
</center>
</div>
</div>
<!-- Temporary filler for gap between cards -->
<p></p>
<?php
};
?>
</body>
</html>
<file_sep><?php
session_start();
if(!$_SESSION['validUser'] == true){
header('Location: ../html/login.php');
}
?>
<!doctype html>
<html>
<head>
<!-- javascript files -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="../js/userNav.js"></script>
<!-- Bootsrap CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Meta Data-->
<meta charset="UTF-8">
<meta name="description" content="photography">
<meta name="author" content="<NAME> photography">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title -->
<title>Update Products</title>
</head>
<body>
<div id="userNav"></div>
<h1>Update Product:</h1>
<?php
require 'selectProduct.php';
while( $row=$stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="p-3 col-9 m-auto">
<form method="POST" action="update.php" enctype="multipart/form-data" >
<input type="hidden" name="size" value="1000000">
<input type="hidden" name="id" value="<?php echo $row['product_ID']?>">
<div class="form-group">
<label for="updateImage">Update Image</label>
<input type="file" class="form-control" id="updateImage" name="updateImage" value="$_FILES['product_image']['name'];">
</div>
<div class="form-group">
<label for="updateName">Product Name</label>
<input type="text" class="form-control" id="updateName" name="updateName" value="<?php echo $row['product_Name']?>">
</div>
<div class="form-group">
<label for="updatePrice">Update Price</label>
<input type="text" class="form-control" id="updatePrice" name="updatePrice" value="<?php echo $row['product_Price']?>">
</div>
<div class="form-group">
<label for="updateDescription">Update Description</label>
<textarea class="form-control" id="updateDescription" name="updateDescription" value="<?php echo $row['product_Description']?>"> </textarea>
</div>
<div class="form-group">
<label for="updateBuyNow">Update Buy Now Button Code</label>
<textarea class="form-control" id="updateBuyNow" name="updateBuyNow" value="<?php echo $row['product_BuyNow']?>"></textarea>
</div>
<div class="form-group">
<label for="updateBuyNow2">Update Physical Good Buy Now Button Code</label>
<textarea class="form-control" id="updateBuyNow2" name="updateBuyNow2" value="<?php echo $row['product_BuyNow2']?>"></textarea>
</div>
<div class="form-group">
<label for="updateAddToCart">Update Add To Card Button Code</label>
<textarea class="form-control" id="updateAddToCart" name="updateAddToCart" value="<?php echo $row['product_AddToCart']?>"></textarea>
</div>
<!--
<div class="form-group">
<label for="updateViewCart">Update Buy Now Button Code</label>
<textarea class="form-control" id="updateViewCart" name="updateViewCart" value="<?php echo $row['product_ViewCart']?>"></textarea>
</div>
-->
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</form>
</div>
<?php
}
?>
</body>
</html> | 70b5f0c1c357f8a36fc28e8780c3c43f36f3fab9 | [
"JavaScript",
"PHP"
] | 14 | PHP | dnhuck/davidhuck.net | 12f7fb9473f376ae1d385071d6bf7f2d7fe343f7 | 9850cb7c5f6d5f96b15ff0f762b8d537c92d17aa | |
refs/heads/master | <repo_name>Tiance-Zhang/clinic-backend<file_sep>/src/main/java/com/harilab/clinic/service/AuthService.java
package com.harilab.clinic.service;
import com.harilab.clinic.model.Clinician;
import com.harilab.clinic.repository.ClinicianRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AuthService {
@Autowired
private ClinicianRepository repository;
public boolean clinicianLogin(Clinician clinician) {
Clinician other = repository.findClinicianByNameAndPassword(clinician.getUsername(), clinician.getPassword());
return other != null;
}
}
<file_sep>/src/main/java/com/harilab/clinic/service/ClinicianService.java
package com.harilab.clinic.service;
import com.harilab.clinic.model.Clinician;
import com.harilab.clinic.repository.ClinicianRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ClinicianService {
@Autowired
private ClinicianRepository repository;
// create clinician
public Clinician saveClinician(Clinician clinician){
return repository.save(clinician);
}
public List<Clinician> saveClinicians(List<Clinician> clinicians){
return repository.saveAll(clinicians);
}
// get clinician
public List<Clinician> getClinicians(){
return repository.findAll();
}
public Clinician getClinicianById(int id){
return repository.findById(id).orElse(null);
}
// public Clinician getClinicianByName(String name){
// return repository.findByName(name);
// }
// delete clinician
public String deleteClinicianById(int id){
repository.deleteById(id);
return "Clinician removed !!" + id;
}
// update clinician
public Clinician updateClinician(Clinician clinician){
Clinician existingClinician = repository.findById(clinician.getId()).orElse(null);
existingClinician.setUsername(clinician.getUsername());
existingClinician.setPassword(<PASSWORD>ician.<PASSWORD>());
return repository.save(existingClinician);
}
}
<file_sep>/src/main/java/com/harilab/clinic/controller/ParticipantController.java
package com.harilab.clinic.controller;
import com.harilab.clinic.model.Participant;
import com.harilab.clinic.service.ParticipantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class ParticipantController {
@Autowired
private ParticipantService service;
@CrossOrigin
@PostMapping("/participants")
public Participant addParticipant(@RequestBody Participant participant){
return service.saveParticipant(participant);
}
@GetMapping("/participants")
@CrossOrigin
public List<Participant> getParticipants(){
return service.getParticipants();
}
@CrossOrigin
@GetMapping("/participants/alert")
public List<Participant> getParticipantsInAlertOrder(){
return service.getParticipantInAlertOrder();
}
@CrossOrigin
@GetMapping("/participants/{id}")
public Participant getParticipantById(@PathVariable int id){
return service.getParticipantById(id);
}
// @CrossOrigin
// @GetMapping("/participants/{name}")
// public Participant getParticipantByName(@PathVariable String name){
// return service.getParticipantByName(name);
// }
// @CrossOrigin
// @GetMapping("/participants/{device}")
// public Participant getParticipantByDevice(@PathVariable String device){
// return service.getParticipantByDevice(device);
// }
@CrossOrigin
@PatchMapping("/participants")
public Participant updateParticipant(@RequestBody Participant participant){
return service.updateParticipant(participant);
}
@CrossOrigin
@DeleteMapping("/participants/{id}")
public String deleteParticipant(@PathVariable int id){
return service.deleteParticipantById(id);
}
}
<file_sep>/src/main/java/com/harilab/clinic/controller/AuthController.java
package com.harilab.clinic.controller;
import com.harilab.clinic.model.Clinician;
import com.harilab.clinic.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
@Autowired
private AuthService service;
@CrossOrigin
@PostMapping("/login")
public boolean clinicianLogin(@RequestBody Clinician clinician){
return service.clinicianLogin(clinician);
}
}
<file_sep>/src/main/java/com/harilab/clinic/controller/RecordController.java
package com.harilab.clinic.controller;
import com.harilab.clinic.model.Record;
import com.harilab.clinic.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
public class RecordController {
@Autowired
private RecordService service;
@PostMapping("/participants/{pid}/records")
@CrossOrigin
public Record addRecord(@PathVariable int pid, @RequestBody Record record) {
return service.saveRecord(pid, record);
}
@CrossOrigin
@GetMapping("/records/{id}")
public Record getRecordById(@PathVariable int id){
return service.getRecordById(id);
}
@CrossOrigin
@GetMapping("/participants/{pid}/records")
public List<Record> getRecordsByParticipant(@PathVariable int pid){
return service.getRecordsByParticipant(pid);
}
@CrossOrigin
@GetMapping("/participants/{pid}/records/latest")
public Record getLatestRecordByParticipant(@PathVariable int pid){
return service.getLatestRecordByParticipant(pid);
}
@CrossOrigin
@GetMapping("/participants/{pid}/usage/lastweek")
public int[] getWeeklyUsageByParticipant(@PathVariable int pid){
return service.getWeeklyUsageByParticipant(pid);
}
@CrossOrigin
@GetMapping("/participants/{pid}/records/today")
public List<Record> getTodayRecordsByParticipant(@PathVariable int pid){
return service.getTodayRecordsByParticipant(pid);
}
@CrossOrigin
@PatchMapping("/records")
public Record updateRecord(@RequestBody Record record) {
return service.updateRecord(record);
}
@CrossOrigin
@DeleteMapping("/records/{id}")
public String deleteRecord(@PathVariable int id) {
return service.deleteRecordById(id);
}
}
<file_sep>/src/main/java/com/harilab/clinic/service/ParticipantService.java
package com.harilab.clinic.service;
import com.harilab.clinic.model.Participant;
import com.harilab.clinic.repository.ParticipantRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.List;
@Service
public class ParticipantService {
@Autowired
private ParticipantRepository repository;
// create participant
public Participant saveParticipant(Participant participant) {
return repository.save(participant);
}
public List<Participant> saveParticipants(List<Participant> participants) {
return repository.saveAll(participants);
}
// get participant
public List<Participant> getParticipants() {
return repository.findAll();
}
public List<Participant> getParticipantInAlertOrder(){
List<Participant> result = getParticipants();
// update
for(Participant p: result){
participantAlertUpdateHelper(p);
}
result.sort(new CompareByAlertDays());
return result;
}
private void participantAlertUpdateHelper(Participant participant) {
LocalDate currentDate = LocalDate.now();
LocalDate lastRecordDate = Instant.ofEpochMilli(participant.getLast_record_time().getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
int days = Period.between(lastRecordDate, currentDate).getDays();
participant.setAlert_days(days);
repository.save(participant);
}
public Participant getParticipantById(int id) {
return repository.findById(id).orElse(null);
}
// public Participant getParticipantByName(String name){
// return repository.findByName(name);
// }
// public Participant getParticipantByDevice(String device){
// return repository.findByDevice(device);
// }
// public Participant getParticipantsByClinicianId(int cid){ return repository.findByClinicianId(cid); }
// delete participant
public String deleteParticipantById(int id) {
repository.deleteById(id);
return "Participant removed !!" + id;
}
// update participant
public Participant updateParticipant(Participant participant) {
Participant existingParticipant = repository.findById(participant.getId()).orElse(null);
existingParticipant.setUsername(participant.getUsername());
existingParticipant.setDevice_id(participant.getDevice_id());
return repository.save(existingParticipant);
}
/**
* Comparator class used to sort record in reversed time order.
*/
private class CompareByAlertDays implements Comparator<Participant> {
public int compare(Participant one, Participant two) {
return Integer.compare (two.getAlert_days(), one.getAlert_days());
}
}
}
| 6e0400d84cdd56462e4d6c486a456afa91dc6aeb | [
"Java"
] | 6 | Java | Tiance-Zhang/clinic-backend | 85cb8de45a80f8350fdb7a779ff96d4205d98751 | c71bcac2fb04d5186b7c0abc4e0b2a37fc7c583b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.