repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
G2159687/espd
app/src/main/java/com/github/epd/sprout/items/food/Food.java
3404
package com.github.epd.sprout.items.food; import com.github.epd.sprout.Assets; import com.github.epd.sprout.actors.buffs.Hunger; import com.github.epd.sprout.actors.hero.Hero; import com.github.epd.sprout.effects.Speck; import com.github.epd.sprout.effects.SpellSprite; import com.github.epd.sprout.items.Item; import com.github.epd.sprout.items.artifacts.HornOfPlenty; import com.github.epd.sprout.items.scrolls.ScrollOfRecharging; import com.github.epd.sprout.messages.Messages; import com.github.epd.sprout.sprites.ItemSpriteSheet; import com.github.epd.sprout.utils.GLog; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Random; import java.util.ArrayList; public class Food extends Item { private static final float TIME_TO_EAT = 3f; public static final String AC_EAT = Messages.get(Food.class, "ac_eat"); public float energy = Hunger.HUNGRY; public String message = Messages.get(this, "eat_msg"); { stackable = true; name = Messages.get(this, "name"); image = ItemSpriteSheet.RATION; bones = true; defaultAction = AC_EAT; } @Override public ArrayList<String> actions(Hero hero) { ArrayList<String> actions = super.actions(hero); actions.add(AC_EAT); return actions; } @Override public void execute(Hero hero, String action) { if (action.equals(AC_EAT)) { int hungerori = hero.buff(Hunger.class).hungerLevel(); detach(hero.belongings.backpack); hero.buff(Hunger.class).satisfy(energy); GLog.i(message); int healEnergy = Math.max(7, Math.round(energy / 40)); switch (hero.heroClass) { case WARRIOR: if (hero.HP < hero.HT) { hero.HP = Math.min(hero.HP + Random.Int(3, healEnergy), hero.HT); hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1); } break; case MAGE: hero.belongings.charge(false); ScrollOfRecharging.charge(hero); if (hero.HP < hero.HT) { hero.HP = Math.min((hero.HP + Random.Int(1, 3)), hero.HT); hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1); } break; case ROGUE: if (hero.HP < hero.HT) { hero.HP = Math.min((hero.HP + Random.Int(1, 3)), hero.HT); hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1); } case HUNTRESS: if (hero.HP < hero.HT) { hero.HP = Math.min((hero.HP + Random.Int(1, 3)), hero.HT); hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1); } break; } if (hero.buff(HornOfPlenty.hornRecharge.class) != null && hero.buff(HornOfPlenty.hornRecharge.class).level() > 48) { if (hungerori - hero.buff(Hunger.class).hungerLevel() >= hungerori) { int extra = ((int) energy - hungerori) / 20; if (extra > 0 && hero.HP < hero.HT){ hero.HP = Math.min(hero.HP + extra, hero.HT); hero.sprite.emitter().burst(Speck.factory(Speck.HEALING), 1); GLog.p(Messages.get(HornOfPlenty.class,"overfull")); } } } hero.sprite.operate(hero.pos); hero.busy(); SpellSprite.show(hero, SpellSprite.FOOD); Sample.INSTANCE.play(Assets.SND_EAT); hero.spend(TIME_TO_EAT); } else { super.execute(hero, action); } } @Override public String info() { return Messages.get(this, "desc"); } @Override public boolean isUpgradable() { return false; } @Override public boolean isIdentified() { return true; } @Override public int price() { return 10 * quantity; } }
gpl-3.0
simple-codeblocks/Codeblocks
src/plugins/scriptedwizard/resources/glut/files/main.cpp
4326
/* * GLUT Shapes Demo * * Written by Nigel Stewart November 2003 * * This program is test harness for the sphere, cone * and torus shapes in GLUT. * * Spinning wireframe and smooth shaded shapes are * displayed until the ESC or q key is pressed. The * number of geometry stacks and slices can be adjusted * using the + and - keys. */ #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include <stdlib.h> static int slices = 16; static int stacks = 16; /* GLUT callback Handlers */ static void resize(int width, int height) { const float ar = (float) width / (float) height; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity() ; } static void display(void) { const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0; const double a = t*90.0; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3d(1,0,0); glPushMatrix(); glTranslated(-2.4,1.2,-6); glRotated(60,1,0,0); glRotated(a,0,0,1); glutSolidSphere(1,slices,stacks); glPopMatrix(); glPushMatrix(); glTranslated(0,1.2,-6); glRotated(60,1,0,0); glRotated(a,0,0,1); glutSolidCone(1,1,slices,stacks); glPopMatrix(); glPushMatrix(); glTranslated(2.4,1.2,-6); glRotated(60,1,0,0); glRotated(a,0,0,1); glutSolidTorus(0.2,0.8,slices,stacks); glPopMatrix(); glPushMatrix(); glTranslated(-2.4,-1.2,-6); glRotated(60,1,0,0); glRotated(a,0,0,1); glutWireSphere(1,slices,stacks); glPopMatrix(); glPushMatrix(); glTranslated(0,-1.2,-6); glRotated(60,1,0,0); glRotated(a,0,0,1); glutWireCone(1,1,slices,stacks); glPopMatrix(); glPushMatrix(); glTranslated(2.4,-1.2,-6); glRotated(60,1,0,0); glRotated(a,0,0,1); glutWireTorus(0.2,0.8,slices,stacks); glPopMatrix(); glutSwapBuffers(); } static void key(unsigned char key, int x, int y) { switch (key) { case 27 : case 'q': exit(0); break; case '+': slices++; stacks++; break; case '-': if (slices>3 && stacks>3) { slices--; stacks--; } break; } glutPostRedisplay(); } static void idle(void) { glutPostRedisplay(); } const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f }; const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f }; const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f }; const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; const GLfloat high_shininess[] = { 100.0f }; /* Program entry point */ int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitWindowSize(640,480); glutInitWindowPosition(10,10); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("GLUT Shapes"); glutReshapeFunc(resize); glutDisplayFunc(display); glutKeyboardFunc(key); glutIdleFunc(idle); glClearColor(1,1,1,1); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess); glutMainLoop(); return EXIT_SUCCESS; }
gpl-3.0
pperichon/domoticz
hardware/DomoticzHardware.cpp
38078
#include "stdafx.h" #include <iostream> #include "DomoticzHardware.h" #include "../main/Logger.h" #include "../main/localtime_r.h" #include "../main/Helper.h" #include "../main/RFXtrx.h" #include "../main/SQLHelper.h" #include "../main/mainworker.h" #include "hardwaretypes.h" #define round(a) ( int ) ( a + .5 ) CDomoticzHardwareBase::CDomoticzHardwareBase() { m_HwdID=0; //should be uniquely assigned m_bEnableReceive=false; m_rxbufferpos=0; m_SeqNr=0; m_pUserData=NULL; m_bIsStarted=false; m_stopHeartbeatrequested = false; mytime(&m_LastHeartbeat); mytime(&m_LastHeartbeatReceive); m_DataTimeout = 0; m_bSkipReceiveCheck = false; m_bOutputLog = true; m_iHBCounter = 0; m_baro_minuteCount = 0; m_last_forecast = wsbaroforcast_unknown; mytime(&m_BaroCalcLastTime); }; CDomoticzHardwareBase::~CDomoticzHardwareBase() { } bool CDomoticzHardwareBase::Start() { m_iHBCounter = 0; return StartHardware(); } bool CDomoticzHardwareBase::Stop() { boost::lock_guard<boost::mutex> l(readQueueMutex); return StopHardware(); } void CDomoticzHardwareBase::EnableOutputLog(const bool bEnableLog) { m_bOutputLog = bEnableLog; } bool CDomoticzHardwareBase::onRFXMessage(const unsigned char *pBuffer, const size_t Len) { if (!m_bEnableReceive) return true; //receiving not enabled size_t ii=0; while (ii<Len) { if (m_rxbufferpos == 0) //1st char of a packet received { if (pBuffer[ii]==0) //ignore first char if 00 return true; } m_rxbuffer[m_rxbufferpos]=pBuffer[ii]; m_rxbufferpos++; if (m_rxbufferpos>=sizeof(m_rxbuffer)) { //something is out of sync here!! //restart _log.Log(LOG_ERROR,"input buffer out of sync, going to restart!...."); m_rxbufferpos=0; return false; } if (m_rxbufferpos > m_rxbuffer[0]) { sDecodeRXMessage(this, (const unsigned char *)&m_rxbuffer, NULL, -1); m_rxbufferpos = 0; //set to zero to receive next message } ii++; } return true; } void CDomoticzHardwareBase::StartHeartbeatThread() { m_stopHeartbeatrequested = false; m_Heartbeatthread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&CDomoticzHardwareBase::Do_Heartbeat_Work, this))); } void CDomoticzHardwareBase::StopHeartbeatThread() { m_stopHeartbeatrequested = true; if (m_Heartbeatthread) { m_Heartbeatthread->join(); // Wait a while. The read thread might be reading. Adding this prevents a pointer error in the async serial class. sleep_milliseconds(10); } } void CDomoticzHardwareBase::Do_Heartbeat_Work() { int secCounter = 0; int hbCounter = 0; while (!m_stopHeartbeatrequested) { sleep_milliseconds(200); if (m_stopHeartbeatrequested) break; secCounter++; if (secCounter == 5) { secCounter = 0; hbCounter++; if (hbCounter % 12 == 0) { mytime(&m_LastHeartbeat); } } } } void CDomoticzHardwareBase::SetHeartbeatReceived() { mytime(&m_LastHeartbeatReceive); } void CDomoticzHardwareBase::HandleHBCounter(const int iInterval) { m_iHBCounter++; if (m_iHBCounter % iInterval == 0) { SetHeartbeatReceived(); } } //Sensor Helpers void CDomoticzHardwareBase::SendTempSensor(const int NodeID, const int BatteryLevel, const float temperature, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.TEMP.packetlength = sizeof(tsen.TEMP) - 1; tsen.TEMP.packettype = pTypeTEMP; tsen.TEMP.subtype = sTypeTEMP5; tsen.TEMP.battery_level = BatteryLevel; tsen.TEMP.rssi = RssiLevel; tsen.TEMP.id1 = (NodeID & 0xFF00) >> 8; tsen.TEMP.id2 = NodeID & 0xFF; tsen.TEMP.tempsign = (temperature >= 0) ? 0 : 1; int at10 = round(std::abs(temperature*10.0f)); tsen.TEMP.temperatureh = (BYTE)(at10 / 256); at10 -= (tsen.TEMP.temperatureh * 256); tsen.TEMP.temperaturel = (BYTE)(at10); sDecodeRXMessage(this, (const unsigned char *)&tsen.TEMP, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendHumiditySensor(const int NodeID, const int BatteryLevel, const int humidity, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.HUM.packetlength = sizeof(tsen.HUM) - 1; tsen.HUM.packettype = pTypeHUM; tsen.HUM.subtype = sTypeHUM1; tsen.HUM.battery_level = BatteryLevel; tsen.HUM.rssi = RssiLevel; tsen.HUM.id1 = (NodeID & 0xFF00) >> 8; tsen.HUM.id2 = NodeID & 0xFF; tsen.HUM.humidity = (BYTE)humidity; tsen.HUM.humidity_status = Get_Humidity_Level(tsen.HUM.humidity); sDecodeRXMessage(this, (const unsigned char *)&tsen.HUM, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendBaroSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float pressure, const int forecast, const std::string &defaultname) { _tGeneralDevice gdevice; gdevice.subtype = sTypeBaro; gdevice.intval1 = (NodeID << 8) | ChildID; gdevice.intval2 = forecast; gdevice.floatval1 = pressure; sDecodeRXMessage(this, (const unsigned char *)&gdevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendTempHumSensor(const int NodeID, const int BatteryLevel, const float temperature, const int humidity, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.TEMP_HUM.packetlength = sizeof(tsen.TEMP_HUM) - 1; tsen.TEMP_HUM.packettype = pTypeTEMP_HUM; tsen.TEMP_HUM.subtype = sTypeTH5; tsen.TEMP_HUM.battery_level = BatteryLevel; tsen.TEMP_HUM.rssi = RssiLevel; tsen.TEMP_HUM.id1 = (NodeID&0xFF00)>>8; tsen.TEMP_HUM.id2 = NodeID & 0xFF; tsen.TEMP_HUM.tempsign = (temperature >= 0) ? 0 : 1; int at10 = round(std::abs(temperature*10.0f)); tsen.TEMP_HUM.temperatureh = (BYTE)(at10 / 256); at10 -= (tsen.TEMP_HUM.temperatureh * 256); tsen.TEMP_HUM.temperaturel = (BYTE)(at10); tsen.TEMP_HUM.humidity = (BYTE)humidity; tsen.TEMP_HUM.humidity_status = Get_Humidity_Level(tsen.TEMP_HUM.humidity); sDecodeRXMessage(this, (const unsigned char *)&tsen.TEMP_HUM, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendTempHumBaroSensor(const int NodeID, const int BatteryLevel, const float temperature, const int humidity, const float pressure, int forecast, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.TEMP_HUM_BARO.packetlength = sizeof(tsen.TEMP_HUM_BARO) - 1; tsen.TEMP_HUM_BARO.packettype = pTypeTEMP_HUM_BARO; tsen.TEMP_HUM_BARO.subtype = sTypeTHB1; tsen.TEMP_HUM_BARO.battery_level = BatteryLevel; tsen.TEMP_HUM_BARO.rssi = RssiLevel; tsen.TEMP_HUM_BARO.id1 = (NodeID & 0xFF00) >> 8; tsen.TEMP_HUM_BARO.id2 = NodeID & 0xFF; tsen.TEMP_HUM_BARO.tempsign = (temperature >= 0) ? 0 : 1; int at10 = round(std::abs(temperature*10.0f)); tsen.TEMP_HUM_BARO.temperatureh = (BYTE)(at10 / 256); at10 -= (tsen.TEMP_HUM_BARO.temperatureh * 256); tsen.TEMP_HUM_BARO.temperaturel = (BYTE)(at10); tsen.TEMP_HUM_BARO.humidity = (BYTE)humidity; tsen.TEMP_HUM_BARO.humidity_status = Get_Humidity_Level(tsen.TEMP_HUM.humidity); int ab10 = round(pressure); tsen.TEMP_HUM_BARO.baroh = (BYTE)(ab10 / 256); ab10 -= (tsen.TEMP_HUM_BARO.baroh * 256); tsen.TEMP_HUM_BARO.barol = (BYTE)(ab10); tsen.TEMP_HUM_BARO.forecast = (BYTE)forecast; sDecodeRXMessage(this, (const unsigned char *)&tsen.TEMP_HUM_BARO, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendTempHumBaroSensorFloat(const int NodeID, const int BatteryLevel, const float temperature, const int humidity, const float pressure, int forecast, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.TEMP_HUM_BARO.packetlength = sizeof(tsen.TEMP_HUM_BARO) - 1; tsen.TEMP_HUM_BARO.packettype = pTypeTEMP_HUM_BARO; tsen.TEMP_HUM_BARO.subtype = sTypeTHBFloat; tsen.TEMP_HUM_BARO.battery_level = 9; tsen.TEMP_HUM_BARO.rssi = RssiLevel; tsen.TEMP_HUM_BARO.id1 = (NodeID & 0xFF00) >> 8; tsen.TEMP_HUM_BARO.id2 = NodeID & 0xFF; tsen.TEMP_HUM_BARO.tempsign = (temperature >= 0) ? 0 : 1; int at10 = round(std::abs(temperature*10.0f)); tsen.TEMP_HUM_BARO.temperatureh = (BYTE)(at10 / 256); at10 -= (tsen.TEMP_HUM_BARO.temperatureh * 256); tsen.TEMP_HUM_BARO.temperaturel = (BYTE)(at10); tsen.TEMP_HUM_BARO.humidity = (BYTE)humidity; tsen.TEMP_HUM_BARO.humidity_status = Get_Humidity_Level(tsen.TEMP_HUM.humidity); int ab10 = round(pressure*10.0f); tsen.TEMP_HUM_BARO.baroh = (BYTE)(ab10 / 256); ab10 -= (tsen.TEMP_HUM_BARO.baroh * 256); tsen.TEMP_HUM_BARO.barol = (BYTE)(ab10); tsen.TEMP_HUM_BARO.forecast = forecast; sDecodeRXMessage(this, (const unsigned char *)&tsen.TEMP_HUM_BARO, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendTempBaroSensor(const int NodeID, const int BatteryLevel, const float temperature, const float pressure, const std::string &defaultname) { _tTempBaro tsensor; tsensor.id1 = NodeID; tsensor.temp = temperature; tsensor.baro = pressure; tsensor.altitude = 188; //this is probably not good, need to take the rising/falling of the pressure into account? //any help would be welcome! tsensor.forecast = baroForecastNoInfo; if (tsensor.baro < 1000) tsensor.forecast = baroForecastRain; else if (tsensor.baro < 1020) tsensor.forecast = baroForecastCloudy; else if (tsensor.baro < 1030) tsensor.forecast = baroForecastPartlyCloudy; else tsensor.forecast = baroForecastSunny; sDecodeRXMessage(this, (const unsigned char *)&tsensor, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendSetPointSensor(const int NodeID, const int ChildID, const unsigned char SensorID, const float Temp, const std::string &defaultname) { _tThermostat thermos; thermos.subtype = sTypeThermSetpoint; thermos.id1 = 0; thermos.id2 = NodeID; thermos.id3 = ChildID; thermos.id4 = SensorID; thermos.dunit = 1; thermos.temp = Temp; sDecodeRXMessage(this, (const unsigned char *)&thermos, defaultname.c_str(), -1); } void CDomoticzHardwareBase::SendDistanceSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float distance, const std::string &defaultname) { _tGeneralDevice gdevice; gdevice.subtype = sTypeDistance; gdevice.intval1 = (NodeID << 8) | ChildID; gdevice.floatval1 = distance; sDecodeRXMessage(this, (const unsigned char *)&gdevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendTextSensor(const int NodeID, const int ChildID, const int BatteryLevel, const std::string &textMessage, const std::string &defaultname) { _tGeneralDevice gdevice; gdevice.subtype = sTypeTextStatus; gdevice.intval1 = (NodeID << 8) | ChildID; std::string sstatus = textMessage; if (sstatus.size() > 63) sstatus = sstatus.substr(0, 63); strcpy(gdevice.text, sstatus.c_str()); sDecodeRXMessage(this, (const unsigned char *)&gdevice, defaultname.c_str(), BatteryLevel); } std::string CDomoticzHardwareBase::GetTextSensorText(const int NodeID, const int ChildID, bool &bExists) { bExists = false; std::string ret = ""; std::vector<std::vector<std::string> > result; char szTmp[30]; sprintf(szTmp, "%08X", (NodeID << 8) | ChildID); result = m_sql.safe_query("SELECT sValue FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Type==%d) AND (Subtype==%d)", m_HwdID, szTmp, int(pTypeGeneral), int(sTypeTextStatus)); if (!result.empty()) { bExists = true; ret = result[0][0]; } return ret; } void CDomoticzHardwareBase::SendRainSensor(const int NodeID, const int BatteryLevel, const float RainCounter, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.RAIN.packetlength = sizeof(tsen.RAIN) - 1; tsen.RAIN.packettype = pTypeRAIN; tsen.RAIN.subtype = sTypeRAIN3; tsen.RAIN.battery_level = BatteryLevel; tsen.RAIN.rssi = RssiLevel; tsen.RAIN.id1 = (NodeID & 0xFF00) >> 8; tsen.RAIN.id2 = NodeID & 0xFF; tsen.RAIN.rainrateh = 0; tsen.RAIN.rainratel = 0; uint64_t tr10 = int((float(RainCounter)*10.0f)); tsen.RAIN.raintotal1 = (BYTE)(tr10 / 65535); tr10 -= (tsen.RAIN.raintotal1 * 65535); tsen.RAIN.raintotal2 = (BYTE)(tr10 / 256); tr10 -= (tsen.RAIN.raintotal2 * 256); tsen.RAIN.raintotal3 = (BYTE)(tr10); sDecodeRXMessage(this, (const unsigned char *)&tsen.RAIN, defaultname.c_str(), BatteryLevel); } float CDomoticzHardwareBase::GetRainSensorValue(const int NodeID, bool &bExists) { char szIdx[10]; sprintf(szIdx, "%d", NodeID & 0xFFFF); int Unit = 0; std::vector<std::vector<std::string> > results; results = m_sql.safe_query("SELECT ID,sValue FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Unit == %d) AND (Type==%d) AND (Subtype==%d)", m_HwdID, szIdx, Unit, int(pTypeRAIN), int(sTypeRAIN3)); if (results.size() < 1) { bExists = false; return 0.0f; } std::vector<std::string> splitresults; StringSplit(results[0][1], ";", splitresults); if (splitresults.size() != 2) { bExists = false; return 0.0f; } bExists = true; return (float)atof(splitresults[1].c_str()); } bool CDomoticzHardwareBase::GetWindSensorValue(const int NodeID, int &WindDir, float &WindSpeed, float &WindGust, float &WindTemp, float &WindChill, bool bHaveWindTemp, bool &bExists) { char szIdx[10]; sprintf(szIdx, "%d", NodeID & 0xFFFF); int Unit = 0; std::vector<std::vector<std::string> > results; if (!bHaveWindTemp) results = m_sql.safe_query("SELECT ID,sValue FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Unit == %d) AND (Type==%d) AND (Subtype==%d)", m_HwdID, szIdx, Unit, int(pTypeWIND), int(sTypeWINDNoTemp)); else results = m_sql.safe_query("SELECT ID,sValue FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Unit == %d) AND (Type==%d) AND (Subtype==%d)", m_HwdID, szIdx, Unit, int(pTypeWIND), int(sTypeWIND4)); if (results.size() < 1) { bExists = false; return 0.0f; } std::vector<std::string> splitresults; StringSplit(results[0][1], ";", splitresults); if (splitresults.size() != 6) { bExists = false; return 0.0f; } bExists = true; WindDir = (int)atof(splitresults[0].c_str()); WindSpeed = (float)atof(splitresults[2].c_str()); WindGust = (float)atof(splitresults[3].c_str()); WindTemp = (float)atof(splitresults[4].c_str()); WindChill = (float)atof(splitresults[5].c_str()); return bExists; } void CDomoticzHardwareBase::SendWattMeter(const int NodeID, const int ChildID, const int BatteryLevel, const float musage, const std::string &defaultname) { _tUsageMeter umeter; umeter.id1 = 0; umeter.id2 = 0; umeter.id3 = 0; umeter.id4 = NodeID; umeter.dunit = ChildID; umeter.fusage = musage; sDecodeRXMessage(this, (const unsigned char *)&umeter, defaultname.c_str(), BatteryLevel); } //Obsolete, we should not call this anymore //when all calls are removed, we should delete this function void CDomoticzHardwareBase::SendKwhMeterOldWay(const int NodeID, const int ChildID, const int BatteryLevel, const double musage, const double mtotal, const std::string &defaultname) { SendKwhMeter(NodeID, ChildID, BatteryLevel, musage * 1000, mtotal, defaultname); } void CDomoticzHardwareBase::SendKwhMeter(const int NodeID, const int ChildID, const int BatteryLevel, const double musage, const double mtotal, const std::string &defaultname) { _tGeneralDevice gdevice; gdevice.subtype = sTypeKwh; gdevice.intval1 = (NodeID << 8) | ChildID; gdevice.floatval1 = (float)musage; gdevice.floatval2 = (float)(mtotal*1000.0); sDecodeRXMessage(this, (const unsigned char *)&gdevice, defaultname.c_str(), BatteryLevel); } double CDomoticzHardwareBase::GetKwhMeter(const int NodeID, const int ChildID, bool &bExists) { int dID = (NodeID << 8) | ChildID; char szTmp[30]; sprintf(szTmp, "%08X", dID); std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT ID FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Type==%d) AND (Subtype==%d)", m_HwdID, szTmp, int(pTypeGeneral), int(sTypeKwh)); if (result.size() < 1) { bExists = false; return 0; } result = m_sql.safe_query("SELECT MAX(Counter) FROM Meter_Calendar WHERE (DeviceRowID=='%q')", result[0][0].c_str()); if (result.size() < 1) { bExists = false; return 0.0f; } bExists = true; return (float)atof(result[0][0].c_str()); } void CDomoticzHardwareBase::SendMeterSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float metervalue, const std::string &defaultname, const int RssiLevel /* =12 */) { unsigned long counter = (unsigned long)(metervalue*1000.0f); RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.RFXMETER.packetlength = sizeof(tsen.RFXMETER) - 1; tsen.RFXMETER.packettype = pTypeRFXMeter; tsen.RFXMETER.subtype = sTypeRFXMeterCount; tsen.RFXMETER.rssi = RssiLevel; tsen.RFXMETER.id1 = (BYTE)NodeID; tsen.RFXMETER.id2 = (BYTE)ChildID; tsen.RFXMETER.count1 = (BYTE)((counter & 0xFF000000) >> 24); tsen.RFXMETER.count2 = (BYTE)((counter & 0x00FF0000) >> 16); tsen.RFXMETER.count3 = (BYTE)((counter & 0x0000FF00) >> 8); tsen.RFXMETER.count4 = (BYTE)(counter & 0x000000FF); sDecodeRXMessage(this, (const unsigned char *)&tsen.RFXMETER, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendLuxSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float Lux, const std::string &defaultname) { _tLightMeter lmeter; lmeter.id1 = 0; lmeter.id2 = 0; lmeter.id3 = 0; lmeter.id4 = NodeID; lmeter.dunit = ChildID; lmeter.fLux = Lux; lmeter.battery_level = BatteryLevel; sDecodeRXMessage(this, (const unsigned char *)&lmeter, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendAirQualitySensor(const int NodeID, const int ChildID, const int BatteryLevel, const int AirQuality, const std::string &defaultname) { _tAirQualityMeter meter; meter.len = sizeof(_tAirQualityMeter) - 1; meter.type = pTypeAirQuality; meter.subtype = sTypeVoltcraft; meter.airquality = AirQuality; meter.id1 = NodeID; meter.id2 = ChildID; sDecodeRXMessage(this, (const unsigned char *)&meter, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendUsageSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float Usage, const std::string &defaultname) { _tUsageMeter umeter; umeter.id1 = 0; umeter.id2 = 0; umeter.id3 = 0; umeter.id4 = NodeID; umeter.dunit = ChildID; umeter.fusage = Usage; sDecodeRXMessage(this, (const unsigned char *)&umeter, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendSwitchIfNotExists(const int NodeID, const int ChildID, const int BatteryLevel, const bool bOn, const double Level, const std::string &defaultname) { //make device ID unsigned char ID1 = (unsigned char)((NodeID & 0xFF000000) >> 24); unsigned char ID2 = (unsigned char)((NodeID & 0xFF0000) >> 16); unsigned char ID3 = (unsigned char)((NodeID & 0xFF00) >> 8); unsigned char ID4 = (unsigned char)NodeID & 0xFF; char szIdx[10]; sprintf(szIdx, "%X%02X%02X%02X", ID1, ID2, ID3, ID4); std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT Name,nValue,sValue FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Unit == %d) AND (Type==%d) AND (Subtype==%d)", m_HwdID, szIdx, ChildID, int(pTypeLighting2), int(sTypeAC)); if (result.size() < 1) { SendSwitch(NodeID, ChildID, BatteryLevel, bOn, Level, defaultname); } } void CDomoticzHardwareBase::SendSwitch(const int NodeID, const int ChildID, const int BatteryLevel, const bool bOn, const double Level, const std::string &defaultname, const int RssiLevel /* =12 */) { double rlevel = (16.0 / 100.0)*Level; int level = int(rlevel); //make device ID unsigned char ID1 = (unsigned char)((NodeID & 0xFF000000) >> 24); unsigned char ID2 = (unsigned char)((NodeID & 0xFF0000) >> 16); unsigned char ID3 = (unsigned char)((NodeID & 0xFF00) >> 8); unsigned char ID4 = (unsigned char)NodeID & 0xFF; char szIdx[10]; sprintf(szIdx, "%X%02X%02X%02X", ID1, ID2, ID3, ID4); std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT Name,nValue,sValue FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Unit == %d) AND (Type==%d) AND (Subtype==%d)", m_HwdID, szIdx, ChildID, int(pTypeLighting2), int(sTypeAC)); if (!result.empty()) { //check if we have a change, if not do not update it int nvalue = atoi(result[0][1].c_str()); if ((!bOn) && (nvalue == light2_sOff)) return; if ((bOn && (nvalue != light2_sOff))) { //Check Level int slevel = atoi(result[0][2].c_str()); if (slevel == level) return; } } //Send as Lighting 2 tRBUF lcmd; memset(&lcmd, 0, sizeof(RBUF)); lcmd.LIGHTING2.packetlength = sizeof(lcmd.LIGHTING2) - 1; lcmd.LIGHTING2.packettype = pTypeLighting2; lcmd.LIGHTING2.subtype = sTypeAC; lcmd.LIGHTING2.id1 = ID1; lcmd.LIGHTING2.id2 = ID2; lcmd.LIGHTING2.id3 = ID3; lcmd.LIGHTING2.id4 = ID4; lcmd.LIGHTING2.unitcode = ChildID; if (!bOn) { lcmd.LIGHTING2.cmnd = light2_sOff; } else { if (level!=0) lcmd.LIGHTING2.cmnd = light2_sSetLevel; else lcmd.LIGHTING2.cmnd = light2_sOn; } lcmd.LIGHTING2.level = level; lcmd.LIGHTING2.filler = 0; lcmd.LIGHTING2.rssi = RssiLevel; sDecodeRXMessage(this, (const unsigned char *)&lcmd.LIGHTING2, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendBlindSensor(const int NodeID, const int ChildID, const int BatteryLevel, const int Command, const std::string &defaultname, const int RssiLevel /* =12 */) { //Send as Blinds tRBUF lcmd; memset(&lcmd, 0, sizeof(RBUF)); lcmd.BLINDS1.packetlength = sizeof(lcmd.LIGHTING2) - 1; lcmd.BLINDS1.packettype = pTypeBlinds; lcmd.BLINDS1.subtype = sTypeBlindsT0; lcmd.BLINDS1.id1 = 0; lcmd.BLINDS1.id2 = 0; lcmd.BLINDS1.id3 = NodeID; lcmd.BLINDS1.id4 = 0; lcmd.BLINDS1.unitcode = ChildID; lcmd.BLINDS1.cmnd = Command; lcmd.BLINDS1.filler = 0; lcmd.BLINDS1.rssi = RssiLevel; sDecodeRXMessage(this, (const unsigned char *)&lcmd.BLINDS1, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendRGBWSwitch(const int NodeID, const int ChildID, const int BatteryLevel, const double Level, const bool bIsRGBW, const std::string &defaultname) { int level = int(Level); int subType = (bIsRGBW == true) ? sTypeLimitlessRGBW : sTypeLimitlessRGB; //Send as LimitlessLight _tLimitlessLights lcmd; lcmd.id = NodeID; lcmd.subtype = subType; if (level == 0) lcmd.command = Limitless_LedOff; else lcmd.command = Limitless_LedOn; lcmd.dunit = ChildID; lcmd.value = level; sDecodeRXMessage(this, (const unsigned char *)&lcmd, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendVoltageSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float Volt, const std::string &defaultname) { _tGeneralDevice gDevice; gDevice.subtype = sTypeVoltage; gDevice.id = ChildID; gDevice.intval1 = (NodeID << 8) | ChildID; gDevice.floatval1 = Volt; sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendCurrentSensor(const int NodeID, const int BatteryLevel, const float Current1, const float Current2, const float Current3, const std::string &defaultname, const int RssiLevel /* =12 */) { tRBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.CURRENT.packetlength = sizeof(tsen.CURRENT) - 1; tsen.CURRENT.packettype = pTypeCURRENT; tsen.CURRENT.subtype = sTypeELEC1; tsen.CURRENT.rssi = RssiLevel; tsen.CURRENT.id1 = (NodeID & 0xFF00) >> 8; tsen.CURRENT.id2 = NodeID & 0xFF; tsen.CURRENT.battery_level = BatteryLevel; int at10 = round(std::abs(Current1*10.0f)); tsen.CURRENT.ch1h = (BYTE)(at10 / 256); at10 -= (tsen.TEMP.temperatureh * 256); tsen.CURRENT.ch1l = (BYTE)(at10); at10 = round(std::abs(Current2*10.0f)); tsen.CURRENT.ch2h = (BYTE)(at10 / 256); at10 -= (tsen.TEMP.temperatureh * 256); tsen.CURRENT.ch2l = (BYTE)(at10); at10 = round(std::abs(Current3*10.0f)); tsen.CURRENT.ch3h = (BYTE)(at10 / 256); at10 -= (tsen.TEMP.temperatureh * 256); tsen.CURRENT.ch3l = (BYTE)(at10); sDecodeRXMessage(this, (const unsigned char *)&tsen.CURRENT, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendPercentageSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float Percentage, const std::string &defaultname) { _tGeneralDevice gDevice; gDevice.subtype = sTypePercentage; gDevice.id = ChildID; gDevice.intval1 = NodeID; gDevice.floatval1 = Percentage; sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } bool CDomoticzHardwareBase::CheckPercentageSensorExists(const int NodeID, const int ChildID) { std::vector<std::vector<std::string> > result; char szTmp[30]; sprintf(szTmp, "%08X", (unsigned int)NodeID); result = m_sql.safe_query("SELECT Name FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Type==%d) AND (Subtype==%d)", m_HwdID, szTmp, int(pTypeGeneral), int(sTypePercentage)); return (!result.empty()); } void CDomoticzHardwareBase::SendWaterflowSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float LPM, const std::string &defaultname) { _tGeneralDevice gDevice; gDevice.subtype = sTypeWaterflow; gDevice.id = ChildID; gDevice.intval1 = (NodeID << 8) | ChildID; gDevice.floatval1 = LPM; sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendCustomSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float Dust, const std::string &defaultname, const std::string &defaultLabel) { std::vector<std::vector<std::string> > result; char szTmp[30]; sprintf(szTmp, "0000%02X%02X", NodeID, ChildID); result = m_sql.safe_query("SELECT Name FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Type==%d) AND (Subtype==%d)", m_HwdID, szTmp, int(pTypeGeneral), int(sTypeCustom)); bool bDoesExists = !result.empty(); _tGeneralDevice gDevice; gDevice.subtype = sTypeCustom; gDevice.id = ChildID; gDevice.intval1 = (NodeID << 8) | ChildID; gDevice.floatval1 = Dust; if (bDoesExists) sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); else { m_mainworker.PushAndWaitRxMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); //Set the Label std::string soptions = "1;" + defaultLabel; m_sql.safe_query("UPDATE DeviceStatus SET Options='%q' WHERE (HardwareID==%d) AND (DeviceID=='%q') AND (Type==%d) AND (Subtype==%d)", soptions.c_str(), m_HwdID, szTmp, int(pTypeGeneral), int(sTypeCustom)); } } //wind direction is in steps of 22.5 degrees (360/16) void CDomoticzHardwareBase::SendWind(const int NodeID, const int BatteryLevel, const int WindDir, const float WindSpeed, const float WindGust, const float WindTemp, const float WindChill, const bool bHaveWindTemp, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.WIND.packetlength = sizeof(tsen.WIND) - 1; tsen.WIND.packettype = pTypeWIND; if (!bHaveWindTemp) tsen.WIND.subtype = sTypeWINDNoTemp; else tsen.WIND.subtype = sTypeWIND4; tsen.WIND.battery_level = BatteryLevel; tsen.WIND.rssi = RssiLevel; tsen.WIND.id1 = (NodeID & 0xFF00) >> 8; tsen.WIND.id2 = NodeID & 0xFF; int aw = WindDir; tsen.WIND.directionh = (BYTE)(aw / 256); aw -= (tsen.WIND.directionh * 256); tsen.WIND.directionl = (BYTE)(aw); int sw = round(WindSpeed*10.0f); tsen.WIND.av_speedh = (BYTE)(sw / 256); sw -= (tsen.WIND.av_speedh * 256); tsen.WIND.av_speedl = (BYTE)(sw); int gw = round(WindGust*10.0f); tsen.WIND.gusth = (BYTE)(gw / 256); gw -= (tsen.WIND.gusth * 256); tsen.WIND.gustl = (BYTE)(gw); if (!bHaveWindTemp) { //No temp, only chill tsen.WIND.tempsign = (WindChill >= 0) ? 0 : 1; tsen.WIND.chillsign = (WindChill >= 0) ? 0 : 1; int at10 = round(std::abs(WindChill*10.0f)); tsen.WIND.temperatureh = (BYTE)(at10 / 256); tsen.WIND.chillh = (BYTE)(at10 / 256); at10 -= (tsen.WIND.chillh * 256); tsen.WIND.temperaturel = (BYTE)(at10); tsen.WIND.chilll = (BYTE)(at10); } else { //temp+chill tsen.WIND.tempsign = (WindTemp >= 0) ? 0 : 1; int at10 = round(std::abs(WindTemp*10.0f)); tsen.WIND.temperatureh = (BYTE)(at10 / 256); at10 -= (tsen.WIND.temperatureh * 256); tsen.WIND.temperaturel = (BYTE)(at10); tsen.WIND.chillsign = (WindChill >= 0) ? 0 : 1; at10 = round(std::abs(WindChill*10.0f)); tsen.WIND.chillh = (BYTE)(at10 / 256); at10 -= (tsen.WIND.chillh * 256); tsen.WIND.chilll = (BYTE)(at10); } sDecodeRXMessage(this, (const unsigned char *)&tsen.WIND, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendPressureSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float pressure, const std::string &defaultname) { _tGeneralDevice gdevice; gdevice.subtype = sTypePressure; gdevice.intval1 = (NodeID << 8) | ChildID; gdevice.floatval1 = pressure; sDecodeRXMessage(this, (const unsigned char *)&gdevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendSolarRadiationSensor(const unsigned char NodeID, const int BatteryLevel, const float radiation, const std::string &defaultname) { _tGeneralDevice gdevice; gdevice.subtype = sTypeSolarRadiation; gdevice.id = NodeID; gdevice.floatval1 = radiation; sDecodeRXMessage(this, (const unsigned char *)&gdevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendSoundSensor(const int NodeID, const int BatteryLevel, const int sLevel, const std::string &defaultname) { _tGeneralDevice gDevice; gDevice.subtype = sTypeSoundLevel; gDevice.id = 1; gDevice.intval1 = NodeID; gDevice.intval2 = sLevel; sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendAlertSensor(const int NodeID, const int BatteryLevel, const int alertLevel, const std::string &message, const std::string &defaultname) { _tGeneralDevice gDevice; gDevice.subtype = sTypeAlert; gDevice.id = (unsigned char)NodeID; gDevice.intval1 = alertLevel; sprintf(gDevice.text, "%.63s", message.c_str()); sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendGeneralSwitchSensor(const int NodeID, const int BatteryLevel, const int switchState, const char* defaultname, const int unitCode) { _tGeneralSwitch gSwitch; gSwitch.id = NodeID; gSwitch.unitcode = unitCode; gSwitch.cmnd = switchState; sDecodeRXMessage(this, (const unsigned char *)&gSwitch, defaultname, BatteryLevel); } void CDomoticzHardwareBase::SendMoistureSensor(const int NodeID, const int BatteryLevel, const int mLevel, const std::string &defaultname) { _tGeneralDevice gDevice; gDevice.subtype = sTypeSoilMoisture; gDevice.id = 1; gDevice.intval1 = NodeID; gDevice.intval2 = mLevel; sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendUVSensor(const int NodeID, const int ChildID, const int BatteryLevel, const float UVI, const std::string &defaultname, const int RssiLevel /* =12 */) { RBUF tsen; memset(&tsen, 0, sizeof(RBUF)); tsen.UV.packetlength = sizeof(tsen.UV) - 1; tsen.UV.packettype = pTypeUV; tsen.UV.subtype = sTypeUV1; tsen.UV.battery_level = BatteryLevel; tsen.UV.rssi = RssiLevel; tsen.UV.id1 = (unsigned char)NodeID; tsen.UV.id2 = (unsigned char)ChildID; tsen.UV.uv = (BYTE)round(UVI * 10); sDecodeRXMessage(this, (const unsigned char *)&tsen.UV, defaultname.c_str(), BatteryLevel); } void CDomoticzHardwareBase::SendZWaveAlarmSensor(const int NodeID, const int InstanceID, const int BatteryLevel, const int aType, const int aValue, const std::string &defaultname) { uint8_t ID1 = 0; uint8_t ID2 = (unsigned char)((NodeID & 0xFF00) >> 8); uint8_t ID3 = (unsigned char)NodeID & 0xFF; uint8_t ID4 = InstanceID; unsigned long lID = (ID1 << 24) + (ID2 << 16) + (ID3 << 8) + ID4; _tGeneralDevice gDevice; gDevice.subtype = sTypeZWaveAlarm; gDevice.id = aType; gDevice.intval1 = (int)(lID); gDevice.intval2 = aValue; sDecodeRXMessage(this, (const unsigned char *)&gDevice, defaultname.c_str(), BatteryLevel); } int CDomoticzHardwareBase::CalculateBaroForecast(const double pressure) { //From 0 to 5 min. if (m_baro_minuteCount <= 5){ m_pressureSamples[0][m_baro_minuteCount] = pressure; } //From 30 to 35 min. else if ((m_baro_minuteCount >= 30) && (m_baro_minuteCount <= 35)){ m_pressureSamples[1][m_baro_minuteCount - 30] = pressure; } //From 60 to 65 min. else if ((m_baro_minuteCount >= 60) && (m_baro_minuteCount <= 65)){ m_pressureSamples[2][m_baro_minuteCount - 60] = pressure; } //From 90 to 95 min. else if ((m_baro_minuteCount >= 90) && (m_baro_minuteCount <= 95)){ m_pressureSamples[3][m_baro_minuteCount - 90] = pressure; } //From 120 to 125 min. else if ((m_baro_minuteCount >= 120) && (m_baro_minuteCount <= 125)){ m_pressureSamples[4][m_baro_minuteCount - 120] = pressure; } //From 150 to 155 min. else if ((m_baro_minuteCount >= 150) && (m_baro_minuteCount <= 155)){ m_pressureSamples[5][m_baro_minuteCount - 150] = pressure; } //From 180 to 185 min. else if ((m_baro_minuteCount >= 180) && (m_baro_minuteCount <= 185)){ m_pressureSamples[6][m_baro_minuteCount - 180] = pressure; } //From 210 to 215 min. else if ((m_baro_minuteCount >= 210) && (m_baro_minuteCount <= 215)){ m_pressureSamples[7][m_baro_minuteCount - 210] = pressure; } //From 240 to 245 min. else if ((m_baro_minuteCount >= 240) && (m_baro_minuteCount <= 245)){ m_pressureSamples[8][m_baro_minuteCount - 240] = pressure; } if (m_baro_minuteCount == 5) { // Avg pressure in first 5 min, value averaged from 0 to 5 min. m_pressureAvg[0] = ((m_pressureSamples[0][0] + m_pressureSamples[0][1] + m_pressureSamples[0][2] + m_pressureSamples[0][3] + m_pressureSamples[0][4] + m_pressureSamples[0][5]) / 6); } else if (m_baro_minuteCount == 35) { // Avg pressure in 30 min, value averaged from 0 to 5 min. m_pressureAvg[1] = ((m_pressureSamples[1][0] + m_pressureSamples[1][1] + m_pressureSamples[1][2] + m_pressureSamples[1][3] + m_pressureSamples[1][4] + m_pressureSamples[1][5]) / 6); double change = (m_pressureAvg[1] - m_pressureAvg[0]); m_dP_dt = change / 5; } else if (m_baro_minuteCount == 65) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[2] = ((m_pressureSamples[2][0] + m_pressureSamples[2][1] + m_pressureSamples[2][2] + m_pressureSamples[2][3] + m_pressureSamples[2][4] + m_pressureSamples[2][5]) / 6); double change = (m_pressureAvg[2] - m_pressureAvg[0]); m_dP_dt = change / 10; } else if (m_baro_minuteCount == 95) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[3] = ((m_pressureSamples[3][0] + m_pressureSamples[3][1] + m_pressureSamples[3][2] + m_pressureSamples[3][3] + m_pressureSamples[3][4] + m_pressureSamples[3][5]) / 6); double change = (m_pressureAvg[3] - m_pressureAvg[0]); m_dP_dt = change / 15; } else if (m_baro_minuteCount == 125) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[4] = ((m_pressureSamples[4][0] + m_pressureSamples[4][1] + m_pressureSamples[4][2] + m_pressureSamples[4][3] + m_pressureSamples[4][4] + m_pressureSamples[4][5]) / 6); double change = (m_pressureAvg[4] - m_pressureAvg[0]); m_dP_dt = change / 20; } else if (m_baro_minuteCount == 155) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[5] = ((m_pressureSamples[5][0] + m_pressureSamples[5][1] + m_pressureSamples[5][2] + m_pressureSamples[5][3] + m_pressureSamples[5][4] + m_pressureSamples[5][5]) / 6); double change = (m_pressureAvg[5] - m_pressureAvg[0]); m_dP_dt = change / 25; } else if (m_baro_minuteCount == 185) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[6] = ((m_pressureSamples[6][0] + m_pressureSamples[6][1] + m_pressureSamples[6][2] + m_pressureSamples[6][3] + m_pressureSamples[6][4] + m_pressureSamples[6][5]) / 6); double change = (m_pressureAvg[6] - m_pressureAvg[0]); m_dP_dt = change / 30; } else if (m_baro_minuteCount == 215) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[7] = ((m_pressureSamples[7][0] + m_pressureSamples[7][1] + m_pressureSamples[7][2] + m_pressureSamples[7][3] + m_pressureSamples[7][4] + m_pressureSamples[7][5]) / 6); double change = (m_pressureAvg[7] - m_pressureAvg[0]); m_dP_dt = change / 35; } else if (m_baro_minuteCount == 245) { // Avg pressure at end of the hour, value averaged from 0 to 5 min. m_pressureAvg[8] = ((m_pressureSamples[8][0] + m_pressureSamples[8][1] + m_pressureSamples[8][2] + m_pressureSamples[8][3] + m_pressureSamples[8][4] + m_pressureSamples[8][5]) / 6); double change = (m_pressureAvg[8] - m_pressureAvg[0]); m_dP_dt = change / 40; // note this is for t = 4 hour m_baro_minuteCount -= 30; m_pressureAvg[0] = m_pressureAvg[1]; m_pressureAvg[1] = m_pressureAvg[2]; m_pressureAvg[2] = m_pressureAvg[3]; m_pressureAvg[3] = m_pressureAvg[4]; m_pressureAvg[4] = m_pressureAvg[5]; m_pressureAvg[5] = m_pressureAvg[6]; m_pressureAvg[6] = m_pressureAvg[7]; m_pressureAvg[7] = m_pressureAvg[8]; } m_baro_minuteCount++; if (m_baro_minuteCount < 36) //if time is less than 35 min return wsbaroforcast_unknown; // Unknown, more time needed else if (m_dP_dt < (-0.25)) return wsbaroforcast_heavy_rain; // Quickly falling LP, Thunderstorm, not stable else if (m_dP_dt > 0.25) return wsbaroforcast_unstable; // Quickly rising HP, not stable weather else if ((m_dP_dt > (-0.25)) && (m_dP_dt < (-0.05))) return wsbaroforcast_rain; // Slowly falling Low Pressure System, stable rainy weather else if ((m_dP_dt > 0.05) && (m_dP_dt < 0.25)) return wsbaroforcast_sunny; // Slowly rising HP stable good weather else if ((m_dP_dt >(-0.05)) && (m_dP_dt < 0.05)) return wsbaroforcast_stable; // Stable weather else return wsbaroforcast_unknown; // Unknown }
gpl-3.0
tschroedter/csharp_examples
InterviewTests/MYOB/Game/CircleAsBitArray.cs
3981
using System; using System.Collections.Generic; using System.Linq; using Game.Interfaces; namespace Game { public class CircleAsBitArray : ICircle { internal const long DefaultMaxLoopCount = 10000000; private bool[] m_BitArray; public CircleAsBitArray() { MaxLoopCount = DefaultMaxLoopCount; } public long MaxLoopCount { get; private set; } public IEnumerable <int> Run(int numberOfPeopleStandingInACircle, int numberOfPeopleToCountOverEachTime) { m_BitArray = Enumerable.Repeat(true, numberOfPeopleStandingInACircle + 1).ToArray(); m_BitArray [ 0 ] = false; IEnumerable <int> result = StartCounting(numberOfPeopleToCountOverEachTime); return result; } private IEnumerable <int> StartCounting(int countTo) { var result = new List <int>(); var fromPersonId = 1; do { int removePersonId = NextPersonIdForCountTo(m_BitArray, fromPersonId, countTo); result.Add(removePersonId); m_BitArray [ removePersonId ] = false; if ( !m_BitArray.Any(x => x) ) { break; } fromPersonId = NextPersonId(m_BitArray, removePersonId); } while ( true ); return result; } // Started off with recursive implementation but changed it when I tested with big numbers: // Got StackOverflow exception and change implementation. internal int NextPersonIdForCountTo(bool[] bitArray, int fromPersonId, int countTo) { if ( countTo == 1 ) { return fromPersonId; } int nextPersonId = fromPersonId; var currentCount = 0; var loopCounter = 0; do { if ( bitArray [ nextPersonId ] ) { currentCount++; if ( currentCount == countTo ) { break; } } nextPersonId = ( nextPersonId + 1 ) % bitArray.Length; if ( loopCounter++ > MaxLoopCount ) { throw new ArgumentException( "Calling NextPersonIdForCountTo(...) might be in an endless loop and was stop!"); } } while ( true ); return nextPersonId; } // Started off with recursive implementation but changed it when I tested with big numbers: // Got StackOverflow exception and change implementation. internal int NextPersonId(bool[] bitArray, int personId) { int nextPersonId = personId; var loopCounter = 0; do { nextPersonId = ( nextPersonId + 1 ) % bitArray.Length; if ( bitArray [ nextPersonId ] ) { break; } if ( loopCounter++ > MaxLoopCount ) { throw new ArgumentException("Calling NextPersonId(...) might be in an endless loop and was stop!"); } } while ( true ); return nextPersonId; } public void SetMaxLoopCount(int maxLoopCount) { if ( maxLoopCount > 0 ) { MaxLoopCount = maxLoopCount; } } } }
gpl-3.0
ItsLastDay/academic_university_2016-2018
subjects/BigData/hw02/first_metric/first_metric.py
1949
from pyspark import SparkConf, SparkContext import datetime from operator import add import sys import re access_log_pattern = re.compile('^(?P<ip>.*?) - - (?P<time>.*?) "(?P<page>.*?)" ' + \ '(?P<code>.*?) .*? "(?P<referrer>.*?)" ".*?"$') HDFS_DIR = '/user/bigdatashad/logs/{}' def count_referers(events): events = events[1] start_timestamp = None last_timestamp = None result = [] last_ref = '' for event in events: timestamp, ref = event if not start_timestamp or timestamp - last_timestamp > 30 * 60: if start_timestamp is not None: result.append((last_ref, 1)) start_timestamp = timestamp last_ref = ref if timestamp == start_timestamp: last_ref = max(last_ref, ref) last_timestamp = timestamp if start_timestamp is not None: result.append((last_ref, 1)) return result def extract_fields(s): match = re.match(access_log_pattern, s) if not match or match.group('code') != '200': return [] try: date = datetime.datetime.strptime(match.group('time')[1:-7], "%d/%b/%Y:%H:%M:%S") except: return [] timestamp = int(date.strftime("%s")) return [((match.group('ip'), timestamp), (timestamp, match.group('referrer')))] date = sys.argv[1] conf = SparkConf().setAppName("Session referrers") sc = SparkContext(conf=conf) log = sc.textFile("/user/bigdatashad/logs/{}".format(date)) fields = log.flatMap(extract_fields) ips_sorted = fields.repartitionAndSortWithinPartitions(partitionFunc=lambda s: hash(s[0]))\ .map(lambda x: (x[0][0], x[1]), True) ips_grouped = ips_sorted.groupByKey() ag_referers = ips_grouped.flatMap(count_referers) #print(ag_referers.take(10)) total_result = ag_referers.foldByKey(0, add) #print(total_result.take(10)) total_result.saveAsTextFile('/user/mkoltsov/hw2/first_metric/{}'.format(date))
gpl-3.0
ewized/CommonUtils
src/main/java/com/archeinteractive/dev/commonutils/configuration/ConfigModel.java
4444
package com.archeinteractive.dev.commonutils.configuration; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import java.io.*; /* * SuperEasyConfig - Config * * Based off of codename_Bs EasyConfig v2.1 * which was inspired by md_5 * * An even awesomer super-duper-lazy Config lib! * * 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. * * @author MrFigg * @version 1.2 */ public abstract class ConfigModel extends ConfigObject { protected transient File CONFIG_FILE = null; protected transient String CONFIG_HEADER = null; public ConfigModel() { CONFIG_HEADER = null; } protected void onLoad() {} // Called after a load, override to act on loads protected void onSave() {} // Called after a save, override to act on saves public ConfigModel load(File file) throws InvalidConfigurationException { if (file == null) throw new InvalidConfigurationException(new NullPointerException()); if (!file.exists()) throw new InvalidConfigurationException(new IOException("File doesn't exist")); CONFIG_FILE = file; return reload(); } public ConfigModel reload() throws InvalidConfigurationException { if (CONFIG_FILE == null) throw new InvalidConfigurationException(new NullPointerException()); if (!CONFIG_FILE.exists()) throw new InvalidConfigurationException(new IOException("File doesn't exist")); YamlConfiguration yamlConfig = YamlConfiguration.loadConfiguration(CONFIG_FILE); try { onLoad(yamlConfig); yamlConfig.save(CONFIG_FILE); } catch (Exception ex) { throw new InvalidConfigurationException(ex); } onLoad(); return this; } public ConfigModel save(File file) throws InvalidConfigurationException { if (file == null) throw new InvalidConfigurationException(new NullPointerException()); CONFIG_FILE = file; return save(); } public ConfigModel save() throws InvalidConfigurationException { if (CONFIG_FILE == null) throw new InvalidConfigurationException(new NullPointerException()); if (!CONFIG_FILE.exists()) { try { if (CONFIG_FILE.getParentFile() != null) CONFIG_FILE.getParentFile().mkdirs(); CONFIG_FILE.createNewFile(); if (CONFIG_HEADER != null) { Writer newConfig = new BufferedWriter(new FileWriter(CONFIG_FILE)); boolean firstLine = true; for (String line : CONFIG_HEADER.split("\n")) { if (!firstLine) { newConfig.write("\n"); } else { firstLine = false; } newConfig.write("# " + line); } newConfig.close(); } } catch (Exception ex) { throw new InvalidConfigurationException(ex); } } YamlConfiguration yamlConfig = YamlConfiguration.loadConfiguration(CONFIG_FILE); try { onSave(yamlConfig); yamlConfig.save(CONFIG_FILE); } catch (Exception ex) { throw new InvalidConfigurationException(ex); } onSave(); return this; } public ConfigModel init(File file) throws InvalidConfigurationException { if (file == null) throw new InvalidConfigurationException(new NullPointerException()); CONFIG_FILE = file; return init(); } public ConfigModel init() throws InvalidConfigurationException { if (CONFIG_FILE == null) throw new InvalidConfigurationException(new NullPointerException()); if (CONFIG_FILE.exists()) { return reload(); } else { return save(); } } }
gpl-3.0
bfrgoncalves/Online-PhyloViZ
public/javascripts/App/main/data_Analysis/saveTreePositions.js
757
function saveTreePositions(graphObject){ var graph = graphObject.graphGL; var layout = graphObject.layout; var datasetID = graphObject.datasetID; var Positions = {}; var nodePositions = {}; var linkPositions = {}; graph.forEachNode(function(node){ var position = layout.getNodePosition(node.id); nodePositions[node.id] = [{ x : position.x, y : position.y}]; }); Positions.nodes = [nodePositions]; Positions.isLogScale = graphObject.isLogScale; $.ajax({ url: '/api/db/postgres/update/positions/data', type: 'PUT', data: { dataset_id: datasetID, change: JSON.stringify(Positions), }, dataType: "json", success: function(data){ alert('Positions saved!'); } }); }
gpl-3.0
alexreinking/CommandCenter-New
lib/imu/imudecoder.cpp
5704
#include "imudecoder.h" #include <cmath> #include <cstdlib> #include <sys/time.h> #define PI 3.1415926535897932384 #define IMU_TAG "VNYMR," IMUDecoder::IMUDecoder() { for(int i = 0; i < 12; i++) nmeaIndices[i] = i; nmeaDatums[0] = yawString; nmeaDatums[1] = pitchString; nmeaDatums[2] = rollString; nmeaDatums[3] = magnetXString; nmeaDatums[4] = magnetYString; nmeaDatums[5] = magnetZString; nmeaDatums[6] = accelXString; nmeaDatums[7] = accelYString; nmeaDatums[8] = accelZString; nmeaDatums[9] = gyroXString; nmeaDatums[10] = gyroYString; nmeaDatums[11] = gyroZString; initNmea(&nmeaData, IMU_TAG, sizeof(nmeaDatums) / sizeof(sizeof(*nmeaDatums)), nmeaIndices, nmeaDatums); } bool IMUDecoder::decodeByte(int8_t newByte) { if(newByte == -1) return false; bool ret; if (ret = parseNmea(&nmeaData, newByte)) { // It parsed! Something happened! lastCalcData = currentCalcData; convertToCalcData(); // Time stamp our just converted time! struct timeval currentTime; gettimeofday(&currentTime, NULL); currentCalcData.accel.timestamp = (double)currentTime.tv_sec + (double)currentTime.tv_usec / 1000000; calculateIntegratedData(); } return ret; } void IMUDecoder::convertToCalcData() { currentCalcData.yaw = strtod(yawString, NULL); currentCalcData.pitch = strtod(pitchString, NULL); currentCalcData.roll = strtod(rollString, NULL); currentCalcData.accel.coordX = strtod(accelXString, NULL); currentCalcData.accel.coordY = strtod(accelYString, NULL); currentCalcData.accel.coordZ = strtod(accelZString, NULL); currentCalcData.angVel.coordX = strtod(gyroXString, NULL); currentCalcData.angVel.coordY = strtod(gyroYString, NULL); currentCalcData.angVel.coordZ = strtod(gyroZString, NULL); } void IMUDecoder::calculateIntegratedData() { rotateCoordinatesBodytoSpace(&currentCalcData.accel, &currentCalcData.spaceAccel, &currentCalcData); integrateWithTime(&currentCalcData.spaceAccel, &lastCalcData.spaceAccel, &currentCalcData.spaceVel); rotateCoordinatesSpacetoBody(&currentCalcData.spaceVel, &currentCalcData.vel, &currentCalcData); integrateWithTime(&currentCalcData.spaceVel, &lastCalcData.spaceVel, &currentCalcData.spacePos); rotateCoordinatesSpacetoBody(&currentCalcData.spacePos, &currentCalcData.pos, &currentCalcData); } void IMUDecoder::rotateCoordinatesBodytoSpace(Vector3D* vectorIn, Vector3D* vectorOut, ImuCalcData* imuCalcData) { double cosYaw = cos(imuCalcData->yaw); double sinYaw = sin(imuCalcData->yaw); double cosPitch = cos(imuCalcData->pitch); double sinPitch = sin(imuCalcData->pitch); double cosRoll = cos(imuCalcData->roll); double sinRoll = sin(imuCalcData->roll); vectorOut->coordX = cosYaw*(cosPitch*vectorIn->coordX + sinPitch*(sinRoll*vectorIn->coordY + cosRoll*vectorIn->coordZ)) - sinYaw*(cosRoll*vectorIn->coordY - sinRoll*vectorIn->coordZ); vectorOut->coordY = sinYaw*(cosPitch*vectorIn->coordX + sinPitch*(sinRoll*vectorIn->coordY + cosRoll*vectorIn->coordZ)) + cosYaw*(cosRoll*vectorIn->coordY - sinRoll*vectorIn->coordZ); vectorOut->coordZ = -sinPitch*vectorIn->coordX + cosPitch*(sinRoll*vectorIn->coordY + cosRoll*vectorIn->coordZ); vectorOut->timestamp = vectorIn->timestamp; } void IMUDecoder::rotateCoordinatesSpacetoBody(Vector3D* vectorIn, Vector3D* vectorOut, ImuCalcData* imuCalcData) { double cosYaw = cos(imuCalcData->yaw); double sinYaw = sin(imuCalcData->yaw); double cosPitch = cos(imuCalcData->pitch); double sinPitch = sin(imuCalcData->pitch); double cosRoll = cos(imuCalcData->roll); double sinRoll = sin(imuCalcData->roll); vectorOut->coordX = cosPitch*(cosYaw*vectorIn->coordX + sinYaw*vectorIn->coordY) - sinPitch*vectorIn->coordZ; vectorOut->coordY = cosRoll*(-sinYaw*vectorIn->coordX + cosYaw*vectorIn->coordY) + sinRoll*(sinPitch*(cosYaw*vectorIn->coordX + sinYaw*vectorIn->coordY) + cosPitch*vectorIn->coordZ); vectorOut->coordZ = -sinRoll*(-sinYaw*vectorIn->coordX + cosYaw*vectorIn->coordY) + cosRoll*(sinPitch*(cosYaw*vectorIn->coordX + sinYaw*vectorIn->coordY) + cosPitch*vectorIn->coordZ); vectorOut->timestamp = vectorIn->timestamp; } void IMUDecoder::integrateWithTime(Vector3D* vectorNew, Vector3D* vectorOld, Vector3D* vectorIntegrated) { //trapazoid integration scheme vectorIntegrated->coordX = (vectorNew->timestamp - vectorOld->timestamp) * (vectorNew->coordX + vectorOld->coordX)/2; vectorIntegrated->coordY = (vectorNew->timestamp - vectorOld->timestamp) * (vectorNew->coordY + vectorOld->coordY)/2; vectorIntegrated->coordZ = (vectorNew->timestamp - vectorOld->timestamp) * (vectorNew->coordZ + vectorOld->coordZ)/2; vectorIntegrated->timestamp = vectorNew->timestamp; } ImuCalcData IMUDecoder::getCurrentData() const { return currentCalcData; } void IMUDecoder::printIMUDetails() { printf("Acceleration: X: %f, Y: %f, Z: %f\n", currentCalcData.accel.coordX, currentCalcData.accel.coordY, currentCalcData.accel.coordZ); printf(" Velocity: X: %f, Y: %f, Z: %f\n", currentCalcData.vel.coordX, currentCalcData.vel.coordY, currentCalcData.vel.coordZ); printf(" Position: X: %f, Y: %f, Z: %f\n", currentCalcData.pos.coordX, currentCalcData.pos.coordY, currentCalcData.pos.coordZ); printf(" Heading: X: %f, Y: %f, Z: %f\n", currentCalcData.yaw, currentCalcData.pitch, currentCalcData.roll); }
gpl-3.0
sgvandijk/libbats
Preprocessor/debug.hh
3993
/* Debug.hh - C++ debugging preprocessor macro's Copyright (C) 2004 A. Bram Neijt <b.neijt@gmail.com> 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, 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ ///\file ///\brief Preprosessor macro's for easy debug info printing /// ///These preprosessor instructions place info as debugging information on the screen. ///You should use DEBUGLEVEL to set the level of debugging info you want. When DEBUGLEVEL is not defined /// these macro's evaluate to nothing. /// ///If DEBUGLEVEL is set to 1, Level1 debug info is printed. If DEBUGLEVEL is set to 2, all Level2 and lower are printed. etc. /// ///Which level you use for what is totally your choice, but I try to use this: ///1. Current debugging problems ONLY ///2. Single run messages (initialization etc.) ///3. General messages ///4. Messages inside loops and large messages (common) ///5. Messages inside multiple loops or very large /// ///To set the debuglevel of a class, place \#define DEBUGLEVEL in the internal header file (in contrast to the header). This will keep multiple defenitions from occuring when compiling. /// ///The output generated is: "[Filename]:[Line number]: [information]\n" /// ///The extraction operator is used for creating the debug line, so info can contain more then multiple elements devided /// by extraction operators. ///\section examples Examples ///\code /// _debugLevel2("Starting algorithm with:" << "something."); /// _debugLevel3("And thinking about running it" << i << " times."); ///\endcode ///NEW: FLUSHING HAS BEEN DISABLED, ENABLE FOR SEGFAULT DEBUGGING ///NEW: BATS_NO_DEBUG WILL DISABLE ALL DEBUG STATEMENTS, DEFINE IT WITH THE g++ ARGUMENTS //No include guards, to keep the defenitions as much up to date as possible, due to the dependencie on DEBUGLEVEL. #ifdef BATS_NO_DEBUG #ifdef DEBUGLEVEL #undef DEBUGLEVEL #endif #define DEBUGLEVEL 0 #endif #ifdef _debugLevel1 #undef _debugLevel1 #endif #ifdef _debugLevel2 #undef _debugLevel2 #endif #ifdef _debugLevel3 #undef _debugLevel3 #endif #ifdef _debugLevel4 #undef _debugLevel4 #endif //Change this from "\n" to std::endl to disable/enable flushing #define __DEBUG_LINE_ENDING_STATEMENT__ std::endl //#include <ctime> #include "../TimeVal/timeval.hh" #if DEBUGLEVEL > 0 #include <iostream> #define _debugLevel1(info) std::cerr << mvds::TimeVal::getTimeOfDay() << " D1:" << __FILE__ << ":" << __LINE__ << ": " << info << __DEBUG_LINE_ENDING_STATEMENT__ #else ///\brief Output info when DEBUGLEVEL is 1 or more #define _debugLevel1(info) #endif #if DEBUGLEVEL > 1 #define _debugLevel2(info) std::cerr << mvds::TimeVal::getTimeOfDay() << " D2:" << __FILE__ << ":" << __LINE__ << ": " << info << __DEBUG_LINE_ENDING_STATEMENT__ #else ///\brief Output info when DEBUGLEVEL is 2 or more #define _debugLevel2(info) #endif #if DEBUGLEVEL > 2 #define _debugLevel3(info) std::cerr << mvds::TimeVal::getTimeOfDay() << " D3:" << __FILE__ << ":" << __LINE__ << ": " << info << __DEBUG_LINE_ENDING_STATEMENT__ #else ///\brief Output info when DEBUGLEVEL is 3 or more #define _debugLevel3(info) #endif #if DEBUGLEVEL > 3 #define _debugLevel4(info) std::cerr << mvds::TimeVal::getTimeOfDay() << " D4:" << __FILE__ << ":" << __LINE__ << ": " << info << __DEBUG_LINE_ENDING_STATEMENT__ #else ///\brief Output info when DEBUGLEVEL is 4 or more #define _debugLevel4(info) #endif
gpl-3.0
MNoya/DotaCraft
game/dota_addons/dotacraft/scripts/vscripts/items/auras/vampiric.lua
696
item_scourge_bone_chimes = class({}) -- Reutilizes "heroes/dread_lord/vampiric_aura" LinkLuaModifier("modifier_vampiric_aura", "heroes/dread_lord/vampiric_aura", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_vampiric_aura_buff", "heroes/dread_lord/vampiric_aura", LUA_MODIFIER_MOTION_NONE) function item_scourge_bone_chimes:GetIntrinsicModifierName() return "modifier_vampiric_aura" end -------------------------------------------------------------------------------- neutral_vampiric_aura = class({}) function neutral_vampiric_aura:GetIntrinsicModifierName() return "modifier_vampiric_aura" end --------------------------------------------------------------------------------
gpl-3.0
csalgadow/demokratian_2.x.x
modulos/ui/minified/i18n/jquery.ui.datepicker-ja.min.js
951
/*! jQuery UI - v1.10.0 - 2013-01-24 * http://jqueryui.com * Includes: jquery.ui.datepicker-ja.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e) { e.datepicker.regional.ja = {closeText: "閉じる", prevText: "&#x3C;前", nextText: "次&#x3E;", currentText: "今日", monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], monthNamesShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], dayNames: ["日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日"], dayNamesShort: ["日", "月", "火", "水", "木", "金", "土"], dayNamesMin: ["日", "月", "火", "水", "木", "金", "土"], weekHeader: "週", dateFormat: "yy/mm/dd", firstDay: 0, isRTL: !1, showMonthAfterYear: !0, yearSuffix: "年"}, e.datepicker.setDefaults(e.datepicker.regional.ja) });
gpl-3.0
gohdan/DFC
known_files/hashes/assets/plugins/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/attributes.js
56
MODX Evolution 1.0.5 = 8956771d3aec26e696cb208b0f075cc2
gpl-3.0
ramsodev/DitaManagement
dita/dita.glosssentry/src/net/ramso/dita/glosssentry/Thead.java
1762
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.02 at 08:16:27 PM CEST // package net.ramso.dita.glosssentry; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{}thead.class"> * &lt;attribute ref="{}class default="- topic/thead ""/> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "thead") public class Thead extends TheadClass { @XmlAttribute(name = "class") protected String clazz; /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { if (clazz == null) { return "- topic/thead "; } else { return clazz; } } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } }
gpl-3.0
drewlu/ossql
src/s3ql/fsck.py
31852
''' fsck.py - this file is part of S3QL (http://s3ql.googlecode.com) Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org> This program can be distributed under the terms of the GNU GPLv3. ''' from __future__ import division, print_function, absolute_import from .backends.common import NoSuchObject from .common import ROOT_INODE, CTRL_INODE, inode_for_path, sha256_fh, get_path from .database import NoSuchRowError from os.path import basename from s3ql.backends.common import CompressFilter import logging import os import re import shutil import stat import time log = logging.getLogger("fsck") S_IFMT = (stat.S_IFDIR | stat.S_IFREG | stat.S_IFSOCK | stat.S_IFBLK | stat.S_IFCHR | stat.S_IFIFO | stat.S_IFLNK) class Fsck(object): def __init__(self, cachedir_, bucket_, param, conn): self.cachedir = cachedir_ self.bucket = bucket_ self.expect_errors = False self.found_errors = False self.uncorrectable_errors = False self.blocksize = param['blocksize'] self.conn = conn # Set of blocks that have been unlinked by check_cache. # check_block_refcounts() will not report errors if these blocks still # exist even though they have refcount=0 self.unlinked_blocks = set() # Similarly for objects self.unlinked_objects = set() def check(self): """Check file system Sets instance variable `found_errors`. """ # Create indices required for reference checking log.info('Creating temporary extra indices...') self.conn.execute('CREATE INDEX tmp1 ON blocks(obj_id)') self.conn.execute('CREATE INDEX tmp2 ON inode_blocks(block_id)') self.conn.execute('CREATE INDEX tmp3 ON inodes(block_id)') self.conn.execute('CREATE INDEX tmp4 ON contents(inode)') try: self.check_foreign_keys() self.check_cache() self.check_lof() self.check_name_refcount() self.check_contents() self.check_loops() self.check_inode_sizes() self.check_inode_unix() self.check_inode_refcount() self.check_block_refcount() self.check_obj_refcounts() self.check_keylist() finally: log.info('Dropping temporary indices...') for idx in ('tmp1', 'tmp2', 'tmp3', 'tmp4'): self.conn.execute('DROP INDEX %s' % idx) def log_error(self, *a, **kw): '''Log file system error if not expected''' if not self.expect_errors: return log.warn(*a, **kw) def check_foreign_keys(self): '''Check for referential integrity Checks that all foreign keys in the SQLite tables actually resolve. This is necessary, because we disable runtime checking by SQLite for performance reasons. ''' log.info("Checking referential integrity...") for (table,) in self.conn.query("SELECT name FROM sqlite_master WHERE type='table'"): for row in self.conn.query('PRAGMA foreign_key_list(%s)' % table): sql_objs = { 'src_table': table, 'dst_table': row[2], 'src_col': row[3], 'dst_col': row[4] } for (val,) in self.conn.query('SELECT %(src_table)s.%(src_col)s ' 'FROM %(src_table)s LEFT JOIN %(dst_table)s ' 'ON %(src_table)s.%(src_col)s = %(dst_table)s.%(dst_col)s ' 'WHERE %(dst_table)s.%(dst_col)s IS NULL ' 'AND %(src_table)s.%(src_col)s IS NOT NULL' % sql_objs): self.found_errors = True self.uncorrectable_errors = True sql_objs['val'] = val self.log_error('%(src_table)s.%(src_col)s refers to non-existing key %(val)s ' 'in %(dst_table)s.%(dst_col)s!', sql_objs) self.log_error("Don't know how to fix this problem!") def check_cache(self): """Commit uncommitted cache files""" log.info("Checking cached objects...") if not os.path.exists(self.cachedir): return for filename in os.listdir(self.cachedir): self.found_errors = True match = re.match('^(\\d+)-(\\d+)$', filename) if match: inode = int(match.group(1)) blockno = int(match.group(2)) else: raise RuntimeError('Strange file in cache directory: %s' % filename) self.log_error("Committing block %d of inode %d to backend", blockno, inode) fh = open(os.path.join(self.cachedir, filename), "rb") size = os.fstat(fh.fileno()).st_size hash_ = sha256_fh(fh) try: (block_id, obj_id) = self.conn.get_row('SELECT id, obj_id FROM blocks WHERE hash=?', (hash_,)) except NoSuchRowError: obj_id = self.conn.rowid('INSERT INTO objects (refcount) VALUES(1)') block_id = self.conn.rowid('INSERT INTO blocks (refcount, hash, obj_id, size) ' 'VALUES(?, ?, ?, ?)', (1, hash_, obj_id, size)) with self.bucket.open_write('s3ql_data_%d' % obj_id) as dest: fh.seek(0) shutil.copyfileobj(fh, dest) if isinstance(dest, CompressFilter): obj_size = dest.compr_size else: obj_size = fh.tell() self.conn.execute('UPDATE objects SET compr_size=? WHERE id=?', (obj_size, obj_id)) else: self.conn.execute('UPDATE blocks SET refcount=refcount+1 WHERE id=?', (block_id,)) try: old_block_id = self.conn.get_val('SELECT block_id FROM inode_blocks_v ' 'WHERE inode=? AND blockno=?', (inode, blockno)) except NoSuchRowError: if blockno == 0: self.conn.execute('UPDATE inodes SET block_id=? WHERE id=?', (block_id, inode)) else: self.conn.execute('INSERT INTO inode_blocks (block_id, inode, blockno) VALUES(?,?,?)', (block_id, inode, blockno)) else: if blockno == 0: self.conn.execute('UPDATE inodes SET block_id=? WHERE id=?', (block_id, inode)) else: self.conn.execute('UPDATE inode_blocks SET block_id=? WHERE inode=? AND blockno=?', (block_id, inode, blockno)) # We just decrease the refcount, but don't take any action # because the reference count might be wrong self.conn.execute('UPDATE blocks SET refcount=refcount-1 WHERE id=?', (old_block_id,)) self.unlinked_blocks.add(old_block_id) fh.close() os.unlink(os.path.join(self.cachedir, filename)) def check_lof(self): """Ensure that there is a lost+found directory""" log.info('Checking lost+found...') timestamp = time.time() - time.timezone try: (inode_l, name_id) = self.conn.get_row("SELECT inode, name_id FROM contents_v " "WHERE name=? AND parent_inode=?", (b"lost+found", ROOT_INODE)) except NoSuchRowError: self.found_errors = True self.log_error("Recreating missing lost+found directory") inode_l = self.conn.rowid("INSERT INTO inodes (mode,uid,gid,mtime,atime,ctime,refcount) " "VALUES (?,?,?,?,?,?,?)", (stat.S_IFDIR | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR, os.getuid(), os.getgid(), timestamp, timestamp, timestamp, 1)) self.conn.execute("INSERT INTO contents (name_id, inode, parent_inode) VALUES(?,?,?)", (self._add_name(b"lost+found"), inode_l, ROOT_INODE)) mode = self.conn.get_val('SELECT mode FROM inodes WHERE id=?', (inode_l,)) if not stat.S_ISDIR(mode): self.found_errors = True self.log_error('/lost+found is not a directory! Old entry will be saved as ' '/lost+found/inode-%s*', inode_l) # We leave the old inode unassociated, so that it will be added # to lost+found later on. inode_l = self.conn.rowid("INSERT INTO inodes (mode,uid,gid,mtime,atime,ctime,refcount) " "VALUES (?,?,?,?,?,?,?)", (stat.S_IFDIR | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR, os.getuid(), os.getgid(), timestamp, timestamp, timestamp, 2)) self.conn.execute('UPDATE contents SET inode=? WHERE name_id=? AND parent_inode=?', (inode_l, name_id, ROOT_INODE)) def check_contents(self): """Check direntry names""" log.info('Checking directory entry names...') for (name, id_p) in self.conn.query('SELECT name, parent_inode FROM contents_v ' 'WHERE LENGTH(name) > 255'): path = get_path(id_p, self.conn, name) self.log_error('Entry name %s... in %s has more than 255 characters, ' 'this could cause problems', name[:40], path[:-len(name)]) self.found_errors = True def check_loops(self): """Ensure that all directories can be reached from root""" log.info('Checking directory reachability...') self.conn.execute('CREATE TEMPORARY TABLE loopcheck (inode INTEGER PRIMARY KEY, ' 'parent_inode INTEGER)') self.conn.execute('CREATE INDEX ix_loopcheck_parent_inode ON loopcheck(parent_inode)') self.conn.execute('INSERT INTO loopcheck (inode, parent_inode) ' 'SELECT inode, parent_inode FROM contents JOIN inodes ON inode == id ' 'WHERE mode & ? == ?', (S_IFMT, stat.S_IFDIR)) self.conn.execute('CREATE TEMPORARY TABLE loopcheck2 (inode INTEGER PRIMARY KEY)') self.conn.execute('INSERT INTO loopcheck2 (inode) SELECT inode FROM loopcheck') def delete_tree(inode_p): for (inode,) in self.conn.query("SELECT inode FROM loopcheck WHERE parent_inode=?", (inode_p,)): delete_tree(inode) self.conn.execute('DELETE FROM loopcheck2 WHERE inode=?', (inode_p,)) delete_tree(ROOT_INODE) if self.conn.has_val("SELECT 1 FROM loopcheck2"): self.found_errors = True self.uncorrectable_errors = True self.log_error("Found unreachable filesystem entries!\n" "This problem cannot be corrected automatically yet.") self.conn.execute("DROP TABLE loopcheck") self.conn.execute("DROP TABLE loopcheck2") def check_inode_sizes(self): """Check if inode sizes agree with blocks""" log.info('Checking inodes (sizes)...') self.conn.execute('CREATE TEMPORARY TABLE min_sizes ' '(id INTEGER PRIMARY KEY, min_size INTEGER NOT NULL)') try: self.conn.execute(''' INSERT INTO min_sizes (id, min_size) SELECT inode, MAX(blockno * ? + size) FROM inode_blocks_v JOIN blocks ON block_id == blocks.id GROUP BY inode''', (self.blocksize,)) self.conn.execute(''' CREATE TEMPORARY TABLE wrong_sizes AS SELECT id, size, min_size FROM inodes JOIN min_sizes USING (id) WHERE size < min_size''') for (id_, size_old, size) in self.conn.query('SELECT * FROM wrong_sizes'): self.found_errors = True self.log_error("Size of inode %d (%s) does not agree with number of blocks, " "setting from %d to %d", id_, get_path(id_, self.conn), size_old, size) self.conn.execute("UPDATE inodes SET size=? WHERE id=?", (size, id_)) finally: self.conn.execute('DROP TABLE min_sizes') self.conn.execute('DROP TABLE IF EXISTS wrong_sizes') def _add_name(self, name): '''Get id for *name* and increase refcount Name is inserted in table if it does not yet exist. ''' try: name_id = self.conn.get_val('SELECT id FROM names WHERE name=?', (name,)) except NoSuchRowError: name_id = self.conn.rowid('INSERT INTO names (name, refcount) VALUES(?,?)', (name, 1)) else: self.conn.execute('UPDATE names SET refcount=refcount+1 WHERE id=?', (name_id,)) return name_id def _del_name(self, name_id): '''Decrease refcount for name_id, remove if it reaches 0''' self.conn.execute('UPDATE names SET refcount=refcount-1 WHERE id=?', (name_id,)) self.conn.execute('DELETE FROM names WHERE refcount=0 AND id=?', (name_id,)) def check_inode_refcount(self): """Check inode reference counters""" log.info('Checking inodes (refcounts)...') self.conn.execute('CREATE TEMPORARY TABLE refcounts ' '(id INTEGER PRIMARY KEY, refcount INTEGER NOT NULL)') try: self.conn.execute('INSERT INTO refcounts (id, refcount) ' 'SELECT inode, COUNT(name_id) FROM contents GROUP BY inode') self.conn.execute(''' CREATE TEMPORARY TABLE wrong_refcounts AS SELECT id, refcounts.refcount, inodes.refcount FROM inodes LEFT JOIN refcounts USING (id) WHERE inodes.refcount != refcounts.refcount OR refcounts.refcount IS NULL''') for (id_, cnt, cnt_old) in self.conn.query('SELECT * FROM wrong_refcounts'): # No checks for root and control if id_ in (ROOT_INODE, CTRL_INODE): continue self.found_errors = True if cnt is None: (id_p, name) = self.resolve_free(b"/lost+found", b"inode-%d" % id_) self.log_error("Inode %d not referenced, adding as /lost+found/%s", id_, name) self.conn.execute("INSERT INTO contents (name_id, inode, parent_inode) " "VALUES (?,?,?)", (self._add_name(basename(name)), id_, id_p)) self.conn.execute("UPDATE inodes SET refcount=? WHERE id=?", (1, id_)) else: self.log_error("Inode %d (%s) has wrong reference count, setting from %d to %d", id_, get_path(id_, self.conn), cnt_old, cnt) self.conn.execute("UPDATE inodes SET refcount=? WHERE id=?", (cnt, id_)) finally: self.conn.execute('DROP TABLE refcounts') self.conn.execute('DROP TABLE IF EXISTS wrong_refcounts') def check_block_refcount(self): """Check block reference counters""" log.info('Checking blocks (refcounts)...') self.conn.execute('CREATE TEMPORARY TABLE refcounts ' '(id INTEGER PRIMARY KEY, refcount INTEGER NOT NULL)') try: self.conn.execute(''' INSERT INTO refcounts (id, refcount) SELECT block_id, COUNT(blockno) FROM inode_blocks_v GROUP BY block_id ''') self.conn.execute(''' CREATE TEMPORARY TABLE wrong_refcounts AS SELECT id, refcounts.refcount, blocks.refcount, obj_id FROM blocks LEFT JOIN refcounts USING (id) WHERE blocks.refcount != refcounts.refcount OR refcounts.refcount IS NULL''') for (id_, cnt, cnt_old, obj_id) in self.conn.query('SELECT * FROM wrong_refcounts'): if cnt is None and id_ in self.unlinked_blocks and cnt_old == 0: # Block was unlinked by check_cache and can now really be # removed (since we have checked that there are truly no # other references) self.conn.execute('DELETE FROM blocks WHERE id=?', (id_,)) # We can't remove associated objects yet, because their refcounts # might be wrong, too. self.conn.execute('UPDATE objects SET refcount=refcount-1 WHERE id=?', (obj_id,)) self.unlinked_objects.add(obj_id) elif cnt is None: self.found_errors = True (id_p, name) = self.resolve_free(b"/lost+found", b"block-%d" % id_) self.log_error("Block %d not referenced, adding as /lost+found/%s", id_, name) timestamp = time.time() - time.timezone inode = self.conn.rowid(""" INSERT INTO inodes (mode,uid,gid,mtime,atime,ctime,refcount,block_id) VALUES (?,?,?,?,?,?,?,?)""", (stat.S_IFREG | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR, os.getuid(), os.getgid(), timestamp, timestamp, timestamp, 1, id_)) self.conn.execute("INSERT INTO contents (name_id, inode, parent_inode) VALUES (?,?,?)", (self._add_name(basename(name)), inode, id_p)) self.conn.execute("UPDATE blocks SET refcount=? WHERE id=?", (1, id_)) else: self.found_errors = True self.log_error("Block %d has wrong reference count, setting from %d to %d", id_, cnt_old, cnt) self.conn.execute("UPDATE blocks SET refcount=? WHERE id=?", (cnt, id_)) finally: self.conn.execute('DROP TABLE refcounts') self.conn.execute('DROP TABLE IF EXISTS wrong_refcounts') def check_name_refcount(self): """Check name reference counters""" log.info('Checking names (refcounts)...') self.conn.execute('CREATE TEMPORARY TABLE refcounts ' '(id INTEGER PRIMARY KEY, refcount INTEGER NOT NULL)') try: self.conn.execute(''' INSERT INTO refcounts (id, refcount) SELECT name_id, COUNT(name_id) FROM contents GROUP BY name_id''') self.conn.execute(''' CREATE TEMPORARY TABLE wrong_refcounts AS SELECT id, refcounts.refcount, names.refcount FROM names LEFT JOIN refcounts USING (id) WHERE names.refcount != refcounts.refcount OR refcounts.refcount IS NULL''') for (id_, cnt, cnt_old) in self.conn.query('SELECT * FROM wrong_refcounts'): self.found_errors = True if cnt is None: self.log_error("Name %d not referenced, removing (old refcount: %d)", id_, cnt_old) self.conn.execute('DELETE FROM names WHERE id=?', (id_,)) else: self.log_error("Name %d has wrong reference count, setting from %d to %d", id_, cnt_old, cnt) self.conn.execute("UPDATE names SET refcount=? WHERE id=?", (cnt, id_)) finally: self.conn.execute('DROP TABLE refcounts') self.conn.execute('DROP TABLE IF EXISTS wrong_refcounts') def check_inode_unix(self): """Check inode attributes for agreement with UNIX conventions This means: - Only directories should have child entries - Only regular files should have data blocks and a size - Only symlinks should have a target - Only devices should have a device number - symlink size is length of target Note that none of this is enforced by S3QL. However, as long as S3QL only communicates with the UNIX FUSE module, none of the above should happen (and if it does, it would probably confuse the system quite a lot). """ log.info('Checking inodes (types)...') for (inode, mode, size, target, rdev) \ in self.conn.query("SELECT id, mode, size, target, rdev " "FROM inodes LEFT JOIN symlink_targets ON id = inode"): if stat.S_ISLNK(mode) and target is None: self.found_errors = True self.log_error('Inode %d (%s): symlink does not have target. ' 'This is probably going to confuse your system!', inode, get_path(inode, self.conn)) if stat.S_ISLNK(mode) and target is not None and size != len(target): self.found_errors = True self.log_error('Inode %d (%s): symlink size (%d) does not agree with target ' 'length (%d). This is probably going to confuse your system!', inode, get_path(inode, self.conn), size, len(target)) if size != 0 and (not stat.S_ISREG(mode) and not stat.S_ISLNK(mode) and not stat.S_ISDIR(mode)): self.found_errors = True self.log_error('Inode %d (%s) is not regular file but has non-zero size. ' 'This is may confuse your system!', inode, get_path(inode, self.conn)) if target is not None and not stat.S_ISLNK(mode): self.found_errors = True self.log_error('Inode %d (%s) is not symlink but has symlink target. ' 'This is probably going to confuse your system!', inode, get_path(inode, self.conn)) if rdev != 0 and not (stat.S_ISBLK(mode) or stat.S_ISCHR(mode)): self.found_errors = True self.log_error('Inode %d (%s) is not device but has device number. ' 'This is probably going to confuse your system!', inode, get_path(inode, self.conn)) has_children = self.conn.has_val('SELECT 1 FROM contents WHERE parent_inode=? LIMIT 1', (inode,)) if has_children and not stat.S_ISDIR(mode): self.found_errors = True self.log_error('Inode %d (%s) is not a directory but has child entries. ' 'This is probably going to confuse your system!', inode, get_path(inode, self.conn)) if (not stat.S_ISREG(mode) and self.conn.has_val('SELECT 1 FROM inode_blocks_v WHERE inode=?', (inode,))): self.found_errors = True self.log_error('Inode %d (%s) is not a regular file but has data blocks. ' 'This is probably going to confuse your system!', inode, get_path(inode, self.conn)) def check_obj_refcounts(self): """Check object reference counts""" log.info('Checking object reference counts...') self.conn.execute('CREATE TEMPORARY TABLE refcounts ' '(id INTEGER PRIMARY KEY, refcount INTEGER NOT NULL)') try: self.conn.execute('INSERT INTO refcounts (id, refcount) ' 'SELECT obj_id, COUNT(obj_id) FROM blocks GROUP BY obj_id') self.conn.execute(''' CREATE TEMPORARY TABLE wrong_refcounts AS SELECT id, refcounts.refcount, objects.refcount FROM objects LEFT JOIN refcounts USING (id) WHERE objects.refcount != refcounts.refcount OR refcounts.refcount IS NULL''') for (id_, cnt, cnt_old) in self.conn.query('SELECT * FROM wrong_refcounts'): if cnt is None and id_ in self.unlinked_objects and cnt_old == 0: # Object was unlinked by check_block_refcounts self.conn.execute('DELETE FROM objects WHERE id=?', (id_,)) else: self.found_errors = True self.log_error("Object %s has invalid refcount, setting from %d to %d", id_, cnt_old, cnt or 0) if cnt is not None: self.conn.execute("UPDATE objects SET refcount=? WHERE id=?", (cnt, id_)) else: # Orphaned object will be picked up by check_keylist self.conn.execute('DELETE FROM objects WHERE id=?', (id_,)) finally: self.conn.execute('DROP TABLE refcounts') self.conn.execute('DROP TABLE IF EXISTS wrong_refcounts') def check_keylist(self): """Check the list of objects. Checks that: - all objects are referred in the object table - all objects in the object table exist - object has correct hash """ log.info('Checking object list...') lof_id = self.conn.get_val("SELECT inode FROM contents_v " "WHERE name=? AND parent_inode=?", (b"lost+found", ROOT_INODE)) # We use this table to keep track of the objects that we have seen self.conn.execute("CREATE TEMP TABLE obj_ids (id INTEGER PRIMARY KEY)") try: for (i, obj_name) in enumerate(self.bucket.list('s3ql_data_')): if i != 0 and i % 5000 == 0: log.info('..processed %d objects so far..', i) # We only bother with data objects obj_id = int(obj_name[10:]) self.conn.execute('INSERT INTO obj_ids VALUES(?)', (obj_id,)) for (obj_id,) in self.conn.query('SELECT id FROM obj_ids ' 'EXCEPT SELECT id FROM objects'): try: if obj_id in self.unlinked_objects: del self.bucket['s3ql_data_%d' % obj_id] else: # TODO: Save the data in lost+found instead del self.bucket['s3ql_data_%d' % obj_id] self.found_errors = True self.log_error("Deleted spurious object %d", obj_id) except NoSuchObject: pass self.conn.execute('CREATE TEMPORARY TABLE missing AS ' 'SELECT id FROM objects EXCEPT SELECT id FROM obj_ids') moved_inodes = set() for (obj_id,) in self.conn.query('SELECT * FROM missing'): if (not self.bucket.is_list_create_consistent() and ('s3ql_data_%d' % obj_id) in self.bucket): # Object was just not in list yet continue self.found_errors = True self.log_error("object %s only exists in table but not in bucket, deleting", obj_id) for (id_,) in self.conn.query('SELECT inode FROM inode_blocks_v JOIN blocks ON block_id = id ' 'WHERE obj_id=?', (obj_id,)): # Same file may lack several blocks, but we want to move it # only once if id_ in moved_inodes: continue moved_inodes.add(id_) for (name, name_id, id_p) in self.conn.query('SELECT name, name_id, parent_inode ' 'FROM contents_v WHERE inode=?', (id_,)): path = get_path(id_p, self.conn, name) self.log_error("File may lack data, moved to /lost+found: %s", path) (_, newname) = self.resolve_free(b"/lost+found", path[1:].replace('_', '__').replace('/', '_')) self.conn.execute('UPDATE contents SET name_id=?, parent_inode=? ' 'WHERE name_id=? AND parent_inode=?', (self._add_name(newname), lof_id, name_id, id_p)) self._del_name(name_id) self.conn.execute("DELETE FROM blocks WHERE obj_id=?", (obj_id,)) self.conn.execute("DELETE FROM objects WHERE id=?", (obj_id,)) finally: self.conn.execute('DROP TABLE obj_ids') self.conn.execute('DROP TABLE IF EXISTS missing') def resolve_free(self, path, name): '''Return parent inode and name of an unused directory entry The directory entry will be in `path`. If an entry `name` already exists there, we append a numeric suffix. ''' if not isinstance(path, bytes): raise TypeError('path must be of type bytes') inode_p = inode_for_path(path, self.conn) # Debugging http://code.google.com/p/s3ql/issues/detail?id=217 # and http://code.google.com/p/s3ql/issues/detail?id=261 if len(name) > 255-4: name = '%s ... %s' % (name[0:120], name[-120:]) i = 0 newname = name name += b'-' try: while True: self.conn.get_val("SELECT inode FROM contents_v " "WHERE name=? AND parent_inode=?", (newname, inode_p)) i += 1 newname = name + bytes(i) except NoSuchRowError: pass return (inode_p, newname)
gpl-3.0
jmarine/webgl8x8boardgames
game.js
4075
/* WebGL 8x8 board games Copyright (C) 2011 by Jordi Mariné Fort 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 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/>. */ var game = null; var NONE = 0; var PLAYER1 = 1; var PLAYER2 = 2; var PAWN = 1; var QUEEN = 2; var KING = 3; var BISHOP = 4; var KNIGHT = 5; var ROOK = 6; var PIECE_CHARS = " PQKBNR"; var app = app || {} app.model = app.model || {} app.model.GameFactory = { createGame: function(gameType) { var camelGameType = gameType.substring(0,1).toUpperCase() + gameType.substring(1).toLowerCase(); return eval(" new app.model." + camelGameType + "()"); } } app.model.Game = (function() { function Game() { return this; } Game.prototype.getTurn = function() { return this.turn; } Game.prototype.isOver = function() { return (this.getMovements().length == 0); } Game.prototype.getOpponent = function() { return (this.turn == PLAYER1) ? PLAYER2 : PLAYER1; } Game.prototype.toggleTurn = function() { this.turn = this.getOpponent(); return this.turn; } Game.prototype.getPieceIndex = function(x,y) { var index = y*8 + x; return index; } Game.prototype.setPiece = function(x,y, player, pieceType) { var index = this.getPieceIndex(x,y); var playerFactor = 0; if(player == PLAYER1) playerFactor = 1; if(player == PLAYER2) playerFactor = -1; this.pieces[index] = playerFactor * pieceType; } Game.prototype.getPiece = function(x,y) { var index = this.getPieceIndex(x,y); var val = this.pieces[index]; if(val) { return val; } else return NONE; } Game.prototype.getPieceChar = function(type,player) { var pieceChar = PIECE_CHARS.charAt(type); if(player == PLAYER2) pieceChar = pieceChar.toLowerCase(); return pieceChar; } Game.prototype.parsePieceType = function(ch) { var index = PIECE_CHARS.indexOf(ch); if(index < 0) index = NONE; return index; } Game.prototype.getPieceType = function(piece) { if(piece < 0) piece = -piece; return piece; } Game.prototype.getPieceOwner = function(piece) { if(!piece) return NONE; else if(piece > 0) return PLAYER1; else if(piece < 0) return PLAYER2; } Game.prototype.makeMove = function(move) { var player = this.getTurn(); while(move != null) { this.makeStep(player, move); move=move.nextMove; } this.toggleTurn(); this.movements = null; } // METHODS TO OVERRIDE Game.prototype.getBoardRotationDegrees = function() { return 0; } Game.prototype.getPreferedLevelAI = function(alg) { if(alg == "MCTS") return 50; else return 4; } Game.prototype.toString = function() { return "[Game]"; } Game.prototype.clone = function() { var copy = new this.constructor(); copy.turn = this.turn; copy.pieces = this.pieces.slice(0); return copy; } Game.prototype.initFromStateStr = function(str) { } Game.prototype.newGame = function(player1, player2) { } Game.prototype.parseMoveString = function(str) { return null; } Game.prototype.getMoveString = function(move) { return "null"; } Game.prototype.isValidMove = function(str) { var move = this.parseMoveString(str); return (move != null); } Game.prototype.makeStep = function(player, move) { } Game.prototype.getPieceValue = function(pieceType) { return 0; } Game.prototype.evaluateState = function(depth) { return 0; } Game.prototype.isQuiescenceMove = function(move) { return true; } Game.prototype.getMovements = function() { return []; } Game.prototype.getWinner = function() { return NONE; } return Game; })();
gpl-3.0
leftstick/naive-mock
www/common/page/index.js
145
export {default as page} from './page'; export {default as pageTitle} from './pageTitle'; export {default as pageContent} from './pageContent';
gpl-3.0
heidtgg/leichtathletik-homepage
intern_bearbeiten/EditAthlete.php
5855
<?php include "Athlete.php"; function SelectDataBase($MYSQL_HOST, $MYSQL_BENUTZER, $MYSQL_KENNWORT, $MYSQL_DATENBANK){ $db_link = new mysqli($MYSQL_HOST, $MYSQL_BENUTZER, $MYSQL_KENNWORT); $db_link->select_db( $MYSQL_DATENBANK); return $db_link; } function DeleteAthlete($database){ $ID = $_POST['ID']; $sql = "UPDATE `athleten` SET `athleten`.`del` = 1 WHERE `athleten`.`ID` =".$ID." LIMIT 1"; $db_erg = $database->query( $sql ); } function GetAllAthletesFromDataBase($database){ $sql = "SELECT * FROM `athleten` WHERE `del` != 1 ORDER by athleten.athleten.Vorname Asc"; $db_erg = $database->query($sql); return $db_erg; } function GetAthleteWithID($ID, $database){ $sql = "SELECT * FROM `athleten` WHERE `ID` = $ID"; $db_erg = $database->query($sql); $SelectedAthlete = $db_erg->fetch_array( MYSQLI_ASSOC); return $SelectedAthlete; } function CheckForImageType($FileName){ $Erlaubte_Dateiendungen = array( "jpg", "gif", "zip" ); $DateiEndung = array_pop( explode( ".", strtolower( $FileName ) ) ); if (!in_array( $DateiEndung, $Erlaubte_Dateiendungen )) { die( "Die angeh&auml;ngte Datei hat eine nicht erlaubte Dateiendung!" ); } } function GenerateFileName($OldFileName){ date_default_timezone_set('UTC'); $datum = date("Y-m-d"); $Dateiname_bereinigen = array( 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss', ' ' => '_' ); $NewFileName = strtr( strtolower( $_FILES['datei']['name'] ), $Dateiname_bereinigen ); $NewFileName = "../artikelgraphik/athleten/" .$datum."_".$NewFileName; return $NewFileName; } function ImageUpload($FileName){ // UMASK resetten um Dateirechte zu ändern (wird nur fuer Linux benoetigt, Windows ignoriert das) $umask_alt = umask( 0 ); // Hochgeladenen Datei verschieben if (@move_uploaded_file( $_FILES['datei']['tmp_name'], $FileName )){ // Dateirechte setzen, damit man später die Datei wieder vom FTP bekommt und die UMASK auf den alten Wert setzen @chmod( $FileName, 0755 ); umask( $umask_alt ); } else{ // UMASK resetten umask( $umask_alt ); // Hier steht Code der ausgefuehrt wird, wenn der Upload fehl schlug } } $Identity = 0; $db_sel = SelectDataBase("sql82.your-server.de", "laftsg_2_w", "cHZVpEv6", "athleten"); if (isset( $_POST['trash'] )){ DeleteAthlete($db_sel); } if (isset( $_POST['OK'] )) { $Identity = $_POST['SelectedAthleteID']; $SelectedAthlete = GetAthleteWithID($Identity, $db_sel); } if (isset( $_POST['eintragen'] )) { // Maskierende Slashes aus POST entfernen $_POST = get_magic_quotes_gpc() ? array_map( 'stripslashes', $_POST ) : $_POST; if ($_FILES['datei']['size'] > 0){ CheckForImageType($_FILES['datei']['name']); $FileName = GenerateFileName($_FILES['datei']['name']); ImageUpload($FileName); } // Inhalte der Felder aus POST holen $EditedAthlet = new Athlete($_POST); $EditedAthlet->CheckForNewImage($FileName); $sql = $EditedAthlet->GenerateSQLString(); // Schickt die Anfrage an die DB und schreibt die Daten in die Tabelle $db_sel->query( $sql ); // Pruefen ob der neue Datensatz tatsaechlich eingefuegt wurde if ($db_sel->affected_rows == 1) { echo "<h3>Der Datensatz wurde hinzugef&uuml;gt!</h3>"; } else { echo "<h3>Der Datensatz konnte <strong>nicht</strong> hinzugef&uuml;gt werden!</h3>"; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style type="text/css"> form { background-color:#ddd; padding:20px; border:6px solid #ddd; } </style><title>Neuer Datenbankeintrag</title> </head> <body> <!--Das Formular --> <!-----------------> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="formular" id="formular" enctype="multipart/form-data"> <p> Vorhandene Datens&auml;tze k&ouml;nnen durch diese Kn&ouml;pfe erreicht werden</p> <select name="SelectedAthleteID" id="SelectedAthleteID" style="background-color: #FFFFFF; color: #000000;"> <option value="0" selected> </option> <?php $db_erg = GetAllAthletesFromDataBase($db_sel); //ORDER BY `athleten`.`athleten` DESC while ($zeile = $db_erg->fetch_array( MYSQLI_ASSOC)){ echo "<option value=\"".$zeile['ID']."\">".$zeile['Vorname']." ".$zeile['Nachname']."</option>"; } ?></select><br /> <input type="submit" name="OK" id="OK" value="OK"/><br> <!-- Anpassen der Eingabe Felder im Fall einer Auswahl --> <?php ?> <!-- ID --> <input type="hidden" name="ID" value="<?php echo $Identity ?>"> <!--Eingabe--> Vorname: <input type="text" name="Vorname" id="Vorname" /<?php if ($Identity != 0){echo "value=\"".$SelectedAthlete['Vorname']."\"";}?>><br/> Nachname: <input type="text" name="Nachname" id="Nachname" /<?php if ($Identity != 0){echo "value=\"".$SelectedAthlete['Nachname']."\"";}?>><br/> Bemerkung: <textarea name="Bemerkung" id="Bemerkung" cols="100" rows="2"><?php if ($Identity != 0){echo $SelectedAthlete['Bemerkung'];}?></textarea><br/> <!--Bild: <input type="text" name="Bild" id="Bild" /<?php if ($Identity != 0){echo "value=\"".$zeile['Bild']."\"";}?>><br/>--> <input type="text" name="BildAlt" id="BildAlt" value="<?php if ($Identity != 0){echo $SelectedAthlete['Bild'] ;}?>"> Bild: <?php if ($Identity != 0){echo "Vorhandenes Bild: "; echo $SelectedAthlete['Bild']; echo "<br>";}?><input type="file" name="datei" id="datei"><br /> StartpassNr: <input type="text" name="StartpassNr" id="StartpassNr" /<?php if ($Identity != 0){echo "value=\"".$SelectedAthlete['StartpassNr']."\"";}?>><br/> <!--Abschicken Knopf--> <input type="submit" name="eintragen" id="eintragen" value="Abschicken" /> <input type="submit" name="trash" id="trash" value="diesen Beitrag entfernen" /> </body> </html>
gpl-3.0
IrbisChaos/synchronizer
src/main/java/com/intenso/jira/plugins/synchronizer/config/SynchronizerConfigBuilder.java
6499
// // Decompiled by Procyon v0.5.30 // package com.intenso.jira.plugins.synchronizer.config; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import com.intenso.jira.plugins.synchronizer.utils.Builder; @JsonIgnoreProperties(ignoreUnknown = true) public class SynchronizerConfigBuilder implements Builder<SynchronizerConfig> { @JsonProperty private String cronOutgoingJob; @JsonProperty private String cronOutgoingResponseJob; @JsonProperty private String cronIncomingJob; @JsonProperty private String cronIncomingResponseJob; @JsonProperty private String cronPullJob; @JsonProperty private String cronPullResponsesJob; @JsonProperty private String cronPullConfigurationJob; @JsonProperty private String cronArchivizationJob; @JsonProperty private String cronClearOldQueueLogsJob; @JsonProperty private Integer retryCount; @JsonProperty private Integer queueIn; @JsonProperty private Integer queueOut; @JsonProperty private Integer workflowRestApi; @JsonProperty private Integer genDiagnosticPanel; @JsonProperty private Integer genRemoteIssuePanel; @JsonProperty private String[] genExtCommnetsTabPerm; @JsonProperty private String[] genCreateOnDemandPerm; @Override public SynchronizerConfig build() { return new SynchronizerConfig(this); } public String getCronOutgoingJob() { return this.cronOutgoingJob; } public SynchronizerConfigBuilder cronOutgoingJob(final String cronOutgoingJob) { this.cronOutgoingJob = cronOutgoingJob; return this; } public String getCronOutgoingResponseJob() { return this.cronOutgoingResponseJob; } public SynchronizerConfigBuilder cronOutgoingResponseJob(final String cronOutgoingResponseJob) { this.cronOutgoingResponseJob = cronOutgoingResponseJob; return this; } public String getCronIncomingJob() { return this.cronIncomingJob; } public SynchronizerConfigBuilder cronIncomingJob(final String cronIncomingJob) { this.cronIncomingJob = cronIncomingJob; return this; } public String getCronIncomingResponseJob() { return this.cronIncomingResponseJob; } public SynchronizerConfigBuilder cronIncomingResponseJob(final String cronIncomingResponseJob) { this.cronIncomingResponseJob = cronIncomingResponseJob; return this; } public String getCronArchivizationJob() { return this.cronArchivizationJob; } public SynchronizerConfigBuilder cronArchivizationJob(final String cronArchivizationJob) { this.cronArchivizationJob = cronArchivizationJob; return this; } public Integer getRetryCount() { return this.retryCount; } public SynchronizerConfigBuilder retryCount(final Integer retryCount) { this.retryCount = retryCount; return this; } public String getCronPullJob() { return this.cronPullJob; } public String getCronPullResponseJob() { return this.cronPullResponsesJob; } public String getCronPullResponsesJob() { return this.cronPullResponsesJob; } public SynchronizerConfigBuilder cronPullResponsesJob(final String cronPullResponsesJob) { this.cronPullResponsesJob = cronPullResponsesJob; return this; } public SynchronizerConfigBuilder cronPullJob(final String cronPullJob) { this.cronPullJob = cronPullJob; return this; } public SynchronizerConfigBuilder cronPullConfigurationJob(final String cronPullConfigurationJob) { this.cronPullConfigurationJob = cronPullConfigurationJob; return this; } public String getCronPullConfigurationJob() { return this.cronPullConfigurationJob; } public SynchronizerConfigBuilder cronClearOldQueueLogsJob(final String cronClearOldQueueLogsJob) { this.cronClearOldQueueLogsJob = cronClearOldQueueLogsJob; return this; } public String getCronClearOldQueueLogsJob() { return this.cronClearOldQueueLogsJob; } public Integer getQueueIn() { return this.queueIn; } public SynchronizerConfigBuilder queueIn(final Integer queueIn) { this.queueIn = queueIn; return this; } public Integer getQueueOut() { return this.queueOut; } public SynchronizerConfigBuilder queueOut(final Integer queueOut) { this.queueOut = queueOut; return this; } public Integer getGenDiagnosticPanel() { return this.genDiagnosticPanel; } public SynchronizerConfigBuilder genDiagnosticPanel(final Integer genDiagnosticPanel) { this.genDiagnosticPanel = genDiagnosticPanel; return this; } public String[] getGenExtCommnetsTabPerm() { return this.genExtCommnetsTabPerm; } public SynchronizerConfigBuilder genExtCommnetsTabPerm(final String genExtCommnetsTabPerm) { if (genExtCommnetsTabPerm != null && !genExtCommnetsTabPerm.isEmpty()) { this.genExtCommnetsTabPerm = genExtCommnetsTabPerm.split("\\\\"); } else { this.genExtCommnetsTabPerm = null; } return this; } public String[] getGenCreateOnDemandPerm() { return this.genCreateOnDemandPerm; } public SynchronizerConfigBuilder genCreateOnDemandPerm(final String genCreateOnDemandPerm) { if (genCreateOnDemandPerm != null && !genCreateOnDemandPerm.isEmpty()) { this.genCreateOnDemandPerm = genCreateOnDemandPerm.split("\\\\"); } else { this.genCreateOnDemandPerm = null; } return this; } public Integer getGenRemoteIssuePanel() { return this.genRemoteIssuePanel; } public SynchronizerConfigBuilder genRemoteIssuePanel(final Integer genRemoteIssuePanel) { this.genRemoteIssuePanel = genRemoteIssuePanel; return this; } public Integer getWorkflowRestApi() { return this.workflowRestApi; } public SynchronizerConfigBuilder workflowRestApi(final Integer workflowRestApi) { this.workflowRestApi = workflowRestApi; return this; } }
gpl-3.0
mateor/pdroid
android-4.0.3_r1/trunk/frameworks/base/core/java/android/widget/Advanceable.java
1253
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; /** * This interface can be implemented by any collection-type view which has a notion of * progressing through its set of children. The interface exists to give AppWidgetHosts a way of * taking responsibility for automatically advancing such collections. * * @hide */ public interface Advanceable { /** * Advances this collection, eg. shows the next view. */ public void advance(); /** * Called by the AppWidgetHost once before it begins to call advance(), allowing the * collection to do any required setup. */ public void fyiWillBeAdvancedByHostKThx(); }
gpl-3.0
otavanopisto/pyramus
framework/src/main/java/fi/otavanopisto/pyramus/koski/model/aikuistenperusopetus/AikuistenPerusopetuksenKurssinTunnistePV2017.java
951
package fi.otavanopisto.pyramus.koski.model.aikuistenperusopetus; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import fi.otavanopisto.pyramus.koski.KoodistoViite; import fi.otavanopisto.pyramus.koski.koodisto.AikuistenPerusopetuksenPaattovaiheenKurssit2017; @JsonDeserialize(using = JsonDeserializer.None.class) public class AikuistenPerusopetuksenKurssinTunnistePV2017 extends AikuistenPerusopetuksenKurssinTunniste { public AikuistenPerusopetuksenKurssinTunnistePV2017() { } public AikuistenPerusopetuksenKurssinTunnistePV2017(AikuistenPerusopetuksenPaattovaiheenKurssit2017 tunniste) { this.tunniste.setValue(tunniste); } public KoodistoViite<AikuistenPerusopetuksenPaattovaiheenKurssit2017> getTunniste() { return tunniste; } private final KoodistoViite<AikuistenPerusopetuksenPaattovaiheenKurssit2017> tunniste = new KoodistoViite<>(); }
gpl-3.0
jschultz/okular-kf5-tagging
generators/chm/lib/libchmfile.cpp
3656
/*************************************************************************** * Copyright (C) 2004-2007 by Georgy Yunaev, gyunaev@ulduzsoft.com * * Please do not use email address above for bug reports; see * * the README file * * * * 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 2 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, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "libchmfile.h" #include "libchmfileimpl.h" #include <QPixmap> LCHMFile::LCHMFile( ) { m_impl = new LCHMFileImpl(); } LCHMFile::~ LCHMFile( ) { delete m_impl; } bool LCHMFile::loadFile( const QString & archiveName ) { return m_impl->loadFile( archiveName ); } void LCHMFile::closeAll( ) { m_impl->closeAll(); } QString LCHMFile::title( ) const { return m_impl->title(); } QString LCHMFile::homeUrl( ) const { QString url = m_impl->homeUrl(); return url.isNull() ? QStringLiteral("/") : url; } bool LCHMFile::hasTableOfContents( ) const { return !m_impl->m_topicsFile.isNull(); } bool LCHMFile::hasIndexTable( ) const { return !m_impl->m_indexFile.isNull(); } bool LCHMFile::hasSearchTable( ) const { return m_impl->m_searchAvailable; } bool LCHMFile::parseTableOfContents( QVector< LCHMParsedEntry > * topics ) const { return m_impl->parseFileAndFillArray( m_impl->m_topicsFile, topics, false ); } bool LCHMFile::parseIndex( QVector< LCHMParsedEntry > * indexes ) const { return m_impl->parseFileAndFillArray( m_impl->m_indexFile, indexes, true ); } bool LCHMFile::getFileContentAsString( QString * str, const QString & url ) { return m_impl->getFileContentAsString( str, url ); } bool LCHMFile::getFileContentAsBinary( QByteArray * data, const QString & url ) { return m_impl->getFileContentAsBinary( data, url ); } bool LCHMFile::enumerateFiles( QStringList * files ) { return m_impl->enumerateFiles( files ); } QString LCHMFile::getTopicByUrl( const QString & url ) { return m_impl->getTopicByUrl( url ); } const QPixmap * LCHMFile::getBookIconPixmap( unsigned int imagenum ) { return m_impl->getBookIconPixmap( imagenum ); } const LCHMTextEncoding * LCHMFile::currentEncoding( ) const { return m_impl->m_currentEncoding; } bool LCHMFile::setCurrentEncoding( const LCHMTextEncoding * encoding ) { return m_impl->setCurrentEncoding( encoding ); } QString LCHMFile::normalizeUrl( const QString & url ) const { return m_impl->normalizeUrl( url ); } bool LCHMFile::getFileSize(unsigned int * size, const QString & url) { return m_impl->getFileSize( size, url ); }
gpl-3.0
Filechaser/nzbToMedia
nzbToRadarr-with-extemp4conv.py
1122
from core.checkandconvertbysickbeardmp4conv import checkandconvert from core.subprocesslauncher import Subprocesslauncher import os import sys def main(): # Paths and make sure they exist path_to_python = sys.executable path_of_script = os.path.dirname(os.path.realpath(__file__)) nzbtomediadirectory = os.path.abspath(os.path.join(path_of_script)) path_of_nzbtosickbeardpy = os.path.abspath(os.path.join(nzbtomediadirectory,'nzbToRadarr.py')) if not (os.path.isfile(path_of_nzbtosickbeardpy) and os.path.exists(nzbtomediadirectory)): print('not all files present') print('I am going to crash with an evil exception') sys.exit(1) #Runs checkandconvert Files are checked and converted to mp4 the return value is given back afterwards answer = checkandconvert() postprocessing = Subprocesslauncher(path_to_python,path_of_nzbtosickbeardpy,sys.argv[1:],terminalprefix='NZBTORADARR ') answerpostprocessing = postprocessing.launch() #old #return answerpostprocessing sys.exit(answerpostprocessing) if __name__ == '__main__': exit(main())
gpl-3.0
cadrian/photofam
photofam-model/src/main/java/net/cadrian/photofam/model/Image.java
2413
/** * This file is part or PhotoFam. * * PhotoFam 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, version 3 of the License. * * 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 net.cadrian.photofam.model; import java.util.Collection; /** * @author Cyril ADRIAN */ public interface Image { /** * @return the image album, never <code>null</code> */ Album getAlbum (); /** * @return the image name; never <code>null</code>. */ String getName (); /** * @param name * the new name of the image */ void setName (String name); /** * @return the path to the image */ String getPath (); /** * @return the tags of the image; never <code>null</code> (but may be empty). */ Collection<Tag> getTags (); /** * @return the image metadata */ Metadata getMetadata (); /** * @return the format of the image; never <code>null</code>. */ String getFormat (); /** * @return the data of the image; never <code>null</code>. */ java.awt.Image getImage (); /** * @param size * the length (in pixels) of the square containing the thumbnail * * @return the thumbnail data of the image; never <code>null</code>. */ java.awt.Image getThumbnail (int size); /** * @param a_tagName * the complete name of the tag to add * * @return the newly added tag */ Tag addTag (String a_tagName); /** * @param a_tag * the tag to add */ void addTag (Tag a_tag); /** * @param a_tag * the tag to remove */ void removeTag (Tag a_tag); /** * @return the rotation angle (in degrees) - usually 0, 90, 180, 270 */ int getRotation (); /** * @param a_angle * the rotation angle (in degrees) */ void rotate (int a_angle); /** * @return <code>true</code> if the image is visible, <code>false</code> otherwise */ boolean isVisible (); /** * @param enable */ void setVisible (boolean enable); }
gpl-3.0
NewmanMDB/VimConfig
tags/unity5/UnityEditor/AudioLowPassFilterInspector.cs
1009
namespace UnityEditor { using System; using UnityEngine; [CustomEditor(typeof(AudioLowPassFilter)), CanEditMultipleObjects] internal class AudioLowPassFilterInspector : Editor { private SerializedProperty m_LowpassLevelCustomCurve; private SerializedProperty m_LowpassResonanceQ; private void OnEnable() { this.m_LowpassResonanceQ = base.serializedObject.FindProperty("m_LowpassResonanceQ"); this.m_LowpassLevelCustomCurve = base.serializedObject.FindProperty("lowpassLevelCustomCurve"); } public override void OnInspectorGUI() { base.serializedObject.Update(); AudioSourceInspector.AnimProp(new GUIContent("Cutoff Frequency"), this.m_LowpassLevelCustomCurve, 22000f, 0f, true); EditorGUILayout.PropertyField(this.m_LowpassResonanceQ, new GUILayoutOption[0]); base.serializedObject.ApplyModifiedProperties(); } } }
gpl-3.0
romanalexander/MobArena
src/com/garbagemule/MobArena/framework/Arena.java
6080
package com.garbagemule.MobArena.framework; import java.util.*; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.garbagemule.MobArena.ArenaClass; import com.garbagemule.MobArena.ArenaListener; import com.garbagemule.MobArena.ArenaPlayer; import com.garbagemule.MobArena.ClassLimitManager; import com.garbagemule.MobArena.MASpawnThread; import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.MonsterManager; import com.garbagemule.MobArena.RewardManager; import com.garbagemule.MobArena.ScoreboardManager; import com.garbagemule.MobArena.leaderboards.Leaderboard; import com.garbagemule.MobArena.region.ArenaRegion; import com.garbagemule.MobArena.repairable.Repairable; import com.garbagemule.MobArena.util.inventory.InventoryManager; import com.garbagemule.MobArena.util.timer.AutoStartTimer; import com.garbagemule.MobArena.waves.WaveManager; public interface Arena { /*///////////////////////////////////////////////////////////////////////// // // NEW METHODS IN REFACTORING // /////////////////////////////////////////////////////////////////////////*/ public ConfigurationSection getSettings(); public World getWorld(); public void setWorld(World world); public boolean isEnabled(); public void setEnabled(boolean value); public boolean isProtected(); public void setProtected(boolean value); public boolean isRunning(); public boolean inEditMode(); public void setEditMode(boolean value); public int getMinPlayers(); public int getMaxPlayers(); public List<ItemStack> getEntryFee(); public Set<Map.Entry<Integer,List<ItemStack>>> getEveryWaveEntrySet(); public List<ItemStack> getAfterWaveReward(int wave); public Set<Player> getPlayersInArena(); public Set<Player> getPlayersInLobby(); public Set<Player> getReadyPlayersInLobby(); public Set<Player> getSpectators(); public MASpawnThread getSpawnThread(); public WaveManager getWaveManager(); public Location getPlayerEntry(Player p); public ArenaListener getEventListener(); public void setLeaderboard(Leaderboard leaderboard); public ArenaPlayer getArenaPlayer(Player p); public Set<Block> getBlocks(); public void addBlock(Block b); public boolean removeBlock(Block b); public boolean hasPet(Entity e); public void addRepairable(Repairable r); public ArenaRegion getRegion(); public InventoryManager getInventoryManager(); public RewardManager getRewardManager(); public MonsterManager getMonsterManager(); public ClassLimitManager getClassLimitManager(); public void revivePlayer(Player p); public ScoreboardManager getScoreboard(); public void scheduleTask(Runnable r, int delay); public boolean startArena(); public boolean endArena(); public void forceStart(); public void forceEnd(); public boolean playerJoin(Player p, Location loc); public void playerReady(Player p); public boolean playerLeave(Player p); public void playerDeath(Player p); public void playerRespawn(Player p); public Location getRespawnLocation(Player p); public void playerSpec(Player p, Location loc); public void storePlayerData(Player p, Location loc); public void storeContainerContents(); public void restoreContainerContents(); public void movePlayerToLobby(Player p); public void movePlayerToSpec(Player p); public void movePlayerToEntry(Player p); public void discardPlayer(Player p); public void repairBlocks(); public void queueRepairable(Repairable r); /*//////////////////////////////////////////////////////////////////// // // Items & Cleanup // ////////////////////////////////////////////////////////////////////*/ public void assignClass(Player p, String className); public void assignClassGiveInv(Player p, String className, ItemStack[] contents); public void addRandomPlayer(Player p); public void assignRandomClass(Player p); public void assignClassPermissions(Player p); public void removeClassPermissions(Player p); public void addPermission(Player p, String perm, boolean value); /*//////////////////////////////////////////////////////////////////// // // Initialization & Checks // ////////////////////////////////////////////////////////////////////*/ public void restoreRegion(); /*//////////////////////////////////////////////////////////////////// // // Getters & Misc // ////////////////////////////////////////////////////////////////////*/ public boolean inArena(Player p); public boolean inLobby(Player p); public boolean inSpec(Player p); public boolean isDead(Player p); public String configName(); public String arenaName(); public MobArena getPlugin(); public Map<String,ArenaClass> getClasses(); public int getPlayerCount(); public List<Player> getAllPlayers(); public Collection<ArenaPlayer> getArenaPlayerSet(); public List<Player> getNonreadyPlayers(); public boolean canAfford(Player p); public boolean takeFee(Player p); public boolean refund(Player p); public boolean canJoin(Player p); public boolean canSpec(Player p); public boolean hasIsolatedChat(); public Player getLastPlayerStanding(); public AutoStartTimer getAutoStartTimer(); }
gpl-3.0
cward13/DarwinOp-Robocup2015
Player/Config/Walk/Config_OP_Walk.lua
23797
module(..., package.seeall); require('vector') require 'unix' -- Walk Parameters walk = {}; ---------------------------------------------- -- Stance and velocity limit values ---------------------------------------------- walk.stanceLimitX={-0.10,0.10}; walk.stanceLimitY={0.07,0.20}; walk.stanceLimitA={0*math.pi/180,30*math.pi/180}; --walk.velLimitX={-.03,.06};--reduced speed for stability walk.velLimitX={-.03,.08}; walk.velLimitY={-.03,.03}; walk.velLimitA={-.4,.4}; walk.velDelta={0.02,0.02,0.15} ---------------------------------------------- -- Stance parameters --------------------------------------------- walk.bodyHeight = 0.295; walk.bodyTilt=15*math.pi/180; -- orig=20, 30 seems to be too much {spa} walk.footX= -0.020; walk.footY = 0.035; walk.supportX = 0; walk.supportY = 0.010; --walk.qLArm=math.pi/180*vector.new({90,8,-40}); --walk.qRArm=math.pi/180*vector.new({90,-8,-40}); walk.qLArm=math.pi/180*vector.new({90,2,-20}); walk.qRArm=math.pi/180*vector.new({90,-2,-20}); walk.qLArmKick=math.pi/180*vector.new({90,30,-60}); walk.qRArmKick=math.pi/180*vector.new({90,-30,-60}); walk.hardnessSupport = .5; walk.hardnessSwing = 1; walk.hardnessArm=.3; --------------------------------------------- -- Gait parameters --------------------------------------------- walk.tStep = 0.35; walk.tZmp = 0.165; walk.stepHeight = 0.045; -- default: 0.035 walk.phSingle={0.1,0.9}; -------------------------------------------- -- Compensation parameters -------------------------------------------- walk.hipRollCompensation = 4*math.pi/180; walk.ankleMod = vector.new({-1,0})*1*math.pi/180; walk.spreadComp = 0.015; -------------------------------------------------------------- --Imu feedback parameters, alpha / gain / deadband / max -------------------------------------------------------------- gyroFactor = 0.273*math.pi/180 * 300 / 1024; --dps to rad/s conversion if Config.servo.pid==1 then walk.ankleImuParamX={0.5,0.3*gyroFactor, 1*math.pi/180, 25*math.pi/180}; walk.kneeImuParamX={0.5,1.2*gyroFactor, 1*math.pi/180, 25*math.pi/180}; walk.ankleImuParamY={0.5,0.7*gyroFactor, 1*math.pi/180, 25*math.pi/180}; walk.hipImuParamY={0.5,0.3*gyroFactor, 1*math.pi/180, 25*math.pi/180}; walk.armImuParamX={0.9,10*gyroFactor, 20*math.pi/180, 45*math.pi/180}; -- walk.armImuParamY={0.3,10*gyroFactor, 20*math.pi/180, 45*math.pi/180}; --DISABLE Y BALANCING walk.armImuParamY={0.9,10*gyroFactor, 20*math.pi/180, 45*math.pi/180}; else walk.ankleImuParamX={0.9,0.3*gyroFactor, 0, 25*math.pi/180}; walk.kneeImuParamX={0.9,1.2*gyroFactor, 0, 25*math.pi/180}; walk.ankleImuParamY={0.9,0.7*gyroFactor, 0, 25*math.pi/180}; walk.hipImuParamY={0.9,0.3*gyroFactor, 0, 25*math.pi/180}; walk.armImuParamX={0.9,10*gyroFactor, 20*math.pi/180, 45*math.pi/180}; walk.armImuParamY={0.9,10*gyroFactor, 20*math.pi/180, 45*math.pi/180}; end -------------------------------------------- -- Support point modulation values -------------------------------------------- walk.velFastForward = 0.05; walk.velFastTurn = 0.15; --walk.supportFront = 0.01; --Lean back when walking fast forward walk.supportFront = 0.03; --Lean back when walking fast forward walk.supportFront2 = 0.03; --Lean front when accelerating forward walk.supportBack = -0.02; --Lean back when walking backward walk.supportSideX = -0.01; --Lean back when sidestepping walk.supportSideX = -0.005; --Lean back when sidestepping walk.supportSideY = 0.02; --Lean sideways when sidestepping walk.supportTurn = 0.02; --Lean front when turning walk.turnCompThreshold = 0.1; walk.turnComp = 0.005; --Lean front when turning walk.turnComp = 0.003; --Lean front when turning -------------------------------------------- -- WalkKick parameters -------------------------------------------- walk.walkKickDef={} --tStep stepType supportLeg stepHeight -- SupportMod shiftFactor footPos1 footPos2 walk.walkKickDef["FrontLeft"]={ {0.30, 1, 0, 0.035 , {0,0}, 0.6, {0.06,0,0} }, {0.40, 2, 1, 0.05 , {0.02,-0.02}, 0.5, {0.12,0,0}, {0.09,0,0} }, {walk.tStep, 1, 0, 0.035 , {0,0}, 0.5, {0.04,0,0} }, } walk.walkKickDef["FrontRight"]={ {0.30, 1, 1, 0.035 , {0,0}, 0.4, {0.06,0,0} }, {0.40, 2, 0, 0.05 , {0.02,0.02}, 0.5, {0.12,0,0}, {0.09,0,0} }, {walk.tStep, 1, 1, 0.035 , {0,0}, 0.5, {0.04,0,0} }, } --Close-range walkkick (step back and then walkkick) walk.walkKickDef["FrontLeft2"]={ {0.30, 1, 1, 0.035 , {0,0}, 0.4, {-0.06,0,0} }, {0.30, 1, 0, 0.035 , {0.02,0}, 0.6, {0.06,0,0} }, {0.40, 2, 1, 0.05 , {0.0,-0.02}, 0.5, {0.12,0,0}, {0.09,0,0} }, {walk.tStep, 1, 0, 0.035 , {0,0}, 0.5, {0.04,0,0} }, } walk.walkKickDef["FrontRight2"]={ {0.30, 1, 0, 0.035 , {0,0}, 0.6, {-0.06,0,0} }, {0.30, 1, 1, 0.035 , {0.02,0}, 0.4, {0.06,0,0} }, {0.40, 2, 0, 0.05 , {0.0,0.02}, 0.5, {0.12,0,0}, {0.09,0,0} }, {walk.tStep, 1, 1, 0.035 , {0,0}, 0.5, {0.04,0,0} }, } --[[ walk.walkKickDef["SideLeft"]={ {0.30, 1, 1, 0.035 , {0,0}, 0.4, {0.04,0.04,0} }, {0.35, 3, 0, 0.07 , {-0.01,0.01}, 0.5, {0.06,-0.05,0},{0.09,0.005,0}}, {0.25, 1, 1, 0.035 , {0,0}, 0.5, {0,0,0} },} walk.walkKickDef["SideRight"]={ {0.30, 1, 0, 0.035 , {0,0}, 0.6, {0.04,-0.04,0} }, {0.35, 3, 1, 0.07 , {-0.01,-0.01},0.5, {0.06,0.05,0},{0.09,-0.005,0}}, {0.25, 1, 0, 0.035 , {0,0},0.5, {0,0,0} }, } --]] --Short-range walking sidekick walk.walkKickDef["SideLeft"]={ {0.30, 1, 1, 0.035 , {0,0}, 0.4, {0.0,0.04,0} }, {0.35, 3, 0, 0.05 , {-0.01,0.01}, 0.5, {0.06,-0.05,0},{0.09,0.005,0}}, {0.25, 1, 1, 0.035 , {0.01,0}, 0.5, {0,0,0} },} walk.walkKickDef["SideRight"]={ {0.30, 1, 0, 0.035 , {0,0}, 0.6, {0.0,-0.04,0} }, {0.35, 3, 1, 0.05 , {-0.01,-0.01},0.5, {0.06,0.05,0},{0.09,-0.005,0}}, {0.25, 1, 0, 0.035 , {0.01,0},0.5, {0,0,0} }, } --With more sweep walk.walkKickDef["SideLeft"]={ {0.30, 1, 1, 0.035 , {0,0}, 0.4, {0.0,0.04,10*math.pi/180} }, {0.35, 3, 0, 0.05 , {0.01,0.01}, 0.5, {0.06,-0.05,-20*math.pi/180},{0.09,0.005,0}}, {0.25, 1, 1, 0.035 , {0.01,0}, 0.5, {0,0,0} },} walk.walkKickDef["SideRight"]={ {0.30, 1, 0, 0.035 , {0,0}, 0.6, {0.0,-0.04,-10*math.pi/180} }, {0.35, 3, 1, 0.05 , {0.01,-0.01},0.5, {0.06,0.05,20*math.pi/180},{0.09,-0.005,0}}, {0.25, 1, 0, 0.035 , {0.01,0},0.5, {0,0,0} }, } -- tStep stepType supportLeg stepHeight -- SupportMod shiftFactor footPos1 footPos2 -- Boxing walk kick walk.walkKickDef["PunchLeft"]={ {0.60, 1, 0, 0.035 , {0,0}, 0.7, {0,0,0} }, {0.60, 2, 1, 0.07 , {0.02,-0.02}, 0.5, {0,0,0}, {0,0,0} }, {walk.tStep, 1, 0, 0.035 , {0,0}, 0.5, {0,0,0} }, } walk.walkKickDef["PunchRight"]={ {0.60, 1, 1, 0.035 , {0,0}, 0.3, {0,0,0} }, {0.60, 2, 0, 0.07 , {0.02,0.02}, 0.5, {0,0,0}, {0,0,0} }, {walk.tStep, 1, 1, 0.035 , {0,0}, 0.5, {0,0,0} }, } walk.walkKickPh=0.5; -------------------------------------------- -- Robot - specific calibration parameters -------------------------------------------- walk.kickXComp = 0; walk.supportCompL = {0,0,0}; walk.supportCompR = {0,0,0}; walk.servoBias = {0,0,0,0,0,0,0,0,0,0,0,0}; walk.footXComp = 0; walk.footYComp = 0; --Default pitch angle offset of OP walk.headPitchBias = 40* math.pi / 180; walk.headPitchBiasComp = 0; local robotName = unix.gethostname(); local robotID = 0; --Load robot specific calibration value require('calibration'); if calibration.cal and calibration.cal[robotName] then walk.supportCompL = calibration.cal[robotName].supportCompL; -- added by david walk.supportCompR = calibration.cal[robotName].supportCompR; -- added by David walk.servoBias = calibration.cal[robotName].servoBias; walk.footXComp = calibration.cal[robotName].footXComp; walk.footYComp = calibration.cal[robotName].footYComp; -- added by david walk.kickXComp = calibration.cal[robotName].kickXComp; walk.kickYComp = calibration.cal[robotName].kickYComp; walk.headPitchBiasComp = calibration.cal[robotName].headPitchBiasComp; print(robotName.." walk parameters loaded") end ------------------------------------------------ -- Upper body motion keyframes ----------------------------------------------- -- tDuration qLArm qRArm bodyRot walk.motionDef={}; walk.motionDef["hurray1"]={ {1.0,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, --possibility: duration, {pitch, roll, elbow}, {pitch, roll, elbow} {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.4,{-30*math.pi/180, 30*math.pi/180, -90*math.pi/180}, {-30*math.pi/180,-30*math.pi/180,-90*math.pi/180}}, {0.4,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.4,{-30*math.pi/180, 30*math.pi/180, -90*math.pi/180}, {-30*math.pi/180,-30*math.pi/180,-90*math.pi/180}}, {0.4,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.4,{-30*math.pi/180, 30*math.pi/180, -90*math.pi/180}, {-30*math.pi/180,-30*math.pi/180,-90*math.pi/180}}, {1.0,{90*math.pi/180, 8*math.pi/180,-40*math.pi/180}, {90*math.pi/180, -8*math.pi/180,-40*math.pi/180}} } --pointing up walk.motionDef["point"]={ {1.0,{-40*math.pi/180, 50*math.pi/180, 0*math.pi/180}, {160*math.pi/180,-60*math.pi/180,-90*math.pi/180}, {20*math.pi/180,0*math.pi/180,-20*math.pi/180}}, {3.0,{-40*math.pi/180, 50*math.pi/180, 0*math.pi/180}, {160*math.pi/180,-60*math.pi/180,-90*math.pi/180}, {20*math.pi/180,0*math.pi/180,-20*math.pi/180}}, {1.0,{90*math.pi/180, 8*math.pi/180,-40*math.pi/180}, {90*math.pi/180, -8*math.pi/180,-40*math.pi/180}, {0,20*math.pi/180,0}} } --Two arm punching up walk.motionDef["hurray2"]={ {0.5,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.2, {40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {-30*math.pi/180,-30*math.pi/180,-90*math.pi/180}}, {0.2,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.2,{-30*math.pi/180, 30*math.pi/180, -90*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.2,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.2, {40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {-30*math.pi/180,-30*math.pi/180,-90*math.pi/180}}, {0.2,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.2,{-30*math.pi/180, 30*math.pi/180, -90*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.2,{40*math.pi/180, 20*math.pi/180, -140*math.pi/180}, {40*math.pi/180,-20*math.pi/180,-140*math.pi/180}}, {0.5,{90*math.pi/180, 8*math.pi/180,-40*math.pi/180}, {90*math.pi/180, -8*math.pi/180,-40*math.pi/180}} } --Two arm side swing walk.motionDef["swing"]={ {0.5,{90*math.pi/180, 90*math.pi/180, -40*math.pi/180}, {90*math.pi/180,-90*math.pi/180,-40*math.pi/180}, {0*math.pi/180,20*math.pi/180,-20*math.pi/180}}, {0.5,{90*math.pi/180, 90*math.pi/180, -40*math.pi/180}, {90*math.pi/180,-90*math.pi/180,-40*math.pi/180}, {0*math.pi/180,20*math.pi/180,20*math.pi/180}}, {0.5,{90*math.pi/180, 90*math.pi/180, -40*math.pi/180}, {90*math.pi/180,-90*math.pi/180,-40*math.pi/180}, {0*math.pi/180,20*math.pi/180,-20*math.pi/180}}, {0.5,{90*math.pi/180, 8*math.pi/180,-40*math.pi/180}, {90*math.pi/180, -8*math.pi/180,-40*math.pi/180}, {0*math.pi/180,20*math.pi/180,0*math.pi/180}} } --One-Two Punching walk.motionDef["2punch"]={ {0.2,{90*math.pi/180, 40*math.pi/180, -160*math.pi/180}, {90*math.pi/180,-40*math.pi/180,-160*math.pi/180}, {0*math.pi/180,20*math.pi/180,0*math.pi/180}}, {0.2,{90*math.pi/180, 30*math.pi/180, -160*math.pi/180}, {90*math.pi/180,-30*math.pi/180,-160*math.pi/180}, {0*math.pi/180,20*math.pi/180,20*math.pi/180}}, {0.2,{90*math.pi/180, 30*math.pi/180, -160*math.pi/180}, {90*math.pi/180,-30*math.pi/180,-160*math.pi/180}, {0*math.pi/180,20*math.pi/180,20*math.pi/180}}, --right jab {0.2,{90*math.pi/180, 30*math.pi/180, -160*math.pi/180}, {-20*math.pi/180,-30*math.pi/180,0*math.pi/180}, {0*math.pi/180,20*math.pi/180,20*math.pi/180}}, --left straignt {0.3,{-20*math.pi/180, 20*math.pi/180, 0*math.pi/180}, {90*math.pi/180,-40*math.pi/180,-160*math.pi/180}, {0*math.pi/180,20*math.pi/180,-30*math.pi/180}}, --retract {0.2,{90*math.pi/180, 40*math.pi/180, -160*math.pi/180}, {90*math.pi/180,-40*math.pi/180,-160*math.pi/180}, {0*math.pi/180,20*math.pi/180,-30*math.pi/180}}, {0.3,{90*math.pi/180, 8*math.pi/180,-40*math.pi/180}, {90*math.pi/180, -8*math.pi/180,-40*math.pi/180}, {0*math.pi/180,20*math.pi/180,0*math.pi/180}} } walk.motionDef["jabright"]={ --right jab {0.2, {90*math.pi/180, 30*math.pi/180, -160*math.pi/180}, {-20*math.pi/180,-30*math.pi/180,0*math.pi/180}, }, --retract {0.2, {90*math.pi/180, 40*math.pi/180, -160*math.pi/180}, {90*math.pi/180,-40*math.pi/180,-160*math.pi/180}, }, } walk.motionDef["jableft"]={ --right jab {0.2, {-20*math.pi/180, 30*math.pi/180, 0*math.pi/180}, {90*math.pi/180,-40*math.pi/180,-160*math.pi/180}, }, --retract {0.2, {90*math.pi/180, 40*math.pi/180, -160*math.pi/180}, {90*math.pi/180,-40*math.pi/180,-160*math.pi/180}, }, } -- test1 behavior walk.motionDef["prePick"] = { {1.0, {90*math.pi/180, 10*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -10*math.pi/180, -20*math.pi/180}, {0*math.pi/180,60*math.pi/180,0*math.pi/180} }, {1.0, {90*math.pi/180, 8*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -8*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180, 0*math.pi/180} } } walk.motionDef["pickupLow"]={ {1.0, {90*math.pi/180, 10*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -10*math.pi/180, -20*math.pi/180}, {0*math.pi/180,60*math.pi/180,0*math.pi/180} }, {1.0, {10*math.pi/180, 10*math.pi/180, -20*math.pi/180}, {10*math.pi/180, -10*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 60*math.pi/180, 0*math.pi/180} }, -- pick {1.0, {10*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {10*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 60*math.pi/180, 0*math.pi/180} }, -- stand up {1.0, {20*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {20*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 5*math.pi/180,0*math.pi/180} }, --[[ -- hold for 10 s {10.0, {20*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {20*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180,0*math.pi/180} }, -- drop {1.0, {10*math.pi/180, 8*math.pi/180, -20*math.pi/180}, {10*math.pi/180, -8*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180,0*math.pi/180} }, {1.0, {90*math.pi/180, 8*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -8*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180, 0*math.pi/180} } ]]-- } walk.motionDef["pickupHigh"]={ {2.0, {90*math.pi/180, 10*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -10*math.pi/180, -20*math.pi/180}, {0*math.pi/180,60*math.pi/180,0*math.pi/180} }, {1.0, {10*math.pi/180, 10*math.pi/180,-20*math.pi/180}, {10*math.pi/180, -10*math.pi/180, -20*math.pi/180}, {0*math.pi/180,60*math.pi/180,0*math.pi/180} }, -- pick {1.0, {10*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {10*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180,60*math.pi/180,0*math.pi/180} }, -- stand up {2.0, {-60*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {-60*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 10*math.pi/180,0*math.pi/180} }, --[[ -- hold for 10 s {10.0, {-60*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {-60*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180,0*math.pi/180} }, -- drop {1.0, {10*math.pi/180, 8*math.pi/180, -20*math.pi/180}, {10*math.pi/180, -8*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180,0*math.pi/180} }, {1.0, {90*math.pi/180, 8*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -8*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180, 0*math.pi/180} } ]]-- } walk.motionDef["drop"]={ {2.0, {0*math.pi/180, -15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 15*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180, 0*math.pi/180} }, --[[ {2.0, {30*math.pi/180, -10*math.pi/180, -20*math.pi/180}, {30*math.pi/180, 10*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180, 0*math.pi/180} }, ]]-- {2.0, {90*math.pi/180, 8*math.pi/180, -20*math.pi/180}, {90*math.pi/180, -8*math.pi/180, -20*math.pi/180}, {0*math.pi/180, 20*math.pi/180, 0*math.pi/180} }, } walk.walkKickSupportMod = {{0,0},{0,0}} --ZMP-preview step definitions zmpstep = {}; zmpstep.bodyHeight = 0.295; zmpstep.bodyTilt = 23*math.pi/180;-- modified this too, origional was 20 zmpstep.tZmp = 0.165; zmpstep.stepHeight = 0.035; zmpstep.phSingle={0.1,0.9}; -- zmpstep.hipRollCompensation = 3*math.pi/180; zmpstep.supportX = 0.0; zmpstep.supportY = 0.02; zmpstep.motionDef={}; zmpstep.params = true; zmpstep.param_k1_px={-826.152540,-303.478776,-33.247242} zmpstep.param_a={ {1.000000,0.010000,0.000050}, {0.000000,1.000000,0.010000}, {0.000000,0.000000,1.000000}, } zmpstep.param_b={0.000000,0.000050,0.010000,0.010000} zmpstep.param_k1={ 185.714242,120.443259,71.400488,34.823349,7.805849, -11.895432,-26.011485,-35.877042,-42.520477,-46.733353, -49.124239,-50.160332,-50.199666,-49.516014,-48.318153, -46.764757,-44.975909,-43.042004,-41.030621,-38.991837, -36.962325,-34.968520,-33.029059,-31.156661,-29.359574, -27.642690,-26.008398,-24.457241,-22.988416,-21.600159, -20.290035,-19.055155,-17.892348,-16.798283,-15.769559, -14.802778,-13.894588,-13.041723,-12.241025,-11.489461, -10.784129,-10.122268,-9.501256,-8.918610,-8.371986, -7.859169,-7.378076,-6.926745,-6.503330,-6.106098, -5.733420,-5.383770,-5.055712,-4.747901,-4.459077, -4.188056,-3.933728,-3.695054,-3.471061,-3.260833, -3.063515,-2.878305,-2.704450,-2.541245,-2.388030, -2.244185,-2.109130,-1.982321,-1.863247,-1.751431, -1.646425,-1.547807,-1.455185,-1.368189,-1.286472, -1.209709,-1.137597,-1.069849,-1.006198,-0.946392, -0.890196,-0.837388,-0.787761,-0.741120,-0.697283, -0.656078,-0.617345,-0.580932,-0.546697,-0.514508, -0.484239,-0.455773,-0.429000,-0.403815,-0.380123, -0.357830,-0.336851,-0.317105,-0.298516,-0.281012, -0.264525,-0.248992,-0.234353,-0.220550,-0.207531, -0.195245,-0.183645,-0.172684,-0.162321,-0.152514, -0.143225,-0.134417,-0.126056,-0.118108,-0.110541, -0.103324,-0.096430,-0.089831,-0.083498,-0.077409, -0.071538,-0.065863,-0.060363,-0.055019,-0.049812, -0.044729,-0.039756,-0.034885,-0.030113,-0.025442, -0.020883,-0.016457,-0.012197,-0.008157,-0.004410, -0.001061,0.001747,0.003821,0.004903,0.004650, 0.002610,-0.001812,-0.009393,-0.021152,-0.038414, -0.062904,-0.096865,-0.143208,-0.205710,-0.289267, } --Supportfoot relstep zmpmod duration steptype zmpstep.motionDef["nonstop_kick_left"]={ support_start = 0, --Left support stepDef={ {0, {0.06,0,0} ,{0.02,0},0.25}, --LS step {2, {0,0,0} ,{0.02,0},0.05}, --DS step {1, {0,-0.01,0} ,{0.02,-0.01},0.2,1}, --RS step, lifting {1, {0.18,0,0} ,{0.02,-0.01},0.2,2}, --RS step kicking {1, {-0.06,0.01,0},{0.01,0.0},0.1,3}, --RS step returning {1, {0.0,0,0} ,{0.00,0.0},0.1,4}, --RS step landing {2, {0,0,0} ,{0.005,0}, 0.07}, --DS step {0, {0.06,0.0,0} ,{0.005,0},0.25}, --LS step -------------------------------------------------------------- {1, {0.0,0,0},{0,0},0.25,9}, --LS step {0, {0.0,0,0},{0,0},0.25}, --LS step {1, {0.0,0,0},{0,0},0.25}, --LS step {0, {0.0,0,0},{0,0},0.25}, --LS step {2, {0,0,0},{0,0},0.25}, --DS step {2, {0,0,0},{0,0},0.05}, --DS step }, support_end = 1, --Next RS step } zmpstep.motionDef["nonstop_kick_right"]={ support_start = 1, --Right support stepDef={ {1, {0.06,0.0,0} ,{0.02,0},0.25}, --RS step {2, {0,0,0} ,{0.02,0},0.05}, --DS step {0, {0,0.01,0} ,{0.02,0.01},0.2,1}, --LS step, lifting {0, {0.18,0,0} ,{0.02,0.01},0.2,2}, --LS step kicking {0, {-0.06,-0.01,0},{0.01,0.0},0.1,3}, --LS step returning {0, {0.0,0,0} ,{0.00,0.0},0.1,4}, --LS step landing {2, {0,0,0} ,{0.005,0.0}, 0.07}, --DS step {1, {0.06,0.0,0} ,{0.005,0},0.25}, --RS step --------------------------------------------------------------- {0, {0.0,0,0},{0,0},0.25,9}, --LS step {1, {0.0,0,0},{0,0},0.25}, --LS step {0, {0.0,0,0},{0,0},0.25}, --LS step {1, {0.0,0,0},{0,0},0.25}, --LS step {2, {0,0,0},{0,0},0.5}, --DS step {2, {0,0,0},{0,0},0.05,9}, --DS step }, support_end = 0, --next LS step } ------------------------------------------------------------------- -- Little more slow stepkick (wait a bit after landing) ------------------------------------------------------------------- zmpstep.motionDef["nonstop_kick_left"]={ support_start = 0, --Left support stepDef={ {0, {0.06,0,0} ,{0.02,0},0.25}, --LS step {2, {0,0,0} ,{0.02,0},0.05}, --DS step {1, {0,-0.01,0} ,{0.02,-0.01},0.2,1}, --RS step, lifting {1, {0.18,0,0} ,{0.02,-0.01},0.2,2}, --RS step kicking --[[ {1, {-0.06,0.01,0},{0.01,0.0},0.1,3}, --RS step returning {1, {0.0,0,0} ,{0.00,0.0},0.1,4}, --RS step landing {2, {0,0,0} ,{0.005,0}, 0.30}, --DS step --]] {1, {-0.06,0.01,0},{-0.01, 0.0},0.1,3}, --RS step returning {1, {0.0,0,0} ,{-0.01, 0.0},0.1,4}, --RS step landing {2, {0,0,0} ,{-0.01, 0.0}, 0.30}, --DS step {0, {0.06,0.0,0} ,{0.005,0},0.25}, --LS step -------------------------------------------------------------- {1, {0.0,0,0},{0,0},0.25,9}, --LS step {0, {0.0,0,0},{0,0},0.25}, --LS step {1, {0.0,0,0},{0,0},0.25}, --LS step {0, {0.0,0,0},{0,0},0.25}, --LS step {2, {0,0,0},{0,0},0.25}, --DS step {2, {0,0,0},{0,0},0.05}, --DS step }, support_end = 1, --Next RS step } zmpstep.motionDef["nonstop_kick_right"]={ support_start = 1, --Right support stepDef={ {1, {0.06,0.0,0} ,{0.02,0},0.25}, --RS step {2, {0,0,0} ,{0.02,0},0.05}, --DS step {0, {0,0.01,0} ,{0.02,0.01},0.2,1}, --LS step, lifting {0, {0.18,0,0} ,{0.02,0.01},0.2,2}, --LS step kicking --[[ {0, {-0.06,-0.01,0},{0.01,0.0},0.1,3}, --LS step returning {0, {0.0,0,0} ,{0.00,0.0},0.1,4}, --LS step landing {2, {0,0,0} ,{0.005,0.0}, 0.30}, --DS step --]] {0, {-0.06,-0.01,0},{-0.01, 0.0},0.1,3}, --LS step returning {0, {0.0,0,0} ,{-0.01, 0.0},0.1,4}, --LS step landing {2, {0,0,0} ,{-0.01, 0.0}, 0.30}, --DS step {1, {0.06,0.0,0} ,{0.005,0},0.25}, --RS step --------------------------------------------------------------- {0, {0.0,0,0},{0,0},0.25,9}, --LS step {1, {0.0,0,0},{0,0},0.25}, --LS step {0, {0.0,0,0},{0,0},0.25}, --LS step {1, {0.0,0,0},{0,0},0.25}, --LS step {2, {0,0,0},{0,0},0.5}, --DS step {2, {0,0,0},{0,0},0.05,9}, --DS step }, support_end = 0, --next LS step }
gpl-3.0
dzung2t/noithatgo
ci_app/modules/feedbacks/views/admin/list_feedbacks.php
2344
<?php echo form_open('', array('id' => 'feedback_form'), array('feedback_id' => 0, 'from_list' => TRUE)); echo form_close(); ?> <div class="page_header"> <h1 class="fleft">Ý kiến khách hàng</h1> <small class="fleft">"Quản lý ý kiến phản hồi của khách hàng"</small> <span class="fright"><a class="button add" href= "/dashboard/feedbacks/add"><em>&nbsp;</em>Thêm ý kiến phản hồi</a></span> <br class="clear"/> </div> <br class="clear"/>&nbsp; <div class="form_content"> <?php $this->load->view('admin/filter_form'); ?> <table class="list" style="width: 100%;"> <tr> <th class="left">TÊN KHÁCH HÀNG</th> <th class="left">Ý KIẾN PHẢN HỒI</th> <th class="center">NGÀY GỬI</th> <th class="center">HIỂN THỊ</th> <th class="right">CHỨC NĂNG</th> </tr> <?php foreach($feedbacks as $index => $feedback): $created_date = get_vndate_string($feedback->created_date); $style = $index % 2 == 0 ? 'even' : 'odd'; $check = $feedback->status == ACTIVE_PAGE ? 'checked' : ''; ?> <tr class="<?php echo $style ?>"> <td><?php echo $feedback->customer?></td> <td><?php echo $feedback->content;?></td> <td class="center"><?php echo $created_date?></td> <td class="center"><input type="checkbox" <?php echo $check;?> onclick="change_feedback_status(<?php echo $feedback->id;?>)"></td> <td class="right" style="white-space:nowrap;" class="action"> <a class="edit" href="javascript:void(0);" onclick="submit_feedback(<?php echo $feedback->id ?>, 'edit');"><em></em></a> <a class="del" href="javascript:void(0);" onclick="submit_feedback(<?php echo $feedback->id ?>, 'delete');"><em></em></a> </td> <?php endforeach;?> <?php $left_page_links = 'Trang ' . $page . ' / ' . $total_pages . ' (<span>Tổng: ' . $total_rows . '</span>)'; ?> <tr class="list-footer"> <th colspan="4"><?php echo $left_page_links; ?></th> <th colspan="4" class="right"><?php if(isset($page_links) && $page_links!=='') echo 'Chuyển trang: '.$page_links; else echo '&nbsp;'; ?></th> </tr> </table> <br class="clear"/>&nbsp; </div>
gpl-3.0
jrc436/executors
Executors/src/nlp/util/TextNormalizer.java
1024
package nlp.util; public class TextNormalizer { public static final String disfluencyString = "[disfluency]"; public static String normalizeWord(String word) { if (word.equals(disfluencyString)) { return word; } String normalized = crushPCT(word.toLowerCase()).trim(); if (normalized.isEmpty()) { return ""; } if (!normalized.equals("<unk>") && !normalized.equals("<s>") && !normalized.equals("</s>") && !normalized.matches("[a-z\\d]+")) { throw new RuntimeException("This needs to be updated for a String like: "+word); } return normalized; } private static final String pcts = ".,:#&;-''{}!?()[]/_="; public static boolean isPCT(String inp) { for (int i = 0; i < inp.length(); i++) { if (!pcts.contains(""+inp.charAt(i))) { return false; } } return true; } private static String crushPCT(String inp) { String crushed = ""; for (int i = 0; i < inp.length(); i++) { if (!pcts.contains(""+inp.charAt(i))) { crushed += inp.charAt(i); } } return crushed; } }
gpl-3.0
ltworf/lapdog
main.cpp
4318
/* * lapdog - take actions on devices (dis)appearance on the LAN * Copyright (C) 2014-2018 Salvo Tomaselli <tiposchi@tiscali.it> * * 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/>. */ #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <iostream> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <time.h> #include <unistd.h> #include "configuration.h" #include "devices.h" #include "main.h" #include "config.h" devices *devs = devices::getinstance(); unsigned int signals = 0; void reload_signal(int _) { __sync_fetch_and_or(&signals, SIGL_RELOAD); } void dump_signal(int _) { __sync_fetch_and_or(&signals, SIGL_DUMP); } void int_signal(int _) { __sync_fetch_and_or(&signals, SIGL_INT); } void dump_status() { devs->dump(1); int fd = open(CONF_STATUS_DUMP_FILE, O_WRONLY | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH); if (fd == -1) { syslog(LOG_ERR,"Can't write status on " CONF_STATUS_DUMP_FILE); return; } devs->dump(fd); close(fd); } /** * If lapdog is already running, sends the instance * a signal and prints the status instead. * * In this case, the program will just terminate. **/ void already_running() { int readable = access(PIDFILE, R_OK); if (readable != 0) { return; } printf("Reading status...\n"); //Read the pid int fd = open(PIDFILE, O_RDONLY); char buffer[128]; memset(buffer, 0, 128); int read_amount = read(fd, buffer, sizeof(buffer) - 1); if (read_amount == sizeof(buffer) - 1) { syslog(LOG_DEBUG,"Pidfile content too long"); exit(1); } close(fd); //Convert the pid to int int pid = atoi(buffer); //Send the signal kill(pid, SIGUSR1); //Wait for the dumpfile to be created { int count = 0; for (count = 0; count < 10; count++) { if (access(CONF_STATUS_DUMP_FILE, R_OK)==0) break; usleep(100000); } if (count == 10) { printf("Daemon is not responding...\n"); exit(1); } } //Print the dumpfile fd = open(CONF_STATUS_DUMP_FILE, O_RDONLY); while ((read_amount = read(fd, buffer, sizeof(buffer) - 1)) != 0) write(1, buffer, read_amount); close(fd); unlink(CONF_STATUS_DUMP_FILE); exit(0); } void create_pidfile() { int fd = open(PIDFILE, O_CREAT | O_WRONLY, 0444); if (fd == -1) { syslog(LOG_ERR,"Unable to create pidfile " PIDFILE); exit (1); } dprintf(fd, "%d", getpid()); close(fd); } void destroy_pidfile() { unlink(PIDFILE); } int main(int argc, char **argv) { syslog(LOG_INFO, "Starting lapdog " LAPDOG_VERSION); already_running(); create_pidfile(); configuration *config = configuration::getconfig(); signal(SIGHUP, reload_signal); signal(SIGUSR1, dump_signal); signal(SIGINT, int_signal); signal(SIGTERM, int_signal); time_t last_ping_all = 0; while(true) { sleep(config->sleep_time); if (time(NULL) - last_ping_all >= config->sleep_time) { devs->ping_all(); last_ping_all = time(NULL); } //Check the mask for signals occurred unsigned int signals_occurred = __sync_fetch_and_and(&signals, 0); if (signals_occurred != 0) { if (signals_occurred & SIGL_RELOAD) devs->load_config(); if (signals_occurred & SIGL_DUMP) dump_status(); if (signals_occurred & SIGL_INT) { destroy_pidfile(); exit(0); } } } return 0; }
gpl-3.0
rafiss/transparent
backend/transparent/core/Module.java
14822
package transparent.core; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.math.BigInteger; import java.util.Locale; import transparent.core.database.Database; public class Module { /* contains the full command to execute the module, or the remote URL */ private String path; /* name of source for which this module is a parser */ private String sourceName; /* unique name of module */ private String moduleName; /* module-specific URL (for example, to a repository) */ private String moduleUrl; /* the URL of the online merchant that this module parses */ private String sourceUrl; /* specifies whether the module is remote */ private boolean remote; /* specifies whether websites should be downloaded in blocks or all at once */ private boolean useBlockedDownload; /* specifies the API for communication between the modules and core */ private Api api; /* unique integer identifier for the module */ private final long id; /* the output log associated with this module */ private final PrintStream log; /* indicates whether activity should be logged to standard out */ private boolean logActivity; private static final NullOutputStream NULL_STREAM = new NullOutputStream(); /** * The index of this module as it is stored in the persistent database. * A value of -1 indicates either this module is not stored in the * underlying database, or that the stored copy is stale. */ private int persistentIndex = -1; /** * The newly-assigned index of this module as it will be stored * in the persistent database when it is saved. */ private int index = -1; public Module(long id, String moduleName, String sourceName, String path, String url, String sourceUrl, OutputStream log, Api api, boolean isRemote, boolean blockedDownload) { this.path = path; this.sourceName = sourceName; this.moduleName = moduleName; this.moduleUrl = url; this.sourceUrl = sourceUrl; this.remote = isRemote; this.api = api; this.useBlockedDownload = blockedDownload; this.id = id; this.log = new ModuleLogStream(log); } /** * WARNING: do not convert this directly to a string, as Java will * interpret it as a signed value. Use {@link Module#getIdString()} * instead. */ public long getId() { return id; } public String getIdString() { return Core.toUnsignedString(id); } public String getPath() { return path; } public String getSourceName() { return sourceName; } public String getModuleName() { return moduleName; } public String getSourceUrl() { return sourceUrl; } public String getModuleUrl() { return moduleUrl; } public boolean isRemote() { return remote; } public Api getApi() { return api; } public boolean blockedDownload() { return useBlockedDownload; } public boolean isLoggingActivity() { return logActivity; } public void setPath(String path) { this.path = path; this.persistentIndex = -1; } public void setApi(Api api) { if (this.api != api) this.persistentIndex = -1; this.api = api; } public void setSourceName(String sourceName) { this.sourceName = sourceName; this.persistentIndex = -1; } public void setModuleName(String moduleName) { this.moduleName = moduleName; this.persistentIndex = -1; } public void setSourceUrl(String url) { this.sourceUrl = url; this.persistentIndex = -1; } public void setModuleUrl(String url) { this.moduleUrl = url; this.persistentIndex = -1; } public void setRemote(boolean isRemote) { if (this.remote != isRemote) this.persistentIndex = -1; this.remote = isRemote; } public void setBlockedDownload(boolean useBlockedDownload) { if (this.useBlockedDownload != useBlockedDownload) this.persistentIndex = -1; this.useBlockedDownload = useBlockedDownload; } public void setLoggingActivity(boolean logActivity) { this.logActivity = logActivity; } public PrintStream getLogStream() { return log; } public int getPersistentIndex() { return persistentIndex; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public boolean equals(Object that) { if (that == null) return false; else if (that == this) return true; else if (!that.getClass().equals(this.getClass())) return false; Module other = (Module) that; return (other.id == id); } @Override public int hashCode() { return (int) ((id >> 32) ^ id); } public void logInfo(String className, String methodName, String message) { log.println(className + '.' + methodName + ": " + message); if (logActivity) { Console.println("Module " + getIdString() + " (name: '" + moduleName + "') information:" + Core.NEWLINE + className + '.' + methodName + ": " + message); Console.flush(); } } public void logError(String className, String methodName, String message) { log.println(className + '.' + methodName + " ERROR: " + message); if (logActivity) { Console.lockConsole(); Console.println("Module " + getIdString() + " (name: '" + moduleName + "') reported error:"); Console.printError(className, methodName, message); Console.unlockConsole(); } } public void logError(String className, String methodName, String message, Exception exception) { log.println(className + '.' + methodName + " ERROR: " + message + " Exception thrown: " + exception); if (logActivity) { Console.lockConsole(); Console.println("Module " + getIdString() + " (name: '" + moduleName + "') reported error:"); Console.printError(className, methodName, message, exception); Console.unlockConsole(); } } public void logUserAgentChange(String newUserAgent) { if (logActivity) { Console.lockConsole(); Console.println("Module " + getIdString() + " (name: '" + moduleName + "') changed user agent to: " + newUserAgent); Console.flush(); Console.unlockConsole(); } } public void logHttpGetRequest(String url) { if (logActivity) { Console.println("Module " + getIdString() + " (name: '" + moduleName + "') requested HTTP GET: " + url); Console.flush(); } } public void logHttpPostRequest(String url, byte[] post) { if (logActivity) { Console.lockConsole(); Console.println("Module " + getIdString() + " (name: '" + moduleName + "') requested HTTP POST:"); Console.println("\tURL: " + url); Console.print("\tPOST data: "); try { Console.write(post); } catch (IOException e) { Console.print("<unable to write data>"); } Console.println(); Console.unlockConsole(); Console.flush(); } } public void logDownloadProgress(int downloaded) { if (logActivity) { Console.println("Module " + getIdString() + " (name: '" + moduleName + "') downloading: " + downloaded + " bytes"); Console.flush(); } } public void logDownloadCompleted(int downloaded) { if (logActivity) { Console.println("Module " + getIdString() + " (name: '" + moduleName + "') completed download: " + downloaded + " bytes"); Console.flush(); } } public void logDownloadAborted() { if (logActivity) { Console.println("Module " + getIdString() + " (name: '" + moduleName + "') aborted download due to download size limit."); Console.flush(); } } public static Module load(long id, String name, String source, String path, String url, String sourceUrl, Api api, boolean isRemote, boolean blockedDownload) { PrintStream log; try { File logdir = new File("log"); if (!logdir.exists() && !logdir.mkdir()) { Console.printError("Module", "load", "Unable to create log directory." + " Logging is disabled for this module. (name = " + name + ", id = " + Core.toUnsignedString(id) + ")"); log = new PrintStream(NULL_STREAM); } else if (!logdir.isDirectory()) { Console.printError("Module", "load", "'log' is not a directory." + " Logging is disabled for this module. (name = " + name + ", id = " + Core.toUnsignedString(id) + ")"); log = new PrintStream(NULL_STREAM); } else { String filename = "log/" + name + "." + Core.toUnsignedString(id) + ".log"; File logfile = new File(filename); if (!logfile.exists()) { log = new PrintStream(new FileOutputStream(filename)); } else { log = new PrintStream(new FileOutputStream(filename, true)); } } } catch (IOException e) { Console.printError("Module", "load", "Unable to initialize output log." + " Logging is disabled for this module. (name = " + name + ", id = " + Core.toUnsignedString(id) + ")", e); log = new PrintStream(NULL_STREAM); } return new Module(id, name, source, path, url, sourceUrl, log, api, isRemote, blockedDownload); } public static Module load(Database database, int index) { long id = -1; String path, source, url, sourceUrl; boolean blocked = true; boolean remote = true; String name = "<unknown>"; Api api = null; try { id = new BigInteger(database.getMetadata("module." + index + ".id")).longValue(); path = database.getMetadata("module." + index + ".path"); name = database.getMetadata("module." + index + ".name"); source = database.getMetadata("module." + index + ".source"); url = database.getMetadata("module." + index + ".url"); sourceUrl = database.getMetadata("module." + index + ".source_url"); api = Api.load(database.getMetadata("module." + index + ".api")); String blockedString = database.getMetadata("module." + index + ".blocked"); String remoteString = database.getMetadata("module." + index + ".remote"); if (blockedString.equals("0")) blocked = false; if (remoteString.equals("0")) remote = false; } catch (RuntimeException e) { Console.printError("Module", "load", "Error loading module id.", e); return null; } Module module = load(id, name, source, path, url, sourceUrl, api, remote, blocked); module.persistentIndex = index; module.index = index; return module; } public boolean save(Database database, int index) { if (database.setMetadata( "module." + index + ".id", getIdString()) && database.setMetadata( "module." + index + ".path", path) && database.setMetadata( "module." + index + ".name", moduleName) && database.setMetadata( "module." + index + ".source", sourceName) && database.setMetadata( "module." + index + ".url", moduleUrl) && database.setMetadata( "module." + index + ".source_url", sourceUrl) && database.setMetadata( "module." + index + ".api", api.save()) && database.setMetadata( "module." + index + ".remote", remote ? "1" : "0") && database.setMetadata( "module." + index + ".blocked", useBlockedDownload ? "1" : "0")) { this.persistentIndex = index; this.index = index; return true; } return false; } class ModuleLogStream extends PrintStream { public ModuleLogStream(OutputStream log) { super(log == null ? NULL_STREAM : log); } @Override public void print(boolean b) { super.print(b); if (logActivity) Console.print(b); } @Override public void print(char c) { super.print(c); if (logActivity) Console.print(c); } @Override public void print(int i) { super.print(i); if (logActivity) Console.print(i); } @Override public void print(long l) { super.print(l); if (logActivity) Console.print(l); } @Override public void print(float f) { super.print(f); if (logActivity) Console.print(f); } @Override public void print(double d) { super.print(d); if (logActivity) Console.print(d); } @Override public void print(char s[]) { super.print(s); if (logActivity) Console.print(s); } @Override public void print(String s) { super.print(s); if (logActivity) Console.print(s); } @Override public void print(Object obj) { super.print(obj); if (logActivity) Console.print(obj); } @Override public void println() { super.println(); if (logActivity) Console.println(); } @Override public void println(boolean x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(char x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(int x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(long x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(float x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(double x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(char x[]) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(String x) { super.println(x); if (logActivity) Console.println(x); } @Override public void println(Object x) { super.println(x); if (logActivity) Console.println(x); } @Override public PrintStream format(String format, Object ... args) { super.format(format, args); if (logActivity) Console.format(format, args); return this; } @Override public PrintStream format(Locale l, String format, Object ... args) { super.format(l, format, args); if (logActivity) Console.format(l, format, args); return this; } @Override public PrintStream append(CharSequence csq, int start, int end) { super.append(csq, start, end); if (logActivity) Console.append(csq, start, end); return this; } } public static enum Api { BINARY, JSON; public static Api load(String src) { if (src.toLowerCase().equals("binary")) return BINARY; else if (src.toLowerCase().equals("json")) return JSON; else return null; } public String save() { switch (this) { case BINARY: return "binary"; case JSON: return "json"; default: return null; } } } } class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
gpl-3.0
regionbibliotekhalland/digitalaskyltar
itemharvester.py
7998
# -*- coding: utf-8 -*- # Copyright 2013 Regionbibliotek Halland # # This file is part of Digitala skyltar. # # Digitala skyltar 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. # # Digitala skyltar 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 Digitala skyltar. If not, see <http://www.gnu.org/licenses/>. import urllib from formattedtext import filterHtml subjectstrip = ' .' class CouldNotReadBookError(Exception): """Can be thrown when it is not possible to get information about a book """ def __init__(self, value): """Initiate the exception. Argument value -- message for the exception """ self.value = value def __str__(self): return 'Could not read book data: ' + self.value def __repr__(self): return self.__str__() def _getTextTag(content, index): """Return the text data of an XML element Argument content -- the XML string where the text is index -- the next text element after this index will be returned """ startindex = content.find(">", index) stopindex = content.find("<", startindex) return content[startindex + 1:stopindex] class BookInfo: """Information about a book harvested from Libra.""" def __init__(self, content, reqlibrary = None): """Parse the information about the book. Optionally the book must be available at library reqlibrary or else a CouldNotReadBookError will be thrown. Arguments content -- XML string describing the book reqlibrary -- if specified, a book will only be parsed if it is available at this library """ # Extracting the description text if content.find("ctl00_lblDescr") != -1: startindex = content.find("ctl00_lblDescr") stopindex = content[startindex:].find("</span>") bookDescription = content[startindex+16:startindex + stopindex] else: raise CouldNotReadBookError('Can\'t read book from Libra: No description found') self.rawtext = bookDescription # Extracting author metadata if content.find("/ff") != -1: startindex = content.find("/ff") stopindex = content[startindex+5:].find("</a>") author = content[startindex+5:startindex + stopindex + 5] else: author = "" self.author = author # Extracting the title - upgrade with regex if content.find("<td>Titel:</td>") != -1: startindex = content.find("<td>Titel:</td>") stopindex = content[startindex+15:].find("</td>") title = content[startindex+15:startindex + stopindex + 15] startindex = title.find(">") title = title[startindex+1:] while title[-1] == '/' or title[-1] == ' ': title = title[0:len(title)-1] else: title = "" self.title = title # Saving the ISBN of the title in question startindex = content.find("ctl00_imgCover") stopindex = content[startindex+21:].find('"') imageUrl = content[startindex+21:stopindex+startindex+21] startindex = imageUrl.find("isbn=") stopindex = imageUrl[startindex+5:].find("&") self.isbn = imageUrl[startindex+5:startindex+5+stopindex] # Extract the location of the title in the library # startindex = content.find("dgHoldings_ctl02_lblShelf") # stopindex = content[startindex:].find("</span>") # shelf = content[startindex+27:startindex+stopindex] # self.shelf = filterHtml(shelf) # # startindex = content.find("dgHoldings_ctl02_lblBranchDepartment") # stopindex = content[startindex:].find("</span>") # libandsection = content[startindex+38:startindex+stopindex] # startindex = libandsection.find('&nbsp;') # startindex = libandsection.find('&nbsp;', startindex + 6) # # self.section = libandsection[startindex+6:] #Get library specific data startindex = content.find("lblBranchDepartment") finalstop = content.find("</table>", startindex) found = False self.shelves = [] while((startindex >= 0) and (startindex < finalstop)): #Get library libandsection = _getTextTag(content, startindex) delimiter = libandsection.find('&nbsp') library = libandsection[:delimiter] if((reqlibrary is None) or (library == reqlibrary)): #Get section delimiter = libandsection.rfind(';') self.section = libandsection[delimiter + 1:] #Get shelf startindex = content.find("lblShelf", startindex) shelf = _getTextTag(content, startindex) shelf = filterHtml(shelf) self.shelves.append(shelf) #Get availability startindex = content.find("lblAvailable", startindex) self.available = _getTextTag(content, startindex) found = True startindex = content.find("lblBranchDepartment", startindex + 1) if(not found): raise CouldNotReadBookError('Book not present at library ' + reqlibrary) # Extract the books subjects self.subjects = [] startindex = content.find(u"Ämnesord") startindex = content.find("<td", startindex) finalstop = content.find("</td>", startindex) startindex = content.find("<a", startindex) while((startindex >= 0) and (startindex < finalstop)): startindex = content.find(">", startindex) stopindex = content.find("<", startindex) subject = content[startindex + 1:stopindex] subject = subject.strip(subjectstrip) self.subjects.append(subject) startindex = content.find("<a", stopindex) # print(self.title + ' has the following subjects:\n') # # for i in self.subjects: # print(' ' + i) def harvestBookInfo(url, reqlibrary): """Harvest a book from an url. Will throw a CouldNotReadBookError if reqlibrary is not None and the book is not available at that library. Arguments url -- an url pointing to the book data reqlibrary -- if not None, the book must be available at this library """ try: page = urllib.urlopen(url) except IOError: raise CouldNotReadBookError('Could not read url ' + self._url) content = page.read() content = unicode(content, 'utf8') page.close() return BookInfo(content, reqlibrary) #Test code if __name__ == "__main__": bi = harvestBookInfo(r'http://bib.kommunen.varberg.se/opac/show_holdings.aspx?paging=false&bokid=135403', 'Varbergs bibliotek') print(bi.title.encode('utf-8') + ':') print(' Section ' + bi.section.encode('utf-8')) #print(' Shelf ' + bi.shelf.encode('utf-8')) print(' Availability ' + bi.available.encode('utf-8')) print(' Subjects:') for i in bi.subjects: print(' ' + i)
gpl-3.0
mumblepins/Eyrie-App
app/src/main/java/com/dansull/eyrie/ScheduleFragment.java
17560
package com.dansull.eyrie; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import com.yahoo.mobile.client.android.util.ScheduleBar; import com.yahoo.mobile.client.android.util.ThumbPiece; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; //import android.util.Log; //import android.app.Fragment; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ScheduleFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ScheduleFragment#newInstance} factory method to * create an instance of this fragment. */ public class ScheduleFragment extends Fragment { public static final String SCHEDULE_BARS_KEY = "schedule_bars"; private static final String ARG_SECTION_NUMBER = "section_number"; private int sectionNumber; private OnFragmentInteractionListener mListener; private Map<Day, ScheduleBar> scheduleBars = new HashMap<>(); private ScheduleBar activeBar; private int contextMenuPushLoc; private ScrollView scrollView; // private HashMap<Day, List<ThumbPiece>> scheduleList; // private Map<Day, ThumbPiece> rightMostThumb = new HashMap<>(); private List<ThumbPiece> thumbBuffer; private boolean thumbsCopied = false; private String jsonString = null; public ScheduleFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment ScheduleFragment. */ public static ScheduleFragment newInstance(int sectionNumber) { ScheduleFragment fragment = new ScheduleFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public static String capitalize(String str) { return capitalize(str, null); } public static String capitalize(String str, char[] delimiters) { int delimLen = (delimiters == null ? -1 : delimiters.length); if (str == null || str.length() == 0 || delimLen == 0) { return str; } int strLen = str.length(); StringBuffer buffer = new StringBuffer(strLen); boolean capitalizeNext = true; for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); if (isDelimiter(ch, delimiters)) { buffer.append(ch); capitalizeNext = true; } else if (capitalizeNext) { buffer.append(Character.toTitleCase(ch)); capitalizeNext = false; } else { buffer.append(Character.toLowerCase(ch)); } } return buffer.toString(); } private static boolean isDelimiter(char ch, char[] delimiters) { if (delimiters == null) { return Character.isWhitespace(ch); } for (int i = 0, isize = delimiters.length; i < isize; i++) { if (ch == delimiters[i]) { return true; } } return false; } public int getSectionNumber() { return sectionNumber; } @Override public void onSaveInstanceState(Bundle bundle) { // bundle.putSerializable(MONDAY_KEY,); // // Log.i("saving", "saving"); // bundle.putSerializable(SCHEDULE_BARS_KEY, (Serializable) scheduleBars); // saveToPrefs(); super.onSaveInstanceState(bundle); } public void saveToPrefs() { SharedPreferences settings = getActivity().getSharedPreferences(MainActivity.PREFERENCES_KEY, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString( SCHEDULE_BARS_KEY + String.valueOf(sectionNumber), toJson().toString()); // Log.i(SCHEDULE_BARS_KEY + String.valueOf(sectionNumber), toJson().toString()); // Commit the edits! editor.commit(); } private ActionBar getActionBar() { return getActivity().getActionBar(); } @Override public void onDestroy() { super.onDestroy(); // saveToPrefs(); } public JSONObject toJson() { JSONObject returnJson = new JSONObject(); for (Day day : Day.values()) { try { returnJson.putOpt(String.valueOf(day), scheduleBars.get(day).toJson()); } catch (JSONException e) { e.printStackTrace(); } } return returnJson; } public void fromJson(JSONObject json) { for (Day day : Day.values()) { // Log.i("day",String.valueOf(day)); scheduleBars.get(day).clearThumbs(); if (json.has(String.valueOf(day))) { // Log.i("yes","yes"); try { scheduleBars.get(day).fromJson(json.getJSONArray(String.valueOf(day))); } catch (JSONException e) { e.printStackTrace(); } } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // getActivity().setContentView(R.layout.fragment_schedule); if (getArguments() != null) { sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER); } // for (int i = 0; i < 7; i++) { // // scheduleBars.put(Day.values()[i],new ScheduleBar(getActivity())); // } } private void openOurContextMenu(ScheduleBar bar, int loc, View v) { activeBar = bar; contextMenuPushLoc = loc; getActivity().openContextMenu(v); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(capitalize(activeBar.getDay().toString())); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.schedule_bar_context_menu, menu); menu.findItem(R.id.paste_day).setVisible(thumbsCopied); MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { onContextItemSelected(item); return true; } }; for (int i = 0, n = menu.size(); i < n; i++) menu.getItem(i).setOnMenuItemClickListener(listener); } @Override public boolean onContextItemSelected(MenuItem item) { // Log.i("get", String.valueOf(activeBar)); // Log.i("no", String.valueOf(item.getSubMenu().getItem(item.getSubMenu().size() - 1).getTitle())); // toastSend(String.valueOf(activeBar)); switch (item.getItemId()) { case R.id.add_switch: // Log.i("ContextMenu", "Add Switch"); // ((ScheduleBar)fl.findViewById(R.id.scrollView).findViewById(R.id.linearScheduleLayout).findViewById(activeDay)).addThumb(); activeBar.addThumb(68, contextMenuPushLoc); updateSeekBars(); break; case R.id.clear_day: // Log.i("ContextMenu", "Clear Day"); activeBar.clearThumbs(); updateSeekBars(); break; case R.id.copy_day: // Log.i("ContextMenu", "Copy Day"); thumbsCopied = true; thumbBuffer = new ArrayList<>(); for (ThumbPiece thumbPiece : activeBar.getThumbs()) { thumbBuffer.add(thumbPiece.clone()); } updateSeekBars(); break; case R.id.paste_day: // Log.i("ContextMenu", "Paste Day"); activeBar.setThumbs(thumbBuffer); updateSeekBars(); break; case R.id.duplicate_day: // Log.i("ContextMenu", "Duplicate Day"); thumbsCopied = false; thumbBuffer = new ArrayList<>(activeBar.getThumbs()); for (Day key : scheduleBars.keySet()) { scheduleBars.get(key).setThumbs(thumbBuffer); } // for (int i = 0; i < ((ViewGroup) scrollView.findViewById(R.id.linearScheduleLayout)).getChildCount(); i++) { // View child = ((ViewGroup) scrollView.findViewById(R.id.scrollView).findViewById(R.id.linearScheduleLayout)).getChildAt(i); // if (child instanceof ScheduleBar) { // ((ScheduleBar) ((ViewGroup) scrollView.findViewById(R.id.scrollView).findViewById(R.id.linearScheduleLayout)).getChildAt(i)).setThumbs(thumbBuffer); // } // } updateSeekBars(); break; } return true; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_schedule, container, false); scrollView = (ScrollView) rootView.findViewById(R.id.scrollView); registerForContextMenu(scrollView); for (int i = 0; i < ((ViewGroup) scrollView.findViewById(R.id.linearScheduleLayout)).getChildCount(); i++) { View child = ((ViewGroup) scrollView.findViewById(R.id.linearScheduleLayout)).getChildAt(i); if (child instanceof com.yahoo.mobile.client.android.util.ScheduleBar) { final int ourChildId = child.getId(); switch (ourChildId) { case R.id.sundayBar: ((ScheduleBar) child).setDay(Day.SUNDAY); scheduleBars.put(Day.SUNDAY, (ScheduleBar) child); break; case R.id.mondayBar: ((ScheduleBar) child).setDay(Day.MONDAY); scheduleBars.put(Day.MONDAY, (ScheduleBar) child); break; case R.id.tuesdayBar: ((ScheduleBar) child).setDay(Day.TUESDAY); scheduleBars.put(Day.TUESDAY, (ScheduleBar) child); break; case R.id.wednesdayBar: ((ScheduleBar) child).setDay(Day.WEDNESDAY); scheduleBars.put(Day.WEDNESDAY, (ScheduleBar) child); break; case R.id.thursdayBar: ((ScheduleBar) child).setDay(Day.THURSDAY); scheduleBars.put(Day.THURSDAY, (ScheduleBar) child); break; case R.id.fridayBar: ((ScheduleBar) child).setDay(Day.FRIDAY); scheduleBars.put(Day.FRIDAY, (ScheduleBar) child); break; case R.id.saturdayBar: ((ScheduleBar) child).setDay(Day.SATURDAY); scheduleBars.put(Day.SATURDAY, (ScheduleBar) child); break; } // Log.i("whee", getResources().getResourceName(child.getId())); ((ScheduleBar) child).setOnLongPressListener( new ScheduleBar.OnLongPressListener() { @Override public void onLongPressListener(ScheduleBar bar, int loc) { openOurContextMenu(bar, loc, scrollView); } } ); ((ScheduleBar) child).setOnRangeSeekBarChangeListener( new ScheduleBar.OnRangeSeekBarChangeListener() { @Override public void onRangeSeekBarValuesChanged(ScheduleBar bar, List<?> thumbPieceList) { updateSeekBars(); } }); } } // if (getArguments().containsKey(SCHEDULE_BARS_KEY)) { // Map<Day, ScheduleBar> scheduleBarsTemp = (Map<Day, ScheduleBar>) getArguments().getSerializable(SCHEDULE_BARS_KEY); // for (Map.Entry<Day, ScheduleBar> barTemp : scheduleBarsTemp.entrySet()) { // Day key = barTemp.getKey(); // ScheduleBar value = barTemp.getValue(); // scheduleBars.get(key).setThumbs(value.getThumbs()); // } // } refreshBars(); // ((TextView) rootView.findViewById(R.id.section_label)).setText(String.valueOf(sectionNumber)); return rootView; } public void refreshBars() { SharedPreferences settings = getActivity().getSharedPreferences(MainActivity.PREFERENCES_KEY, Context.MODE_PRIVATE); if (settings.contains(SCHEDULE_BARS_KEY + String.valueOf(sectionNumber))) { jsonString = settings.getString(SCHEDULE_BARS_KEY + String.valueOf(sectionNumber), null); } if (jsonString != null) { try { fromJson(new JSONObject(jsonString)); // Log.i("tried","jj"); } catch (JSONException e) { e.printStackTrace(); } jsonString = null; } updateSeekBars(false); } public void enableBars(boolean enabled) { for (ScheduleBar bar : scheduleBars.values()) { bar.setEnabled(enabled); } } private void updateSeekBars() { for (Day day : Day.values()) { int n = 1; while (n < 7) { int prev = day.getValue() - n; while (prev < 0) prev += 7; // Log.i("Day", Day.get(prev).toString()); ThumbPiece tempThumb = getScheduleBar(Day.get(prev)).getRightMostThumb(); if (tempThumb != null) { getScheduleBar(day).updateLeftTemp(tempThumb.getTemp()); n = 10; continue; } n++; } } saveToPrefs(); } private void updateSeekBars(boolean save) { for (Day day : Day.values()) { int n = 1; while (n < 7) { int prev = day.getValue() - n; while (prev < 0) prev += 7; // Log.i("Day", Day.get(prev).toString()); ThumbPiece tempThumb = getScheduleBar(Day.get(prev)).findRightMostThumb(); if (tempThumb != null) { getScheduleBar(day).updateLeftTemp(tempThumb.getTemp()); n = 10; continue; } n++; } } if (save) saveToPrefs(); } public ScheduleBar getScheduleBar(Day day) { return scheduleBars.get(day); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; // saveToPrefs(); } public enum Day { SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6); private final int value; private Day(int value) { this.value = value; } public static Day get(int value) { for (Day day : Day.values()) if (day.getValue() == value) return day; return null; } public int getValue() { return value; } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } }
gpl-3.0
FendiJatmiko/tryout
config/database.php
4215
<?php return [ /* |-------------------------------------------------------------------------- | PDO Fetch Style |-------------------------------------------------------------------------- | | By default, database results will be returned as instances of the PHP | stdClass object; however, you may desire to retrieve records in an | array format for simplicity. Here you can tweak the fetch style. | */ 'fetch' => PDO::FETCH_CLASS, /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'sqlite'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'database' => storage_path('database.sqlite'), 'prefix' => '', ], 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'test'), 'username' => env('DB_USERNAME', 'root'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ], 'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', ], ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ];
gpl-3.0
Chevrotl/PicoloWars
variables.js
593
var TABLE_INFO = {'hauteur' : 0, 'largeur':0} //Struct : //{ //id_player : player //} var LIST_OF_PLAYER = {} //Struct : //{ //id_game : {map:jsonMap, players:{list player}} //} var LIST_OF_GAMES = {} //structure : // { // hauteur : int, // largeur : int, // cases : [{ // x : int, // y : int, // bloc : bool, // img : string, // }] // } var JSON_TABLE = { "hauteur" : 30, "largeur" : 45, "cases" : [{ x:0, y:0, bloc:false, img:"backgroundGreen.png" }] }; exports.TABLE_INFO = TABLE_INFO; exports.LIST_OF_PLAYER = LIST_OF_PLAYER; exports.LIST_OF_GAMES = LIST_OF_GAMES;
gpl-3.0
s20121035/rk3288_android5.1_repo
external/apache-harmony/security/src/test/api/java.injected/java/security/cert/myCertPath.java
1557
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Vera Y. Petrashkova */ package java.security.cert; import java.util.*; import java.security.cert.CertPath; /** * Class for CertPath creating */ public class myCertPath extends CertPath { public List getCertificates() { return new Vector(); } public byte[] getEncoded() { return new byte[0]; } public byte[] getEncoded(String s) { return new byte[0]; } public Iterator getEncodings() { return (Iterator) (new StringTokenizer("ss ss ss ss")); } protected myCertPath(String s) { super(s); } public CertPath get(String s) { return new myCertPath(s); } public myCertPath(String s, String s1) { super(s); } }
gpl-3.0
Mindful/vmime
src/vmime/security/sasl/SASLContext.cpp
5149
// // VMime library (http://www.vmime.org) // Copyright (C) 2002-2013 Vincent Richard <vincent@vmime.org> // // 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, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // Linking this library statically or dynamically with other modules is making // a combined work based on this library. Thus, the terms and conditions of // the GNU General Public License cover the whole combination. // #include "vmime/config.hpp" #if VMIME_HAVE_MESSAGING_FEATURES && VMIME_HAVE_SASL_SUPPORT #include <sstream> #include <gsasl.h> #include "vmime/security/sasl/SASLContext.hpp" #include "vmime/security/sasl/SASLMechanism.hpp" #include "vmime/base.hpp" #include "vmime/utility/encoder/encoderFactory.hpp" #include "vmime/utility/stream.hpp" #include "vmime/utility/outputStreamStringAdapter.hpp" #include "vmime/utility/inputStreamStringAdapter.hpp" #include "vmime/utility/inputStreamByteBufferAdapter.hpp" namespace vmime { namespace security { namespace sasl { SASLContext::SASLContext() { if (gsasl_init(&m_gsaslContext) != GSASL_OK) throw std::bad_alloc(); } SASLContext::~SASLContext() { gsasl_done(m_gsaslContext); } shared_ptr <SASLSession> SASLContext::createSession (const string& serviceName, shared_ptr <authenticator> auth, shared_ptr <SASLMechanism> mech) { return make_shared <SASLSession> (serviceName, dynamicCast <SASLContext>(shared_from_this()), auth, mech); } shared_ptr <SASLMechanism> SASLContext::createMechanism(const string& name) { return SASLMechanismFactory::getInstance()->create (dynamicCast <SASLContext>(shared_from_this()), name); } shared_ptr <SASLMechanism> SASLContext::suggestMechanism (const std::vector <shared_ptr <SASLMechanism> >& mechs) { if (mechs.empty()) return null; std::ostringstream oss; for (unsigned int i = 0 ; i < mechs.size() ; ++i) oss << mechs[i]->getName() << " "; const string mechList = oss.str(); const char* suggested = gsasl_client_suggest_mechanism (m_gsaslContext, mechList.c_str()); if (suggested) { for (unsigned int i = 0 ; i < mechs.size() ; ++i) { if (mechs[i]->getName() == suggested) return mechs[i]; } } return null; } void SASLContext::decodeB64(const string& input, byte_t** output, size_t* outputLen) { string res; utility::inputStreamStringAdapter is(input); utility::outputStreamStringAdapter os(res); shared_ptr <utility::encoder::encoder> dec = utility::encoder::encoderFactory::getInstance()->create("base64"); dec->decode(is, os); byte_t* out = new byte_t[res.length()]; std::copy(res.begin(), res.end(), out); *output = out; *outputLen = res.length(); } const string SASLContext::encodeB64(const byte_t* input, const size_t inputLen) { string res; utility::inputStreamByteBufferAdapter is(input, inputLen); utility::outputStreamStringAdapter os(res); shared_ptr <utility::encoder::encoder> enc = utility::encoder::encoderFactory::getInstance()->create("base64"); enc->encode(is, os); return res; } const string SASLContext::getErrorMessage(const string& fname, const int code) { string msg = fname + "() returned "; #define ERROR(x) \ case x: msg += #x; break; switch (code) { ERROR(GSASL_NEEDS_MORE) ERROR(GSASL_UNKNOWN_MECHANISM) ERROR(GSASL_MECHANISM_CALLED_TOO_MANY_TIMES) ERROR(GSASL_MALLOC_ERROR) ERROR(GSASL_BASE64_ERROR) ERROR(GSASL_CRYPTO_ERROR) ERROR(GSASL_SASLPREP_ERROR) ERROR(GSASL_MECHANISM_PARSE_ERROR) ERROR(GSASL_AUTHENTICATION_ERROR) ERROR(GSASL_INTEGRITY_ERROR) ERROR(GSASL_NO_CLIENT_CODE) ERROR(GSASL_NO_SERVER_CODE) ERROR(GSASL_NO_CALLBACK) ERROR(GSASL_NO_ANONYMOUS_TOKEN) ERROR(GSASL_NO_AUTHID) ERROR(GSASL_NO_AUTHZID) ERROR(GSASL_NO_PASSWORD) ERROR(GSASL_NO_PASSCODE) ERROR(GSASL_NO_PIN) ERROR(GSASL_NO_SERVICE) ERROR(GSASL_NO_HOSTNAME) ERROR(GSASL_GSSAPI_RELEASE_BUFFER_ERROR) ERROR(GSASL_GSSAPI_IMPORT_NAME_ERROR) ERROR(GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR) ERROR(GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR) ERROR(GSASL_GSSAPI_UNWRAP_ERROR) ERROR(GSASL_GSSAPI_WRAP_ERROR) ERROR(GSASL_GSSAPI_ACQUIRE_CRED_ERROR) ERROR(GSASL_GSSAPI_DISPLAY_NAME_ERROR) ERROR(GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR) ERROR(GSASL_KERBEROS_V5_INIT_ERROR) ERROR(GSASL_KERBEROS_V5_INTERNAL_ERROR) ERROR(GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE) ERROR(GSASL_SECURID_SERVER_NEED_NEW_PIN) default: msg += "unknown error"; break; } #undef ERROR return msg; } } // sasl } // security } // vmime #endif // VMIME_HAVE_MESSAGING_FEATURES && VMIME_HAVE_SASL_SUPPORT
gpl-3.0
irgsmirx/WebServer
src/main/java/com/ramforth/webserver/http/headers/StringHttpHeader.java
1156
/* * Copyright (C) 2014 Tobias Ramforth * * 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 com.ramforth.webserver.http.headers; import com.ramforth.webserver.http.HttpHeader; /** * * @author Tobias Ramforth <tobias.ramforth at tu-dortmund.de> */ public class StringHttpHeader extends HttpHeader { public StringHttpHeader(String name, String rawValue) { super(name, rawValue); } public String getValue() { return rawValue; } public void setValue(String value) { this.rawValue = value; } }
gpl-3.0
desht/pnc-repressurized
src/main/java/me/desht/pneumaticcraft/common/progwidgets/IJumpBackWidget.java
320
package me.desht.pneumaticcraft.common.progwidgets; /** * Implemented by widgets that have custom program flow behaviour when a program reaches the end. * It is put onto a stack when executed normally, and then popped off when reaching the end of a program to call it again. */ public interface IJumpBackWidget { }
gpl-3.0
Mazdallier/AncientWarfare2
src/main/java/net/shadowmage/ancientwarfare/npc/entity/faction/NpcCustom_1LeaderElite.java
335
package net.shadowmage.ancientwarfare.npc.entity.faction; import net.minecraft.world.World; public class NpcCustom_1LeaderElite extends NpcFactionLeader { public NpcCustom_1LeaderElite(World par1World) { super(par1World); } @Override public String getNpcType() { return "custom_1.leader.elite"; } }
gpl-3.0
oscarbernal93/cliente-servidor
musicPlayer/server.cc
3715
#include "hermes.hh" #include "apolo.hh" #include <zmqpp/zmqpp.hpp> #define SNAME "μMus" //server's name #define LOG_ENABLED true //if true shows a log in console using namespace zmqpp; using namespace std; int socket_message_manager(vector<string> &mlist, list<string> &playlist,socket &skt); string get_songs(vector<string> &mlist); int console_message_manager(); int main(int argc, char *argv[]){ if ( not ( 2 == argc ) ) { cerr << "Please, write the number of the port to serve" << endl; return 1; } //Starting the server string port_num(argv[1]); //initialize the connection context my_context; socket server_socket(my_context, socket_type::xreply); string address_to_connect("tcp://*:"); address_to_connect += port_num; server_socket.bind( address_to_connect ); cout << SNAME << "> Server started correctly, listening on port " << port_num << endl; //get the file list vector<string> mlist = files_in("music"); //vars list<string> playlist; //Polling Stage poller deadpool; int console = fileno(stdin); //add to the poll te socket and the console input deadpool.add(server_socket, poller::poll_in); deadpool.add(console, poller::poll_in); while (true){ if(deadpool.poll()){ //call a function when the secket has messages to read if(deadpool.has_input(server_socket)){ if(1 == socket_message_manager(mlist,playlist,server_socket)){ return 0; } } //call a function when the console has messages to read if(deadpool.has_input(console)){ if(1 == console_message_manager()){ return 0; } } } } return 0; } int socket_message_manager(vector<string> &mlist, list<string> &playlist,socket &skt) { message minput; message delivery_message; string command; string uname; string ident; string slist; //get the message by parts skt.receive(minput); minput.get(ident,0); minput.get(command,1); minput.get(uname,2); char option = command.at(0); switch(option) { case 'L': if (LOG_ENABLED) cout << uname << "> List songs" << endl; slist = get_songs(mlist); delivery_message << ident << "L" << slist; skt.send(delivery_message); break; case 'U': cout << "upload song..." << endl; //upload_song(); break; case 'A': cout << "add song..." << endl; //add_song(mlist,playlist); break; case 'P': cout << "print playlist..." << endl; //print_playlist(playlist); break; case 'D': cout << "skip song..." << endl; //playlist.pop_front(); break; case 'H': cout << SNAME << "> User " << uname << " connected." << endl; //Answer the Handshake delivery_message << ident << "W" << SNAME; skt.send(delivery_message); break; case 'X': return 0; break; default: cout << "Unrecognized option: " << option << endl; cout << "Use (H)elp to see the available options" << endl; break; } return 0; } int console_message_manager() { string str_console; getline(cin,str_console); cout << "Deberia hacer algo..." << str_console << endl; return 0; } string get_songs(vector<string> &mlist) { string result = ""; //update the file list and print it mlist = files_in("music"); if ( 0 < mlist.size()) { result += "Available Songs:\n"; int counter = 0; for (auto i = mlist.begin(); i != mlist.end(); ++i){ result += number_to_string(counter) + ": " + *i + "\n"; counter++; } } else { result = "There are no songs available.\n"; } return result; }
gpl-3.0
MXtreme/RiverSim
Sources/Graph.cpp
6849
#include "Graph.h" Graph::Graph(){ dim = 0; } int Graph::getDim(){ return dim; } bool Graph::isVisitato(int id){ std::vector<ElemGraph*> all; all = getAllNodeList(); return all[id]->getElementPointer()->getVisitato(); } void Graph::setFalseVisitato(){ std::vector<ElemGraph*> all; all = getAllNodeList(); for (int i = 0; i < dim; i++){ all[i]->getElementPointer()->setVisitato(false); } } void Graph::setVisitato(int id){ std::vector<ElemGraph*> all; all = getAllNodeList(); all[id]->getElementPointer()->setVisitato(true); } bool Graph::isEmpty(){ if (dim == 0){ return true; } else return false; } std::vector<Nodo*> Graph::DFS(ElemGraph * eg){ std::vector<Canale*> next=eg->getNext(); std::vector<Nodo*> adj_node; for(size_t i=0;i<next.size();i++){ std::vector<std::string> adj=next[i]->adj; for(size_t k=0;k<node_list.size();k++){ for(size_t j=0;j<adj.size();j++){ if(node_list[k]->getElemento().name==adj[j] && node_list[k]->getElemento().name!=eg->getElemento().name){ adj_node.push_back(node_list[k]->getElementPointer()); } } } } return adj_node; } std::vector<ElemGraph*> Graph::getAdjs(ElemGraph *eg){ std::vector<Canale*> next=eg->getNext(); std::vector<ElemGraph*> adj_node; for(size_t i=0;i<next.size();i++){ std::vector<std::string> adj=next[i]->adj; for(size_t k=0;k<node_list.size();k++){ for(size_t j=0;j<adj.size();j++){ if(node_list[k]->getElemento().name==adj[j] && node_list[k]->getElemento().name!=eg->getElemento().name){ adj_node.push_back(node_list[k]); } } } } return adj_node; } void Graph::addNode(ElemGraph* eg){ node_list.push_back(eg); } void Graph::incrDim(){ dim++; } ElemGraph* Graph::getNodeList(int id){ return node_list[id]; } void Graph::setNextNodeList(ElemGraph *node){ node_list.push_back(node); } std::vector<ElemGraph*> Graph::getAllNodeList(){ return node_list; } std::vector<Canale*> Graph::getAdj(ElemGraph* eg){ return eg->getNext(); } double Graph::getCanaleHeight(Nodo *a, Nodo *b){ int canale=findCanale(a, b); double max_height=0; Canale tmp=sim->canali[canale]; for(size_t i=0;i<tmp.hj.size();i++){ if(tmp.hj[i]>max_height){ max_height=tmp.hj[i]; } } return max_height; } double Graph::getMaxHeight() { double max = 0; for (size_t i=0; i < sim->canali.size(); i++) { for (size_t j=0; j < sim->canali[i].hj.size(); j++) { if (sim->canali[i].hj[j] > max) max = sim->canali[i].hj[j]; } } return max; } double Graph::getMaxFlow() { double max = 0; for (size_t i=0; i < sim->canali.size(); i++) { for (size_t j=0; j < sim->canali[i].hj.size(); j++) { if (sim->canali[i].hj[j] > max) max = sim->canali[i].hj[j]; } } return max; } double Graph::getCanaleHeightPosition(Nodo *a, Nodo *b){ int canale=findCanale(a, b); double max_height=getCanaleHeight(a, b); double height_peak=0; int segment=0; Canale tmp=sim->canali[canale]; for(size_t i=0;i<tmp.hj.size();i++){ if(tmp.hj[i]==max_height) segment=i; } height_peak=(100*segment)/tmp.hj.size(); return height_peak; } double Graph::getCanaleFlow(Nodo *a, Nodo *b){ int canale=findCanale(a, b); double max_flow=0; Canale tmp=sim->canali[canale]; for(size_t i=0;i<tmp.Qj.size();i++){ if(tmp.Qj[i]>max_flow) max_flow=tmp.Qj[i]; } return max_flow; } double Graph::getCanaleFlowPosition(Nodo *a, Nodo *b){ int canale=findCanale(a, b); double max_flow=getCanaleFlow(a, b); double flow_peak=0; int segment=0; Canale tmp=sim->canali[canale]; for(size_t i=0;i<tmp.Qj.size();i++){ if(tmp.Qj[i]==max_flow) segment=i; } flow_peak=(100*segment)/tmp.Qj.size(); return flow_peak; } int Graph::findCanale(Nodo *a, Nodo *b){ int canale=-1; for(size_t i=0;i<a->canali_in.size();i++){ for(size_t k=0;k<b->canali_out.size();k++){ if(a->canali_in[i]==b->canali_out[k]){ canale=a->canali_in[i]; } } } if(canale==-1){ for(size_t i=0;i<a->canali_out.size();i++){ for(size_t k=0;k<b->canali_in.size();k++){ if(a->canali_out[i]==b->canali_in[k]){ canale=a->canali_out[i]; } } } } return canale; } int Graph::getNSections(Nodo* a, Nodo *b){ int canale=findCanale(a, b); Canale tmp=sim->canali[canale]; return tmp.N; } double Graph::getCanaleHeightSection(Nodo *a, Nodo *b, int sect){ int canale=findCanale(a, b); Canale tmp=sim->canali[canale]; return tmp.hj[sect]; } double Graph::getCanaleFlowSection(Nodo *a, Nodo *b, int sect){ int canale=findCanale(a, b); Canale tmp=sim->canali[canale]; return tmp.Qj[sect]; } double Graph::getCanaleInclinationSection(Nodo *a, Nodo *b){ int canale=findCanale(a, b); Canale tmp=sim->canali[canale]; return tmp.alpha; } void Graph::printVisitato(){ for(int i=0;i<dim;i++){ printf("%d\n",visitato[i]); } } std::string Graph::getCanaleName(Nodo *a, Nodo *b){ int canale=findCanale(a, b); Canale tmp=sim->canali[canale]; return tmp.name; } std::vector<std::string> Graph::getAllCanaliname(){ std::vector<std::string> name; int i; for(i=0;i<node_list.size();i++){ name.push_back(node_list[i]->getElementPointer()->name); } return name; } std::vector<float> Graph::getAvgHeight(){ int canale, i, k, j; float tmp_avg=0; std::vector<float> avg; for(k=0;k<node_list.size();k++){ for(j=0;j<node_list.size();j++){ canale=findCanale(node_list[k]->getElementPointer(), node_list[j]->getElementPointer()); if(canale!=-1){ Canale tmp=sim->canali[canale]; for(i=0;i<tmp.hj.size();i++){ tmp_avg+=tmp.hj[i]; } avg.push_back(tmp_avg/tmp.hj.size()); canale=-1; tmp_avg=0; } } } return avg; } std::vector<float> Graph::getAvgPortata(){ int canale, i, k, j; float tmp_avg=0; std::vector<float> avg; for(k=0;k<node_list.size();k++){ for(j=0;j<node_list.size();j++){ canale=findCanale(node_list[k]->getElementPointer(), node_list[j]->getElementPointer()); if(canale!=-1){ Canale tmp=sim->canali[canale]; for(i=0;i<tmp.Qj.size();i++){ tmp_avg+=tmp.Qj[i]; } avg.push_back(tmp_avg/tmp.Qj.size()); canale=-1; tmp_avg=0; } } } return avg; } std::vector<float> Graph::getPendenza(){ int canale, i, k, j; std::vector<float> pend; for(k=0;k<node_list.size();k++){ for(j=0;j<node_list.size();j++){ canale=findCanale(node_list[k]->getElementPointer(), node_list[j]->getElementPointer()); if(canale!=-1){ Canale tmp=sim->canali[canale]; pend.push_back(tmp.alpha); canale=-1; } } } return pend; }
gpl-3.0
bourey/moodle
install/lang/nl/install.php
7476
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle 2.2dev installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['admindirname'] = 'Admin-map'; $string['availablelangs'] = 'Lijst met beschikbare talen'; $string['chooselanguagehead'] = 'Kies een taal'; $string['chooselanguagesub'] = 'Kies een taal voor de installatie. Deze taal zal ook als standaardtaal voor de site gebruikt worden, maar die instelling kun je later nog wijzigen.'; $string['clialreadyinstalled'] = 'Bestand config.php bestaat al. Gebruik admin/cil/upgrade.php om je site te upgraden.'; $string['cliinstallheader'] = 'Moodle {$a} command line installatieprogramma'; $string['databasehost'] = 'Databank host:'; $string['databasename'] = 'Datanbanknaam:'; $string['databasetypehead'] = 'Kies databankdriver'; $string['dataroot'] = 'Gegevens'; $string['dbprefix'] = 'Tabelvoorvoegsel'; $string['dirroot'] = 'Moodle-map'; $string['environmenthead'] = 'Omgeving controleren ...'; $string['environmentsub2'] = 'Elke Moodleversie vraagt een minimum PHP-versie en een aantal vereiste PHP-extenties. De volledige installatie-omgeving wordt gecontroleerd voor elke installatie en upgrade. Contacteer je server beheerder als je niet weet hoe je de juiste PHP-versie moet installeren of PHP-extenties moet inschakelen.'; $string['errorsinenvironment'] = 'Fouten in je omgeving!'; $string['installation'] = 'Installatie'; $string['langdownloaderror'] = 'De taal "{$a}" kon niet worden gedownload. Het installatieproces gaat verder in het Engels.'; $string['memorylimithelp'] = '<p>De PHP-geheugenlimiet van je server is ingesteld op {$a}.</p> <p>Hierdoor kan Moodle geheugenproblemen krijgen, vooral als je veel modules installeert en/of veel gebruikers hebt.</p> <p>We raden je aan PHP met een hogere geheugenlimiet te configureren indien mogelijk, bijvoorbeeld 40Mb. Er zijn verschillende mogelijkheden om dat te doen. Je kunt proberen: <ol> <li>Indien je kunt PHP hercompileren met <i>--enable-memory-limit</i>. Hierdoor kan Moodle zelf zijn geheugenlimiet instellen. <li>Als je toegang hebt tot het php.ini-bestand, kun je de <b>memory_limit</b>-instelling veranderen naar bv 40Mb. Als je geen toegang hebt kun je je systeembeheerder vragen dit voor je te wijzigen.</li> <li>Op sommige PHP-servers kun je een .htaccess-bestand maken in de Moodle-map met volgende lijn: <p><blockquote>php_value memory_limit 40M</blockquote></p> <p>Opgelet: op sommige servers zal dit verhinderen dat <b>alle</b> PHP-bestanden uitgevoerd worden. (je zult foutmeldingen zien wanneer je naar php-pagina\'s kijkt) Je zult dan het .htaccess-bestand moeten verwijderen.</li> </ol>'; $string['paths'] = 'Paden'; $string['pathserrcreatedataroot'] = 'Datamap ({$a->dataroot}) kan niet aangemaakt worden door het installatiescript'; $string['pathshead'] = 'Bevestig paden'; $string['pathsrodataroot'] = 'De dataroot map is niet beschrijfbaar.'; $string['pathsroparentdataroot'] = 'De bovenliggende map ({$a->parent}) is niet beschrijfbaar. De datamap ({$a->dataroot}) kan niet aangemaakt worden door het installatiescript'; $string['pathssubadmindir'] = 'Sommige webhosts gebruiken /admin als een speciale url om toegang tot bijvoorbeeld een controlepaneel te krijgen. Dit kan conflicten veroorzaken met de standaardlocatie van de Moodle admin scripts. Je kunt dit oplossen door de admin map van Moodle te hernoemen en de nieuwe naam hier te zetten. Bijvoorbeeld <em>moodleadmin</em>. Dat zal de admin links in Moodle herstellen.'; $string['pathssubdataroot'] = 'Je hebt een plaats nodig waar Moodle geüploade bestanden kan bewaren. Deze map moet leesbaar en BESCHRIJFBAAR zijn door de webserver gebruiker (gewoonlijk \'nobody\', \'apache\' of www-data\') en mag niet rechtstreeks toegankelijk zijn vanaf het internet.'; $string['pathssubdirroot'] = 'Volledig pad naar de Moodle-installatie.'; $string['pathssubwwwroot'] = 'Volledig webadres waarlangs de toegang naar Moodle zal gebeuren. Het is niet mogelijk toegang tot Moodle te krijgen via meerdere adressen. Als je site meerdere publieke adressen heeft, dan zul je permanente verwijzingen moeten opzetten voor al die adressen, behalve voor wat je hier invult. Als je site zowel van het internet als van een intranet toegankelijk is, zet dat het internetadres hier en wijzig je DNS-instellingen zodanig dat intranetgebruikers dit publieke adres ook gebruiken. Als het adres niet juist is, wijzig dan de URL in je browser om de installatie met een andere waarde te starten.'; $string['pathsunsecuredataroot'] = 'De plaats van de datamap is niet veilig.'; $string['pathswrongadmindir'] = 'De adminmap bestaat niet'; $string['phpextension'] = '{$a} PHP-extentie'; $string['phpversion'] = 'PHP-versie'; $string['phpversionhelp'] = '<p>Moodle heeft minstens PHP-versie 4.3.0 of 5.1.0 nodig (5.0.x heeft veel bekende problemen).</p> <p>De huidige versie op je server is {$a}</p> <p>Je moet PHP upgraden of verhuizen naar een host met een nieuwere versie van PHP!<br />(Als je 5.0.x draait, kun je ook downgraden naar versie 4.4.x)</p>'; $string['welcomep10'] = '{$a->installername} ({$a->installerversion})'; $string['welcomep20'] = 'Je krijgt deze pagina te zien omdat je met succes het <strong>{$a->packname} {$a->packversion}</strong> packet op je computer gezet en gestart hebt. Proficiat!'; $string['welcomep30'] = 'Deze uitgave van <strong>{$a->installername}</strong> bevat de software die nodig is om een omgeving te creëren waarin <strong>Moodle</strong> zal werken, namelijk:'; $string['welcomep40'] = 'Dit pakket bevat ook <strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong>.'; $string['welcomep50'] = 'Het gebruik van alle programma\'s in dit pakket wordt geregeld door hun respectievelijke licenties. Het complete <strong>{$a->installername}</strong> pakket is <a href="http://www.opensource.org/docs/definition_plain.html">open source</a> en wordt verdeeld onder de <a href="http://www.gnu.org/copyleft/gpl.html">GPL</a> licentie.'; $string['welcomep60'] = 'De volgende pagina\'s leiden je door een aantal makkelijk te volgen stappen om <strong>Moodle</strong> te installeren op je computer. Je kunt de standaardinstellingen overnemen of, optionneel, ze aanpassen aan je noden.'; $string['welcomep70'] = 'Klik op de "volgende"-knop om verder te gaan met de installatie van <strong>Moodle</strong>'; $string['wwwroot'] = 'Web adres';
gpl-3.0
thalerjonathan/phd
coding/prototyping/haskell/declarativeABM/java/SpatialGameABS/src/agent/Agent.java
2954
package agent; import java.util.*; import java.util.concurrent.ThreadLocalRandom; /** * Created by jonathan on 20/01/17. */ public abstract class Agent<M extends Comparable<M>, E> implements Comparable<Agent<M, E>> { private int id; private List<MsgPair> inBox; private List<MsgPair> outBox; private List<Agent<M, E>> neighbours; protected E localEnv; private static int NEXT_ID = 0; public Agent() { this(NEXT_ID++); } public Agent(int id) { this.id = id; this.inBox = new LinkedList<>(); this.outBox = new LinkedList<>(); } public int getId() { return this.id; } List<MsgPair> getInBox() { return inBox; } List<MsgPair> getOutBox() { return outBox; } public void addNeighbour(Agent<M, E> n) { if ( null == this.neighbours ) this.neighbours = new ArrayList<>(); this.neighbours.add(n); } public void setNeighbours(List<Agent<M, E>> ns) { this.neighbours = ns; } public List<Agent<M, E>> getNeighbours() { return this.neighbours; } public E getLocalEnv() { return this.localEnv; } public void step(Double time, Double delta, Map<Integer, E> globalEnv) { Iterator<MsgPair> iter = this.inBox.iterator(); while (iter.hasNext()) { MsgPair p = iter.next(); this.receivedMessage(p.agent, p.msg, globalEnv); } this.inBox.clear(); this.dt(time, delta, globalEnv); } public void broadCastToNeighbours(Message<M> msg) { if ( null == this.neighbours ) return; for (Agent<M, E> n : this.neighbours ) { this.sendMessage(msg, n); } } public void sendMessageToRandomNeighbour(Message<M> msg) { if ( null == this.neighbours ) return; int randIdx = (int) (ThreadLocalRandom.current().nextDouble() * this.neighbours.size()); Agent randNeigh = this.neighbours.get(randIdx); this.sendMessage(msg, randNeigh); } public void sendMessage(Message<M> msg, Agent<M, E> receiver) { this.outBox.add(new MsgPair(receiver, msg)); } public abstract void receivedMessage(Agent<M, E> sender, Message<M> msg, Map<Integer, E> globalEnv); // HASKELL IS BETTER HERE: cannot include the Dt in the Message-Type M in Java, thus need to split it up into separate functions public abstract void dt(Double time, Double delta, Map<Integer, E> globalEnv); @Override public int compareTo(Agent<M, E> o) { return o.id - this.id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Agent<?,?> agent = (Agent<?,?>) o; return id == agent.id; } @Override public int hashCode() { return id; } }
gpl-3.0
richelbilderbeek/ImageRotater
qtimagerotatermenudialog.cpp
894
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #include "qtimagerotatermenudialog.h" #include "qtaboutdialog.h" #include "imagerotatermenudialog.h" #include "qtimagerotatermaindialog.h" #include "ui_qtimagerotatermenudialog.h" #pragma GCC diagnostic pop ribi::QtImageRotaterMenuDialog::QtImageRotaterMenuDialog(QWidget *parent) : QtHideAndShowDialog(parent), ui(new Ui::QtImageRotaterMenuDialog) { ui->setupUi(this); } ribi::QtImageRotaterMenuDialog::~QtImageRotaterMenuDialog() noexcept { delete ui; } void ribi::QtImageRotaterMenuDialog::on_button_start_clicked() { QtImageRotaterMainDialog d; this->ShowChild(&d); } void ribi::QtImageRotaterMenuDialog::on_button_about_clicked() { QtAboutDialog d(ImageRotaterMenuDialog().GetAbout()); this->ShowChild(&d); } void ribi::QtImageRotaterMenuDialog::on_button_quit_clicked() { this->close(); }
gpl-3.0
gohdan/DFC
known_files/hashes/bitrix/modules/cluster/lang/en/admin/cluster_webnode_list.php
61
Bitrix 16.5 Business Demo = 66ea55f088ef66ae9c195489fdbf8872
gpl-3.0
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/MjdJumpRange.java
819
package fr.guiguilechat.jcelechat.model.sde.attributes; import fr.guiguilechat.jcelechat.model.sde.IntAttribute; /** * distance jumped on mjd activation */ public class MjdJumpRange extends IntAttribute { public static final MjdJumpRange INSTANCE = new MjdJumpRange(); @Override public int getId() { return 2066; } @Override public int getCatId() { return 17; } @Override public boolean getHighIsGood() { return true; } @Override public double getDefaultValue() { return 0.0; } @Override public boolean getPublished() { return true; } @Override public boolean getStackable() { return true; } @Override public String toString() { return "MjdJumpRange"; } }
gpl-3.0
applifireAlgo/OnlineShopEx
onlineshopping/src/main/java/shop/app/server/businessservice/retailcontext/retail/PaymentTranExBzService.java
4113
package shop.app.server.businessservice.retailcontext.retail; import com.athena.framework.server.helper.RuntimeLogInfoHelper; import com.athena.ruleengine.server.bzservice.RuleEngineInterface; import com.spartan.shield.sessionService.SessionDataMgtService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import shop.app.server.businessservice.OrderProcessServiceImplEx; import shop.app.server.repository.OrderMainRepository; import shop.app.server.repository.OrderTransactionRepository; import shop.app.shared.defaultdomain.OrderTransaction; import shop.app.shared.retail.OrderMain; import com.athena.framework.server.exception.biz.SpartanBusinessValidationFailedException; import com.athena.framework.server.exception.biz.SpartanDataNotFoundException; import com.athena.framework.server.exception.biz.SpartanIncorrectDataException; import com.athena.framework.server.exception.repository.SpartanPersistenceException; import shop.app.shared.retailcontext.retail.PaymentDetails; @Component public class PaymentTranExBzService { @Autowired private SessionDataMgtService sessionService; @Autowired private RuntimeLogInfoHelper runtimeLogInfoHelper; @Autowired private OrderProcessServiceImplEx orderProcessServiceImplEx; @Autowired private RuleEngineInterface ruleEngineInterface; @Autowired private OrderMainRepository<OrderMain> orderMainRepository; @Autowired private OrderTransactionRepository<OrderTransaction> orderTransactionRepository; public void paymentTranProcessing(PaymentDetails payment) throws SpartanIncorrectDataException, Exception, SpartanBusinessValidationFailedException, SpartanPersistenceException, SpartanDataNotFoundException { try { if (payment == null) { throw new com.athena.framework.server.exception.biz.SpartanDataNotFoundException("invalid parameter"); } shop.app.shared.retailcontext.retail.TransactionResponse transactionresponse_24 = orderProcessServiceImplEx.processOrder(payment); java.lang.String OrderId = (java.lang.String) sessionService.getSessionData("OrderId"); if (OrderId == null) { throw new com.athena.framework.server.exception.biz.SpartanDataNotFoundException("Data not found in session"); } if (OrderId == null) { throw new com.athena.framework.server.exception.biz.SpartanDataNotFoundException("invalid parameter"); } shop.app.shared.retail.OrderMain ordermain_25 = orderMainRepository.findById(OrderId); ruleEngineInterface.initialize("70733eae-2a4f-4e1e-aba7-23061da00c94"); ruleEngineInterface.add(transactionresponse_24); ruleEngineInterface.add(ordermain_25); ruleEngineInterface.add(runtimeLogInfoHelper); ruleEngineInterface.add(payment); ruleEngineInterface.executeRule(); if ((shop.app.shared.defaultdomain.OrderTransaction) ruleEngineInterface.getResult("ordertransaction_26") == null) { throw new com.athena.framework.server.exception.biz.SpartanDataNotFoundException("invalid parameter"); } shop.app.shared.defaultdomain.OrderTransaction ordertransaction_27 = orderTransactionRepository.save((shop.app.shared.defaultdomain.OrderTransaction) ruleEngineInterface.getResult("ordertransaction_26")); } catch (com.athena.framework.server.exception.biz.RuleInitException | com.athena.framework.server.exception.biz.RuleExecuteException | com.athena.framework.server.exception.biz.RuleWorkingMemoryException | com.athena.framework.server.exception.biz.RuleDataException e) { e.printStackTrace(); throw new com.athena.framework.server.exception.biz.SpartanBusinessValidationFailedException("3005"); } catch (Exception e) { e.printStackTrace(); throw new com.athena.framework.server.exception.biz.SpartanBusinessValidationFailedException(e.getCause().getMessage()); } } }
gpl-3.0
tomaszkolonko/ndnSIM-all
ndn-cxx/src/management/nfd-rib-entry.cpp
8915
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2013-2015 Regents of the University of California. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx library 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 Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #include "nfd-rib-entry.hpp" #include "encoding/tlv-nfd.hpp" #include "encoding/block-helpers.hpp" #include "util/concepts.hpp" namespace ndn { namespace nfd { //BOOST_CONCEPT_ASSERT((boost::EqualityComparable<Route>)); BOOST_CONCEPT_ASSERT((WireEncodable<Route>)); BOOST_CONCEPT_ASSERT((WireDecodable<Route>)); static_assert(std::is_base_of<tlv::Error, Route::Error>::value, "Route::Error must inherit from tlv::Error"); //BOOST_CONCEPT_ASSERT((boost::EqualityComparable<RibEntry>)); BOOST_CONCEPT_ASSERT((WireEncodable<RibEntry>)); BOOST_CONCEPT_ASSERT((WireDecodable<RibEntry>)); static_assert(std::is_base_of<tlv::Error, RibEntry::Error>::value, "RibEntry::Error must inherit from tlv::Error"); const time::milliseconds Route::INFINITE_EXPIRATION_PERIOD(time::milliseconds::max()); Route::Route() : m_faceId(0) , m_origin(0) , m_cost(0) , m_mac("") , m_flags(ROUTE_FLAG_CHILD_INHERIT) , m_expirationPeriod(INFINITE_EXPIRATION_PERIOD) , m_hasInfiniteExpirationPeriod(true) { } Route::Route(const Block& block) { wireDecode(block); } template<encoding::Tag TAG> size_t Route::wireEncode(EncodingImpl<TAG>& block) const { size_t totalLength = 0; // Absence of an ExpirationPeriod signifies non-expiration if (!m_hasInfiniteExpirationPeriod) { totalLength += prependNonNegativeIntegerBlock(block, ndn::tlv::nfd::ExpirationPeriod, m_expirationPeriod.count()); } totalLength += prependNonNegativeIntegerBlock(block, ndn::tlv::nfd::Flags, m_flags); totalLength += prependNonNegativeIntegerBlock(block, ndn::tlv::nfd::Cost, m_cost); totalLength += prependStringBlock(block,ndn::tlv::nfd::Mac,m_mac); totalLength += prependNonNegativeIntegerBlock(block, ndn::tlv::nfd::Origin, m_origin); totalLength += prependNonNegativeIntegerBlock(block, ndn::tlv::nfd::FaceId, m_faceId); totalLength += block.prependVarNumber(totalLength); totalLength += block.prependVarNumber(ndn::tlv::nfd::Route); return totalLength; } template size_t Route::wireEncode<encoding::EncoderTag>(EncodingImpl<encoding::EncoderTag>& block) const; template size_t Route::wireEncode<encoding::EstimatorTag>(EncodingImpl<encoding::EstimatorTag>& block) const; const Block& Route::wireEncode() const { if (m_wire.hasWire()) { return m_wire; } EncodingEstimator estimator; size_t estimatedSize = wireEncode(estimator); EncodingBuffer buffer(estimatedSize, 0); wireEncode(buffer); m_wire = buffer.block(); return m_wire; } void Route::wireDecode(const Block& wire) { m_faceId = 0; m_origin = 0; m_cost = 0; m_mac= " "; m_flags = 0; m_expirationPeriod = time::milliseconds::min(); m_wire = wire; if (m_wire.type() != tlv::nfd::Route) { std::stringstream error; error << "Expected Route Block, but Block is of a different type: #" << m_wire.type(); BOOST_THROW_EXCEPTION(Error(error.str())); } m_wire.parse(); Block::element_const_iterator val = m_wire.elements_begin(); if (val != m_wire.elements_end() && val->type() == tlv::nfd::FaceId) { m_faceId = readNonNegativeInteger(*val); ++val; } else { BOOST_THROW_EXCEPTION(Error("Missing required FaceId field")); } if (val != m_wire.elements_end() && val->type() == tlv::nfd::Origin) { m_origin = readNonNegativeInteger(*val); ++val; } else { BOOST_THROW_EXCEPTION(Error("Missing required Origin field")); } if (val != m_wire.elements_end() && val->type() == tlv::nfd::Cost) { m_cost = readNonNegativeInteger(*val); ++val; } else { BOOST_THROW_EXCEPTION(Error("Missing required Cost field")); } if (val != m_wire.elements_end() && val->type() == tlv::nfd::Mac) { m_mac = readNonNegativeInteger(*val); ++val; } else { BOOST_THROW_EXCEPTION(Error("Missing required Mac field")); } if (val != m_wire.elements_end() && val->type() == tlv::nfd::Flags) { m_flags = readNonNegativeInteger(*val); ++val; } else { BOOST_THROW_EXCEPTION(Error("Missing required Flags field")); } if (val != m_wire.elements_end() && val->type() == tlv::nfd::ExpirationPeriod) { m_expirationPeriod = time::milliseconds(readNonNegativeInteger(*val)); m_hasInfiniteExpirationPeriod = false; } else { m_expirationPeriod = INFINITE_EXPIRATION_PERIOD; m_hasInfiniteExpirationPeriod = true; } } std::ostream& operator<<(std::ostream& os, const Route& route) { os << "Route(" << "FaceId: " << route.getFaceId() << ", " << "Origin: " << route.getOrigin() << ", " << "Cost: " << route.getCost() << ", " << "Flags: " << route.getFlags() << ", "; if (!route.hasInfiniteExpirationPeriod()) { os << "ExpirationPeriod: " << route.getExpirationPeriod(); } else { os << "ExpirationPeriod: Infinity"; } os << ")"; return os; } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// RibEntry::RibEntry() { } RibEntry::RibEntry(const Block& block) { wireDecode(block); } template<encoding::Tag TAG> size_t RibEntry::wireEncode(EncodingImpl<TAG>& block) const { size_t totalLength = 0; for (std::list<Route>::const_reverse_iterator it = m_routes.rbegin(); it != m_routes.rend(); ++it) { totalLength += it->wireEncode(block); } totalLength += m_prefix.wireEncode(block); totalLength += block.prependVarNumber(totalLength); totalLength += block.prependVarNumber(tlv::nfd::RibEntry); return totalLength; } template size_t RibEntry::wireEncode<encoding::EncoderTag>(EncodingImpl<encoding::EncoderTag>& block) const; template size_t RibEntry::wireEncode<encoding::EstimatorTag>(EncodingImpl<encoding::EstimatorTag>& block) const; const Block& RibEntry::wireEncode() const { if (m_wire.hasWire()) { return m_wire; } EncodingEstimator estimator; size_t estimatedSize = wireEncode(estimator); EncodingBuffer buffer(estimatedSize, 0); wireEncode(buffer); m_wire = buffer.block(); return m_wire; } void RibEntry::wireDecode(const Block& wire) { m_prefix.clear(); m_routes.clear(); m_wire = wire; if (m_wire.type() != tlv::nfd::RibEntry) { std::stringstream error; error << "Expected RibEntry Block, but Block is of a different type: #" << m_wire.type(); BOOST_THROW_EXCEPTION(Error(error.str())); } m_wire.parse(); Block::element_const_iterator val = m_wire.elements_begin(); if (val != m_wire.elements_end() && val->type() == tlv::Name) { m_prefix.wireDecode(*val); ++val; } else { BOOST_THROW_EXCEPTION(Error("Missing required Name field")); } for (; val != m_wire.elements_end(); ++val) { if (val->type() == tlv::nfd::Route) { m_routes.push_back(Route(*val)); } else { std::stringstream error; error << "Expected Route Block, but Block is of a different type: #" << m_wire.type(); BOOST_THROW_EXCEPTION(Error(error.str())); } } } std::ostream& operator<<(std::ostream& os, const RibEntry& entry) { os << "RibEntry{\n" << " Name: " << entry.getName() << "\n"; for (RibEntry::iterator it = entry.begin(); it != entry.end(); ++it) { os << " " << *it << "\n"; } os << "}"; return os; } } // namespace nfd } // namespace ndn
gpl-3.0
Waikato/moa
moa/src/main/java/moa/gui/experimentertab/TaskTextViewerPanel.java
23382
/* * TaskTextViewerPanel.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author Jansen (moa@cs.rwth-aachen.de) * * 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 moa.gui.experimentertab; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import moa.evaluation.MeasureCollection; import moa.gui.FileExtensionFilter; import moa.gui.GUIUtils; import moa.gui.conceptdrift.CDTaskManagerPanel; import moa.gui.experimentertab.ExpPreviewPanel.TypePanel; import moa.streams.clustering.ClusterEvent; import moa.tasks.ConceptDriftMainTask; /** * This panel displays text. Used to output the results of tasks. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public class TaskTextViewerPanel extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; public static String exportFileExtension = "txt"; protected JTextArea textArea; protected JScrollPane scrollPane; protected JButton exportButton; private javax.swing.JPanel topWrapper; private javax.swing.JSplitPane jSplitPane1; //Added for stream events protected CDTaskManagerPanel taskManagerPanel; protected TypePanel typePanel; public void initVisualEvalPanel() { acc1[0] = getNewMeasureCollection(); acc2[0] = getNewMeasureCollection(); if (clusteringVisualEvalPanel1 != null) { panelEvalOutput.remove(clusteringVisualEvalPanel1); } clusteringVisualEvalPanel1 = new moa.gui.clustertab.ClusteringVisualEvalPanel(); clusteringVisualEvalPanel1.setMeasures(acc1, acc2, this); this.graphCanvas.setGraph(acc1[0], acc2[0], 0, 1000); this.graphCanvas.forceAddEvents(); clusteringVisualEvalPanel1.setMinimumSize(new java.awt.Dimension(280, 118)); clusteringVisualEvalPanel1.setPreferredSize(new java.awt.Dimension(290, 115)); panelEvalOutput.add(clusteringVisualEvalPanel1, gridBagConstraints); } public TaskTextViewerPanel() { this(TypePanel.CLASSIFICATION, null); } public java.awt.GridBagConstraints gridBagConstraints; public TaskTextViewerPanel(ExpPreviewPanel.TypePanel typePanel, CDTaskManagerPanel taskManagerPanel) { this.typePanel = typePanel; this.taskManagerPanel = taskManagerPanel; jSplitPane1 = new javax.swing.JSplitPane(); topWrapper = new javax.swing.JPanel(); this.textArea = new JTextArea(); this.textArea.setEditable(false); this.textArea.setFont(new Font("Monospaced", Font.PLAIN, 12)); this.exportButton = new JButton("Export as .txt file..."); this.exportButton.setEnabled(false); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(this.exportButton); topWrapper.setLayout(new BorderLayout()); this.scrollPane = new JScrollPane(this.textArea); topWrapper.add(this.scrollPane, BorderLayout.CENTER); topWrapper.add(buttonPanel, BorderLayout.SOUTH); this.exportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.addChoosableFileFilter(new FileExtensionFilter( exportFileExtension)); if (fileChooser.showSaveDialog(TaskTextViewerPanel.this) == JFileChooser.APPROVE_OPTION) { File chosenFile = fileChooser.getSelectedFile(); String fileName = chosenFile.getPath(); if (!chosenFile.exists() && !fileName.endsWith(exportFileExtension)) { fileName = fileName + "." + exportFileExtension; } try { PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(fileName))); out.write(TaskTextViewerPanel.this.textArea.getText()); out.close(); } catch (IOException ioe) { GUIUtils.showExceptionDialog( TaskTextViewerPanel.this.exportButton, "Problem saving file " + fileName, ioe); } } } }); //topWrapper.add(this.scrollPane); //topWrapper.add(buttonPanel); panelEvalOutput = new javax.swing.JPanel(); //clusteringVisualEvalPanel1 = new moa.gui.clustertab.ClusteringVisualEvalPanel(); graphPanel = new javax.swing.JPanel(); graphPanelControlTop = new javax.swing.JPanel(); buttonZoomInY = new javax.swing.JButton(); buttonZoomOutY = new javax.swing.JButton(); labelEvents = new javax.swing.JLabel(); graphScrollPanel = new javax.swing.JScrollPane(); graphCanvas = new moa.gui.visualization.GraphCanvas(); // New EventClusters //clusterEvents = new ArrayList<ClusterEvent>(); //clusterEvents.add(new ClusterEvent(this,100,"Change", "Drift")); //graphCanvas.setClusterEventsList(clusterEvents); graphPanelControlBottom = new javax.swing.JPanel(); buttonZoomInX = new javax.swing.JButton(); buttonZoomOutX = new javax.swing.JButton(); setLayout(new java.awt.GridBagLayout()); jSplitPane1.setDividerLocation(200); jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); //topWrapper.setPreferredSize(new java.awt.Dimension(688, 500)); //topWrapper.setLayout(new java.awt.GridBagLayout()); jSplitPane1.setLeftComponent(topWrapper); panelEvalOutput.setBorder(javax.swing.BorderFactory.createTitledBorder("Evaluation")); panelEvalOutput.setLayout(new java.awt.GridBagLayout()); //clusteringVisualEvalPanel1.setMinimumSize(new java.awt.Dimension(280, 118)); //clusteringVisualEvalPanel1.setPreferredSize(new java.awt.Dimension(290, 115)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weighty = 1.0; //panelEvalOutput.add(clusteringVisualEvalPanel1, gridBagConstraints); initVisualEvalPanel(); graphPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Plot")); graphPanel.setPreferredSize(new java.awt.Dimension(530, 115)); graphPanel.setLayout(new java.awt.GridBagLayout()); graphPanelControlTop.setLayout(new java.awt.GridBagLayout()); buttonZoomInY.setText("Zoom in Y"); buttonZoomInY.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonZoomInYActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); graphPanelControlTop.add(buttonZoomInY, gridBagConstraints); buttonZoomOutY.setText("Zoom out Y"); buttonZoomOutY.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonZoomOutYActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); graphPanelControlTop.add(buttonZoomOutY, gridBagConstraints); labelEvents.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); graphPanelControlTop.add(labelEvents, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; graphPanel.add(graphPanelControlTop, gridBagConstraints); graphCanvas.setPreferredSize(new java.awt.Dimension(500, 111)); javax.swing.GroupLayout graphCanvasLayout = new javax.swing.GroupLayout(graphCanvas); graphCanvas.setLayout(graphCanvasLayout); graphCanvasLayout.setHorizontalGroup( graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 515, Short.MAX_VALUE)); graphCanvasLayout.setVerticalGroup( graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 128, Short.MAX_VALUE)); graphScrollPanel.setViewportView(graphCanvas); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); graphPanel.add(graphScrollPanel, gridBagConstraints); buttonZoomInX.setText("Zoom in X"); buttonZoomInX.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonZoomInXActionPerformed(evt); } }); graphPanelControlBottom.add(buttonZoomInX); buttonZoomOutX.setText("Zoom out X"); buttonZoomOutX.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonZoomOutXActionPerformed(evt); } }); graphPanelControlBottom.add(buttonZoomOutX); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; graphPanel.add(graphPanelControlBottom, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 2.0; gridBagConstraints.weighty = 1.0; panelEvalOutput.add(graphPanel, gridBagConstraints); jSplitPane1.setRightComponent(panelEvalOutput); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(jSplitPane1, gridBagConstraints); // acc1[0] = getNewMeasureCollection(); //acc2[0] = getNewMeasureCollection(); //clusteringVisualEvalPanel1.setMeasures(acc1, acc2, this); //this.graphCanvas.setGraph(acc1[0], acc2[0], 0, 1000); } public void setText(String newText) { Point p = this.scrollPane.getViewport().getViewPosition(); this.textArea.setText(newText); this.scrollPane.getViewport().setViewPosition(p); this.exportButton.setEnabled(newText != null); setGraph(newText); } protected MeasureCollection[] acc1 = new MeasureCollection[1]; protected MeasureCollection[] acc2 = new MeasureCollection[1]; protected String secondLine = ""; protected double round(double d) { return (Math.rint(d * 100) / 100); } protected MeasureCollection getNewMeasureCollection() { /*if (this.taskManagerPanel != null) { return new ChangeDetectionMeasures(); } else { return new Accuracy(); }*/ return this.typePanel.getMeasureCollection(); } public void setGraph(String preview) { //Change the graph when there is change in the text double processFrequency = 1000; if (preview != null && !preview.equals("")) { MeasureCollection oldAccuracy = acc1[0]; acc1[0] = getNewMeasureCollection(); Scanner scanner = new Scanner(preview); String firstLine = scanner.nextLine(); boolean isSecondLine = true; boolean isPrequential = firstLine.startsWith("learning evaluation instances,evaluation time"); boolean isHoldOut = firstLine.startsWith("evaluation instances,to"); int accuracyColumn = 6; int kappaColumn = 4; int RamColumn = 2; int timeColumn = 1; int memoryColumn = 9; int kappaTempColumn = 5; if (this.taskManagerPanel instanceof CDTaskManagerPanel) { accuracyColumn = 6; kappaColumn = 4; RamColumn = 2; timeColumn = 1; memoryColumn = 9; } else if (isPrequential || isHoldOut) { accuracyColumn = 4; kappaColumn = 5; RamColumn = 2; timeColumn = 1; memoryColumn = 7; kappaTempColumn = 5; String[] tokensFirstLine = firstLine.split(","); int i = 0; for (String s : tokensFirstLine) { if (s.equals("classifications correct (percent)") || s.equals("[avg] classifications correct (percent)")) { accuracyColumn = i; } else if (s.equals("Kappa Statistic (percent)") || s.equals("[avg] Kappa Statistic (percent)")) { kappaColumn = i; } else if (s.equals("Kappa Temporal Statistic (percent)") || s.equals("[avg] Kappa Temporal Statistic (percent)")) { kappaTempColumn = i; } else if (s.equals("model cost (RAM-Hours)")) { RamColumn = i; } else if (s.equals("evaluation time (cpu seconds)") || s.equals("total train time")) { timeColumn = i; } else if (s.equals("model serialized size (bytes)")) { memoryColumn = i; } i++; } } if (isPrequential || isHoldOut || this.taskManagerPanel instanceof CDTaskManagerPanel) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] tokens = line.split(","); this.acc1[0].addValue(0, round(parseDouble(tokens[accuracyColumn]))); this.acc1[0].addValue(1, round(parseDouble(tokens[kappaColumn]))); this.acc1[0].addValue(2, round(parseDouble(tokens[kappaTempColumn]))); if (!isHoldOut) { this.acc1[0].addValue(3, Math.abs(parseDouble(tokens[RamColumn]))); } this.acc1[0].addValue(4, round(parseDouble(tokens[timeColumn]))); this.acc1[0].addValue(5, round(parseDouble(tokens[memoryColumn]) / (1024 * 1024))); if (isSecondLine == true) { processFrequency = Math.abs(parseDouble(tokens[0])); isSecondLine = false; if (acc1[0].getValue(0, 0) != oldAccuracy.getValue(0, 0)) { //(!line.equals(secondLine)) { //If we are in a new task, compare with the previous secondLine = line; if (processFrequency == this.graphCanvas.getProcessFrequency()) { acc2[0] = oldAccuracy; } } } } } else { this.acc2[0] = getNewMeasureCollection(); } } else { this.acc1[0] = getNewMeasureCollection(); this.acc2[0] = getNewMeasureCollection(); } if (this.taskManagerPanel instanceof CDTaskManagerPanel) { ConceptDriftMainTask cdTask = this.taskManagerPanel.getSelectedCurrenTask(); ArrayList<ClusterEvent> clusterEvents = cdTask.getEventsList(); this.graphCanvas.setClusterEventsList(clusterEvents); } this.graphCanvas.setGraph(acc1[0], acc2[0], this.graphCanvas.getMeasureSelected(), (int) processFrequency); this.graphCanvas.updateCanvas(true); this.graphCanvas.forceAddEvents(); this.clusteringVisualEvalPanel1.update(); } private double parseDouble(String s) { double ret = 0; if (s.equals("?") == false) { ret = Double.parseDouble(s); } return ret; } private void scrollPane0MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_scrollPane0MouseWheelMoved streamPanel0.setZoom(evt.getX(), evt.getY(), (-1) * evt.getWheelRotation(), scrollPane0); }//GEN-LAST:event_scrollPane0MouseWheelMoved private void buttonZoomInXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInXActionPerformed graphCanvas.scaleXResolution(false); }//GEN-LAST:event_buttonZoomInXActionPerformed private void buttonZoomOutYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutYActionPerformed graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 0.8))); graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 0.8))); this.graphCanvas.updateCanvas(true); }//GEN-LAST:event_buttonZoomOutYActionPerformed private void buttonZoomOutXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutXActionPerformed graphCanvas.scaleXResolution(true); }//GEN-LAST:event_buttonZoomOutXActionPerformed private void buttonZoomInYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInYActionPerformed graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 1.2))); graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 1.2))); this.graphCanvas.updateCanvas(true); }//GEN-LAST:event_buttonZoomInYActionPerformed private void buttonRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRunActionPerformed // TODO add your handling code here: }//GEN-LAST:event_buttonRunActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonRun; private javax.swing.JButton buttonScreenshot; private javax.swing.JButton buttonStop; private javax.swing.JButton buttonZoomInX; private javax.swing.JButton buttonZoomInY; private javax.swing.JButton buttonZoomOutX; private javax.swing.JButton buttonZoomOutY; private javax.swing.JCheckBox checkboxDrawClustering; private javax.swing.JCheckBox checkboxDrawGT; private javax.swing.JCheckBox checkboxDrawMicro; private javax.swing.JCheckBox checkboxDrawPoints; private moa.gui.clustertab.ClusteringVisualEvalPanel clusteringVisualEvalPanel1; private javax.swing.JComboBox comboX; private javax.swing.JComboBox comboY; private moa.gui.visualization.GraphCanvas graphCanvas; private javax.swing.JPanel graphPanel; private javax.swing.JPanel graphPanelControlBottom; private javax.swing.JPanel graphPanelControlTop; private javax.swing.JScrollPane graphScrollPanel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel labelEvents; private javax.swing.JLabel labelNumPause; private javax.swing.JLabel labelX; private javax.swing.JLabel labelY; private javax.swing.JLabel label_processed_points; private javax.swing.JLabel label_processed_points_value; private javax.swing.JTextField numPauseAfterPoints; private javax.swing.JPanel panelControl; private javax.swing.JPanel panelEvalOutput; private javax.swing.JPanel panelVisualWrapper; private javax.swing.JScrollPane scrollPane0; private javax.swing.JScrollPane scrollPane1; private javax.swing.JSlider speedSlider; private javax.swing.JSplitPane splitVisual; private moa.gui.visualization.StreamPanel streamPanel0; private moa.gui.visualization.StreamPanel streamPanel1; @Override public void actionPerformed(ActionEvent e) { //reacte on graph selection and find out which measure was selected int selected = Integer.parseInt(e.getActionCommand()); int counter = selected; int m_select = 0; int m_select_offset = 0; boolean found = false; for (int i = 0; i < acc1.length; i++) { for (int j = 0; j < acc1[i].getNumMeasures(); j++) { if (acc1[i].isEnabled(j)) { counter--; if (counter < 0) { m_select = i; m_select_offset = j; found = true; break; } } } if (found) { break; } } this.graphCanvas.setGraph(acc1[m_select], acc2[m_select], m_select_offset, this.graphCanvas.getProcessFrequency()); this.graphCanvas.forceAddEvents(); } }
gpl-3.0
jamesmacwhite/Radarr
src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs
4884
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace NzbDrone.Core.MetadataSource.RadarrAPI { public class Error { [JsonProperty("id")] public string RayId { get; set; } [JsonProperty("status")] public int Status { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("detail")] public string Detail { get; set; } } public class RadarrError { [JsonProperty("errors")] public IList<Error> Errors { get; set; } } public class RadarrAPIException : Exception { public RadarrError APIErrors; public RadarrAPIException(RadarrError apiError) : base(HumanReadable(apiError)) { APIErrors = apiError; } private static string HumanReadable(RadarrError apiErrors) { var firstError = apiErrors.Errors.First(); var details = string.Join("\n", apiErrors.Errors.Select(error => { return $"{error.Title} ({error.Status}, RayId: {error.RayId}), Details: {error.Detail}"; })); return $"Error while calling api: {firstError.Title}\nFull error(s): {details}"; } } public class TitleInfo { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("aka_title")] public string AkaTitle { get; set; } [JsonProperty("aka_clean_title")] public string AkaCleanTitle { get; set; } } public class YearInfo { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("aka_year")] public int AkaYear { get; set; } } public class Title { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("tmdbid")] public int Tmdbid { get; set; } [JsonProperty("votes")] public int Votes { get; set; } [JsonProperty("vote_count")] public int VoteCount { get; set; } [JsonProperty("locked")] public bool Locked { get; set; } [JsonProperty("info_type")] public string InfoType { get; set; } [JsonProperty("info_id")] public int InfoId { get; set; } [JsonProperty("info")] public TitleInfo Info { get; set; } } public class Year { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("tmdbid")] public int Tmdbid { get; set; } [JsonProperty("votes")] public int Votes { get; set; } [JsonProperty("vote_count")] public int VoteCount { get; set; } [JsonProperty("locked")] public bool Locked { get; set; } [JsonProperty("info_type")] public string InfoType { get; set; } [JsonProperty("info_id")] public int InfoId { get; set; } [JsonProperty("info")] public YearInfo Info { get; set; } } public class Mappings { [JsonProperty("titles")] public IList<Title> Titles { get; set; } [JsonProperty("years")] public IList<Year> Years { get; set; } } public class Mapping { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("imdb_id")] public string ImdbId { get; set; } [JsonProperty("mappings")] public Mappings Mappings { get; set; } } public class AddTitleMapping { [JsonProperty("tmdbid")] public string Tmdbid { get; set; } [JsonProperty("info_type")] public string InfoType { get; set; } [JsonProperty("info_id")] public int InfoId { get; set; } [JsonProperty("id")] public int Id { get; set; } [JsonProperty("info")] public TitleInfo Info { get; set; } [JsonProperty("votes")] public int Votes { get; set; } [JsonProperty("vote_count")] public int VoteCount { get; set; } [JsonProperty("locked")] public bool Locked { get; set; } } public class AddYearMapping { [JsonProperty("tmdbid")] public string Tmdbid { get; set; } [JsonProperty("info_type")] public string InfoType { get; set; } [JsonProperty("info_id")] public int InfoId { get; set; } [JsonProperty("id")] public int Id { get; set; } [JsonProperty("info")] public YearInfo Info { get; set; } [JsonProperty("votes")] public int Votes { get; set; } [JsonProperty("vote_count")] public int VoteCount { get; set; } [JsonProperty("locked")] public bool Locked { get; set; } } }
gpl-3.0
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/JRAbstractObjectFactory.java
5849
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.charts.JRAreaPlot; import net.sf.jasperreports.charts.JRBar3DPlot; import net.sf.jasperreports.charts.JRBarPlot; import net.sf.jasperreports.charts.JRBubblePlot; import net.sf.jasperreports.charts.JRCandlestickPlot; import net.sf.jasperreports.charts.JRCategoryDataset; import net.sf.jasperreports.charts.JRCategorySeries; import net.sf.jasperreports.charts.JRLinePlot; import net.sf.jasperreports.charts.JRPie3DPlot; import net.sf.jasperreports.charts.JRPieDataset; import net.sf.jasperreports.charts.JRPiePlot; import net.sf.jasperreports.charts.JRPieSeries; import net.sf.jasperreports.charts.JRTimePeriodDataset; import net.sf.jasperreports.charts.JRTimePeriodSeries; import net.sf.jasperreports.charts.JRTimeSeries; import net.sf.jasperreports.charts.JRTimeSeriesDataset; import net.sf.jasperreports.charts.JRXyzDataset; import net.sf.jasperreports.charts.JRXyzSeries; import net.sf.jasperreports.engine.base.JRBaseFont; /** * @author Teodor Danciu (teodord@users.sourceforge.net) */ public abstract class JRAbstractObjectFactory implements JRVisitor { /** * */ private Map<Object,Object> objectsMap = new HashMap<Object,Object>(); private Object visitResult; /** * */ protected Object get(Object object) { return objectsMap.get(object); } /** * */ public void put(Object object, Object copy) { objectsMap.put(object, copy); } /** * */ public Object getVisitResult(JRVisitable visitable) { if (visitable != null) { visitable.visit(this); return visitResult; } return null; } /** * */ protected void setVisitResult(Object visitResult) { this.visitResult = visitResult; } /** * */ public abstract JRStyle getStyle(JRStyle style); /** * Sets a style or a style reference on an object. * <p/> * If the container includes a style (see {@link JRStyleContainer#getStyle() getStyle()}, * a copy of this style will be created via {@link #getStyle(JRStyle) getStyle(JRStyle)} * and set on the object. * <p/> * In addition to this, the implementation needs to handle the case when the container includes * an external style reference (see {@link JRStyleContainer#getStyleNameReference() getStyleNameReference()}. * * @param setter a setter for the object on which the style should be set. * @param styleContainer the original style container * @see #getStyle(JRStyle) */ public abstract void setStyle(JRStyleSetter setter, JRStyleContainer styleContainer); /** * */ public JRFont getFont(JRStyleContainer styleContainer, JRFont font) { JRBaseFont baseFont = null; if (font != null) { baseFont = (JRBaseFont)get(font); if (baseFont == null) { baseFont = new JRBaseFont(styleContainer, font, this); } } return baseFont; } /** * */ public abstract JRPieDataset getPieDataset(JRPieDataset pieDataset); /** * */ public abstract JRPiePlot getPiePlot(JRPiePlot piePlot); /** * */ public abstract JRPie3DPlot getPie3DPlot(JRPie3DPlot pie3DPlot); /** * */ public abstract JRCategoryDataset getCategoryDataset(JRCategoryDataset categoryDataset); /** * */ public abstract JRTimeSeriesDataset getTimeSeriesDataset( JRTimeSeriesDataset timeSeriesDataset ); /** * */ public abstract JRTimePeriodDataset getTimePeriodDataset( JRTimePeriodDataset timePeriodDataset ); /** * */ public abstract JRTimePeriodSeries getTimePeriodSeries( JRTimePeriodSeries timePeriodSeries ); /** * */ public abstract JRTimeSeries getTimeSeries( JRTimeSeries timeSeries ); /** * */ public abstract JRPieSeries getPieSeries(JRPieSeries pieSeries); /** * */ public abstract JRCategorySeries getCategorySeries(JRCategorySeries categorySeries); /** * */ public abstract JRXyzDataset getXyzDataset( JRXyzDataset xyzDataset ); /** * */ public abstract JRXyzSeries getXyzSeries( JRXyzSeries xyzSeries ); /** * */ public abstract JRBarPlot getBarPlot(JRBarPlot barPlot); /** * */ public abstract JRBar3DPlot getBar3DPlot( JRBar3DPlot barPlot ); /** * */ public abstract JRLinePlot getLinePlot( JRLinePlot linePlot ); /** * */ public abstract JRAreaPlot getAreaPlot( JRAreaPlot areaPlot ); /** * */ public abstract JRBubblePlot getBubblePlot( JRBubblePlot bubblePlot ); /** * */ public abstract JRCandlestickPlot getCandlestickPlot(JRCandlestickPlot candlestickPlot); /** * */ public abstract JRConditionalStyle getConditionalStyle(JRConditionalStyle conditionalStyle, JRStyle parentStyle); public abstract JRExpression getExpression(JRExpression expression, boolean assignNotUsedId); public JRExpression getExpression(JRExpression expression) { return getExpression(expression, false); } }
gpl-3.0
ExistentialEnso/Snapplicator
Snapplicator/Areas/Wiki/Models/WikiArticle.cs
444
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; using Snapplicator.Models; namespace Snapplicator.Areas.Wiki.Models { public class WikiArticle : DbEntity { [Key] public int Id { get; set; } public string Title { get; set; } public string Body { get; set; } } }
gpl-3.0
aczwink/ACStdLib
src_backends/Cocoa/UI/CocoaPushButtonBackend.hh
1884
/* * Copyright (c) 2018 Amir Czwink (amir130@hotmail.de) * * This file is part of Std++. * * Std++ 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. * * Std++ 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 Std++. If not, see <http://www.gnu.org/licenses/>. */ //Global #undef new #include <Cocoa/Cocoa.h> //Local #include <Std++/_Backends/UI/PushButtonBackend.hpp> #import "CocoaWidgetBackend.hh" //Forward delcarations namespace _stdxx_ { class CocoaPushButtonBackend; } //Objective-C class @interface CocoaPushButton : NSButton -(id)initWithBackend:(_stdxx_::CocoaPushButtonBackend *)backend; - (void)OnClick:(id)OnClick; @end namespace _stdxx_ { class CocoaPushButtonBackend : public PushButtonBackend, public CocoaWidgetBackend { public: //Constructor CocoaPushButtonBackend(StdXX::UIBackend& uiBackend, StdXX::UI::PushButton *pushButton); //Destructor ~CocoaPushButtonBackend(); //Methods void Clicked(); StdXX::Math::SizeD GetSizeHint() const override; NSView *GetView() override; StdXX::UI::Widget &GetWidget() override; const StdXX::UI::Widget &GetWidget() const override; void SetEnabled(bool enable) override; void SetText(const StdXX::String &text) override; //OLD STUFF void Repaint() override; void SetEditable(bool enable) const override; //END OLD STUFF private: //Members StdXX::UI::PushButton *pushButton; CocoaPushButton *cocoaButton; }; }
gpl-3.0
anthonybrown/reaction
imports/plugins/core/address/client/components/ShopAddressValidationSettings.js
5308
import React, { Component } from "react"; import PropTypes from "prop-types"; import { i18next } from "/client/api"; import Button from "@reactioncommerce/components/Button/v1"; import { SortableTable } from "/imports/plugins/core/ui/client/components"; import AddressValidationSettingsForm from "./AddressValidationSettingsForm"; export default class ShopAddressValidationSettings extends Component { static propTypes = { addressValidationServices: PropTypes.arrayOf(PropTypes.shape({ displayName: PropTypes.string.isRequired, name: PropTypes.string.isRequired, supportedCountryCodes: PropTypes.arrayOf(PropTypes.string) })), countryOptions: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string.isRequired, value: PropTypes.string.isRequired })), enabledServices: PropTypes.arrayOf(PropTypes.shape({ countryCodes: PropTypes.arrayOf(PropTypes.string), serviceDisplayName: PropTypes.string.isRequired, serviceName: PropTypes.string.isRequired })), onItemAdded: PropTypes.func.isRequired, onItemDeleted: PropTypes.func.isRequired, onItemEdited: PropTypes.func.isRequired }; static defaultProps = { addressValidationServices: [], countryOptions: [], enabledServices: [] }; state = { isAdding: false, selectedServiceNameInAddForm: null } showAddForm = () => { this.setState({ isAdding: true }); }; hideAddForm = () => { this.setState({ isAdding: false }); }; handleAddFormSubmit = (...args) => { const { onItemAdded } = this.props; return onItemAdded(...args) .then((result) => { this.hideAddForm(); return result; }); }; handleAddFormSubmitButton = () => { if (this.addForm) { this.addForm.submit(); } }; handleAddFormChange = (doc) => { this.setState({ selectedServiceNameInAddForm: doc.serviceName }); }; get serviceOptions() { const { addressValidationServices } = this.props; return (addressValidationServices || []).map((addressValidationService) => ({ label: addressValidationService.displayName, value: addressValidationService.name })); } get supportedCountryOptions() { const { addressValidationServices, countryOptions } = this.props; const { selectedServiceNameInAddForm } = this.state; // Don't show any countries in the list until they've selected a service if (!selectedServiceNameInAddForm) return []; const selectedService = (addressValidationServices || []).find((service) => service.name === selectedServiceNameInAddForm); if (!selectedService || !Array.isArray(selectedService.supportedCountryCodes)) return countryOptions; return countryOptions.filter(({ value }) => selectedService.supportedCountryCodes.includes(value)); } renderAddForm() { return ( <div> <AddressValidationSettingsForm countryOptions={this.supportedCountryOptions} onChange={this.handleAddFormChange} onSubmit={this.handleAddFormSubmit} ref={(instance) => { this.addForm = instance; }} serviceOptions={this.serviceOptions} /> <div style={{ display: "flex", justifyContent: "flex-end" }}> <Button actionType="secondary" onClick={this.hideAddForm}>{i18next.t("addressValidation.cancelButtonText")}</Button> <div style={{ marginLeft: 14 }}> <Button actionType="important" onClick={this.handleAddFormSubmitButton}>{i18next.t("addressValidation.entryFormSubmitButtonText")}</Button> </div> </div> </div> ); } render() { const { addressValidationServices, enabledServices, onItemDeleted } = this.props; const { isAdding } = this.state; return ( <div className="clearfix"> <p>{i18next.t("addressValidation.helpText")}</p> <SortableTable className="-striped -highlight" data={enabledServices} columnMetadata={[ { accessor: "serviceDisplayName", Header: "Name" }, { accessor: (item) => { const countries = item.countryCodes || []; if (countries.length === 0) { const selectedService = (addressValidationServices || []).find((service) => service.name === item.serviceName); if (selectedService && selectedService.supportedCountryCodes) return selectedService.supportedCountryCodes.join(", "); return "All"; } return countries.join(", "); }, Header: "Countries", id: "countries" }, { accessor: "_id", Cell: (row) => ( <Button actionType="secondaryDanger" isShortHeight onClick={() => { onItemDeleted(row.value); }}> {i18next.t("addressValidation.deleteItemButtonText")} </Button> ) } ]} filterType="none" /> {!isAdding && <Button actionType="important" isFullWidth onClick={this.showAddForm}>{i18next.t("addressValidation.addNewItemButtonText")}</Button>} {!!isAdding && this.renderAddForm()} </div> ); } }
gpl-3.0
NULL-HDU/barrage-server
libs/color/color_test.go
405
package color import ( "testing" ) func TestWrapAndDye(t *testing.T) { t.Log(Dye(FgRed, "redString")) t.Log(Dye(Underline, Dye(FgYellow, "yellowBoldString"))) redStringWrap := New(FgRed).Wrap("redString") redStringDye := Dye(FgRed, "redString") if redStringDye != redStringWrap { t.Errorf("effort of wrap and dye should be same, but get wrap: %s; dye: %s", redStringWrap, redStringDye) } }
gpl-3.0
cristiangiagante/CustomRenderers
Tools/AddCustomFonts/AddCustomFonts/iOS.cs
3149
using System; using System.Collections.Generic; using System.IO; namespace AddCustomFonts { class iOS : Project { private DirectoryInfo _solutionName; private List<string> _files; private string _resourceFolder = "Resources\\Fonts"; private string _plistFile = "info.plist"; public iOS(DirectoryInfo solutionName, List<string> files) { _solutionName = solutionName; _files = files; } public void CreateResources() { var projectName = new DirectoryInfo(Path.Combine(_solutionName.FullName, _solutionName.Name, _solutionName.Name + ".iOS")); projectName.CreateSubdirectory(_resourceFolder); var resourceFolder = new DirectoryInfo(Path.Combine(projectName.FullName, _resourceFolder)); var rootPath = _solutionName.FullName.Split(new string[] { _solutionName.Name }, StringSplitOptions.RemoveEmptyEntries); var plistPath = Path.Combine(rootPath[0], _solutionName.Name, _solutionName.Name, projectName.Name, _plistFile); var plistFileRead = File.OpenText(plistPath); var content = plistFileRead.ReadToEnd(); plistFileRead.Close(); var nuevoPlistFile = File.Create(plistPath); var plistFileWrite = new StreamWriter(nuevoPlistFile); var keyPlistInfo = @"<key>UIAppFonts</key> <array>"; var tempPath = ""; string fontContent = ""; foreach (string file in _files) { var fileInfo = new FileInfo(file); tempPath = Path.Combine(rootPath[0], _solutionName.Name, _solutionName.Name, projectName.Name, _resourceFolder, fileInfo.Name); if (!File.Exists(tempPath)) { File.Copy(file, tempPath); fontContent += $@"<string>Fonts/{fileInfo.Name}</string>{Environment.NewLine}"; } } if (!string.IsNullOrEmpty(fontContent)) { if (content.Contains("UIAppFonts")) { int indexUIAppFonts = content.LastIndexOf(keyPlistInfo); int indexOffsetUIAppFonts = keyPlistInfo.Length; var newContent = content.Insert(indexUIAppFonts + indexOffsetUIAppFonts, Environment.NewLine + fontContent + Environment.NewLine); plistFileWrite.WriteLine(newContent); plistFileWrite.Close(); } else { int indexUIAppFonts = content.LastIndexOf("</dict>"); var newFontContent = keyPlistInfo + fontContent + $"</array>"; var newContent = content.Insert(indexUIAppFonts, Environment.NewLine + newFontContent + Environment.NewLine); plistFileWrite.WriteLine(newContent); plistFileWrite.Close(); } } else { plistFileWrite.WriteLine(content); plistFileWrite.Close(); } } } }
gpl-3.0
fahmyfarahat/AngularJS-RegisterSystem
app/scripts/controllers/about.js
348
'use strict'; /** * @ngdoc function * @name angularRegisterApp.controller:AboutCtrl * @description * # AboutCtrl * Controller of the angularRegisterApp */ angular.module('angularRegisterApp') .controller('AboutCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
gpl-3.0
WebDaD/StraTic
StraTic-Win/Forms/Editor/Campaign/Campaigns.Designer.cs
1160
namespace StraTic.Forms.Editor.Campaign { partial class Campaigns { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "Campaigns"; } #endregion } }
gpl-3.0
libis/Flandrica
themes/FLANDRICA/temp/js/lightbox.js
11633
/* Lightbox v2.51 by Lokesh Dhakar - http://www.lokeshdhakar.com For more information, visit: http://lokeshdhakar.com/projects/lightbox2/ Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ - free for use in both personal and commercial projects - attribution requires leaving author name, author link, and the license info intact Thanks - Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. - Artemy Tregubenko (arty.name) for cleanup and help in updating to latest proto-aculous in v2.05. Table of Contents ================= LightboxOptions Lightbox - constructor - init - enable - build - start - changeImage - sizeContainer - showImage - updateNav - updateDetails - preloadNeigbhoringImages - enableKeyboardNav - disableKeyboardNav - keyboardAction - end options = new LightboxOptions lightbox = new Lightbox options */ (function() { var $, Lightbox, LightboxOptions; $ = jQuery; LightboxOptions = (function() { function LightboxOptions() { this.fileLoadingImage = 'images/loading.gif'; this.fileCloseImage = 'images/close.png'; this.resizeDuration = 700; this.fadeDuration = 500; this.labelImage = "Image"; this.labelOf = "of"; } return LightboxOptions; })(); Lightbox = (function() { function Lightbox(options) { this.options = options; this.album = []; this.currentImageIndex = void 0; this.init(); } Lightbox.prototype.init = function() { this.enable(); return this.build(); }; Lightbox.prototype.enable = function() { var _this = this; return $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox]', function(e) { _this.start($(e.currentTarget)); return false; }); }; Lightbox.prototype.build = function() { var $lightbox, _this = this; $("<div>", { id: 'lightboxOverlay' }).after($('<div/>', { id: 'lightbox' }).append($('<div/>', { "class": 'lb-outerContainer' }).append($('<div/>', { "class": 'lb-container' }).append($('<img/>', { "class": 'lb-image' }), $('<div/>', { "class": 'lb-nav' }).append($('<a/>', { "class": 'lb-prev' }), $('<a/>', { "class": 'lb-next' })), $('<div/>', { "class": 'lb-loader' }).append($('<a/>', { "class": 'lb-cancel' }).append($('<img/>', { src: this.options.fileLoadingImage }))), $('<span/>', { "class": 'lb-caption' }), $('<div/>', { "class": 'lb-dataContainer' }).append($('<div/>', { "class": 'lb-data' }).append($('<div/>', { "class": 'lb-details' }), $('<span/>', { "class": 'lb-number' }), $('<div/>', { "class": 'lb-closeContainer' }).append($('<a/>', { "class": 'lb-close' }).append($('<img/>', { src: this.options.fileCloseImage }))))))))).appendTo($('body')); $('#lightboxOverlay').hide().on('click', function(e) { _this.end(); return false; }); $lightbox = $('#lightbox'); $lightbox.hide().on('click', function(e) { if ($(e.target).attr('id') === 'lightbox') _this.end(); return false; }); $lightbox.find('.lb-outerContainer').on('click', function(e) { if ($(e.target).attr('id') === 'lightbox') _this.end(); return false; }); $lightbox.find('.lb-prev').on('click', function(e) { _this.changeImage(_this.currentImageIndex - 1); return false; }); $lightbox.find('.lb-next').on('click', function(e) { _this.changeImage(_this.currentImageIndex + 1); return false; }); $lightbox.find('.lb-loader, .lb-close').on('click', function(e) { console.log('wtf'); _this.end(); return false; }); }; Lightbox.prototype.start = function($link) { var $lightbox, $window, a, i, imageNumber, left, top, _len, _ref; $(window).on("resize", this.sizeOverlay); $('select, object, embed').css({ visibility: "hidden" }); $('#lightboxOverlay').width($(document).width()).height($(document).height()).fadeIn(this.options.fadeDuration); this.album = []; imageNumber = 0; if ($link.attr('rel') === 'lightbox') { this.album.push({ link: $link.attr('href'), title: $link.attr('title') }); } else { _ref = $($link.prop("tagName") + '[rel="' + $link.attr('rel') + '"]'); for (i = 0, _len = _ref.length; i < _len; i++) { a = _ref[i]; this.album.push({ link: $(a).attr('href'), title: $(a).attr('title') }); if ($(a).attr('href') === $link.attr('href')) imageNumber = i; } } $window = $(window); top = $window.scrollTop() + $window.height() / 10; left = $window.scrollLeft(); $lightbox = $('#lightbox'); $lightbox.css({ top: top + 'px', left: left + 'px' }).fadeIn(this.options.fadeDuration); this.changeImage(imageNumber); }; Lightbox.prototype.changeImage = function(imageNumber) { var $image, $lightbox, preloader, _this = this; this.disableKeyboardNav(); $lightbox = $('#lightbox'); $image = $lightbox.find('.lb-image'); this.sizeOverlay(); $('#lightboxOverlay').fadeIn(this.options.fadeDuration); $('.loader').fadeIn('slow'); $lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide(); $lightbox.find('.lb-outerContainer').addClass('animating'); preloader = new Image; preloader.onload = function() { $image.attr('src', _this.album[imageNumber].link); $image.width = preloader.width; $image.height = preloader.height; return _this.sizeContainer(preloader.width, preloader.height); }; preloader.src = this.album[imageNumber].link; this.currentImageIndex = imageNumber; }; Lightbox.prototype.sizeOverlay = function() { return $('#lightboxOverlay').width($(document).width()).height($(document).height()); }; Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) { var $container, $lightbox, $outerContainer, containerBottomPadding, containerLeftPadding, containerRightPadding, containerTopPadding, newHeight, newWidth, oldHeight, oldWidth, _this = this; $lightbox = $('#lightbox'); $outerContainer = $lightbox.find('.lb-outerContainer'); oldWidth = $outerContainer.outerWidth(); oldHeight = $outerContainer.outerHeight(); $container = $lightbox.find('.lb-container'); containerTopPadding = parseInt($container.css('padding-top'), 10); containerRightPadding = parseInt($container.css('padding-right'), 10); containerBottomPadding = parseInt($container.css('padding-bottom'), 10); containerLeftPadding = parseInt($container.css('padding-left'), 10); newWidth = imageWidth + containerLeftPadding + containerRightPadding; newHeight = imageHeight + containerTopPadding + containerBottomPadding; if (newWidth !== oldWidth && newHeight !== oldHeight) { $outerContainer.animate({ width: newWidth, height: newHeight }, this.options.resizeDuration, 'swing'); } else if (newWidth !== oldWidth) { $outerContainer.animate({ width: newWidth }, this.options.resizeDuration, 'swing'); } else if (newHeight !== oldHeight) { $outerContainer.animate({ height: newHeight }, this.options.resizeDuration, 'swing'); } setTimeout(function() { $lightbox.find('.lb-dataContainer').width(newWidth); $lightbox.find('.lb-prevLink').height(newHeight); $lightbox.find('.lb-nextLink').height(newHeight); _this.showImage(); }, this.options.resizeDuration); }; Lightbox.prototype.showImage = function() { var $lightbox; $lightbox = $('#lightbox'); $lightbox.find('.lb-loader').hide(); $lightbox.find('.lb-image').fadeIn('slow'); this.updateNav(); this.updateDetails(); this.preloadNeighboringImages(); this.enableKeyboardNav(); }; Lightbox.prototype.updateNav = function() { var $lightbox; $lightbox = $('#lightbox'); $lightbox.find('.lb-nav').show(); if (this.currentImageIndex > 0) $lightbox.find('.lb-prev').show(); if (this.currentImageIndex < this.album.length - 1) { $lightbox.find('.lb-next').show(); } }; Lightbox.prototype.updateDetails = function() { var $lightbox, _this = this; $lightbox = $('#lightbox'); if (typeof this.album[this.currentImageIndex].title !== 'undefined' && this.album[this.currentImageIndex].title !== "") { $lightbox.find('.lb-caption').html(this.album[this.currentImageIndex].title).fadeIn('fast'); } if (this.album.length > 1) { $lightbox.find('.lb-number').html(this.options.labelImage + ' ' + (this.currentImageIndex + 1) + ' ' + this.options.labelOf + ' ' + this.album.length).fadeIn('fast'); } else { $lightbox.find('.lb-number').hide(); } $lightbox.find('.lb-outerContainer').removeClass('animating'); $lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration, function() { return _this.sizeOverlay(); }); }; Lightbox.prototype.preloadNeighboringImages = function() { var preloadNext, preloadPrev; if (this.album.length > this.currentImageIndex + 1) { preloadNext = new Image; preloadNext.src = this.album[this.currentImageIndex + 1].link; } if (this.currentImageIndex > 0) { preloadPrev = new Image; preloadPrev.src = this.album[this.currentImageIndex - 1].link; } }; Lightbox.prototype.enableKeyboardNav = function() { $(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this)); }; Lightbox.prototype.disableKeyboardNav = function() { $(document).off('.keyboard'); }; Lightbox.prototype.keyboardAction = function(event) { var KEYCODE_ESC, KEYCODE_LEFTARROW, KEYCODE_RIGHTARROW, key, keycode; KEYCODE_ESC = 27; KEYCODE_LEFTARROW = 37; KEYCODE_RIGHTARROW = 39; keycode = event.keyCode; key = String.fromCharCode(keycode).toLowerCase(); if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) { this.end(); } else if (key === 'p' || keycode === KEYCODE_LEFTARROW) { if (this.currentImageIndex !== 0) { this.changeImage(this.currentImageIndex - 1); } } else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) { if (this.currentImageIndex !== this.album.length - 1) { this.changeImage(this.currentImageIndex + 1); } } }; Lightbox.prototype.end = function() { this.disableKeyboardNav(); $(window).off("resize", this.sizeOverlay); $('#lightbox').fadeOut(this.options.fadeDuration); $('#lightboxOverlay').fadeOut(this.options.fadeDuration); return $('select, object, embed').css({ visibility: "visible" }); }; return Lightbox; })(); $(function() { var lightbox, options; options = new LightboxOptions; return lightbox = new Lightbox(options); }); }).call(this);
gpl-3.0
aynu/yukar
src/yukar-framework/src/main/java/com/github/aynu/yukar/framework/lang/DataObject.java
733
// ---------------------------------------------------------------------------- // Copyright (C) Yukar Evolution Laboratory. All rights reserved. // GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 // http://www.gnu.org/licenses/gpl-3.0-standalone.html // ---------------------------------------------------------------------------- package com.github.aynu.yukar.framework.lang; import java.io.Serializable; /** * 基底データオブジェクトI/F * <dl> * <dt>使用条件 * <dd>全データオブジェクトの基底クラスのI/Fとすること。 * </dl> * @param <T> データオブジェクト型 * @author nilcy */ public interface DataObject<T extends DataObject<T>> extends Serializable { }
gpl-3.0
MarlonWelter/CRFTool
CRFToolApp/MainWindow.xaml.cs
848
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CRFToolApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); CRFToolAppBase.Build.Do(); CRFBase.Build.Do(); Build.Do(); //userDecisionUI.SetUserOptions( new string[] { "A", "B", "C"}); } } }
gpl-3.0
moritzfl/sorting-algorithms
src/main/java/de/moritzf/sorting/logic/sorting/steps/InsertionStep.java
1920
package de.moritzf.sorting.logic.sorting.steps; import java.util.Arrays; import java.util.StringJoiner; /** * This class represents a step within the insertion sort algorithm. * * @author Moritz Floeter */ public class InsertionStep { /** * The Sorted marker. */ private int sortedMarker; /** * The Search marker. */ private int searchMarker; /** * The Memory. */ private int memory; /** * The Array. */ private int[] array; /** * Instantiates a new Insertion step. * * @param sortedMarker the sorted marker * @param searchMarker the search marker * @param memory the memory * @param array the array */ public InsertionStep(int sortedMarker, int searchMarker, int memory, int[] array) { this.sortedMarker = sortedMarker; this.searchMarker = searchMarker; this.memory = memory; this.array = array; } /** * Gets sorted marker. * * @return the sorted marker */ public int getSortedMarker() { return sortedMarker; } /** * Gets search marker. * * @return the search marker */ public int getSearchMarker() { return searchMarker; } /** * Gets memory. * * @return the memory */ public int getMemory() { return memory; } /** * Get array int [ ]. * * @return the int [ ] */ public int[] getArray() { return array; } @Override public String toString() { return new StringJoiner(", ", this.getClass().getSimpleName() + "[", "]") .add("array = " + Arrays.toString(array)) .add("memory = " + memory) .add("searchMarker = " + searchMarker) .add("sortedMarker = " + sortedMarker) .toString(); } }
gpl-3.0
m3rlin87/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f8.lua
696
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Titan's Gate -- !pos 260 -34 88 195 ----------------------------------- local ID = require("scripts/zones/The_Eldieme_Necropolis/IDs"); require("scripts/globals/keyitems"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (npc:getAnimation() == 9) then if (player:hasKeyItem(dsp.ki.MAGICKED_ASTROLABE)) then npc:openDoor(8); else player:messageSpecial(ID.text.SOLID_STONE); end end return 0; end; -- function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
fanruan/finereport-design
designer_chart/src/com/fr/plugin/chart/custom/CustomPlotDesignerPaneFactory.java
5767
package com.fr.plugin.chart.custom; import com.fr.chart.chartattr.Plot; import com.fr.design.beans.BasicBeanPane; import com.fr.design.mainframe.chart.gui.ChartDataPane; import com.fr.design.mainframe.chart.gui.data.table.AbstractTableDataContentPane; import com.fr.design.mainframe.chart.gui.data.table.CategoryPlotTableDataContentPane; import com.fr.general.FRLogger; import com.fr.plugin.chart.PiePlot4VanChart; import com.fr.plugin.chart.attr.plot.VanChartAxisPlot; import com.fr.plugin.chart.attr.plot.VanChartPlot; import com.fr.plugin.chart.bubble.VanChartBubblePlot; import com.fr.plugin.chart.bubble.data.VanChartBubblePlotTableDataContentPane; import com.fr.plugin.chart.custom.component.CustomPlotLocationPane; import com.fr.plugin.chart.custom.type.CustomPlotType; import com.fr.plugin.chart.designer.style.VanChartStylePane; import com.fr.plugin.chart.designer.style.axis.VanChartAxisPane; import com.fr.plugin.chart.designer.style.axis.gauge.VanChartGaugeAxisPane; import com.fr.plugin.chart.gauge.VanChartGaugePlot; import com.fr.plugin.chart.radar.VanChartRadarPlot; import com.fr.plugin.chart.scatter.VanChartScatterPlot; import com.fr.plugin.chart.scatter.data.VanChartScatterPlotTableDataContentPane; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; /** * Created by Mitisky on 16/6/23. */ public class CustomPlotDesignerPaneFactory { //图表类型对应数据配置界面 private static Map<Class<? extends Plot>, Class<? extends AbstractTableDataContentPane>> plotTableDataContentPaneMap = new HashMap<Class<? extends Plot>, Class<? extends AbstractTableDataContentPane>>(); //图表类型对应的位置面板 private static Map<Class<? extends Plot>, Class<? extends BasicBeanPane<Plot>>> plotPositionMap = new HashMap<Class<? extends Plot>, Class<? extends BasicBeanPane<Plot>>>(); static { plotPositionMap.put(PiePlot4VanChart.class, CustomPlotLocationPane.class); plotPositionMap.put(VanChartRadarPlot.class, CustomPlotLocationPane.class); plotPositionMap.put(VanChartGaugePlot.class, CustomPlotLocationPane.class); } /** * 根据图表类型创建位置面板 * @param plot 图表 * @return 位置面板 */ public static BasicBeanPane<Plot> createCustomPlotPositionPane(Plot plot) { Class<? extends Plot> key = plot.getClass(); if(plotPositionMap.containsKey(key)){ try{ Class<? extends BasicBeanPane<Plot>> cl = plotPositionMap.get(key); Constructor<? extends BasicBeanPane<Plot> > constructor = cl.getConstructor(); return constructor.newInstance(); } catch (Exception e){ FRLogger.getLogger().error(e.getMessage()); } } return null; } /** * 每种类型对应的数据配置界面 * @return */ static { plotTableDataContentPaneMap.put(VanChartScatterPlot.class, VanChartScatterPlotTableDataContentPane.class); plotTableDataContentPaneMap.put(VanChartBubblePlot.class, VanChartBubblePlotTableDataContentPane.class); } /** * 根据图表类型创建数据配置 * @param plot 图表 * @param parent * @return 数据配置界面 */ public static AbstractTableDataContentPane createCustomPlotTableDataContentPane(Plot plot, ChartDataPane parent) { Class<? extends Plot> key = plot.getClass(); if(plotTableDataContentPaneMap.containsKey(key)){ try{ Class<? extends AbstractTableDataContentPane> cl = plotTableDataContentPaneMap.get(key); Constructor<? extends AbstractTableDataContentPane > constructor = cl.getConstructor(ChartDataPane.class); return constructor.newInstance(parent); } catch (Exception e){ FRLogger.getLogger().error(e.getMessage()); } } return new CategoryPlotTableDataContentPane(parent); } /** * plotType是否需要建立新的坐标系面板 */ private static Map<CustomPlotType, Class<? extends VanChartAxisPane>> diffAxisMap = new HashMap<CustomPlotType, Class<? extends VanChartAxisPane>>(); static { diffAxisMap.put(CustomPlotType.POINTER_360, VanChartGaugeAxisPane.class); diffAxisMap.put(CustomPlotType.POINTER_180, VanChartGaugeAxisPane.class); diffAxisMap.put(CustomPlotType.RING, VanChartGaugeAxisPane.class); diffAxisMap.put(CustomPlotType.SLOT, VanChartGaugeAxisPane.class); diffAxisMap.put(CustomPlotType.CUVETTE, VanChartGaugeAxisPane.class); diffAxisMap.put(CustomPlotType.RADAR, null);//默认的为null,直接new,不用反射 diffAxisMap.put(CustomPlotType.STACK_RADAR, null); } public static Boolean isUseDiffAxisPane(VanChartPlot plot){ CustomPlotType customPlotType = CustomPlotFactory.getCustomType(plot); return diffAxisMap.containsKey(customPlotType); } public static VanChartAxisPane createAxisPane(VanChartAxisPlot plot, VanChartStylePane parent) { CustomPlotType key = CustomPlotFactory.getCustomType((VanChartPlot)plot); if(diffAxisMap.containsKey(key)){ try{ Class<? extends VanChartAxisPane> cl = diffAxisMap.get(key); if(cl != null) { Constructor<? extends VanChartAxisPane> constructor = cl.getConstructor(VanChartAxisPlot.class, VanChartStylePane.class); return constructor.newInstance(plot, parent); } } catch (Exception e){ FRLogger.getLogger().error(e.getMessage()); } } return new VanChartAxisPane(plot,parent); } }
gpl-3.0
Firebottle/Firebot
gui/app/services/data-access.service.js
236
"use strict"; (function() { const dataAccess = require("../../backend/common/data-access.js"); angular .module("firebotApp") .factory("dataAccess", function() { return dataAccess; }); }());
gpl-3.0
acressity/acressity
narratives/migrations/0002_narrative_gallery.py
540
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('narratives', '0001_initial'), ('photologue', '0001_initial'), ] operations = [ migrations.AddField( model_name='narrative', name='gallery', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='photologue.Gallery'), ), ]
gpl-3.0
claudiubrehoi/TrainingProject
src/main/java/com/synertrade/training/dao/AddressDAO.java
1155
package com.synertrade.training.dao; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.synertrade.training.util.HibernateUtil; import com.synertrade.training.vo.TrainingAddressVO; public class AddressDAO { public List<TrainingAddressVO> getAddresses(int streetId) { List<TrainingAddressVO> addresses; String query = ""; Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); if(streetId == -1) { query = "from TrainingAddressVO"; } else { query = "from TrainingAddressVO WHERE STREET_ID = " + streetId; } Query q = session.createQuery(query); addresses = (List<TrainingAddressVO>) q.list(); for(TrainingAddressVO addr : addresses) { Hibernate.initialize(addr.getStreet()); Hibernate.initialize(addr.getStreet().getCity()); Hibernate.initialize(addr.getStreet().getCity().getCountry()); Hibernate.initialize(addr.getUsers()); } tx.commit(); HibernateUtil.closeSession(); return addresses; } }
gpl-3.0
ProductionReady/Eleflex
V2.1/src/Versioning Module/Eleflex.Versioning.Storage.SqlServer/App_Start/AutoMapperConfig.cs
1771
#region PRODUCTION READY® ELEFLEX® Software License. Copyright © 2015 Production Ready, LLC. All Rights Reserved. //Copyright © 2015 Production Ready, LLC. All Rights Reserved. //For more information, visit http://www.ProductionReady.com //This file is part of PRODUCTION READY® ELEFLEX®. // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU Affero 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 Affero General Public License for more details. // //You should have received a copy of the GNU Affero General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using Bootstrap.AutoMapper; using AutoMapper; using AutoMapper.Mappers; using DomainModel = Eleflex.Versioning; using StorageModel = Eleflex.Versioning.Storage.SqlServer.Model; namespace Eleflex.Versioning.Storage.SqlServer { /// <summary> /// Registers AutoMapper configurations used in this assembly. /// </summary> public class AutoMapperConfig : IMapCreator { /// <summary> /// Create mappings. /// </summary> /// <param name="mapper"></param> public void CreateMap(IProfileExpression mapper) { //ModuleVersion mapper.CreateMap<DomainModel.ModuleVersion, StorageModel.ModuleVersion>(); mapper.CreateMap<StorageModel.ModuleVersion, DomainModel.ModuleVersion>(); } } }
gpl-3.0
srs-bsns/Realistic-Terrain-Generation
src/main/java/rtg/world/biome/realistic/vanilla/RealisticBiomeVanillaSunflowerPlains.java
3793
package rtg.world.biome.realistic.vanilla; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import rtg.api.config.BiomeConfig; import rtg.api.util.WorldUtil.Terrain; import rtg.api.world.RTGWorld; import rtg.api.world.deco.DecoBaseBiomeDecorations; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; import rtg.api.world.terrain.heighteffect.GroundEffect; import rtg.api.world.biome.RealisticBiomeBase; public class RealisticBiomeVanillaSunflowerPlains extends RealisticBiomeBase { public static Biome biome = Biomes.MUTATED_PLAINS; public static Biome river = Biomes.RIVER; public RealisticBiomeVanillaSunflowerPlains() { super(biome); } @Override public void initConfig() { } @Override public TerrainBase initTerrain() { return new TerrainVanillaSunflowerPlains(); } @Override public SurfaceBase initSurface() { return new SurfaceVanillaSunflowerPlains(getConfig(), biome.topBlock, biome.fillerBlock); } @Override public void initDecos() { DecoBaseBiomeDecorations decoBaseBiomeDecorations = new DecoBaseBiomeDecorations(); this.addDeco(decoBaseBiomeDecorations); } public class TerrainVanillaSunflowerPlains extends TerrainBase { private GroundEffect groundEffect = new GroundEffect(4f); public TerrainVanillaSunflowerPlains() { } @Override public float generateNoise(RTGWorld rtgWorld, int x, int y, float border, float river) { //return terrainPlains(x, y, simplex, river, 160f, 10f, 60f, 200f, 65f); return riverized(65f + groundEffect.added(rtgWorld, x, y), river); } } public class SurfaceVanillaSunflowerPlains extends SurfaceBase { public SurfaceVanillaSunflowerPlains(BiomeConfig config, IBlockState top, IBlockState filler) { super(config, top, filler); } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); float c = Terrain.calcCliff(x, z, noise); boolean cliff = c > 1.4f ? true : false; for (int k = 255; k > -1; k--) { Block b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (cliff) { if (depth > -1 && depth < 2) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble(rtgWorld, i, j, x, z, k)); } else { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else if (depth < 10) { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else { if (depth == 0 && k > 61) { primer.setBlockState(x, k, z, topBlock); } else if (depth < 4) { primer.setBlockState(x, k, z, fillerBlock); } } } } } } }
gpl-3.0
l0b0/cronlist
src/crontab/entry/stepped_range/mod.rs
1509
extern crate num; use self::num::Integer; use std::fmt::Debug; use std::ops::Add; pub struct SteppedRange<T> where for<'a> &'a T: Add<&'a T, Output = T>, T: Clone, T: Debug, T: Integer, { pub start: T, pub end: T, // TODO: Use NonZero trait when stable pub step: T, } impl<T> SteppedRange<T> where for<'a> &'a T: Add<&'a T, Output = T>, T: Clone, T: Debug, T: Integer, { pub fn new(start: T, end: T, step: T) -> SteppedRange<T> { assert_ne!(step, T::zero()); SteppedRange { start, end, step } } } impl<T> Iterator for SteppedRange<T> where for<'a> &'a T: Add<&'a T, Output = T>, T: Clone, T: Debug, T: Integer, { type Item = T; fn next(&mut self) -> Option<T> { if self.start < self.end { let current = self.start.clone(); self.start = &self.start + &self.step; Some(current) } else { None } } } #[cfg(test)] mod tests { use super::SteppedRange; #[test] fn should_return_none_for_empty_range() { let mut range = SteppedRange::new(0, 0, 1); assert_eq!(range.next(), None); } #[test] fn should_return_one_item_for_trivial_range() { let mut range = SteppedRange::new(0, 1, 1); assert_eq!(range.next(), Some(0)); assert_eq!(range.next(), None); } #[test] #[should_panic] fn should_fail_with_step_of_zero() { SteppedRange::new(0, 0, 0); } }
gpl-3.0
hforge/itools
itools/python/python.py
2866
# -*- coding: UTF-8 -*- # Copyright (C) 2005 Luis Arturo Belmar-Letelier <luis@itaapy.com> # Copyright (C) 2005-2009 J. David Ibáñez <jdavid.ibp@gmail.com> # Copyright (C) 2008 David Versmisse <versmisse@lil.univ-littoral.fr> # Copyright (C) 2008 Matthieu France <matthieu@itaapy.com> # Copyright (C) 2008 Sylvain Taverne <taverne.sylvain@gmail.com> # Copyright (C) 2008 Wynand Winterbach <wynand.winterbach@gmail.com> # Copyright (C) 2009 Aurélien Ansel <camumus@gmail.com> # # 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/>. # Import from the Standard Library from ast import parse, Attribute, Name, NodeVisitor, Str # Import from itools from itools.handlers import TextFile, register_handler_class from itools.srx import TEXT class VisitorMSG(NodeVisitor): def __init__(self): self.messages = [] def visit_Call(self, node): if isinstance(node.func, Attribute): try: func = node.func.value.func node = node.func.value except: func = node.func else: func = node.func # Other items for e in node.args: self.visit(e) for e in node.keywords: self.visit(e) if node.starargs: self.visit(node.starargs) if node.kwargs: self.visit(node.kwargs) # Check names if isinstance(func, Name): if func.id in ('MSG', 'INFO', 'ERROR'): text = node.args[0] if isinstance(text, Str): if type(text.s) is unicode and text.s.strip(): # Context = None msg = ((TEXT, text.s),), None, node.lineno self.messages.append(msg) class Python(TextFile): class_mimetypes = ['text/x-python'] class_extension = 'py' def get_units(self, srx_handler=None): data = self.to_str() # Make it work with Windows files (the parser expects '\n' ending # lines) data = ''.join([ x + '\n' for x in data.splitlines() ]) # Parse and Walk ast = parse(data) visitor = VisitorMSG() visitor.generic_visit(ast) return visitor.messages # Register register_handler_class(Python)
gpl-3.0
Nettacker/Nettacker
lib/scan/pma/pma.py
3978
def pma(): return ['/admin/', '/accounts/login/', '/admin1.php/', '/admin.php/', '/admin.html/', '/admin1.php/', '/admin1.html/', '/login.php/', '/admin/cp.php/', '/cp.php/', '/administrator/index.php/', '/administrator/index.html/', '/administartor/', '/admin.login/', '/administrator/login.php/', '/administrator/login.html/', '/phpMyAdmin/', '/phpmyadmin/', '/PMA/', '/pma/', '/dbadmin/', '/mysql/', '/myadmin/', '/phpmyadmin2/', '/phpMyAdmin2/', '/phpMyAdmin-2/', '/php-my-admin/', '/phpMyAdmin-2.2.3/', '/phpMyAdmin-2.2.6/', '/phpMyAdmin-2.5.1/', '/phpMyAdmin-2.5.4/', '/phpMyAdmin-2.5.5-rc1/', '/phpMyAdmin-2.5.5-rc2/', '/phpMyAdmin-2.5.5/', '/phpMyAdmin-2.5.5-pl1/', '/phpMyAdmin-2.5.6-rc1/', '/phpMyAdmin-2.5.6-rc2/', '/phpMyAdmin-2.5.6/', '/phpMyAdmin-2.5.7/', '/phpMyAdmin-2.5.7-pl1/', '/phpMyAdmin-2.6.0-alpha/', '/phpMyAdmin-2.6.0-alpha2/', '/phpMyAdmin-2.6.0-beta1/', '/phpMyAdmin-2.6.0-beta2/', '/phpMyAdmin-2.6.0-rc1/', '/phpMyAdmin-2.6.0-rc2/', '/phpMyAdmin-2.6.0-rc3/', '/phpMyAdmin-2.6.0/', '/phpMyAdmin-2.6.0-pl1/', '/phpMyAdmin-2.6.0-pl2/', '/phpMyAdmin-2.6.0-pl3/', '/phpMyAdmin-2.6.1-rc1/', '/phpMyAdmin-2.6.1-rc2/', '/phpMyAdmin-2.6.1/', '/phpMyAdmin-2.6.1-pl1/', '/phpMyAdmin-2.6.1-pl2/', '/phpMyAdmin-2.6.1-pl3/', '/phpMyAdmin-2.6.2-rc1/', '/phpMyAdmin-2.6.2-beta1/', '/phpMyAdmin-2.6.2-rc1/', '/phpMyAdmin-2.6.2/', '/phpMyAdmin-2.6.2-pl1/', '/phpMyAdmin-2.6.3/', '/phpMyAdmin-2.6.3-rc1/', '/phpMyAdmin-2.6.3/', '/phpMyAdmin-2.6.3-pl1/', '/phpMyAdmin-2.6.4-rc1/', '/phpMyAdmin-2.6.4-pl1/', '/phpMyAdmin-2.6.4-pl2/', '/phpMyAdmin-2.6.4-pl3/', '/phpMyAdmin-2.6.4-pl4/', '/phpMyAdmin-2.6.4/', '/phpMyAdmin-2.7.0-beta1/', '/phpMyAdmin-2.7.0-rc1/', '/phpMyAdmin-2.7.0-pl1/', '/phpMyAdmin-2.7.0-pl2/', '/phpMyAdmin-2.7.0/', '/phpMyAdmin-2.8.0-beta1/', '/phpMyAdmin-2.8.0-rc1/', '/phpMyAdmin-2.8.0-rc2/', '/phpMyAdmin-2.8.0/', '/phpMyAdmin-2.8.0.1/', '/phpMyAdmin-2.8.0.2/', '/phpMyAdmin-2.8.0.3/', '/phpMyAdmin-2.8.0.4/', '/phpMyAdmin-2.8.1-rc1/', '/phpMyAdmin-2.8.1/', '/phpMyAdmin-2.8.2/', '/sqlmanager/', '/mysqlmanager/', '/p/m/a/', '/PMA2005/', '/pma2005/', '/phpmanager/', '/php-myadmin/', '/phpmy-admin/', '/webadmin/', '/sqlweb/', '/websql/', '/webdb/', '/mysqladmin/', '/mysql-admin/', '/mya/', '/mysql/admin/', '/mysql/dbadmin/', '/mysql/sqlmanager/', '/mysql/mysqlmanager/', '/phpMyadmin/', '/phpmyAdmin/', '/phpmyadmin3/', '/phpmyadmin4/', '/2phpmyadmin/', '/phpmy/', '/phppma/', '/db/phpmyadmin/', '/db/phpMyAdmin/', '/admin/phpmyadmin/', '/admin/phpMyAdmin/', '/admin/sysadmin/', '/admin/sqladmin/', '/admin/db/', '/admin/web/', '/admin/pMA/', '/mysql/pma/', '/mysql/pMA/', '/sql/phpmanager/', '/sql/php-myadmin/', '/sql/phpmy-admin/', '/sql/myadmin/', '/sql/webadmin/', '/sql/sqlweb/', '/sql/websql/', '/sql/webdb/', '/sql/sqladmin/', '/sql/sql-admin/', '/sql/phpmyadmin2/', '/sql/phpMyAdmin2/', '/sql/phpMyAdmin/', '/db/myadmin/', '/db/webadmin/', '/db/websql/', '/db/dbadmin/', '/db/db-admin/', '/db/phpmyadmin3/', '/db/phpMyAdmin3/', '/db/phpMyAdmin-3/', '/administrator/phpmyadmin/', '/administrator/phpMyAdmin/', '/administrator/pma/', '/administrator/PMA/', '/phpMyAdmin3/', '/phpMyAdmin4/', '/phpMyAdmin-3/', '/PMA2011/', '/PMA2012/', '/PMA2013/', '/PMA2014/', '/PMA2015/', '/PMA2016/', '/PMA2017/', '/PMA2018/', '/pma2011/', '/pma2012/', '/pma2013/', '/pma2014/', '/pma2015/', '/pma2016/', '/pma2017/', '/pma2018/', '/phpmyadmin2011/', '/phpmyadmin2012/', '/phpmyadmin2013/', '/phpmyadmin2014/', '/phpmyadmin2015/', '/phpmyadmin2016/', '/phpmyadmin2017/', '/phpmyadmin2018/',]
gpl-3.0
unixunited/Talos
Source/Component/NetworkComponent.hpp
3052
// ========================================================================= // // Talos - A 3D game engine with network multiplayer. // Copyright(C) 2015 Jordan Sparks <unixunited@live.com> // // 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/>. // ========================================================================= // // File: NetworkComponent.hpp // Author: Jordan Sparks <unixunited@live.com> // ========================================================================= // // Defines NetworkComponent class. // ========================================================================= // #ifndef __NETWORKCOMPONENT_HPP__ #define __NETWORKCOMPONENT_HPP__ // ========================================================================= // #include "ActorComponent.hpp" #include "Command/CommandTypes.hpp" #include "Network/Update.hpp" // ========================================================================= // // Handles client-side network needs such as client-side prediction, and // server reconciliation. class NetworkComponent : public Component { public: // Default initializes member data. explicit NetworkComponent(void); // Empty. virtual ~NetworkComponent(void) override; // Empty. virtual void init(void) override; // Empty. virtual void destroy(void) override; // Applies server reconciliation to associated actor component. virtual void update(void) override; // Handles command and transform update messages. virtual void message(ComponentMessage& msg) override; // Setters: // Sets internal actor component pointer. void setActorComponentPtr(const ActorComponentPtr actorC); // === // // An input the client has sent but not yet received an update for from the // server. struct PendingCommand{ CommandType type; Ogre::Quaternion yawOrientation; Ogre::Quaternion pitchOrientation; uint32_t sequenceNumber; }; private: // Commands not yet applied by server. std::list<PendingCommand> m_pendingCommands; // Pending server updates that need to be applied locally. std::queue<TransformUpdate> m_serverUpdates; // Have direct access to actor component, the coupling here is acceptable. ActorComponentPtr m_actorC; }; // ========================================================================= // #endif // ========================================================================= //
gpl-3.0
nibblebits/PNPZ80
PNPZ80/src/PNPZ80.cpp
911
/* This source file is protected under the GPL License V3. Please view the file called "COPYING" to view the license with your rights for this source file and the rest of the PNPZ80 project. If the license in the file "COPYING" was not included in this distribution you may find it here: http://www.gnu.org/licenses/gpl.txt*/ #include "PNPZ80.h" extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful }
gpl-3.0
ragnarka/rj-brewery
common/client/gaugeDemo.js
3037
let Highcharts = require('highcharts'); require('highcharts/modules/funnel')(Highcharts); Template.gaugeDemo.helpers({ allTasks: function () { return Session.get("tasks") || 12; }, incompleteTasks: function () { return Session.get("incompleteTasks") || 7; }, gaugeChart: function () { // Gather data: var allTasks = Session.get("tasks") || 12, incompleteTask = Session.get("incompleteTasks") || 3, tasksData = [{ y: incompleteTask, name: "Incomplete" }, { y: allTasks - incompleteTask, name: "Complete" }]; // Use Meteor.defer() to craete chart after DOM is ready: Meteor.defer(function () { // Create standard Highcharts chart with options: Highcharts.chart('chart', { series: [{ type: 'pie', data: tasksData }], credits: { enabled: false } }); }); } }); Template.gaugeDemo.events({ 'submit #f': (event) => { event.preventDefault(); var data = $("#f").serializeArray(); Session.set("tasks", parseInt(data[0].value)); Session.set("incompleteTasks", parseInt(data[1].value)); } }); Template.funnelDemo.helpers({ funnelChart: function () { // Use Meteor.defer() to craete chart after DOM is ready: Meteor.defer(function () { // Create standard Highcharts chart with options: Highcharts.chart('chart', { chart: { type: 'funnel', marginRight: 100 }, title: { text: 'Sales funnel', x: -50 }, plotOptions: { series: { dataLabels: { enabled: true, format: '<b>{point.name}</b> ({point.y:,.0f})', color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black', softConnector: true }, neckWidth: '30%', neckHeight: '25%' //-- Other available options // height: pixels or percent // width: pixels or percent } }, legend: { enabled: false }, series: [{ name: 'Unique users', data: [ ['Website visits', 15654], ['Downloads', 4064], ['Requested price list', 1987], ['Invoice sent', 976], ['Finalized', 846] ] }] }); }); } });
gpl-3.0
eternallyBaffled/itrade
tests/test_itrade_login.py
672
import unittest import itrade_login class EmptyLoginRegistryTestCase(unittest.TestCase): def setUp(self): self.reg = itrade_login.LoginRegistry() def tearDown(self): # conspicuous absence of clean-up logic self.reg = None def test_creation(self): self.assertIsNotNone(self.reg, "LoginRegistry creation failed.") def test_get_empty(self): self.assertIsNone(self.reg.get("any"), "Getting anything from an empty registry should return None.") def test_list_empty(self): self.assertEqual(self.reg.list(), [], "Expected empty list from empty registry.") if __name__ == '__main__': unittest.main()
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/google/i/a/a/a/k.java
450
package com.google.i.a.a.a; import com.google.c.a.a.b.c; public final class k { public static final c a; static { c localc = new c(); a = localc; localc.a(533, 1, null).a(533, 2, null).a(1054, 3, null).a(1054, 4, null).a(1054, 5, null).a(533, 6, null).a(533, 7, null).a(1054, 8, null).a(1054, 9, null); } } /* Location: classes_dex2jar.jar * Qualified Name: com.google.i.a.a.a.k * JD-Core Version: 0.6.2 */
gpl-3.0
toncis/InDonat
forms/kontakt/prigovor/frmprigovorjop.cpp
1157
// // frmprigovorjop.cpp // // Author: // Tonči Sviličić <tonci.svilicic@in2.hr> // // Copyright (c) 2012 Tonči Sviličić // // 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/>. #include "frmprigovorjop.h" #include "ui_frmprigovorjop.h" namespace Kontakt { // [Class Constuctor] FrmPrigovorJop::FrmPrigovorJop(QWidget *parent) : QDialog(parent), ui(new Ui::FrmPrigovorJop) { ui->setupUi(this); } FrmPrigovorJop::~FrmPrigovorJop() { delete ui; } // [Event Handlers] void FrmPrigovorJop::on_btnPotvrda_clicked() { } }
gpl-3.0
Banana4Life/Disconnect
core/src/de/cubeisland/games/entity/ActivatedDoor.java
439
package de.cubeisland.games.entity; import de.cubeisland.games.tile.TileType; public class ActivatedDoor extends AbstractDoor { public ActivatedDoor(int x, int y, TileType type) { super(x, y, type); } @Override public void open() { super.open(); this.type = TileType.AUTO_DOOR; } @Override public void close() { super.close(); this.type = TileType.AUTO_DOOR; } }
gpl-3.0
delletenebre/xbmc-addon-kilogramme
plugin.video.kilogramme/resources/lib/site_onair.py
23356
#!/usr/bin/python # -*- coding: utf-8 -*- import re, json, urllib, traceback from _header import * BASE_URL = 'http://www.onair.kg/api/' BASE_NAME = 'OnAir' BASE_LABEL = 'onair' #GA_CODE = 'UA-337170-16' SETT_DAYS = plugin.get_setting('onair_news_count', int) NK_CODE = '4094' @plugin.route('/site/' + BASE_LABEL) def onair_index(): item_list = get_categories(BASE_URL) items = [] if item_list: items = [{ 'label' : item['title'], 'path' : plugin.url_for('get_all_by_category', id = item['id']), 'thumbnail' : item['icon'], } for item in item_list] items = [{ 'label': set_color('[ Поиск ]', 'dialog', True), 'path': plugin.url_for('onair_search'), 'icon': get_local_icon('find'), }, { 'label': set_color('Последние поступления', 'light', True), 'path': plugin.url_for('onair_lastadded'), }, { 'label': set_color('Популярные - ТОП 10', 'bright', True), 'path': plugin.url_for('onair_popular'), }] + items else: plugin.notify('Сервер недоступен', BASE_NAME, image=get_local_icon('noty_' + BASE_LABEL)) return items @plugin.route('/site/' + BASE_LABEL + '/search') def onair_search(): search_val = plugin.keyboard('', 'Что ищете?') if (search_val): item_list = get_search(search_val) items = [{ 'label' : item['label'], 'path' : plugin.url_for(item['function'], id = item['id'], title = to_utf8(item['title'])) if item['function'] else item['url'], 'thumbnail' : item['icon'], 'info' : item['info'] if item['function'] == False else None, 'properties' : item['properties'] if item['function'] == False else None, 'is_playable': True if item['function'] == False else False } for item in item_list] return items else: plugin.redirect('plugin://' + plugin.id + '/site/' + BASE_LABEL) @plugin.route('/site/' + BASE_LABEL + '/last') def onair_lastadded(): item_list = get_lastadded() items = [{ 'label' : item['label'], 'path' : plugin.url_for(item['function'], id = item['id'], title = to_utf8(item['title'])) if item['function'] else item['url'], 'thumbnail' : item['icon'], 'info' : item['info'] if item['function'] == False else None, 'properties' : item['properties'] if item['function'] == False else None, 'is_playable': True if item['function'] == False else False } for item in item_list] return items @plugin.route('/site/' + BASE_LABEL + '/popular') def onair_popular(): item_list = get_popular() items = [{ 'label' : item['label'], 'path' : plugin.url_for(item['function'], id = item['id'], title = to_utf8(item['title'])) if item['function'] else item['url'], 'thumbnail' : item['icon'], 'info' : item['info'] if item['function'] == False else None, 'properties' : item['properties'] if item['function'] == False else None, 'is_playable': True if item['function'] == False else False } for item in item_list] return items @plugin.route('/site/' + BASE_LABEL + '/all/<id>') def get_all_by_category(id): item_list = get_list(id) items = [{ 'label' : item['title'], 'path' : plugin.url_for(item['function'], id = item['id'], title = to_utf8(item['title'])) if item['function'] else item['url'], 'thumbnail' : item['icon'], 'info' : item['info'] if item['function'] == False else None, 'properties' : item['properties'] if item['function'] == False else None, 'is_playable': True if item['function'] == False else False } for item in item_list['items']] return items @plugin.route('/site/' + BASE_LABEL + '/movie/<id>') def onair_movie(id): item_list = get_movies(id) items = [{ 'label' : item['title'], 'path' : item['url'], 'thumbnail' : item['icon'], 'info' : item['info'], 'properties' : item['properties'], 'is_playable': True } for item in item_list] return items @plugin.route('/site/' + BASE_LABEL + '/movies/genre/<id>') def onair_movies_by_genre(id): item_list = get_movies('movies/genres/' + str(id)) items = [{ 'label' : item['title'], 'path' : item['url'], 'thumbnail' : item['icon'], 'info' : item['info'], 'properties' : item['properties'], 'is_playable': True } for item in item_list] return items @plugin.route('/site/' + BASE_LABEL + '/movies/country/<id>') def onair_movies_by_country(id): item_list = get_movies('movies/countries/' + str(id)) items = [{ 'label' : item['title'], 'path' : item['url'], 'thumbnail' : item['icon'], 'info' : item['info'], 'properties' : item['properties'], 'is_playable': True } for item in item_list] return items @plugin.route('/site/' + BASE_LABEL + '/tvshow/<id>') def onair_serial(id): title = plugin.request.args['title'][0] item_list = get_tvshow_seasons(id, title) items = [{ 'label' : item['title'], 'path' : plugin.url_for('onair_season', id = id, season_id = item['season_id'], season_num = item['season_num'], title = to_utf8(title)), 'thumbnail' : item['icon'], 'is_not_folder': True, } for item in item_list['items']] return items @plugin.route('/site/' + BASE_LABEL + '/tvshows/genre/<id>') def onair_serials_by_genre(id): item_list = get_tvshows_by_genre(id) items = [{ 'label' : item['title'], 'path' : plugin.url_for('onair_serial', id = item['id'], title = to_utf8(item['title'])), 'thumbnail' : item['icon'], } for item in item_list['items']] return items @plugin.route('/site/' + BASE_LABEL + '/tvshows/country/<id>') def onair_serials_by_country(id): item_list = get_tvshows_by_country(id) items = [{ 'label' : item['title'], 'path' : plugin.url_for('onair_serial', id = item['id'], title = to_utf8(item['title'])), 'thumbnail' : item['icon'], } for item in item_list['items']] return items @plugin.route('/site/' + BASE_LABEL + '/tvshow/<id>/season/<season_id>/<season_num>') def onair_season(id, season_id, season_num): title = plugin.request.args['title'][0] plugin.notify('Пожалуйста, подождите', BASE_NAME, 1000, get_local_icon('noty_' + BASE_LABEL)) item_list = get_episodes(season_id, title, season_num) kgontv_playlist(item_list) xbmc.executebuiltin('ActivateWindow(VideoPlaylist)') # method def get_lastadded(): items = [] try: result = common.fetchPage({'link': BASE_URL + 'films/novelties'}) if result['status'] == 200: jsonrs = json.loads(result['content']) setting_days = -1 for jsonr in reversed(jsonrs): if setting_days == SETT_DAYS: break; setting_days = setting_days + 1 date = jsonr['Date'] + '&emsp;' films = jsonr['Films'] for item in films: if 'Type' in item: item_type = item['Type'] if item_type == 'Movie': movie_jsonr = common.fetchPage({'link': BASE_URL + 'movies/' + str(item['Id'])}) if movie_jsonr['status'] == 200: item = json.loads(movie_jsonr['content']) cover = item['PosterFile'] href = item['VideoFile'] info = { 'duration' : str2minutes(item['Duration']) if item['Duration'] else 0, 'plot' : item['Description'], } imdb = str(item['ImdbRating']) kinopoisk = str(item['KinopoiskRating']) rating = '&emsp;' + imdb + ' / ' + kinopoisk country = item['Countries'] genres = item['Genres'] properties = { #'Country': country, #'PlotOutline': item['description'], 'Plot': item['Description'], 'Year': str(item['ReleaseYear']), 'Rating': imdb } country = '&emsp;(' + country + ')' if (country) else '' label = common.replaceHTMLCodes( date + '[B]' + item['Title'] + '[/B]' + country + '&emsp;' + genres + rating ) title = common.replaceHTMLCodes( item['Title'] ) items.append({ 'label': label, 'title': title, 'icon': cover, 'url': href, 'info': info, 'properties': properties, 'function': False, }) elif item_type == 'Serial': id = item['Id'] title = common.replaceHTMLCodes( item['Title'] ) label = item['Title'] if 'AdditionalInfo' in item: label = item['AdditionalInfo'].replace(label, '[B]' + label + '[/B]') label = common.replaceHTMLCodes( date + label ) icon = item['PosterFile'] items.append({ 'label': label, 'title': title, 'icon': icon, 'id': id, 'function': 'onair_serial' }) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return items # method def get_popular(): items = [] try: result = common.fetchPage({'link': BASE_URL + 'films/popular'}) if result['status'] == 200: jsonrs = json.loads(result['content']) for item in jsonrs: if 'Type' in item: item_type = item['Type'] if item_type == 'Movie': movie_jsonr = common.fetchPage({'link': BASE_URL + 'movies/' + str(item['Id'])}) if movie_jsonr['status'] == 200: item = json.loads(movie_jsonr['content']) cover = item['PosterFile'] href = item['VideoFile'] info = { 'duration' : str2minutes(item['Duration']) if item['Duration'] else 0, 'plot' : item['Description'], } imdb = str(item['ImdbRating']) kinopoisk = str(item['KinopoiskRating']) rating = '&emsp;' + imdb + ' / ' + kinopoisk country = item['Countries'] genres = item['Genres'] properties = { #'Country': country, #'PlotOutline': item['description'], 'Plot': item['Description'], 'Year': str(item['ReleaseYear']), 'Rating': imdb } country = '&emsp;(' + country + ')' if (country) else '' label = common.replaceHTMLCodes( '[B]' + item['Title'] + '[/B]' + country + '&emsp;' + genres + rating ) title = common.replaceHTMLCodes( item['Title'] ) items.append({ 'label': label, 'title': title, 'icon': cover, 'url': href, 'info': info, 'properties': properties, 'function': False, }) elif item_type == 'Serial': id = item['Id'] title = common.replaceHTMLCodes( item['Title'] ) label = common.replaceHTMLCodes( '[B]' + item['Title'] + '[/B]' ) icon = item['PosterFile'] items.append({ 'label': label, 'title': title, 'icon': icon, 'id': id, 'function': 'onair_serial' }) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return items #method def get_categories(url): items = [] try: items.append({'title':'Фильмы', 'icon':'', 'id':10}) items.append({'title':'Фильмы по жанрам', 'icon':'', 'id':11}) items.append({'title':'Фильмы по стране', 'icon':'', 'id':12}) items.append({'title':'Сериалы', 'icon':'', 'id':20}) items.append({'title':'Сериалы по жанрам', 'icon':'', 'id':21}) items.append({'title':'Сериалы по стране', 'icon':'', 'id':22}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return items #method def get_list(id): items = [] if ( id == '10' ) : return {'items': get_movies('movies')} try: apiurl = { '11' : 'movies/genres', '12' : 'movies/countries', '20' : 'serials', '21' : 'serials/genres', '22' : 'serials/countries', }.get(id, 'movies') function = { '11' : 'onair_movies_by_genre', '12' : 'onair_movies_by_country', '20' : 'onair_serial', '21' : 'onair_serials_by_genre', '22' : 'onair_serials_by_country', }.get(id, 'movies') result = common.fetchPage({'link': BASE_URL + apiurl}) if result['status'] == 200: jsonr = json.loads(result['content']) for item in jsonr: id = item['Id'] title = item['Name'] if item['Name'] != '-' else 'Без категории' icon = '' items.append({'title':common.replaceHTMLCodes( title ), 'icon':icon, 'id':id, 'function':function}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return {'items':items} #method def get_movies(url): items = [] try: result = common.fetchPage({'link': BASE_URL + url}) if result['status'] == 200: jsonrs = json.loads(result['content']) for jsonr in jsonrs: cover = jsonr['PosterFile'] href = jsonr['VideoFile'] info = { 'duration' : str2minutes(jsonr['Duration']) if jsonr['Duration'] else 0, 'plot' : jsonr['Description'], } imdb = str(jsonr['ImdbRating']) kinopoisk = str(jsonr['KinopoiskRating']) rating = '&emsp;' + imdb + ' / ' + kinopoisk country = jsonr['Countries'] genres = jsonr['Genres'] properties = { #'Country': country, #'PlotOutline': jsonr['description'], 'Plot': jsonr['Description'], 'Year': str(jsonr['ReleaseYear']), 'Rating': imdb } country = '&emsp;(' + country + ')' if (country) else '' title = common.replaceHTMLCodes('[B]' + jsonr['Title'] + '[/B]' + country + '&emsp;' + genres + rating) items.append({'function':False, 'title':title, 'icon':cover, 'url':href, 'info':info, 'properties':properties}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return items #method def get_tvshow_seasons(id, title): items = [] tvshow_title = title.decode('utf-8') title = '' try: result = common.fetchPage({'link': BASE_URL + 'serials/' + str(id) + '/seasons'}) if result['status'] == 200: jsonr = json.loads(result['content']) for item in jsonr: season_id = item['Id'] title = tvshow_title + '&emsp;' + item['Name'] icon = '' items.append({'title':common.replaceHTMLCodes( title ), 'icon':icon, 'season_id':season_id, 'tvshow_title':tvshow_title, 'season_num':item['Name'][6:]}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return {'items':items} #method def get_tvshow_season_episodes(id, title): items = [] tvshow_title = title.decode('utf-8') title = '' try: result = common.fetchPage({'link': BASE_URL + 'seasons/' + str(id) + '/episodes'}) if result['status'] == 200: jsonr = json.loads(result['content']) for item in jsonr: season_id = item['Id'] title = tvshow_title + '&emsp;' + item['Name'] icon = '' items.append({'title':common.replaceHTMLCodes( title ), 'icon':icon, 'season_id':season_id, 'tvshow_title':tvshow_title}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return {'items':items} #method def get_tvshows_by_genre(id): items = [] try: result = common.fetchPage({'link': BASE_URL + 'serials/genres/' + str(id)}) if result['status'] == 200: jsonr = json.loads(result['content']) for item in jsonr: id = item['Id'] title = item['Name'] if item['Name'] != '-' else 'Без категории' icon = '' items.append({'title':common.replaceHTMLCodes( title ), 'icon':icon, 'id':id}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return {'items':items} #method def get_tvshows_by_country(id): items = [] try: result = common.fetchPage({'link': BASE_URL + 'serials/countries/' + str(id)}) if result['status'] == 200: jsonr = json.loads(result['content']) for item in jsonr: id = item['Id'] title = item['Name'] if item['Name'] != '-' else 'Без категории' icon = '' items.append({'title':common.replaceHTMLCodes( title ), 'icon':icon, 'id':id}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return {'items':items} #method def get_episodes(id, season_title, season_num): items = [] try: result = common.fetchPage({'link': BASE_URL + 'seasons/' + str(id) + '/episodes'}) if result['status'] == 200: jsonrs = json.loads(result['content']) for jsonr in jsonrs: icon = '' href = jsonr['VideoFile'] info = { 'duration' : str2minutes(jsonr['Duration']) if jsonr['Duration'] else 0, 'plot' : jsonr['Description'], } title = common.replaceHTMLCodes(season_title.decode('utf-8') + '&emsp;' + 's' + season_num + 'e' + jsonr['Number'] + '&emsp;' + jsonr['Title']) items.append({'title': title, 'url': href, 'icon': icon, 'info':info}) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return items #method def get_search(val): items = [] try: result = common.fetchPage({'link': BASE_URL + 'films/search?title=' + str(val)}) if result['status'] == 200: jsonrs = json.loads(result['content']) for item in jsonrs: item_type = item['Type'] if item_type == 'Movie': movie_jsonr = common.fetchPage({'link': BASE_URL + 'movies/' + str(item['Id'])}) if movie_jsonr['status'] == 200: item = json.loads(movie_jsonr['content']) cover = item['PosterFile'] href = item['VideoFile'] info = { 'duration' : str2minutes(item['Duration']) if item['Duration'] else 0, 'plot' : item['Description'], } imdb = str(item['ImdbRating']) kinopoisk = str(item['KinopoiskRating']) rating = '&emsp;' + imdb + ' / ' + kinopoisk country = item['Countries'] genres = item['Genres'] properties = { #'Country': country, #'PlotOutline': item['description'], 'Plot': item['Description'], 'Year': str(item['ReleaseYear']), 'Rating': imdb } country = '&emsp;(' + country + ')' if (country) else '' label = common.replaceHTMLCodes( '[B]' + item['Title'] + '[/B]' + country + '&emsp;' + genres + rating ) title = common.replaceHTMLCodes( item['Title'] ) items.append({ 'label': label, 'title': title, 'icon': cover, 'url': href, 'info': info, 'properties': properties, 'function': False, }) elif item_type == 'Serial': id = item['Id'] title = common.replaceHTMLCodes( item['Title'] ) label = common.replaceHTMLCodes( '[B]' + item['Title'] + '[/B]' ) icon = item['PosterFile'] items.append({ 'label': label, 'title': title, 'icon': icon, 'id': id, 'function': 'onair_serial' }) except: xbmc.log(traceback.format_exc(), xbmc.LOGERROR) return items
gpl-3.0
GeoKnow/LinkedGeoData
linkedgeodata-core/src/main/java/org/aksw/linkedgeodata/web/main/MainLinkedGeoDataRestServer.java
5181
package org.aksw.linkedgeodata.web.main; import java.net.URL; import java.net.URLClassLoader; import java.security.ProtectionDomain; import javax.servlet.ServletException; import org.aksw.commons.util.slf4j.LoggerCount; import org.aksw.linkedgeodata.web.api.RDFWriterHtml; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.jena.rdf.model.impl.RDFWriterFImpl; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.bio.SocketConnector; import org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* class HtmlWriter implements RDFWriter { @Override public void write(Model model, Writer out, String base) { // TODO Auto-generated method stub } @Override public void write(Model model, OutputStream out, String base) { // TODO Auto-generated method stub } @Override public Object setProperty(String propName, Object propValue) { // TODO Auto-generated method stub return null; } @Override public RDFErrorHandler setErrorHandler(RDFErrorHandler errHandler) { // TODO Auto-generated method stub return null; } } */ /** * * * http://stackoverflow.com/questions/10738816/deploying-a-servlet- * programmatically-with-jetty * http://stackoverflow.com/questions/3718221/add-resources * -to-jetty-programmatically * * @author raven * * */ public class MainLinkedGeoDataRestServer { private static final Logger logger = LoggerFactory.getLogger(MainLinkedGeoDataRestServer.class); private static final Options cliOptions = new Options(); static { cliOptions.addOption("P", "port", true, "Server port"); cliOptions.addOption("s", "service", true, "Sparql service url"); } public static void printClassPath() { ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader)cl).getURLs(); for(URL url: urls){ System.out.println(url.getFile()); } } // Source: // http://eclipsesource.com/blogs/2009/10/02/executable-wars-with-jetty/ public static void main(String[] args) throws Exception { RDFWriterFImpl.setBaseWriterClassName("HTML", RDFWriterHtml.class.getName()); LoggerCount loggerCount = new LoggerCount(logger); //Class.forName("org.postgresql.Driver"); CommandLineParser cliParser = new GnuParser(); CommandLine commandLine = cliParser.parse(cliOptions, args); String portStr = commandLine.getOptionValue("P", "9998"); int port = Integer.parseInt(portStr); AppConfig.lgdServiceUrl = commandLine.getOptionValue("s", "http://linkedgeodata.org/vsparql"); ProtectionDomain protectionDomain = MainLinkedGeoDataRestServer.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); String externalForm = location.toExternalForm(); logger.debug("External form: " + externalForm); // Try to detect whether we are being run from an // archive (uber jar / war) or just from compiled classes if(externalForm.endsWith("/classes/")) { externalForm = "src/main/webapp"; //externalForm = "target/sparqlify-web-admin-server"; } logger.debug("Loading webAppContext from " + externalForm); startServer(port, externalForm); } public static void startServer(int port, String externalForm) { Server server = new Server(); SocketConnector connector = new SocketConnector(); // Set some timeout options to make debugging easier. connector.setMaxIdleTime(1000 * 60 * 60); connector.setSoLingerTime(-1); connector.setPort(port); server.setConnectors(new Connector[] { connector }); final WebAppContext webAppContext = new WebAppContext(); webAppContext.addLifeCycleListener(new AbstractLifeCycleListener() { @Override public void lifeCycleStarting(LifeCycle arg0) { WebAppInitializer initializer = new WebAppInitializer(); try { initializer.onStartup(webAppContext.getServletContext()); } catch (ServletException e) { throw new RuntimeException(e); } } }); webAppContext.setServer(server); webAppContext.setContextPath("/"); //context.setDescriptor(externalForm + "/WEB-INF/web.xml"); webAppContext.setWar(externalForm); server.setHandler(webAppContext); try { server.start(); System.in.read(); server.stop(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
gpl-3.0
gqsteven/shuyaoTest
src/main/java/com/shuyao/modules/sys/service/SysConfigService.java
1184
package com.shuyao.modules.sys.service; import java.util.List; import java.util.Map; import com.shuyao.modules.sys.entity.SysConfigEntity; /** * 系统配置信息 * * @author shuyao * @email shuyao@gmail.com * @date 2017-09-02 */ public interface SysConfigService { /** * 保存配置信息 */ public void save(SysConfigEntity config); /** * 更新配置信息 */ public void update(SysConfigEntity config); /** * 根据key,更新value */ public void updateValueByKey(String key, String value); /** * 删除配置信息 */ public void deleteBatch(Long[] ids); /** * 获取List列表 */ public List<SysConfigEntity> queryList(Map<String, Object> map); /** * 获取总记录数 */ public int queryTotal(Map<String, Object> map); public SysConfigEntity queryObject(Long id); /** * 根据key,获取配置的value值 * * @param key key * @param defaultValue 缺省值 */ public String getValue(String key, String defaultValue); /** * 根据key,获取value的Object对象 * @param key key * @param clazz Object对象 */ public <T> T getConfigObject(String key, Class<T> clazz); }
gpl-3.0
jdber1/opendrop
opendrop/app/keyboard.py
1891
# Copyright © 2020, Joseph Berry, Rico Tabor (opendrop.dev@gmail.com) # OpenDrop is released under the GNU GPL License. You are free to # modify and distribute the code, but always under the same license # # If you use this software in your research, please cite the following # journal articles: # # J. D. Berry, M. J. Neeson, R. R. Dagastine, D. Y. C. Chan and # R. F. Tabor, Measurement of surface and interfacial tension using # pendant drop tensiometry. Journal of Colloid and Interface Science 454 # (2015) 226–237. https://doi.org/10.1016/j.jcis.2015.05.012 # # E. Huang, T. Denning, A. Skoufis, J. Qi, R. R. Dagastine, R. F. Tabor # and J. D. Berry, OpenDrop: Open-source software for pendant drop # tensiometry & contact angle measurements, submitted to the Journal of # Open Source Software # # These citations help us not only to understand who is using and # developing OpenDrop, and for what purpose, but also to justify # continued development of this code and other open source resources. # # OpenDrop is distributed 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 software. If not, see <https://www.gnu.org/licenses/>. from enum import IntEnum from gi.repository import Gdk class Key(IntEnum): UNKNOWN = -1 Up = Gdk.KEY_Up Right = Gdk.KEY_Right Down = Gdk.KEY_Down Left = Gdk.KEY_Left @classmethod def from_value(cls, value: int) -> 'Key': try: return Key(value) except ValueError: return Key.UNKNOWN class Modifier: SHIFT = int(Gdk.ModifierType.SHIFT_MASK) class KeyEvent: def __init__(self, key: Key, modifier: int): self.key = key self.modifier = modifier
gpl-3.0
GlowstonePlusPlus/Glowkit
src/main/java/com/destroystokyo/paper/exception/ServerException.java
622
package com.destroystokyo.paper.exception; /** * Wrapper exception for all exceptions that are thrown by the server. */ public class ServerException extends Exception { public ServerException(String message) { super(message); } public ServerException(String message, Throwable cause) { super(message, cause); } public ServerException(Throwable cause) { super(cause); } protected ServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
gpl-3.0
mahalaxmi123/moodleanalytics
course/lib.php
150232
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Library of useful functions * * @copyright 1999 Martin Dougiamas http://dougiamas.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @package core_course */ defined('MOODLE_INTERNAL') || die; require_once($CFG->libdir.'/completionlib.php'); require_once($CFG->libdir.'/filelib.php'); require_once($CFG->dirroot.'/course/format/lib.php'); define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records. define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds. /** * Number of courses to display when summaries are included. * @var int * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead. */ define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // Max courses in log dropdown before switching to optional. define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000); // Max users in log dropdown before switching to optional. define('COURSE_MAX_USERS_PER_DROPDOWN', 1000); define('FRONTPAGENEWS', '0'); define('FRONTPAGECATEGORYNAMES', '2'); define('FRONTPAGECATEGORYCOMBO', '4'); define('FRONTPAGEENROLLEDCOURSELIST', '5'); define('FRONTPAGEALLCOURSELIST', '6'); define('FRONTPAGECOURSESEARCH', '7'); // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage. define('EXCELROWS', 65535); define('FIRSTUSEDEXCELROW', 3); define('MOD_CLASS_ACTIVITY', 0); define('MOD_CLASS_RESOURCE', 1); //Course types define('CORPLMS_COURSE_TYPE_ELEARNING', 0); define('CORPLMS_COURSE_TYPE_BLENDED', 1); define('CORPLMS_COURSE_TYPE_FACETOFACE', 2); global $CORPLMS_COURSE_TYPES; $CORPLMS_COURSE_TYPES = array( 'elearning' => CORPLMS_COURSE_TYPE_ELEARNING, 'blended' => CORPLMS_COURSE_TYPE_BLENDED, 'facetoface' => CORPLMS_COURSE_TYPE_FACETOFACE, ); function make_log_url($module, $url) { switch ($module) { case 'course': if (strpos($url, 'report/') === 0) { // there is only one report type, course reports are deprecated $url = "/$url"; break; } case 'file': case 'login': case 'lib': case 'admin': case 'category': case 'mnet course': if (strpos($url, '../') === 0) { $url = ltrim($url, '.'); } else { $url = "/course/$url"; } break; case 'calendar': $url = "/calendar/$url"; break; case 'user': case 'blog': $url = "/$module/$url"; break; case 'upload': $url = $url; break; case 'coursetags': $url = '/'.$url; break; case 'library': case '': $url = '/'; break; case 'message': $url = "/message/$url"; break; case 'notes': $url = "/notes/$url"; break; case 'tag': $url = "/tag/$url"; break; case 'role': $url = '/'.$url; break; // Corplms specific modules case 'appraisal': case 'certification': case 'feedback360': case 'reportbuilder': case 'hierarchy': case 'customfield': case 'program': case 'plan': $url = '/corplms/' . $module . '/' . $url; break; case 'position': case 'organisation': case 'competency': case 'goal': $url = '/corplms/hierarchy/' . $url; break; case 'priorityscales': case 'objectivescales': $url = '/corplms/plan/' . $module . '/' . $url; break; case 'my': $url = '/my/' . $url; break; // End Corplms specific modules case 'grade': $url = "/grade/$url"; break; case 'rbembedded': $url = $url; break; default: $url = "/mod/$module/$url"; break; } //now let's sanitise urls - there might be some ugly nasties:-( $parts = explode('?', $url); $script = array_shift($parts); if (strpos($script, 'http') === 0) { $script = clean_param($script, PARAM_URL); } else { $script = clean_param($script, PARAM_PATH); } $query = ''; if ($parts) { $query = implode('', $parts); $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-| $parts = explode('&', $query); $eq = urlencode('='); foreach ($parts as $key=>$part) { $part = urlencode(urldecode($part)); $part = str_replace($eq, '=', $part); $parts[$key] = $part; } $query = '?'.implode('&amp;', $parts); } return $script.$query; } function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='', $modname="", $modid=0, $modaction="", $groupid=0) { global $CFG, $DB; // It is assumed that $date is the GMT time of midnight for that day, // and so the next 86400 seconds worth of logs are printed. /// Setup for group handling. // TODO: I don't understand group/context/etc. enough to be able to do // something interesting with it here // What is the context of a remote course? /// If the group mode is separate, and this user does not have editing privileges, /// then only the user's group can be viewed. //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) { // $groupid = get_current_group($course->id); //} /// If this course doesn't have groups, no groupid can be specified. //else if (!$course->groupmode) { // $groupid = 0; //} $groupid = 0; $joins = array(); $where = ''; $qry = "SELECT l.*, u.firstname, u.lastname, u.picture FROM {mnet_log} l LEFT JOIN {user} u ON l.userid = u.id WHERE "; $params = array(); $where .= "l.hostid = :hostid"; $params['hostid'] = $hostid; // TODO: Is 1 really a magic number referring to the sitename? if ($course != SITEID || $modid != 0) { $where .= " AND l.course=:courseid"; $params['courseid'] = $course; } if ($modname) { $where .= " AND l.module = :modname"; $params['modname'] = $modname; } if ('site_errors' === $modid) { $where .= " AND ( l.action='error' OR l.action='infected' )"; } else if ($modid) { //TODO: This assumes that modids are the same across sites... probably //not true $where .= " AND l.cmid = :modid"; $params['modid'] = $modid; } if ($modaction) { $firstletter = substr($modaction, 0, 1); if ($firstletter == '-') { $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true); $params['modaction'] = '%'.substr($modaction, 1).'%'; } else { $where .= " AND ".$DB->sql_like('l.action', ':modaction', false); $params['modaction'] = '%'.$modaction.'%'; } } if ($user) { $where .= " AND l.userid = :user"; $params['user'] = $user; } if ($date) { $enddate = $date + 86400; $where .= " AND l.time > :date AND l.time < :enddate"; $params['date'] = $date; $params['enddate'] = $enddate; } $result = array(); $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params); if(!empty($result['totalcount'])) { $where .= " ORDER BY $order"; $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum); } else { $result['logs'] = array(); } return $result; } function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='', $modname="", $modid=0, $modaction="", $groupid=0) { global $DB, $SESSION, $USER; // It is assumed that $date is the GMT time of midnight for that day, // and so the next 86400 seconds worth of logs are printed. /// Setup for group handling. /// If the group mode is separate, and this user does not have editing privileges, /// then only the user's group can be viewed. if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) { if (isset($SESSION->currentgroup[$course->id])) { $groupid = $SESSION->currentgroup[$course->id]; } else { $groupid = groups_get_all_groups($course->id, $USER->id); if (is_array($groupid)) { $groupid = array_shift(array_keys($groupid)); $SESSION->currentgroup[$course->id] = $groupid; } else { $groupid = 0; } } } /// If this course doesn't have groups, no groupid can be specified. else if (!$course->groupmode) { $groupid = 0; } $joins = array(); $params = array(); if ($course->id != SITEID || $modid != 0) { $joins[] = "l.course = :courseid"; $params['courseid'] = $course->id; } if ($modname) { $joins[] = "l.module = :modname"; $params['modname'] = $modname; } if ('site_errors' === $modid) { $joins[] = "( l.action='error' OR l.action='infected' )"; } else if ($modid) { $joins[] = "l.cmid = :modid"; $params['modid'] = $modid; } if ($modaction) { $firstletter = substr($modaction, 0, 1); if ($firstletter == '-') { $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true); $params['modaction'] = '%'.substr($modaction, 1).'%'; } else { $joins[] = $DB->sql_like('l.action', ':modaction', false); $params['modaction'] = '%'.$modaction.'%'; } } /// Getting all members of a group. if ($groupid and !$user) { if ($gusers = groups_get_members($groupid)) { $gusers = array_keys($gusers); $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')'; } else { $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false. } } else if ($user) { $joins[] = "l.userid = :userid"; $params['userid'] = $user; } if ($date) { $enddate = $date + 86400; $joins[] = "l.time > :date AND l.time < :enddate"; $params['date'] = $date; $params['enddate'] = $enddate; } $selector = implode(' AND ', $joins); $totalcount = 0; // Initialise $result = array(); $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount); $result['totalcount'] = $totalcount; return $result; } function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100, $url="", $modname="", $modid=0, $modaction="", $groupid=0) { global $CFG, $DB, $OUTPUT; if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage, $modname, $modid, $modaction, $groupid)) { echo $OUTPUT->notification("No logs found!"); echo $OUTPUT->footer(); exit; } $courses = array(); if ($course->id == SITEID) { $courses[0] = ''; if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) { foreach ($ccc as $cc) { $courses[$cc->id] = $cc->shortname; } } } else { $courses[$course->id] = $course->shortname; } $totalcount = $logs['totalcount']; $count=0; $ldcache = array(); $tt = getdate(time()); $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]); $strftimedatetime = get_string("strftimedatetime"); echo "<div class=\"info\">\n"; print_string("displayingrecords", "", $totalcount); echo "</div>\n"; echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage"); $table = new html_table(); $table->classes = array('logtable','generaltable'); $table->align = array('right', 'left', 'left'); $table->head = array( get_string('time'), get_string('ip_address'), get_string('fullnameuser'), get_string('action'), get_string('info') ); $table->data = array(); if ($course->id == SITEID) { array_unshift($table->align, 'left'); array_unshift($table->head, get_string('course')); } // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach. if (empty($logs['logs'])) { $logs['logs'] = array(); } foreach ($logs['logs'] as $log) { if (isset($ldcache[$log->module][$log->action])) { $ld = $ldcache[$log->module][$log->action]; } else { $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action)); $ldcache[$log->module][$log->action] = $ld; } if ($ld && is_numeric($log->info)) { // ugly hack to make sure fullname is shown correctly if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) { $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true); } else { $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info)); } } //Filter log->info $log->info = format_string($log->info); // If $log->url has been trimmed short by the db size restriction // code in add_to_log, keep a note so we don't add a link to a broken url $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...'); $row = array(); if ($course->id == SITEID) { if (empty($log->course)) { $row[] = get_string('site'); } else { $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>"; } } $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime); $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid"); $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700))); $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)))); $displayaction="$log->module $log->action"; if ($brokenurl) { $row[] = $displayaction; } else { $link = make_log_url($log->module,$log->url); $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700)); } $row[] = $log->info; $table->data[] = $row; } echo html_writer::table($table); echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage"); } function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100, $url="", $modname="", $modid=0, $modaction="", $groupid=0) { global $CFG, $DB, $OUTPUT; if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage, $modname, $modid, $modaction, $groupid)) { echo $OUTPUT->notification("No logs found!"); echo $OUTPUT->footer(); exit; } if ($course->id == SITEID) { $courses[0] = ''; if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) { foreach ($ccc as $cc) { $courses[$cc->id] = $cc->shortname; } } } $totalcount = $logs['totalcount']; $count=0; $ldcache = array(); $tt = getdate(time()); $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]); $strftimedatetime = get_string("strftimedatetime"); echo "<div class=\"info\">\n"; print_string("displayingrecords", "", $totalcount); echo "</div>\n"; echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage"); echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n"; echo "<tr>"; if ($course->id == SITEID) { echo "<th class=\"c0 header\">".get_string('course')."</th>\n"; } echo "<th class=\"c1 header\">".get_string('time')."</th>\n"; echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n"; echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n"; echo "<th class=\"c4 header\">".get_string('action')."</th>\n"; echo "<th class=\"c5 header\">".get_string('info')."</th>\n"; echo "</tr>\n"; if (empty($logs['logs'])) { echo "</table>\n"; return; } $row = 1; foreach ($logs['logs'] as $log) { $log->info = $log->coursename; $row = ($row + 1) % 2; if (isset($ldcache[$log->module][$log->action])) { $ld = $ldcache[$log->module][$log->action]; } else { $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action)); $ldcache[$log->module][$log->action] = $ld; } if (0 && $ld && !empty($log->info)) { // ugly hack to make sure fullname is shown correctly if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) { $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true); } else { $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info)); } } //Filter log->info $log->info = format_string($log->info); echo '<tr class="r'.$row.'">'; if ($course->id == SITEID) { $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID))); echo "<td class=\"r$row c0\" >\n"; echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n"; echo "</td>\n"; } echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a'). ' '.userdate($log->time, $strftimedatetime)."</td>\n"; echo "<td class=\"r$row c2\" >\n"; $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid"); echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700))); echo "</td>\n"; $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))); echo "<td class=\"r$row c3\" >\n"; echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n"; echo "</td>\n"; echo "<td class=\"r$row c4\">\n"; echo $log->action .': '.$log->module; echo "</td>\n"; echo "<td class=\"r$row c5\">{$log->info}</td>\n"; echo "</tr>\n"; } echo "</table>\n"; echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage"); } function print_log_csv($course, $user, $date, $order='l.time DESC', $modname, $modid, $modaction, $groupid) { global $DB, $CFG; require_once($CFG->libdir . '/csvlib.class.php'); $csvexporter = new csv_export_writer('tab'); $header = array(); $header[] = get_string('course'); $header[] = get_string('time'); $header[] = get_string('ip_address'); $header[] = get_string('fullnameuser'); $header[] = get_string('action'); $header[] = get_string('info'); if (!$logs = build_logs_array($course, $user, $date, $order, '', '', $modname, $modid, $modaction, $groupid)) { return false; } $courses = array(); if ($course->id == SITEID) { $courses[0] = ''; if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) { foreach ($ccc as $cc) { $courses[$cc->id] = $cc->shortname; } } } else { $courses[$course->id] = $course->shortname; } $count=0; $ldcache = array(); $tt = getdate(time()); $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]); $strftimedatetime = get_string("strftimedatetime"); $csvexporter->set_filename('logs', '.txt'); $title = array(get_string('savedat').userdate(time(), $strftimedatetime)); $csvexporter->add_data($title); $csvexporter->add_data($header); if (empty($logs['logs'])) { return true; } foreach ($logs['logs'] as $log) { if (isset($ldcache[$log->module][$log->action])) { $ld = $ldcache[$log->module][$log->action]; } else { $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action)); $ldcache[$log->module][$log->action] = $ld; } if ($ld && is_numeric($log->info)) { // ugly hack to make sure fullname is shown correctly if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) { $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true); } else { $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info)); } } //Filter log->info $log->info = format_string($log->info); $log->info = strip_tags(urldecode($log->info)); // Some XSS protection $coursecontext = context_course::instance($course->id); $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext)); $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext)); $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url); $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info); $csvexporter->add_data($row); } $csvexporter->download_file(); return true; } function print_log_xls($course, $user, $date, $order='l.time DESC', $modname, $modid, $modaction, $groupid) { global $CFG, $DB; require_once("$CFG->libdir/excellib.class.php"); if (!$logs = build_logs_array($course, $user, $date, $order, '', '', $modname, $modid, $modaction, $groupid)) { return false; } $courses = array(); if ($course->id == SITEID) { $courses[0] = ''; if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) { foreach ($ccc as $cc) { $courses[$cc->id] = $cc->shortname; } } } else { $courses[$course->id] = $course->shortname; } $count=0; $ldcache = array(); $tt = getdate(time()); $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]); $strftimedatetime = get_string("strftimedatetime"); $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1)); $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false); $filename .= '.xls'; $workbook = new MoodleExcelWorkbook('-'); $workbook->send($filename); $worksheet = array(); $headers = array(get_string('course'), get_string('time'), get_string('ip_address'), get_string('fullnameuser'), get_string('action'), get_string('info')); // Creating worksheets for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) { $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages; $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle); $worksheet[$wsnumber]->set_column(1, 1, 30); $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat'). userdate(time(), $strftimedatetime)); $col = 0; foreach ($headers as $item) { $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,''); $col++; } } if (empty($logs['logs'])) { $workbook->close(); return true; } $formatDate = $workbook->add_format(); $formatDate->set_num_format(MoodleExcelWorkbook::NUMBER_FORMAT_STANDARD_DATETIME); $row = FIRSTUSEDEXCELROW; $wsnumber = 1; $myxls =& $worksheet[$wsnumber]; foreach ($logs['logs'] as $log) { if (isset($ldcache[$log->module][$log->action])) { $ld = $ldcache[$log->module][$log->action]; } else { $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action)); $ldcache[$log->module][$log->action] = $ld; } if ($ld && is_numeric($log->info)) { // ugly hack to make sure fullname is shown correctly if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) { $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true); } else { $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info)); } } // Filter log->info $log->info = format_string($log->info); $log->info = strip_tags(urldecode($log->info)); // Some XSS protection if ($nroPages>1) { if ($row > EXCELROWS) { $wsnumber++; $myxls =& $worksheet[$wsnumber]; $row = FIRSTUSEDEXCELROW; } } $coursecontext = context_course::instance($course->id); $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), ''); $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934 $myxls->write($row, 2, $log->ip, ''); $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext)); $myxls->write($row, 3, $fullname, ''); $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url); $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', ''); $myxls->write($row, 5, $log->info, ''); $row++; } $workbook->close(); return true; } function print_log_ods($course, $user, $date, $order='l.time DESC', $modname, $modid, $modaction, $groupid) { global $CFG, $DB; require_once("$CFG->libdir/odslib.class.php"); if (!$logs = build_logs_array($course, $user, $date, $order, '', '', $modname, $modid, $modaction, $groupid)) { return false; } $courses = array(); if ($course->id == SITEID) { $courses[0] = ''; if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) { foreach ($ccc as $cc) { $courses[$cc->id] = $cc->shortname; } } } else { $courses[$course->id] = $course->shortname; } $count=0; $ldcache = array(); $tt = getdate(time()); $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]); $strftimedatetime = get_string("strftimedatetime"); $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1)); $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false); $filename .= '.ods'; $workbook = new MoodleODSWorkbook('-'); $workbook->send($filename); $worksheet = array(); $headers = array(get_string('course'), get_string('time'), get_string('ip_address'), get_string('fullnameuser'), get_string('action'), get_string('info')); // Creating worksheets for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) { $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages; $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle); $worksheet[$wsnumber]->set_column(1, 1, 30); $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat'). userdate(time(), $strftimedatetime)); $col = 0; foreach ($headers as $item) { $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,''); $col++; } } if (empty($logs['logs'])) { $workbook->close(); return true; } $row = FIRSTUSEDEXCELROW; $wsnumber = 1; $myxls =& $worksheet[$wsnumber]; foreach ($logs['logs'] as $log) { if (isset($ldcache[$log->module][$log->action])) { $ld = $ldcache[$log->module][$log->action]; } else { $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action)); $ldcache[$log->module][$log->action] = $ld; } if ($ld && is_numeric($log->info)) { // ugly hack to make sure fullname is shown correctly if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) { $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true); } else { $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info)); } } // Filter log->info $log->info = format_string($log->info); $log->info = strip_tags(urldecode($log->info)); // Some XSS protection if ($nroPages>1) { if ($row > EXCELROWS) { $wsnumber++; $myxls =& $worksheet[$wsnumber]; $row = FIRSTUSEDEXCELROW; } } $coursecontext = context_course::instance($course->id); $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext))); $myxls->write_date($row, 1, $log->time); $myxls->write_string($row, 2, $log->ip); $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext)); $myxls->write_string($row, 3, $fullname); $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url); $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')'); $myxls->write_string($row, 5, $log->info); $row++; } $workbook->close(); return true; } /** * Checks the integrity of the course data. * * In summary - compares course_sections.sequence and course_modules.section. * * More detailed, checks that: * - course_sections.sequence contains each module id not more than once in the course * - for each moduleid from course_sections.sequence the field course_modules.section * refers to the same section id (this means course_sections.sequence is more * important if they are different) * - ($fullcheck only) each module in the course is present in one of * course_sections.sequence * - ($fullcheck only) removes non-existing course modules from section sequences * * If there are any mismatches, the changes are made and records are updated in DB. * * Course cache is NOT rebuilt if there are any errors! * * This function is used each time when course cache is being rebuilt with $fullcheck = false * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true * * @param int $courseid id of the course * @param array $rawmods result of funciton {@link get_course_mods()} - containst * the list of enabled course modules in the course. Retrieved from DB if not specified. * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway. * @param array $sections records from course_sections table for this course. * Retrieved from DB if not specified * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing * course modules from sequences. Only to be used in site maintenance mode when we are * sure that another user is not in the middle of the process of moving/removing a module. * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages. * @return array array of messages with found problems. Empty output means everything is ok */ function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) { global $DB; $messages = array(); if ($sections === null) { $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence'); } if ($fullcheck) { // Retrieve all records from course_modules regardless of module type visibility. $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section'); } if ($rawmods === null) { $rawmods = get_course_mods($courseid); } if (!$fullcheck && (empty($sections) || empty($rawmods))) { // If either of the arrays is empty, no modules are displayed anyway. return true; } $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. '; // First make sure that each module id appears in section sequences only once. // If it appears in several section sequences the last section wins. // If it appears twice in one section sequence, the first occurence wins. $modsection = array(); foreach ($sections as $sectionid => $section) { $sections[$sectionid]->newsequence = $section->sequence; if (!empty($section->sequence)) { $sequence = explode(",", $section->sequence); $sequenceunique = array_unique($sequence); if (count($sequenceunique) != count($sequence)) { // Some course module id appears in this section sequence more than once. ksort($sequenceunique); // Preserve initial order of modules. $sequence = array_values($sequenceunique); $sections[$sectionid]->newsequence = join(',', $sequence); $messages[] = $debuggingprefix.'Sequence for course section ['. $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"'; } foreach ($sequence as $cmid) { if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) { // Some course module id appears to be in more than one section's sequences. $wrongsectionid = $modsection[$cmid]; $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ','); $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['. $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']'; } $modsection[$cmid] = $sectionid; } } } // Add orphaned modules to their sections if they exist or to section 0 otherwise. if ($fullcheck) { foreach ($rawmods as $cmid => $mod) { if (!isset($modsection[$cmid])) { // This is a module that is not mentioned in course_section.sequence at all. // Add it to the section $mod->section or to the last available section. if ($mod->section && isset($sections[$mod->section])) { $modsection[$cmid] = $mod->section; } else { $firstsection = reset($sections); $modsection[$cmid] = $firstsection->id; } $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ','); $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['. $modsection[$cmid].']'; } } foreach ($modsection as $cmid => $sectionid) { if (!isset($rawmods[$cmid])) { // Section $sectionid refers to module id that does not exist. $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ','); $messages[] = $debuggingprefix.'Course module ['.$cmid. '] does not exist but is present in the sequence of section ['.$sectionid.']'; } } } // Update changed sections. if (!$checkonly && !empty($messages)) { foreach ($sections as $sectionid => $section) { if ($section->newsequence !== $section->sequence) { $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence)); } } } // Now make sure that all modules point to the correct sections. foreach ($rawmods as $cmid => $mod) { if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) { if (!$checkonly) { $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid])); } $messages[] = $debuggingprefix.'Course module ['.$cmid. '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']'; } } return $messages; } /** * For a given course, returns an array of course activity objects * Each item in the array contains he following properties: */ function get_array_of_activities($courseid) { // cm - course module id // mod - name of the module (eg forum) // section - the number of the section (eg week or topic) // name - the name of the instance // visible - is the instance visible or not // groupingid - grouping id // groupmembersonly - is this instance visible to group members only // extra - contains extra string to include in any link global $CFG, $DB; if(!empty($CFG->enableavailability)) { require_once($CFG->libdir.'/conditionlib.php'); } $course = $DB->get_record('course', array('id'=>$courseid)); if (empty($course)) { throw new moodle_exception('courseidnotfound'); } $mod = array(); $rawmods = get_course_mods($courseid); if (empty($rawmods)) { return $mod; // always return array } if ($sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence')) { // First check and correct obvious mismatches between course_sections.sequence and course_modules.section. if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) { debugging(join('<br>', $errormessages)); $rawmods = get_course_mods($courseid); $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence'); } // Build array of activities. foreach ($sections as $section) { if (!empty($section->sequence)) { $sequence = explode(",", $section->sequence); foreach ($sequence as $seq) { if (empty($rawmods[$seq])) { continue; } $mod[$seq] = new stdClass(); $mod[$seq]->id = $rawmods[$seq]->instance; $mod[$seq]->cm = $rawmods[$seq]->id; $mod[$seq]->mod = $rawmods[$seq]->modname; // Oh dear. Inconsistent names left here for backward compatibility. $mod[$seq]->section = $section->section; $mod[$seq]->sectionid = $rawmods[$seq]->section; $mod[$seq]->module = $rawmods[$seq]->module; $mod[$seq]->added = $rawmods[$seq]->added; $mod[$seq]->score = $rawmods[$seq]->score; $mod[$seq]->idnumber = $rawmods[$seq]->idnumber; $mod[$seq]->visible = $rawmods[$seq]->visible; $mod[$seq]->visibleold = $rawmods[$seq]->visibleold; $mod[$seq]->groupmode = $rawmods[$seq]->groupmode; $mod[$seq]->groupingid = $rawmods[$seq]->groupingid; $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly; $mod[$seq]->indent = $rawmods[$seq]->indent; $mod[$seq]->completion = $rawmods[$seq]->completion; $mod[$seq]->extra = ""; $mod[$seq]->completiongradeitemnumber = $rawmods[$seq]->completiongradeitemnumber; $mod[$seq]->completionview = $rawmods[$seq]->completionview; $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected; $mod[$seq]->showdescription = $rawmods[$seq]->showdescription; $mod[$seq]->availability = $rawmods[$seq]->availability; $modname = $mod[$seq]->mod; $functionname = $modname."_get_coursemodule_info"; if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) { continue; } include_once("$CFG->dirroot/mod/$modname/lib.php"); if ($hasfunction = function_exists($functionname)) { if ($info = $functionname($rawmods[$seq])) { if (!empty($info->icon)) { $mod[$seq]->icon = $info->icon; } if (!empty($info->iconcomponent)) { $mod[$seq]->iconcomponent = $info->iconcomponent; } if (!empty($info->name)) { $mod[$seq]->name = $info->name; } if ($info instanceof cached_cm_info) { // When using cached_cm_info you can include three new fields // that aren't available for legacy code if (!empty($info->content)) { $mod[$seq]->content = $info->content; } if (!empty($info->extraclasses)) { $mod[$seq]->extraclasses = $info->extraclasses; } if (!empty($info->iconurl)) { // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB. $url = new moodle_url($info->iconurl); $mod[$seq]->iconurl = $url->out(false); } if (!empty($info->onclick)) { $mod[$seq]->onclick = $info->onclick; } if (!empty($info->customdata)) { $mod[$seq]->customdata = $info->customdata; } } else { // When using a stdclass, the (horrible) deprecated ->extra field // is available for BC if (!empty($info->extra)) { $mod[$seq]->extra = $info->extra; } } } } // When there is no modname_get_coursemodule_info function, // but showdescriptions is enabled, then we use the 'intro' // and 'introformat' fields in the module table if (!$hasfunction && $rawmods[$seq]->showdescription) { if ($modvalues = $DB->get_record($rawmods[$seq]->modname, array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) { // Set content from intro and introformat. Filters are disabled // because we filter it with format_text at display time $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname, $modvalues, $rawmods[$seq]->id, false); // To save making another query just below, put name in here $mod[$seq]->name = $modvalues->name; } } if (!isset($mod[$seq]->name)) { $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance)); } // Minimise the database size by unsetting default options when they are // 'empty'. This list corresponds to code in the cm_info constructor. foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly', 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content', 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview', 'completionexpected', 'score', 'showdescription') as $property) { if (property_exists($mod[$seq], $property) && empty($mod[$seq]->{$property})) { unset($mod[$seq]->{$property}); } } // Special case: this value is usually set to null, but may be 0 if (property_exists($mod[$seq], 'completiongradeitemnumber') && is_null($mod[$seq]->completiongradeitemnumber)) { unset($mod[$seq]->completiongradeitemnumber); } } } } } return $mod; } /** * Returns the localised human-readable names of all used modules * * @param bool $plural if true returns the plural forms of the names * @return array where key is the module name (component name without 'mod_') and * the value is the human-readable string. Array sorted alphabetically by value */ function get_module_types_names($plural = false) { static $modnames = null; global $DB, $CFG; if ($modnames === null) { $modnames = array(0 => array(), 1 => array()); if ($allmods = $DB->get_records("modules")) { foreach ($allmods as $mod) { if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) { $modnames[0][$mod->name] = get_string("modulename", "$mod->name"); $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name"); } } core_collator::asort($modnames[0]); core_collator::asort($modnames[1]); } } return $modnames[(int)$plural]; } /** * Set highlighted section. Only one section can be highlighted at the time. * * @param int $courseid course id * @param int $marker highlight section with this number, 0 means remove higlightin * @return void */ function course_set_marker($courseid, $marker) { global $DB; $DB->set_field("course", "marker", $marker, array('id' => $courseid)); format_base::reset_course_cache($courseid); } /** * For a given course section, marks it visible or hidden, * and does the same for every activity in that section * * @param int $courseid course id * @param int $sectionnumber The section number to adjust * @param int $visibility The new visibility * @return array A list of resources which were hidden in the section */ function set_section_visible($courseid, $sectionnumber, $visibility) { global $DB; $resourcestotoggle = array(); if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) { $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id)); $event = \core\event\course_section_updated::create(array( 'context' => context_course::instance($courseid), 'objectid' => $section->id, 'other' => array( 'sectionnum' => $sectionnumber ) )); $event->add_record_snapshot('course_sections', $section); $event->trigger(); if (!empty($section->sequence)) { $modules = explode(",", $section->sequence); foreach ($modules as $moduleid) { if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) { if ($visibility) { // As we unhide the section, we use the previously saved visibility stored in visibleold. set_coursemodule_visible($moduleid, $cm->visibleold); } else { // We hide the section, so we hide the module but we store the original state in visibleold. set_coursemodule_visible($moduleid, 0); $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid)); } \core\event\course_module_updated::create_from_cm($cm)->trigger(); } } } rebuild_course_cache($courseid, true); // Determine which modules are visible for AJAX update if (!empty($modules)) { list($insql, $params) = $DB->get_in_or_equal($modules); $select = 'id ' . $insql . ' AND visible = ?'; array_push($params, $visibility); if (!$visibility) { $select .= ' AND visibleold = 1'; } $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params); } } return $resourcestotoggle; } /** * Retrieve all metadata for the requested modules * * @param object $course The Course * @param array $modnames An array containing the list of modules and their * names * @param int $sectionreturn The section to return to * @return array A list of stdClass objects containing metadata about each * module */ function get_module_metadata($course, $modnames, $sectionreturn = null) { global $CFG, $OUTPUT; // get_module_metadata will be called once per section on the page and courses may show // different modules to one another static $modlist = array(); if (!isset($modlist[$course->id])) { $modlist[$course->id] = array(); } $return = array(); $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey())); if ($sectionreturn !== null) { $urlbase->param('sr', $sectionreturn); } foreach($modnames as $modname => $modnamestr) { if (!course_allowed_module($course, $modname)) { continue; } if (isset($modlist[$course->id][$modname])) { // This module is already cached $return[$modname] = $modlist[$course->id][$modname]; continue; } // Include the module lib $libfile = "$CFG->dirroot/mod/$modname/lib.php"; if (!file_exists($libfile)) { continue; } include_once($libfile); // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!! $gettypesfunc = $modname.'_get_types'; $types = MOD_SUBTYPE_NO_CHILDREN; if (function_exists($gettypesfunc)) { $types = $gettypesfunc(); } if ($types !== MOD_SUBTYPE_NO_CHILDREN) { if (is_array($types) && count($types) > 0) { $group = new stdClass(); $group->name = $modname; $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon')); foreach($types as $type) { if ($type->typestr === '--') { continue; } if (strpos($type->typestr, '--') === 0) { $group->title = str_replace('--', '', $type->typestr); continue; } // Set the Sub Type metadata $subtype = new stdClass(); $subtype->title = $type->typestr; $subtype->type = str_replace('&amp;', '&', $type->type); $subtype->name = preg_replace('/.*type=/', '', $subtype->type); $subtype->archetype = $type->modclass; // The group archetype should match the subtype archetypes and all subtypes // should have the same archetype $group->archetype = $subtype->archetype; if (!empty($type->help)) { $subtype->help = $type->help; } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) { $subtype->help = get_string('help' . $subtype->name, $modname); } $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name)); $group->types[] = $subtype; } $modlist[$course->id][$modname] = $group; } } else { $module = new stdClass(); $module->title = $modnamestr; $module->name = $modname; $module->link = new moodle_url($urlbase, array('add' => $modname)); $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon')); $sm = get_string_manager(); if ($sm->string_exists('modulename_help', $modname)) { $module->help = get_string('modulename_help', $modname); if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs $link = get_string('modulename_link', $modname); $linktext = get_string('morehelp'); $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink')); } } $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); $modlist[$course->id][$modname] = $module; } if (isset($modlist[$course->id][$modname])) { $return[$modname] = $modlist[$course->id][$modname]; } else { debugging("Invalid module metadata configuration for {$modname}"); } } return $return; } /** * Return the course category context for the category with id $categoryid, except * that if $categoryid is 0, return the system context. * * @param integer $categoryid a category id or 0. * @return context the corresponding context */ function get_category_or_system_context($categoryid) { if ($categoryid) { return context_coursecat::instance($categoryid, IGNORE_MISSING); } else { return context_system::instance(); } } /** * Returns full course categories trees to be used in html_writer::select() * * Calls {@link coursecat::make_categories_list()} to build the tree and * adds whitespace to denote nesting * * @return array array mapping coursecat id to the display name */ function make_categories_options() { global $CFG; require_once($CFG->libdir. '/coursecatlib.php'); $cats = coursecat::make_categories_list('', 0, ' / '); foreach ($cats as $key => $value) { // Prefix the value with the number of spaces equal to category depth (number of separators in the value). $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value; } return $cats; } /** * Print the buttons relating to course requests. * * @param object $context current page context. */ function print_course_request_buttons($context) { global $CFG, $DB, $OUTPUT; if (empty($CFG->enablecourserequests)) { return; } if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) { /// Print a button to request a new course echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get'); } /// Print a button to manage pending requests if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) { $disabled = !$DB->record_exists('course_request', array()); echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled)); } } /** * Does the user have permission to edit things in this category? * * @param integer $categoryid The id of the category we are showing, or 0 for system context. * @return boolean has_any_capability(array(...), ...); in the appropriate context. */ function can_edit_in_category($categoryid = 0) { $context = get_category_or_system_context($categoryid); return has_any_capability(array('moodle/category:manage', 'moodle/course:create', 'moodle/course:update', 'corplms/program:createprogram', 'corplms/program:configuredetails', 'corplms/certification:createcertification', 'corplms/certification:configurecertification'), $context); } /// MODULE FUNCTIONS ///////////////////////////////////////////////////////////////// function add_course_module($mod) { global $DB; $mod->added = time(); unset($mod->id); $cmid = $DB->insert_record("course_modules", $mod); rebuild_course_cache($mod->course, true); return $cmid; } /** * Creates missing course section(s) and rebuilds course cache * * @param int|stdClass $courseorid course id or course object * @param int|array $sections list of relative section numbers to create * @return bool if there were any sections created */ function course_create_sections_if_missing($courseorid, $sections) { global $DB; if (!is_array($sections)) { $sections = array($sections); } $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all()); if (is_object($courseorid)) { $courseorid = $courseorid->id; } $coursechanged = false; foreach ($sections as $sectionnum) { if (!in_array($sectionnum, $existing)) { $cw = new stdClass(); $cw->course = $courseorid; $cw->section = $sectionnum; $cw->summary = ''; $cw->summaryformat = FORMAT_HTML; $cw->sequence = ''; $id = $DB->insert_record("course_sections", $cw); $coursechanged = true; } } if ($coursechanged) { rebuild_course_cache($courseorid, true); } return $coursechanged; } /** * Adds an existing module to the section * * Updates both tables {course_sections} and {course_modules} * * Note: This function does not use modinfo PROVIDED that the section you are * adding the module to already exists. If the section does not exist, it will * build modinfo if necessary and create the section. * * @param int|stdClass $courseorid course id or course object * @param int $cmid id of the module already existing in course_modules table * @param int $sectionnum relative number of the section (field course_sections.section) * If section does not exist it will be created * @param int|stdClass $beforemod id or object with field id corresponding to the module * before which the module needs to be included. Null for inserting in the * end of the section * @return int The course_sections ID where the module is inserted */ function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) { global $DB, $COURSE; if (is_object($beforemod)) { $beforemod = $beforemod->id; } if (is_object($courseorid)) { $courseid = $courseorid->id; } else { $courseid = $courseorid; } // Do not try to use modinfo here, there is no guarantee it is valid! $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING); if (!$section) { // This function call requires modinfo. course_create_sections_if_missing($courseorid, $sectionnum); $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST); } $modarray = explode(",", trim($section->sequence)); if (empty($section->sequence)) { $newsequence = "$cmid"; } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) { $insertarray = array($cmid, $beforemod); array_splice($modarray, $key[0], 1, $insertarray); $newsequence = implode(",", $modarray); } else { $newsequence = "$section->sequence,$cmid"; } $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id)); $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid)); if (is_object($courseorid)) { rebuild_course_cache($courseorid->id, true); } else { rebuild_course_cache($courseorid, true); } return $section->id; // Return course_sections ID that was used. } /** * Change the group mode of a course module. * * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}. * * @param int $id course module ID. * @param int $groupmode the new groupmode value. * @return bool True if the $groupmode was updated. */ function set_coursemodule_groupmode($id, $groupmode) { global $DB; $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST); if ($cm->groupmode != $groupmode) { $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id)); rebuild_course_cache($cm->course, true); } return ($cm->groupmode != $groupmode); } function set_coursemodule_idnumber($id, $idnumber) { global $DB; $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST); if ($cm->idnumber != $idnumber) { $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id)); rebuild_course_cache($cm->course, true); } return ($cm->idnumber != $idnumber); } /** * Set the visibility of a module and inherent properties. * * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}. * * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered * has been moved to {@link set_section_visible()} which was the only place from which * the parameter was used. * * @param int $id of the module * @param int $visible state of the module * @return bool false when the module was not found, true otherwise */ function set_coursemodule_visible($id, $visible) { global $DB, $CFG; require_once($CFG->libdir.'/gradelib.php'); require_once($CFG->dirroot.'/calendar/lib.php'); // Trigger developer's attention when using the previously removed argument. if (func_num_args() > 2) { debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides has been removed.', DEBUG_DEVELOPER); } if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) { return false; } // Create events and propagate visibility to associated grade items if the value has changed. // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades. if ($cm->visible == $visible) { return true; } if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) { return false; } if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) { foreach($events as $event) { if ($visible) { $event = new calendar_event($event); $event->toggle_visibility(true); } else { $event = new calendar_event($event); $event->toggle_visibility(false); } } } // Updating visible and visibleold to keep them in sync. Only changing a section visibility will // affect visibleold to allow for an original visibility restore. See set_section_visible(). $cminfo = new stdClass(); $cminfo->id = $id; $cminfo->visible = $visible; $cminfo->visibleold = $visible; $DB->update_record('course_modules', $cminfo); // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there. // Note that this must be done after updating the row in course_modules, in case // the modules grade_item_update function needs to access $cm->visible. if (plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) && component_callback_exists('mod_' . $modulename, 'grade_item_update')) { $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST); component_callback('mod_' . $modulename, 'grade_item_update', array($instance)); } else { $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course)); if ($grade_items) { foreach ($grade_items as $grade_item) { $grade_item->set_hidden(!$visible); } } } rebuild_course_cache($cm->course, true); return true; } /** * This function will handles the whole deletion process of a module. This includes calling * the modules delete_instance function, deleting files, events, grades, conditional data, * the data in the course_module and course_sections table and adding a module deletion * event to the DB. * * @param int $cmid the course module id * @since Moodle 2.5 */ function course_delete_module($cmid) { global $CFG, $DB; require_once($CFG->libdir.'/gradelib.php'); require_once($CFG->dirroot.'/blog/lib.php'); require_once($CFG->dirroot.'/calendar/lib.php'); require_once($CFG->dirroot . '/tag/lib.php'); // Get the course module. if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) { return true; } // Get the module context. $modcontext = context_module::instance($cm->id); // Get the course module name. $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST); // Get the file location of the delete_instance function for this module. $modlib = "$CFG->dirroot/mod/$modulename/lib.php"; // Include the file required to call the delete_instance function for this module. if (file_exists($modlib)) { require_once($modlib); } else { throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null, "Cannot delete this module as the file mod/$modulename/lib.php is missing."); } $deleteinstancefunction = $modulename . '_delete_instance'; // Ensure the delete_instance function exists for this module. if (!function_exists($deleteinstancefunction)) { throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null, "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php."); } // Call the delete_instance function, if it returns false throw an exception. if (!$deleteinstancefunction($cm->instance)) { throw new moodle_exception('cannotdeletemoduleinstance', '', '', null, "Cannot delete the module $modulename (instance)."); } // Remove all module files in case modules forget to do that. $fs = get_file_storage(); $fs->delete_area_files($modcontext->id); // Delete events from calendar. if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) { foreach($events as $event) { $calendarevent = calendar_event::load($event->id); $calendarevent->delete(); } } // Delete grade items, outcome items and grades attached to modules. if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename, 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) { foreach ($grade_items as $grade_item) { $grade_item->delete('moddelete'); } } // Delete completion and availability data; it is better to do this even if the // features are not turned on, in case they were turned on previously (these will be // very quick on an empty table). $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id)); $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id, 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY)); // Delete all tag instances associated with the instance of this module. tag_delete_instances('mod_' . $modulename, $modcontext->id); // Delete the context. context_helper::delete_instance(CONTEXT_MODULE, $cm->id); // Delete the module from the course_modules table. $DB->delete_records('course_modules', array('id' => $cm->id)); // Delete module from that section. if (!delete_mod_from_section($cm->id, $cm->section)) { throw new moodle_exception('cannotdeletemodulefromsection', '', '', null, "Cannot delete the module $modulename (instance) from section."); } // Trigger event for course module delete action. $event = \core\event\course_module_deleted::create(array( 'courseid' => $cm->course, 'context' => $modcontext, 'objectid' => $cm->id, 'other' => array( 'modulename' => $modulename, 'instanceid' => $cm->instance, ) )); $event->add_record_snapshot('course_modules', $cm); $event->trigger(); rebuild_course_cache($cm->course, true); } function delete_mod_from_section($modid, $sectionid) { global $DB; if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) { $modarray = explode(",", $section->sequence); if ($key = array_keys ($modarray, $modid)) { array_splice($modarray, $key[0], 1); $newsequence = implode(",", $modarray); $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id)); rebuild_course_cache($section->course, true); return true; } else { return false; } } return false; } /** * Moves a section within a course, from a position to another. * Be very careful: $section and $destination refer to section number, * not id!. * * @param object $course * @param int $section Section number (not id!!!) * @param int $destination * @return boolean Result */ function move_section_to($course, $section, $destination) { /// Moves a whole course section up and down within the course global $USER, $DB; if (!$destination && $destination != 0) { return true; } // compartibility with course formats using field 'numsections' $courseformatoptions = course_get_format($course)->get_format_options(); if ((array_key_exists('numsections', $courseformatoptions) && ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) { return false; } // Get all sections for this course and re-order them (2 of them should now share the same section number) if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id), 'section ASC, id ASC', 'id, section')) { return false; } $movedsections = reorder_sections($sections, $section, $destination); // Update all sections. Do this in 2 steps to avoid breaking database // uniqueness constraint $transaction = $DB->start_delegated_transaction(); foreach ($movedsections as $id => $position) { if ($sections[$id] !== $position) { $DB->set_field('course_sections', 'section', -$position, array('id' => $id)); } } foreach ($movedsections as $id => $position) { if ($sections[$id] !== $position) { $DB->set_field('course_sections', 'section', $position, array('id' => $id)); } } // If we move the highlighted section itself, then just highlight the destination. // Adjust the higlighted section location if we move something over it either direction. if ($section == $course->marker) { course_set_marker($course->id, $destination); } elseif ($section > $course->marker && $course->marker >= $destination) { course_set_marker($course->id, $course->marker+1); } elseif ($section < $course->marker && $course->marker <= $destination) { course_set_marker($course->id, $course->marker-1); } $transaction->allow_commit(); rebuild_course_cache($course->id, true); return true; } /** * Reordering algorithm for course sections. Given an array of section->section indexed by section->id, * an original position number and a target position number, rebuilds the array so that the * move is made without any duplication of section positions. * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to * insert a section before the first one, you must give 0 as the target (section 0 can never be moved). * * @param array $sections * @param int $origin_position * @param int $target_position * @return array */ function reorder_sections($sections, $origin_position, $target_position) { if (!is_array($sections)) { return false; } // We can't move section position 0 if ($origin_position < 1) { echo "We can't move section position 0"; return false; } // Locate origin section in sections array if (!$origin_key = array_search($origin_position, $sections)) { echo "searched position not in sections array"; return false; // searched position not in sections array } // Extract origin section $origin_section = $sections[$origin_key]; unset($sections[$origin_key]); // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!) $found = false; $append_array = array(); foreach ($sections as $id => $position) { if ($found) { $append_array[$id] = $position; unset($sections[$id]); } if ($position == $target_position) { if ($target_position < $origin_position) { $append_array[$id] = $position; unset($sections[$id]); } $found = true; } } // Append moved section $sections[$origin_key] = $origin_section; // Append rest of array (if applicable) if (!empty($append_array)) { foreach ($append_array as $id => $position) { $sections[$id] = $position; } } // Renumber positions $position = 0; foreach ($sections as $id => $p) { $sections[$id] = $position; $position++; } return $sections; } /** * Move the module object $mod to the specified $section * If $beforemod exists then that is the module * before which $modid should be inserted * * @param stdClass|cm_info $mod * @param stdClass|section_info $section * @param int|stdClass $beforemod id or object with field id corresponding to the module * before which the module needs to be included. Null for inserting in the * end of the section * @return int new value for module visibility (0 or 1) */ function moveto_module($mod, $section, $beforemod=NULL) { global $OUTPUT, $DB; // Current module visibility state - return value of this function. $modvisible = $mod->visible; // Remove original module from original section. if (! delete_mod_from_section($mod->id, $mod->section)) { echo $OUTPUT->notification("Could not delete module from existing section"); } // If moving to a hidden section then hide module. if ($mod->section != $section->id) { if (!$section->visible && $mod->visible) { // Module was visible but must become hidden after moving to hidden section. $modvisible = 0; set_coursemodule_visible($mod->id, 0); // Set visibleold to 1 so module will be visible when section is made visible. $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id)); } if ($section->visible && !$mod->visible) { // Hidden module was moved to the visible section, restore the module visibility from visibleold. set_coursemodule_visible($mod->id, $mod->visibleold); $modvisible = $mod->visibleold; } } // Add the module into the new section. course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod); return $modvisible; } /** * Returns the list of all editing actions that current user can perform on the module * * @param cm_info $mod The module to produce editing buttons for * @param int $indent The current indenting (default -1 means no move left-right actions) * @param int $sr The section to link back to (used for creating the links) * @return array array of action_link or pix_icon objects */ function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) { global $COURSE, $SITE; static $str; $coursecontext = context_course::instance($mod->course); $modcontext = context_module::instance($mod->id); $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign'); $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport'); // No permission to edit anything. if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) { return array(); } $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext); if (!isset($str)) { $str = get_strings(array('delete', 'move', 'moveright', 'moveleft', 'editsettings', 'duplicate', 'hide', 'show'), 'moodle'); $str->assign = get_string('assignroles', 'role'); $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone")); $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate")); $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible")); } $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey())); if ($sr !== null) { $baseurl->param('sr', $sr); } $actions = array(); // Update. if ($hasmanageactivities) { $actions['update'] = new action_menu_link_secondary( new moodle_url($baseurl, array('update' => $mod->id)), new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->editsettings, array('class' => 'editing_update', 'data-action' => 'update') ); } // Indent. if ($hasmanageactivities && $indent >= 0) { $indentlimits = new stdClass(); $indentlimits->min = 0; $indentlimits->max = 16; if (right_to_left()) { // Exchange arrows on RTL $rightarrow = 't/left'; $leftarrow = 't/right'; } else { $rightarrow = 't/right'; $leftarrow = 't/left'; } if ($indent >= $indentlimits->max) { $enabledclass = 'hidden'; } else { $enabledclass = ''; } $actions['moveright'] = new action_menu_link_secondary( new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')), new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->moveright, array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright', 'data-keepopen' => true) ); if ($indent <= $indentlimits->min) { $enabledclass = 'hidden'; } else { $enabledclass = ''; } $actions['moveleft'] = new action_menu_link_secondary( new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')), new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->moveleft, array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft', 'data-keepopen' => true) ); } // Hide/Show. if (has_capability('moodle/course:activityvisibility', $modcontext)) { if ($mod->visible) { $actions['hide'] = new action_menu_link_secondary( new moodle_url($baseurl, array('hide' => $mod->id)), new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->hide, array('class' => 'editing_hide', 'data-action' => 'hide') ); } else { $actions['show'] = new action_menu_link_secondary( new moodle_url($baseurl, array('show' => $mod->id)), new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->show, array('class' => 'editing_show', 'data-action' => 'show') ); } } // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php) // Note that restoring on front page is never allowed. if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) { $actions['duplicate'] = new action_menu_link_secondary( new moodle_url($baseurl, array('duplicate' => $mod->id)), new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->duplicate, array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sr' => $sr) ); } // Groupmode. if ($hasmanageactivities && !$mod->coursegroupmodeforce) { if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) { if ($mod->effectivegroupmode == SEPARATEGROUPS) { $nextgroupmode = VISIBLEGROUPS; $grouptitle = $str->groupsseparate; $actionname = 'groupsseparate'; $groupimage = 'i/groups'; } else if ($mod->effectivegroupmode == VISIBLEGROUPS) { $nextgroupmode = NOGROUPS; $grouptitle = $str->groupsvisible; $actionname = 'groupsvisible'; $groupimage = 'i/groupv'; } else { $nextgroupmode = SEPARATEGROUPS; $grouptitle = $str->groupsnone; $actionname = 'groupsnone'; $groupimage = 'i/groupn'; } $actions[$actionname] = new action_menu_link_primary( new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)), new pix_icon($groupimage, null, 'moodle', array('class' => 'iconsmall')), $grouptitle, array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode, 'aria-live' => 'assertive') ); } else { $actions['nogroupsupport'] = new action_menu_filler(); } } // Assign. if (has_capability('moodle/role:assign', $modcontext)){ $actions['assign'] = new action_menu_link_secondary( new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)), new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->assign, array('class' => 'editing_assign', 'data-action' => 'assignroles') ); } // Delete. if ($hasmanageactivities) { $actions['delete'] = new action_menu_link_secondary( new moodle_url($baseurl, array('delete' => $mod->id)), new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str->delete, array('class' => 'editing_delete', 'data-action' => 'delete') ); } return $actions; } /** * Returns the rename action. * * @param cm_info $mod The module to produce editing buttons for * @param int $sr The section to link back to (used for creating the links) * @return The markup for the rename action, or an empty string if not available. */ function course_get_cm_rename_action(cm_info $mod, $sr = null) { global $COURSE, $OUTPUT; static $str; static $baseurl; $modcontext = context_module::instance($mod->id); $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext); if (!isset($str)) { $str = get_strings(array('edittitle')); } if (!isset($baseurl)) { $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey())); } if ($sr !== null) { $baseurl->param('sr', $sr); } // AJAX edit title. if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) && (($mod->course == $COURSE->id) || ($mod->course == SITEID))) { // we will not display link if we are on some other-course page (where we should not see this module anyway) return html_writer::span( html_writer::link( new moodle_url($baseurl, array('update' => $mod->id)), $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')), array( 'class' => 'editing_title', 'data-action' => 'edittitle', 'title' => $str->edittitle, ) ) ); } return ''; } /** * Returns the move action. * * @param cm_info $mod The module to produce a move button for * @param int $sr The section to link back to (used for creating the links) * @return The markup for the move action, or an empty string if not available. */ function course_get_cm_move(cm_info $mod, $sr = null) { global $OUTPUT; static $str; static $baseurl; $modcontext = context_module::instance($mod->id); $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext); if (!isset($str)) { $str = get_strings(array('move')); } if (!isset($baseurl)) { $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey())); if ($sr !== null) { $baseurl->param('sr', $sr); } } if ($hasmanageactivities) { $pixicon = 'i/dragdrop'; if (!course_ajax_enabled($mod->get_course())) { // Override for course frontpage until we get drag/drop working there. $pixicon = 't/move'; } return html_writer::link( new moodle_url($baseurl, array('copy' => $mod->id)), $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')), array('class' => 'editing_move', 'data-action' => 'move') ); } return ''; } /** * given a course object with shortname & fullname, this function will * truncate the the number of chars allowed and add ... if it was too long */ function course_format_name ($course,$max=100) { $context = context_course::instance($course->id); $shortname = format_string($course->shortname, true, array('context' => $context)); $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id))); $str = $shortname.': '. $fullname; if (core_text::strlen($str) <= $max) { return $str; } else { return core_text::substr($str,0,$max-3).'...'; } } /** * Is the user allowed to add this type of module to this course? * @param object $course the course settings. Only $course->id is used. * @param string $modname the module name. E.g. 'forum' or 'quiz'. * @return bool whether the current user is allowed to add this type of module to this course. */ function course_allowed_module($course, $modname) { if (is_numeric($modname)) { throw new coding_exception('Function course_allowed_module no longer supports numeric module ids. Please update your code to pass the module name.'); } $capability = 'mod/' . $modname . ':addinstance'; if (!get_capability_info($capability)) { // Debug warning that the capability does not exist, but no more than once per page. static $warned = array(); $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) { debugging('The module ' . $modname . ' does not define the standard capability ' . $capability , DEBUG_DEVELOPER); $warned[$modname] = 1; } // If the capability does not exist, the module can always be added. return true; } $coursecontext = context_course::instance($course->id); return has_capability($capability, $coursecontext); } /** * Efficiently moves many courses around while maintaining * sortorder in order. * * @param array $courseids is an array of course ids * @param int $categoryid * @return bool success */ function move_courses($courseids, $categoryid) { global $DB; if (empty($courseids)) { // Nothing to do. return false; } if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) { return false; } $courseids = array_reverse($courseids); $newparent = context_coursecat::instance($category->id); $i = 1; list($where, $params) = $DB->get_in_or_equal($courseids); $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname'); foreach ($dbcourses as $dbcourse) { $course = new stdClass(); $course->id = $dbcourse->id; $course->category = $category->id; $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++; if ($category->visible == 0) { // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get // to previous state if somebody unhides the category. $course->visible = 0; } $DB->update_record('course', $course); // Update context, so it can be passed to event. $context = context_course::instance($course->id); $context->update_moved($newparent); // Trigger a course updated event. $event = \core\event\course_updated::create(array( 'objectid' => $course->id, 'context' => context_course::instance($course->id), 'other' => array('shortname' => $dbcourse->shortname, 'fullname' => $dbcourse->fullname) )); $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id)); $event->trigger(); } fix_course_sortorder(); cache_helper::purge_by_event('changesincourse'); return true; } /** * Returns the display name of the given section that the course prefers * * Implementation of this function is provided by course format * @see format_base::get_section_name() * * @param int|stdClass $courseorid The course to get the section name for (object or just course id) * @param int|stdClass $section Section object from database or just field course_sections.section * @return string Display name that the course format prefers, e.g. "Week 2" */ function get_section_name($courseorid, $section) { return course_get_format($courseorid)->get_section_name($section); } /** * Tells if current course format uses sections * * @param string $format Course format ID e.g. 'weeks' $course->format * @return bool */ function course_format_uses_sections($format) { $course = new stdClass(); $course->format = $format; return course_get_format($course)->uses_sections(); } /** * Returns the information about the ajax support in the given source format * * The returned object's property (boolean)capable indicates that * the course format supports Moodle course ajax features. * * @param string $format * @return stdClass */ function course_format_ajax_support($format) { $course = new stdClass(); $course->format = $format; return course_get_format($course)->supports_ajax(); } /** * Can the current user delete this course? * Course creators have exception, * 1 day after the creation they can sill delete the course. * @param int $courseid * @return boolean */ function can_delete_course($courseid) { global $USER; $context = context_course::instance($courseid); if (has_capability('moodle/course:delete', $context)) { return true; } // hack: now try to find out if creator created this course recently (1 day) if (!has_capability('moodle/course:create', $context)) { return false; } $since = time() - 60*60*24; $course = get_course($courseid); if ($course->timecreated < $since) { return false; // Return if the course was not created in last 24 hours. } $logmanger = get_log_manager(); $readers = $logmanger->get_readers('\core\log\sql_select_reader'); $reader = reset($readers); if (empty($reader)) { return false; // No log reader found. } // A proper reader. $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since"; $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created'); return (bool)$reader->get_events_select_count($select, $params); } /** * Save the Your name for 'Some role' strings. * * @param integer $courseid the id of this course. * @param array $data the data that came from the course settings form. */ function save_local_role_names($courseid, $data) { global $DB; $context = context_course::instance($courseid); foreach ($data as $fieldname => $value) { if (strpos($fieldname, 'role_') !== 0) { continue; } list($ignored, $roleid) = explode('_', $fieldname); // make up our mind whether we want to delete, update or insert if (!$value) { $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid)); } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) { $rolename->name = $value; $DB->update_record('role_names', $rolename); } else { $rolename = new stdClass; $rolename->contextid = $context->id; $rolename->roleid = $roleid; $rolename->name = $value; $DB->insert_record('role_names', $rolename); } } } /** * Returns options to use in course overviewfiles filemanager * * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id; * may be empty if course does not exist yet (course create form) * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc. * or null if overviewfiles are disabled */ function course_overviewfiles_options($course) { global $CFG; if (empty($CFG->courseoverviewfileslimit)) { return null; } $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY); if (in_array('*', $accepted_types) || empty($accepted_types)) { $accepted_types = '*'; } else { // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered. // Make sure extensions are prefixed with dot unless they are valid typegroups foreach ($accepted_types as $i => $type) { if (substr($type, 0, 1) !== '.') { require_once($CFG->libdir. '/filelib.php'); if (!count(file_get_typegroup('extension', $type))) { // It does not start with dot and is not a valid typegroup, this is most likely extension. $accepted_types[$i] = '.'. $type; $corrected = true; } } } if (!empty($corrected)) { set_config('courseoverviewfilesext', join(',', $accepted_types)); } } $options = array( 'maxfiles' => $CFG->courseoverviewfileslimit, 'maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'accepted_types' => $accepted_types ); if (!empty($course->id)) { $options['context'] = context_course::instance($course->id); } else if (is_int($course) && $course > 0) { $options['context'] = context_course::instance($course); } return $options; } /** * Create a course and either return a $course object * * Please note this functions does not verify any access control, * the calling code is responsible for all validation (usually it is the form definition). * * @param array $editoroptions course description editor options * @param object $data - all the data needed for an entry in the 'course' table * @return object new course instance */ function create_course($data, $editoroptions = NULL) { global $DB; //check the categoryid - must be given for all new courses $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST); // Check if the shortname already exists. if (!empty($data->shortname)) { if ($DB->record_exists('course', array('shortname' => $data->shortname))) { throw new moodle_exception('shortnametaken', '', '', $data->shortname); } } // Check if the idnumber already exists. if (!empty($data->idnumber)) { if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) { throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber); } } $data->timecreated = time(); $data->timemodified = $data->timecreated; // place at beginning of any category $data->sortorder = 0; if ($editoroptions) { // summary text is updated later, we need context to store the files first $data->summary = ''; $data->summary_format = FORMAT_HTML; } if (!isset($data->visible)) { // data not from form, add missing visibility info $data->visible = $category->visible; } $data->visibleold = $data->visible; $newcourseid = $DB->insert_record('course', $data); $context = context_course::instance($newcourseid, MUST_EXIST); if ($editoroptions) { // Save the files used in the summary editor and store $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0); $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid)); $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid)); } if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) { // Save the course overviewfiles $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0); } // update course format options course_get_format($newcourseid)->update_course_format_options($data); $course = course_get_format($newcourseid)->get_course(); // Setup the blocks blocks_add_default_course_blocks($course); // Create a default section. course_create_sections_if_missing($course, 0); fix_course_sortorder(); // purge appropriate caches in case fix_course_sortorder() did not change anything cache_helper::purge_by_event('changesincourse'); // new context created - better mark it as dirty $context->mark_dirty(); // Save any custom role names. save_local_role_names($course->id, (array)$data); // set up enrolments enrol_course_updated(true, $course, $data); // Trigger a course created event. $event = \core\event\course_created::create(array( 'objectid' => $course->id, 'context' => context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname) )); $event->trigger(); return $course; } /** * Update a course. * * Please note this functions does not verify any access control, * the calling code is responsible for all validation (usually it is the form definition). * * @param object $data - all the data needed for an entry in the 'course' table * @param array $editoroptions course description editor options * @return void */ function update_course($data, $editoroptions = NULL) { global $DB; $data->timemodified = time(); $oldcourse = course_get_format($data->id)->get_course(); $context = context_course::instance($oldcourse->id); if ($editoroptions) { $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0); } if ($overviewfilesoptions = course_overviewfiles_options($data->id)) { $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0); } // Check we don't have a duplicate shortname. if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) { if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) { throw new moodle_exception('shortnametaken', '', '', $data->shortname); } } // Check we don't have a duplicate idnumber. if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) { if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) { throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber); } } if (!isset($data->category) or empty($data->category)) { // prevent nulls and 0 in category field unset($data->category); } $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category); if (!isset($data->visible)) { // data not from form, add missing visibility info $data->visible = $oldcourse->visible; } if ($data->visible != $oldcourse->visible) { // reset the visibleold flag when manually hiding/unhiding course $data->visibleold = $data->visible; $changesincoursecat = true; } else { if ($movecat) { $newcategory = $DB->get_record('course_categories', array('id'=>$data->category)); if (empty($newcategory->visible)) { // make sure when moving into hidden category the course is hidden automatically $data->visible = 0; } } } // Update with the new data $DB->update_record('course', $data); // make sure the modinfo cache is reset rebuild_course_cache($data->id); // update course format options with full course data course_get_format($data->id)->update_course_format_options($data, $oldcourse); $course = $DB->get_record('course', array('id'=>$data->id)); if ($movecat) { $newparent = context_coursecat::instance($course->category); $context->update_moved($newparent); } $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder)); if ($fixcoursesortorder) { fix_course_sortorder(); } // purge appropriate caches in case fix_course_sortorder() did not change anything cache_helper::purge_by_event('changesincourse'); if ($changesincoursecat) { cache_helper::purge_by_event('changesincoursecat'); } // Test for and remove blocks which aren't appropriate anymore blocks_remove_inappropriate($course); // Save any custom role names. save_local_role_names($course->id, $data); // update enrol settings enrol_course_updated(false, $course, $data); // Trigger a course updated event. $event = \core\event\course_updated::create(array( 'objectid' => $course->id, 'context' => context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname) )); $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id)); $event->trigger(); if ($oldcourse->format !== $course->format) { // Remove all options stored for the previous format // We assume that new course format migrated everything it needed watching trigger // 'course_updated' and in method format_XXX::update_course_format_options() $DB->delete_records('course_format_options', array('courseid' => $course->id, 'format' => $oldcourse->format)); } } /** * Average number of participants * @return integer */ function average_number_of_participants() { global $DB, $SITE; //count total of enrolments for visible course (except front page) $sql = 'SELECT COUNT(*) FROM ( SELECT DISTINCT ue.userid, e.courseid FROM {user_enrolments} ue, {enrol} e, {course} c WHERE ue.enrolid = e.id AND e.courseid <> :siteid AND c.id = e.courseid AND c.visible = 1) total'; $params = array('siteid' => $SITE->id); $enrolmenttotal = $DB->count_records_sql($sql, $params); //count total of visible courses (minus front page) $coursetotal = $DB->count_records('course', array('visible' => 1)); $coursetotal = $coursetotal - 1 ; //average of enrolment if (empty($coursetotal)) { $participantaverage = 0; } else { $participantaverage = $enrolmenttotal / $coursetotal; } return $participantaverage; } /** * Average number of course modules * @return integer */ function average_number_of_courses_modules() { global $DB, $SITE; //count total of visible course module (except front page) $sql = 'SELECT COUNT(*) FROM ( SELECT cm.course, cm.module FROM {course} c, {course_modules} cm WHERE c.id = cm.course AND c.id <> :siteid AND cm.visible = 1 AND c.visible = 1) total'; $params = array('siteid' => $SITE->id); $moduletotal = $DB->count_records_sql($sql, $params); //count total of visible courses (minus front page) $coursetotal = $DB->count_records('course', array('visible' => 1)); $coursetotal = $coursetotal - 1 ; //average of course module if (empty($coursetotal)) { $coursemoduleaverage = 0; } else { $coursemoduleaverage = $moduletotal / $coursetotal; } return $coursemoduleaverage; } /** * This class pertains to course requests and contains methods associated with * create, approving, and removing course requests. * * Please note we do not allow embedded images here because there is no context * to store them with proper access control. * * @copyright 2009 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * * @property-read int $id * @property-read string $fullname * @property-read string $shortname * @property-read string $summary * @property-read int $summaryformat * @property-read int $summarytrust * @property-read string $reason * @property-read int $requester */ class course_request { /** * This is the stdClass that stores the properties for the course request * and is externally accessed through the __get magic method * @var stdClass */ protected $properties; /** * An array of options for the summary editor used by course request forms. * This is initially set by {@link summary_editor_options()} * @var array * @static */ protected static $summaryeditoroptions; /** * Static function to prepare the summary editor for working with a course * request. * * @static * @param null|stdClass $data Optional, an object containing the default values * for the form, these may be modified when preparing the * editor so this should be called before creating the form * @return stdClass An object that can be used to set the default values for * an mforms form */ public static function prepare($data=null) { if ($data === null) { $data = new stdClass; } $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options()); return $data; } /** * Static function to create a new course request when passed an array of properties * for it. * * This function also handles saving any files that may have been used in the editor * * @static * @param stdClass $data * @return course_request The newly created course request */ public static function create($data) { global $USER, $DB, $CFG; $data->requester = $USER->id; // Setting the default category if none set. if (empty($data->category) || empty($CFG->requestcategoryselection)) { $data->category = $CFG->defaultrequestcategory; } // Summary is a required field so copy the text over $data->summary = $data->summary_editor['text']; $data->summaryformat = $data->summary_editor['format']; $data->id = $DB->insert_record('course_request', $data); // Create a new course_request object and return it $request = new course_request($data); // Notify the admin if required. if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) { $a = new stdClass; $a->link = "$CFG->wwwroot/course/pending.php"; $a->user = fullname($USER); $strmgr = get_string_manager(); foreach ($users as $user) { $subject = $strmgr->get_string('courserequest', 'moodle', null, $user->lang); $message = $strmgr->get_string('courserequestnotifyemail', 'admin', $a, $user->lang); $request->notify($user, $USER, 'courserequested', $subject, $message); } } return $request; } /** * Returns an array of options to use with a summary editor * * @uses course_request::$summaryeditoroptions * @return array An array of options to use with the editor */ public static function summary_editor_options() { global $CFG; if (self::$summaryeditoroptions === null) { self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0); } return self::$summaryeditoroptions; } /** * Loads the properties for this course request object. Id is required and if * only id is provided then we load the rest of the properties from the database * * @param stdClass|int $properties Either an object containing properties * or the course_request id to load */ public function __construct($properties) { global $DB; if (empty($properties->id)) { if (empty($properties)) { throw new coding_exception('You must provide a course request id when creating a course_request object'); } $id = $properties; $properties = new stdClass; $properties->id = (int)$id; unset($id); } if (empty($properties->requester)) { if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) { print_error('unknowncourserequest'); } } else { $this->properties = $properties; } $this->properties->collision = null; } /** * Returns the requested property * * @param string $key * @return mixed */ public function __get($key) { return $this->properties->$key; } /** * Override this to ensure empty($request->blah) calls return a reliable answer... * * This is required because we define the __get method * * @param mixed $key * @return bool True is it not empty, false otherwise */ public function __isset($key) { return (!empty($this->properties->$key)); } /** * Returns the user who requested this course * * Uses a static var to cache the results and cut down the number of db queries * * @staticvar array $requesters An array of cached users * @return stdClass The user who requested the course */ public function get_requester() { global $DB; static $requesters= array(); if (!array_key_exists($this->properties->requester, $requesters)) { $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester)); } return $requesters[$this->properties->requester]; } /** * Checks that the shortname used by the course does not conflict with any other * courses that exist * * @param string|null $shortnamemark The string to append to the requests shortname * should a conflict be found * @return bool true is there is a conflict, false otherwise */ public function check_shortname_collision($shortnamemark = '[*]') { global $DB; if ($this->properties->collision !== null) { return $this->properties->collision; } if (empty($this->properties->shortname)) { debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER); $this->properties->collision = false; } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) { if (!empty($shortnamemark)) { $this->properties->shortname .= ' '.$shortnamemark; } $this->properties->collision = true; } else { $this->properties->collision = false; } return $this->properties->collision; } /** * Returns the category where this course request should be created * * Note that we don't check here that user has a capability to view * hidden categories if he has capabilities 'moodle/site:approvecourse' and * 'moodle/course:changecategory' * * @return coursecat */ public function get_category() { global $CFG; require_once($CFG->libdir.'/coursecatlib.php'); // If the category is not set, if the current user does not have the rights to change the category, or if the // category does not exist, we set the default category to the course to be approved. // The system level is used because the capability moodle/site:approvecourse is based on a system level. if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) || (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) { $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true); } if (!$category) { $category = coursecat::get_default(); } return $category; } /** * This function approves the request turning it into a course * * This function converts the course request into a course, at the same time * transferring any files used in the summary to the new course and then removing * the course request and the files associated with it. * * @return int The id of the course that was created from this request */ public function approve() { global $CFG, $DB, $USER; $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST); $courseconfig = get_config('moodlecourse'); // Transfer appropriate settings $data = clone($this->properties); unset($data->id); unset($data->reason); unset($data->requester); // Set category $category = $this->get_category(); $data->category = $category->id; // Set misc settings $data->requested = 1; // Apply course default settings $data->format = $courseconfig->format; $data->newsitems = $courseconfig->newsitems; $data->showgrades = $courseconfig->showgrades; $data->showreports = $courseconfig->showreports; $data->maxbytes = $courseconfig->maxbytes; $data->groupmode = $courseconfig->groupmode; $data->groupmodeforce = $courseconfig->groupmodeforce; $data->visible = $courseconfig->visible; $data->visibleold = $data->visible; $data->lang = $courseconfig->lang; $course = create_course($data); $context = context_course::instance($course->id, MUST_EXIST); // add enrol instances if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) { if ($manual = enrol_get_plugin('manual')) { $manual->add_default_instance($course); } } // enrol the requester as teacher if necessary if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) { enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid); } $this->delete(); $a = new stdClass(); $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id))); $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id; $strmgr = get_string_manager(); $this->notify($user, $USER, 'courserequestapproved', $strmgr->get_string('courseapprovedsubject', 'moodle', null, $user->lang), $strmgr->get_string('courseapprovedemail2', 'moodle', $a, $user->lang)); return $course->id; } /** * Reject a course request * * This function rejects a course request, emailing the requesting user the * provided notice and then removing the request from the database * * @param string $notice The message to display to the user */ public function reject($notice) { global $USER, $DB; $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST); $strmgr = get_string_manager(); $this->notify($user, $USER, 'courserequestrejected', $strmgr->get_string('courserejectsubject', 'moodle', null, $user->lang), $strmgr->get_string('courserejectemail', 'moodle', $notice, $user->lang)); $this->delete(); } /** * Deletes the course request and any associated files */ public function delete() { global $DB; $DB->delete_records('course_request', array('id' => $this->properties->id)); } /** * Send a message from one user to another using events_trigger * * @param object $touser * @param object $fromuser * @param string $name * @param string $subject * @param string $message */ protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) { $eventdata = new stdClass(); $eventdata->component = 'moodle'; $eventdata->name = $name; $eventdata->userfrom = $fromuser; $eventdata->userto = $touser; $eventdata->subject = $subject; $eventdata->fullmessage = $message; $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = $message; $eventdata->smallmessage = ''; $eventdata->notification = 1; message_send($eventdata); } } /** * Return a list of page types * @param string $pagetype current page type * @param context $parentcontext Block's parent context * @param context $currentcontext Current context of block * @return array array of page types */ function course_page_type_list($pagetype, $parentcontext, $currentcontext) { if ($pagetype === 'course-index' || $pagetype === 'course-index-category') { // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page $pagetypes = array('*' => get_string('page-x', 'pagetype'), 'course-index-*' => get_string('page-course-index-x', 'pagetype'), ); } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) { // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.) $pagetypes = array('*' => get_string('page-x', 'pagetype')); } else { // Otherwise consider it a page inside a course even if $currentcontext is null $pagetypes = array('*' => get_string('page-x', 'pagetype'), 'course-*' => get_string('page-course-x', 'pagetype'), 'course-view-*' => get_string('page-course-view-x', 'pagetype') ); } return $pagetypes; } // Corplms Functions function get_course_custom_fields($courseid) { global $DB; $sql = "SELECT d.*, f.* FROM {course_info_data} d INNER JOIN {course_info_field} f ON d.fieldid = f.id WHERE d.courseid = ? ORDER BY f.sortorder"; return $DB->get_records_sql($sql, array($courseid)); } /** * Determine whether course ajax should be enabled for the specified course * * @param stdClass $course The course to test against * @return boolean Whether course ajax is enabled or note */ function course_ajax_enabled($course) { global $CFG, $PAGE, $SITE; // The user must be editing for AJAX to be included if (!$PAGE->user_is_editing()) { return false; } // Check that the theme suports if (!$PAGE->theme->enablecourseajax) { return false; } // Check that the course format supports ajax functionality // The site 'format' doesn't have information on course format support if ($SITE->id !== $course->id) { $courseformatajaxsupport = course_format_ajax_support($course->format); if (!$courseformatajaxsupport->capable) { return false; } } // All conditions have been met so course ajax should be enabled return true; } /** * Include the relevant javascript and language strings for the resource * toolbox YUI module * * @param integer $id The ID of the course being applied to * @param array $usedmodules An array containing the names of the modules in use on the page * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site * @param stdClass $config An object containing configuration parameters for ajax modules including: * * resourceurl The URL to post changes to for resource changes * * sectionurl The URL to post changes to for section changes * * pageparams Additional parameters to pass through in the post * @return bool */ function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) { global $CFG, $PAGE, $SITE; // Ensure that ajax should be included if (!course_ajax_enabled($course)) { return false; } if (!$config) { $config = new stdClass(); } // The URL to use for resource changes if (!isset($config->resourceurl)) { $config->resourceurl = '/course/rest.php'; } // The URL to use for section changes if (!isset($config->sectionurl)) { $config->sectionurl = '/course/rest.php'; } // Any additional parameters which need to be included on page submission if (!isset($config->pageparams)) { $config->pageparams = array(); } // Include toolboxes $PAGE->requires->yui_module('moodle-course-toolboxes', 'M.course.init_resource_toolbox', array(array( 'courseid' => $course->id, 'ajaxurl' => $config->resourceurl, 'config' => $config, )) ); $PAGE->requires->yui_module('moodle-course-toolboxes', 'M.course.init_section_toolbox', array(array( 'courseid' => $course->id, 'format' => $course->format, 'ajaxurl' => $config->sectionurl, 'config' => $config, )) ); // Include course dragdrop if (course_format_uses_sections($course->format)) { $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop', array(array( 'courseid' => $course->id, 'ajaxurl' => $config->sectionurl, 'config' => $config, )), null, true); $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop', array(array( 'courseid' => $course->id, 'ajaxurl' => $config->resourceurl, 'config' => $config, )), null, true); } // Require various strings for the command toolbox $PAGE->requires->strings_for_js(array( 'moveleft', 'deletechecktype', 'deletechecktypename', 'edittitle', 'edittitleinstructions', 'show', 'hide', 'groupsnone', 'groupsvisible', 'groupsseparate', 'clicktochangeinbrackets', 'markthistopic', 'markedthistopic', 'movesection', 'movecoursemodule', 'movecoursesection', 'movecontent', 'tocontent', 'emptydragdropregion', 'afterresource', 'aftersection', 'totopofsection', ), 'moodle'); // Include section-specific strings for formats which support sections. if (course_format_uses_sections($course->format)) { $PAGE->requires->strings_for_js(array( 'showfromothers', 'hidefromothers', ), 'format_' . $course->format); } // For confirming resource deletion we need the name of the module in question foreach ($usedmodules as $module => $modname) { $PAGE->requires->string_for_js('pluginname', $module); } // Load drag and drop upload AJAX. require_once($CFG->dirroot.'/course/dnduploadlib.php'); dndupload_add_to_course($course, $enabledmodules); return true; } /** * Returns the sorted list of available course formats, filtered by enabled if necessary * * @param bool $enabledonly return only formats that are enabled * @return array array of sorted format names */ function get_sorted_course_formats($enabledonly = false) { global $CFG; $formats = core_component::get_plugin_list('format'); if (!empty($CFG->format_plugins_sortorder)) { $order = explode(',', $CFG->format_plugins_sortorder); $order = array_merge(array_intersect($order, array_keys($formats)), array_diff(array_keys($formats), $order)); } else { $order = array_keys($formats); } if (!$enabledonly) { return $order; } $sortedformats = array(); foreach ($order as $formatname) { if (!get_config('format_'.$formatname, 'disabled')) { $sortedformats[] = $formatname; } } return $sortedformats; } /** * The URL to use for the specified course (with section) * * @param int|stdClass $courseorid The course to get the section name for (either object or just course id) * @param int|stdClass $section Section object from database or just field course_sections.section * if omitted the course view page is returned * @param array $options options for view URL. At the moment core uses: * 'navigation' (bool) if true and section has no separate page, the function returns null * 'sr' (int) used by multipage formats to specify to which section to return * @return moodle_url The url of course */ function course_get_url($courseorid, $section = null, $options = array()) { return course_get_format($courseorid)->get_view_url($section, $options); } /** * Create a module. * * It includes: * - capability checks and other checks * - create the module from the module info * * @param object $module * @return object the created module info * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course */ function create_module($moduleinfo) { global $DB, $CFG; require_once($CFG->dirroot . '/course/modlib.php'); // Check manadatory attributs. $mandatoryfields = array('modulename', 'course', 'section', 'visible'); if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) { $mandatoryfields[] = 'introeditor'; } foreach($mandatoryfields as $mandatoryfield) { if (!isset($moduleinfo->{$mandatoryfield})) { throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield); } } // Some additional checks (capability / existing instances). $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST); list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section); // Add the module. $moduleinfo->module = $module->id; $moduleinfo = add_moduleinfo($moduleinfo, $course, null); return $moduleinfo; } /** * Update a module. * * It includes: * - capability and other checks * - update the module * * @param object $module * @return object the updated module info * @throws moodle_exception if current user is not allowed to update the module */ function update_module($moduleinfo) { global $DB, $CFG; require_once($CFG->dirroot . '/course/modlib.php'); // Check the course module exists. $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST); // Check the course exists. $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); // Some checks (capaibility / existing instances). list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm); // Retrieve few information needed by update_moduleinfo. $moduleinfo->modulename = $cm->modname; if (!isset($moduleinfo->scale)) { $moduleinfo->scale = 0; } $moduleinfo->type = 'mod'; // Update the module. list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null); return $moduleinfo; } /** * Duplicate a module on the course. * * @param object $course The course * @param object $cm The course module to duplicate * @throws moodle_exception if the plugin doesn't support duplication * @return Object containing: * - fullcontent: The HTML markup for the created CM * - cmid: The CMID of the newly created CM * - redirect: Whether to trigger a redirect following this change */ function mod_duplicate_activity($course, $cm, $sr = null) { global $CFG, $USER, $PAGE, $DB; require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php'); require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php'); require_once($CFG->libdir . '/filelib.php'); $a = new stdClass(); $a->modtype = get_string('modulename', $cm->modname); $a->modname = format_string($cm->name); if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) { throw new moodle_exception('duplicatenosupport', 'error'); } // backup the activity $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id); $backupid = $bc->get_backupid(); $backupbasepath = $bc->get_plan()->get_basepath(); $bc->execute_plan(); $bc->destroy(); // restore the backup immediately $rc = new restore_controller($backupid, $course->id, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING); $cmcontext = context_module::instance($cm->id); if (!$rc->execute_precheck()) { $precheckresults = $rc->get_precheck_results(); if (is_array($precheckresults) && !empty($precheckresults['errors'])) { if (empty($CFG->keeptempdirectoriesonbackup)) { fulldelete($backupbasepath); } } } $rc->execute_plan(); // Now a bit hacky part follows - we try to get the cmid of the newly // restored copy of the module. $newcmid = null; $tasks = $rc->get_plan()->get_tasks(); foreach ($tasks as $task) { if (is_subclass_of($task, 'restore_activity_task')) { if ($task->get_old_contextid() == $cmcontext->id) { $newcmid = $task->get_moduleid(); break; } } } // if we know the cmid of the new course module, let us move it // right below the original one. otherwise it will stay at the // end of the section if ($newcmid) { $info = get_fast_modinfo($course); $newcm = $info->get_cm($newcmid); $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course)); moveto_module($newcm, $section, $cm); moveto_module($cm, $section, $newcm); // Trigger course module created event. We can trigger the event only if we know the newcmid. $event = \core\event\course_module_created::create_from_cm($newcm); $event->trigger(); } rebuild_course_cache($cm->course); $rc->destroy(); if (empty($CFG->keeptempdirectoriesonbackup)) { fulldelete($backupbasepath); } $resp = new stdClass(); if ($newcm) { $courserenderer = $PAGE->get_renderer('core', 'course'); $completioninfo = new completion_info($course); $modulehtml = $courserenderer->course_section_cm($course, $completioninfo, $newcm, null, array()); $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr); $resp->cmid = $newcm->id; } else { // Trigger a redirect $resp->redirect = true; } return $resp; } /** * Compare two objects to find out their correct order based on timestamp (to be used by usort). * Sorts by descending order of time. * * @param stdClass $a First object * @param stdClass $b Second object * @return int 0,1,-1 representing the order */ function compare_activities_by_time_desc($a, $b) { // Make sure the activities actually have a timestamp property. if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) { return 0; } // We treat instances without timestamp as if they have a timestamp of 0. if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) { return 1; } if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) { return -1; } if ($a->timestamp == $b->timestamp) { return 0; } return ($a->timestamp > $b->timestamp) ? -1 : 1; } /** * Compare two objects to find out their correct order based on timestamp (to be used by usort). * Sorts by ascending order of time. * * @param stdClass $a First object * @param stdClass $b Second object * @return int 0,1,-1 representing the order */ function compare_activities_by_time_asc($a, $b) { // Make sure the activities actually have a timestamp property. if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) { return 0; } // We treat instances without timestamp as if they have a timestamp of 0. if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) { return -1; } if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) { return 1; } if ($a->timestamp == $b->timestamp) { return 0; } return ($a->timestamp < $b->timestamp) ? -1 : 1; } /** * Archives activities, with the archive feature, for a specified user and course * * @global moodle_database $DB * @global object $CFG * @param int $userid * @param int $courseid */ function archive_course_activities($userid, $courseid) { global $DB, $CFG; // Get all distinct module names for this course. $sql = "SELECT DISTINCT m.name FROM {modules} m JOIN {course_modules} cm ON cm.module = m.id AND course = :courseid ORDER BY m.name"; if ($modules = $DB->get_records_sql($sql, array('courseid' => $courseid))) { // Set up course completion. $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $completion = new completion_info($course); // Create the reset grade. $grade = new stdClass(); $grade->userid = $userid; $grade->rawgrade = null; foreach ($modules as $mod) { $modfile = $CFG->dirroot . '/mod/' . $mod->name . '/lib.php'; // Check if a module instance is attached to the course and the lib file exists. if ($DB->record_exists($mod->name, array('course' => $courseid)) && file_exists($modfile)) { include_once($modfile); // Does it have the archive feature? if (plugin_supports('mod', $mod->name, FEATURE_ARCHIVE_COMPLETION, 0)) { $modfunction = $mod->name.'_archive_completion'; if (!function_exists($modfunction)) { debugging('feature_archive_completion is supported but is missing the function in the plugin lib file'); } else { $modfunction($userid, $courseid); } } else { // Reset manually. // Reset grades. $updateitemfunc = $mod->name . '_grade_item_update'; if (function_exists($updateitemfunc)) { $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname FROM {" . $mod->name . "} a JOIN {course_modules} cm ON cm.instance = a.id AND cm.course = :courseid JOIN {modules} m ON m.id = cm.module AND m.name = :modname"; $params = array('modname' => $mod->name, 'courseid' => $courseid); if ($modinstances = $DB->get_records_sql($sql, $params)) { foreach ($modinstances as $modinstance) { $updateitemfunc($modinstance, $grade); } } } } $resetview = plugin_supports('mod', $mod->name, FEATURE_COMPLETION_TRACKS_VIEWS, 0); $cms = get_all_instances_in_course($mod->name, $course, $userid); foreach ($cms as $cm) { // Get all instances doesn't return the completion columns. $cm = get_coursemodule_from_id($mod->name, $cm->coursemodule, $courseid); if ($resetview) { // Reset viewed. $completion->set_module_viewed_reset($cm, $userid); } // Reset completion. $completion->update_state($cm, COMPLETION_INCOMPLETE, $userid); // Reset cache after each activity just in case the user reattempts. $completion->invalidatecache($courseid, $userid, true); } } } } return true; } /* * Changes the visibility of a course. * * @param int $courseid The course to change. * @param bool $show True to make it visible, false otherwise. * @return bool */ function course_change_visibility($courseid, $show = true) { $course = new stdClass; $course->id = $courseid; $course->visible = ($show) ? '1' : '0'; $course->visibleold = $course->visible; update_course($course); return true; } /** * Archives course completion * * @global moodle_database $DB * @global object $CFG * @param int $userid * @param int $courseid */ function archive_course_completion($userid, $courseid) { global $DB, $CFG, $COMPLETION_STATUS; require_once($CFG->libdir . '/completionlib.php'); require_once($CFG->libdir . '/grade/grade_item.php'); require_once($CFG->libdir . '/grade/grade_grade.php'); require_once($CFG->dirroot . '/completion/completion_completion.php'); $status = array(COMPLETION_STATUS_COMPLETE, COMPLETION_STATUS_COMPLETEVIARPL); list($statussql, $statusparams) = $DB->get_in_or_equal($status, SQL_PARAMS_NAMED, 'status'); $params = array_merge($statusparams, array('course' => $courseid, 'userid' => $userid)); $where = "course = :course AND userid = :userid AND status {$statussql}"; if (!$course_completion = $DB->get_record_select('course_completions', $where, $params)) { return false; } $history = new StdClass(); $history->courseid = $courseid; $history->userid = $userid; $history->timecompleted = $course_completion->timecompleted; $history->grade = 0; $cc = new completion_completion(array('userid' => $userid, 'course' => $courseid)); $completionstatus = $cc->get_status($course_completion); if ($completionstatus == $COMPLETION_STATUS[COMPLETION_STATUS_COMPLETEVIARPL]) { $history->grade = $cc->rplgrade; } else if ($course_item = grade_item::fetch_course_item($courseid)) { $grade = new grade_grade(array('itemid' => $course_item->id, 'userid' => $userid)); $history->grade = $grade->finalgrade; } // Copy $DB->insert_record('course_completion_history', $history); // Reset course completion. $course = $DB->get_record('course', array('id' => $courseid)); $completion = new completion_info($course); $completion->delete_course_completion_data($userid); $completion->invalidatecache($courseid, $userid, true); return true; } /* * Changes the course sortorder by one, moving it up or down one in respect to sort order. * * @param stdClass|course_in_list $course * @param bool $up If set to true the course will be moved up one. Otherwise down one. * @return bool */ function course_change_sortorder_by_one($course, $up) { global $DB; $params = array($course->sortorder, $course->category); if ($up) { $select = 'sortorder < ? AND category = ?'; $sort = 'sortorder DESC'; } else { $select = 'sortorder > ? AND category = ?'; $sort = 'sortorder ASC'; } fix_course_sortorder(); $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1); if ($swapcourse) { $swapcourse = reset($swapcourse); $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id)); $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id)); // Finally reorder courses. fix_course_sortorder(); cache_helper::purge_by_event('changesincourse'); return true; } return false; } /** * Changes the sort order of courses in a category so that the first course appears after the second. * * @param int|stdClass $courseorid The course to focus on. * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category. * @return bool */ function course_change_sortorder_after_course($courseorid, $moveaftercourseid) { global $DB; if (!is_object($courseorid)) { $course = get_course($courseorid); } else { $course = $courseorid; } if ((int)$moveaftercourseid === 0) { // We've moving the course to the start of the queue. $sql = 'SELECT sortorder FROM {course} WHERE category = :categoryid ORDER BY sortorder'; $params = array( 'categoryid' => $course->category ); $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE); $sql = 'UPDATE {course} SET sortorder = sortorder + 1 WHERE category = :categoryid AND id <> :id'; $params = array( 'categoryid' => $course->category, 'id' => $course->id, ); $DB->execute($sql, $params); $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id)); } else if ($course->id === $moveaftercourseid) { // They're the same - moronic. debugging("Invalid move after course given.", DEBUG_DEVELOPER); return false; } else { // Moving this course after the given course. It could be before it could be after. $moveaftercourse = get_course($moveaftercourseid); if ($course->category !== $moveaftercourse->category) { debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER); return false; } // Increment all courses in the same category that are ordered after the moveafter course. // This makes a space for the course we're moving. $sql = 'UPDATE {course} SET sortorder = sortorder + 1 WHERE category = :categoryid AND sortorder > :sortorder'; $params = array( 'categoryid' => $moveaftercourse->category, 'sortorder' => $moveaftercourse->sortorder ); $DB->execute($sql, $params); $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id)); } fix_course_sortorder(); cache_helper::purge_by_event('changesincourse'); return true; }
gpl-3.0
piwik/piwik
plugins/Referrers/Reports/GetKeywordsFromCampaignId.php
1094
<?php /** * Piwik - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\Referrers\Reports; use Piwik\Piwik; use Piwik\Plugin\ViewDataTable; use Piwik\Plugins\Referrers\Columns\Keyword; class GetKeywordsFromCampaignId extends Base { protected function init() { parent::init(); $this->dimension = new Keyword(); $this->name = Piwik::translate('Referrers_Campaigns'); $this->documentation = Piwik::translate('Referrers_CampaignsReportDocumentation', array('<br />', '<a href="https://matomo.org/docs/tracking-campaigns/" rel="noreferrer noopener" target="_blank">', '</a>')); $this->isSubtableReport = true; $this->order = 10; } public function configureView(ViewDataTable $view) { $view->config->show_search = false; $view->config->show_exclude_low_population = false; $view->config->addTranslation('label', $this->dimension->getName()); } }
gpl-3.0
dplc/dwin
dm/include/win32/INITOID.H
1467
/* * I N I T O I D . H * * Define macros to be used for initializing MAPI OID's * * Copyright 1986-1996 Microsoft Corporation. All Rights Reserved. */ #define MAPI_PREFIX 0x2A,0x86,0x48,0x86,0xf7,0x14,0x03 #ifdef _MAC #undef DEFINE_OID_1 #define DEFINE_OID_1(name, b0, b1) \ EXTERN_C const BYTE name[] = { MAPI_PREFIX, b0, b1 } #undef DEFINE_OID_2 #define DEFINE_OID_2(name, b0, b1, b2) \ EXTERN_C const BYTE name[] = { MAPI_PREFIX, b0, b1, b2 } #undef DEFINE_OID_3 #define DEFINE_OID_3(name, b0, b1, b2, b3) \ EXTERN_C const BYTE name[] = { MAPI_PREFIX, b0, b1, b2, b3 } #undef DEFINE_OID_4 #define DEFINE_OID_4(name, b0, b1, b2, b3, b4) \ EXTERN_C const BYTE name[] = { MAPI_PREFIX, b0, b1, b2, b3, b4 } #else #undef DEFINE_OID_1 #define DEFINE_OID_1(name, b0, b1) \ EXTERN_C const BYTE __based(__segname("_CODE")) name[] =\ { MAPI_PREFIX, b0, b1 } #undef DEFINE_OID_2 #define DEFINE_OID_2(name, b0, b1, b2) \ EXTERN_C const BYTE __based(__segname("_CODE")) name[] =\ { MAPI_PREFIX, b0, b1, b2 } #undef DEFINE_OID_3 #define DEFINE_OID_3(name, b0, b1, b2, b3) \ EXTERN_C const BYTE __based(__segname("_CODE")) name[] =\ { MAPI_PREFIX, b0, b1, b2, b3 } #undef DEFINE_OID_4 #define DEFINE_OID_4(name, b0, b1, b2, b3, b4) \ EXTERN_C const BYTE __based(__segname("_CODE")) name[] =\ { MAPI_PREFIX, b0, b1, b2, b3, b4 } #endif
gpl-3.0
marcosfede/algorithms
array/two_sum/two_sum.go
350
package main import "fmt" func twoSum(nums []int, target int) []int { dic := make(map[int]int) for i := 0; i < len(nums); i++ { num := nums[i] if idx, ok := dic[num]; ok { return []int{idx, i} } dic[target-num] = i } return []int{} } func main() { arr := []int{3, 2, 4} target := 6 res := twoSum(arr, target) fmt.Println(res) }
gpl-3.0
AlronDerRe/LWJGL3_basic_code
basic lwjgl3/src/Graphics/Textures/TextureLoader.java
1913
package Graphics.Textures; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import javax.imageio.ImageIO; import org.lwjgl.opengl.GL11; import org.lwjglx.BufferUtils; public abstract class TextureLoader { public static int generateTexture(String texPath){ BufferedImage img; int texID = glGenTextures(); //Récupération de l'image via les fonctions java.awt try { img = ImageIO.read(new File(texPath)); } catch (IOException e) { System.err.println("Impossible de charger : " + texPath + " !"); e.printStackTrace(); img = null; texID = 0; } if(texID != 0){ int bytePerPixel = 4; int pixels[] = new int[img.getHeight() * img.getWidth()]; img.getRGB(0, 0, img.getWidth(), img.getHeight(), pixels, 0, img.getWidth()); ByteBuffer bb = BufferUtils.createByteBuffer(img.getHeight() * img.getWidth()*bytePerPixel); for(int y = 0; y < img.getHeight(); y++){ for(int x = 0; x < img.getWidth(); x++){ int pixel = pixels[y * img.getWidth() + x]; bb.put((byte) ((pixel >> 16) & 0xFF)); bb.put((byte) ((pixel >> 8) & 0xFF)); bb.put((byte) (pixel & 0xFF)); bb.put((byte) ((pixel >> 24) & 0xFF)); } } bb.flip(); glBindTexture(GL_TEXTURE_2D, texID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //Setup texture scaling filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.getWidth(), img.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, bb); } return texID; } }
gpl-3.0
Konctantin/CSharpAssembler
SharpAssembler.Architectures.X86/Source/Instructions/Xchg.cs
10386
#region Copyright and License /* * SharpAssembler * Library for .NET that assembles a predetermined list of * instructions into machine code. * * Copyright (C) 2011 Daniël Pelsmaeker * * This file is part of SharpAssembler. * * SharpAssembler 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. * * SharpAssembler 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 SharpAssembler. If not, see <http://www.gnu.org/licenses/>. */ #endregion using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using SharpAssembler.Architectures.X86.Operands; namespace SharpAssembler.Architectures.X86.Instructions { /// <summary> /// The XCHG (Exchange) instruction. /// </summary> public class Xchg : X86Instruction, ILockInstruction { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Xchg"/> class. /// </summary> /// <param name="first">The first operand.</param> /// <param name="second">The second operand.</param> public Xchg(RegisterOperand first, RegisterOperand second) : this((Operand)first, second) { #region Contract Contract.Requires<ArgumentNullException>(first != null); Contract.Requires<ArgumentNullException>(second != null); #endregion } /// <summary> /// Initializes a new instance of the <see cref="Xchg"/> class. /// </summary> /// <param name="first">The first operand.</param> /// <param name="second">The second operand.</param> public Xchg(EffectiveAddress first, RegisterOperand second) : this((Operand)first, second) { #region Contract Contract.Requires<ArgumentNullException>(first != null); Contract.Requires<ArgumentNullException>(second != null); #endregion } /// <summary> /// Initializes a new instance of the <see cref="Xchg"/> class. /// </summary> /// <param name="first">The first operand.</param> /// <param name="second">The second operand.</param> private Xchg(Operand first, RegisterOperand second) { #region Contract Contract.Requires<ArgumentNullException>(first != null); Contract.Requires<InvalidCastException>( first is EffectiveAddress || first is RegisterOperand); Contract.Requires<ArgumentNullException>(second != null); #endregion this.first = first; this.second = second; } #endregion #region Properties /// <summary> /// Gets the mnemonic of the instruction. /// </summary> /// <value>The mnemonic of the instruction.</value> public override string Mnemonic { get { return "xchg"; } } private Operand first; /// <summary> /// Gets the first operand of the instruction. /// </summary> /// <value>An <see cref="Operand"/>.</value> public Operand First { get { #region Contract Contract.Ensures(Contract.Result<Operand>() != null); Contract.Ensures( Contract.Result<Operand>() is EffectiveAddress || Contract.Result<Operand>() is RegisterOperand); #endregion return first; } #if OPERAND_SET set { #region Contract Contract.Requires<ArgumentNullException>(value != null); Contract.Requires<InvalidCastException>( value is EffectiveAddress || value is RegisterOperand); #endregion first = value; } #endif } private RegisterOperand second; /// <summary> /// Gets the second operand of the instruction. /// </summary> /// <value>A <see cref="RegisterOperand"/>.</value> public RegisterOperand Second { get { #region Contract Contract.Ensures(Contract.Result<Operand>() != null); #endregion return second; } #if OPERAND_SET set { #region Contract Contract.Requires<ArgumentNullException>(value != null); #endregion second = value; } #endif } private bool lockInstruction = false; /// <summary> /// Gets or sets whether the lock prefix is used. /// </summary> /// <value><see langword="true"/> to enable the lock prefix; otherwise, <see langword="false"/>. /// The default is <see langword="false"/>.</value> /// <remarks> /// When this property is set to <see langword="true"/>, the lock signal is asserted before accessing the /// specified memory location. When the lock signal has already been asserted, the instruction must wait for it /// to be released. Instructions without the lock prefix do not check the lock signal, and will be executed /// even when the lock signal is asserted by some other instruction. /// </remarks> public bool Lock { get { return lockInstruction; } set { lockInstruction = value; } } #endregion #region Methods /// <summary> /// Enumerates an ordered list of operands used by this instruction. /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="Operand"/> objects.</returns> public override IEnumerable<Operand> GetOperands() { // The order is important here! yield return this.first; yield return this.second; } #endregion #region Instruction Variants /// <summary> /// An array of <see cref="SharpAssembler.Architectures.X86.X86Instruction.InstructionVariant"/> objects /// describing the possible variants of this instruction. /// </summary> private static InstructionVariant[] variants = new[]{ // XCHG AX, reg16 new InstructionVariant( new byte[] { 0x90 }, new OperandDescriptor(Register.AX), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose16Bit, OperandEncoding.OpcodeAdd)), // XCHG reg16, AX new InstructionVariant( new byte[] { 0x90 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose16Bit, OperandEncoding.OpcodeAdd), new OperandDescriptor(Register.AX)), // XCHG EAX, reg32 new InstructionVariant( new byte[] { 0x90 }, new OperandDescriptor(Register.EAX), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose32Bit, OperandEncoding.OpcodeAdd)), // XCHG reg32, EAX new InstructionVariant( new byte[] { 0x90 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose32Bit, OperandEncoding.OpcodeAdd), new OperandDescriptor(Register.EAX)), // XCHG RAX, reg64 new InstructionVariant( new byte[] { 0x90 }, new OperandDescriptor(Register.RAX), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose64Bit, OperandEncoding.OpcodeAdd)), // XCHG reg64, RAX new InstructionVariant( new byte[] { 0x90 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose64Bit, OperandEncoding.OpcodeAdd), new OperandDescriptor(Register.RAX)), // XCHG reg/mem8, reg8 new InstructionVariant( new byte[] { 0x86 }, new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose8Bit), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose8Bit)), // XCHG reg8, reg/mem8 new InstructionVariant( new byte[] { 0x86 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose8Bit), new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose8Bit)), // XCHG reg/mem16, reg16 new InstructionVariant( new byte[] { 0x87 }, new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose16Bit), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose16Bit)), // XCHG reg16, reg/mem16 new InstructionVariant( new byte[] { 0x87 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose16Bit), new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose16Bit)), // XCHG reg/mem32, reg32 new InstructionVariant( new byte[] { 0x87 }, new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose32Bit), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose32Bit)), // XCHG reg32, reg/mem32 new InstructionVariant( new byte[] { 0x87 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose32Bit), new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose32Bit)), // XCHG reg/mem64, reg64 new InstructionVariant( new byte[] { 0x87 }, new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose64Bit), new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose64Bit)), // XCHG reg64, reg/mem64 new InstructionVariant( new byte[] { 0x87 }, new OperandDescriptor(OperandType.RegisterOperand, RegisterType.GeneralPurpose64Bit), new OperandDescriptor(OperandType.RegisterOrMemoryOperand, RegisterType.GeneralPurpose64Bit)), }; /// <summary> /// Returns an array containing the <see cref="SharpAssembler.Architectures.X86.X86Instruction.InstructionVariant"/> /// objects representing all the possible variants of this instruction. /// </summary> /// <returns>An array of <see cref="SharpAssembler.Architectures.X86.X86Instruction.InstructionVariant"/> /// objects.</returns> internal override InstructionVariant[] GetVariantList() { return variants; } #endregion #region Invariant /// <summary> /// Asserts the invariants of this type. /// </summary> [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.first != null); Contract.Invariant( this.first is EffectiveAddress || this.first is RegisterOperand); Contract.Invariant(this.second != null); } #endregion } }
gpl-3.0
jdekozak/galgebra
galgebra/map/detail/distance_impl.hpp
670
#if !defined(GALGEBRA_MAP_DISTANCE_IMPL) #define GALGEBRA_MAP_DISTANCE_IMPL #include <boost/mpl/minus.hpp> namespace galgebra { struct map_iterator_tag; } namespace boost { namespace fusion { namespace extension { template<typename Tag> struct distance_impl; template<> struct distance_impl<galgebra::map_iterator_tag> { template<typename First, typename Last> struct apply : boost::mpl::minus<typename Last::index, typename First::index> { typedef apply<First, Last> self; static typename self::type call(First const& first, Last const& last) { return typename self::type(); } }; }; } } } #endif
gpl-3.0
Gwynthell/FFDB
scripts/zones/Apollyon/TextIDs.lua
551
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6376; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6379; -- Obtained: <item> GIL_OBTAINED = 6380; -- Obtained <number> gil KEYITEM_OBTAINED = 6382; -- Obtained key item: <keyitem> CONDITION_FOR_LIMBUS = 7029; -- You have clearance to enter Limbus, but cannot enter while you or a party member is engaged in battle. CHIP_TRADE = 7022; -- -- Cannot find correct TextID for CHIP_TRADE
gpl-3.0
appnativa/rare
source/rare/core/com/appnativa/rare/spot/CheckBoxTree.java
2897
/************************************************************************** * CheckBoxTree.java - Wed Feb 17 10:42:11 PST 2016 * * Copyright (c) appNativa * * All rights reserved. * * Generated by the Sparse Notation(tm) To Java Compiler v1.0 * Note 1: Code entered after the "//USER_IMPORTS_AND_COMMENTS_MARK{}" comment and before the class declaration will be preserved. * Note 2: Code entered out side of the other comment blocks will be preserved * Note 3: If you edit the automatically generated comments and want to preserve your edits remove the //GENERATED_COMMENT{} tags */ package com.appnativa.rare.spot; import com.appnativa.spot.*; //USER_IMPORTS_AND_COMMENTS_MARK{} //GENERATED_COMMENT{} /** * This class represents configuration information for a widget * that displays and manages hierarchical set of data items * <p> * and provides functionality for expanding and contracting * those items. Each node is also preceded by a check box that * can independently selected * </p> * * @author Don DeCoteau * @version 2.0 */ public class CheckBoxTree extends Tree { //GENERATED_MEMBERS{ /** Design: whether checkboxes and the list selection are automatically linked */ public SPOTBoolean linkSelection = new SPOTBoolean(null, false, false ); /** Design: whether the checkbox is leading or trailing the item */ public SPOTBoolean checkboxTrailing = new SPOTBoolean(null, false, false ); /** Behavior: whether checking the parent node will force all children to be selected */ public SPOTBoolean manageChildNodeSelections = new SPOTBoolean(null, true, false ); //}GENERATED_MEMBERS //GENERATED_METHODS{ /** * Creates a new optional <code>CheckBoxTree</code> object. */ public CheckBoxTree() { this(true); } /** * Creates a new <code>CheckBoxTree</code> object. * * @param optional <code>true</code> if the element is optional; <code>false</code> otherwise) */ public CheckBoxTree( boolean optional ) { super( optional, false ); spot_setElements(); } /** * Creates a new <code>CheckBoxTree</code> object. * * @param optional <code>true</code> if the element is optional; <code>false</code> otherwise) * @param setElements <code>true</code> if a call to setElements should be made; <code>false</code> otherwise) */ protected CheckBoxTree( boolean optional,boolean setElements ) { super( optional, setElements ); } /** * Adds elements to the object elements map * */ protected void spot_setElements() { this.elementsSizeHint +=3; super.spot_setElements(); spot_addElement( "linkSelection", linkSelection ); spot_addElement( "checkboxTrailing", checkboxTrailing ); spot_addElement( "manageChildNodeSelections", manageChildNodeSelections ); } //}GENERATED_METHODS //GENERATED_INNER_CLASSES{ //}GENERATED_INNER_CLASSES }
gpl-3.0
sloanr333/opd-legacy
src/com/watabou/legacy/items/scrolls/InventoryScroll.java
2728
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * 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 com.watabou.legacy.items.scrolls; import com.watabou.legacy.Assets; import com.watabou.legacy.actors.buffs.Invisibility; import com.watabou.legacy.items.Item; import com.watabou.legacy.scenes.GameScene; import com.watabou.legacy.windows.WndBag; import com.watabou.legacy.windows.WndOptions; import com.watabou.noosa.audio.Sample; public abstract class InventoryScroll extends Scroll { protected String inventoryTitle = "Select an item"; protected WndBag.Mode mode = WndBag.Mode.ALL; private static final String TXT_WARNING = "Do you really want to cancel this scroll usage? It will be consumed anyway."; private static final String TXT_YES = "Yes, I'm positive"; private static final String TXT_NO = "No, I changed my mind"; @Override protected void doRead() { if (!isKnown()) { setKnown(); identifiedByUse = true; } else { identifiedByUse = false; } GameScene.selectItem( itemSelector, mode, inventoryTitle ); } private void confirmCancelation() { GameScene.show( new WndOptions( name(), TXT_WARNING, TXT_YES, TXT_NO ) { @Override protected void onSelect( int index ) { switch (index) { case 0: curUser.spendAndNext( TIME_TO_READ ); identifiedByUse = false; break; case 1: GameScene.selectItem( itemSelector, mode, inventoryTitle ); break; } } public void onBackPressed() {}; } ); } protected abstract void onItemSelected( Item item ); protected static boolean identifiedByUse = false; protected static WndBag.Listener itemSelector = new WndBag.Listener() { @Override public void onSelect( Item item ) { if (item != null) { ((InventoryScroll)curItem).onItemSelected( item ); curUser.spendAndNext( TIME_TO_READ ); Sample.INSTANCE.play( Assets.SND_READ ); Invisibility.dispel(); } else if (identifiedByUse) { ((InventoryScroll)curItem).confirmCancelation(); } else { curItem.collect( curUser.belongings.backpack ); } } }; }
gpl-3.0
BigMaMonkey/easygen
src/main/java/org/bigmamonkey/modelBuilder/TableField.java
3064
package org.bigmamonkey.modelBuilder; import org.bigmamonkey.util.StringUtil; import java.sql.Types; /** * Created by bigmamonkey on 5/22/17. */ public class TableField { private String name; // 原始字段名 private String upperCaseName; // 首字母大写字段名 private int dataType; // 字段类型值,对应 java.sql.Types中的枚举值 private DbColumnType columnType; private String typeName; // 字段数据库类型,其他类型参见源码:TableField.java private int columnSize; // 字段大小 private String remarks; // 字段注释 public String getName() { return name; } public void setName(String name) throws Exception { this.name = name; this.upperCaseName = StringUtil.ToUpperName(name); } public String getUpperCaseName() { return upperCaseName; } public void setUpperCaseName(String upperCaseName) { this.upperCaseName = upperCaseName; } public int getDataType() { return dataType; } public void setDataType(int dataType) { this.dataType = dataType; switch (dataType) { case Types.INTEGER: columnType = DbColumnType.INTEGER; typeName = "INTEGER"; break; case Types.BIGINT: columnType = DbColumnType.LONG; typeName = "BIGINT"; break; case Types.BIT: columnType = DbColumnType.BOOLEAN; typeName = "BIT"; break; case Types.VARCHAR: columnType = DbColumnType.STRING; typeName = "VARCHAR"; break; case Types.TIMESTAMP: columnType = DbColumnType.DATE; typeName = "TIMESTAMP"; break; case Types.FLOAT: columnType = DbColumnType.FLOAT; typeName = "FLOAT"; break; case Types.REAL: columnType = DbColumnType.FLOAT; typeName = "FLOAT"; break; case Types.DOUBLE: columnType = DbColumnType.DOUBLE; typeName = "DOUBLE"; break; default: columnType = DbColumnType.STRING; typeName = "VARCHAR"; break; } } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public int getColumnSize() { return columnSize; } public void setColumnSize(int columnSize) { this.columnSize = columnSize; } public DbColumnType getColumnType() { return columnType; } public void setColumnType(DbColumnType columnType) { this.columnType = columnType; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } }
gpl-3.0
dasbruns/netzob
src/netzob/Common/Models/Vocabulary/Domain/Parser/all.py
2301
#!/usr/bin/env python # -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011-2014 Georges Bossert and Frédéric Guihéry | #| 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/>. | #+---------------------------------------------------------------------------+ #| @url : http://www.netzob.org | #| @contact : contact@netzob.org | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ # List subpackages to import with the current one # see docs.python.org/2/tutorial/modules.html from netzob.Common.Models.Vocabulary.Domain.Parser.FieldParser import FieldParser from netzob.Common.Models.Vocabulary.Domain.Parser.VariableParser import VariableParser from netzob.Common.Models.Vocabulary.Domain.Parser.MessageParser import MessageParser
gpl-3.0
Xexanos/LibreCarSharing
LibreCarSharing-persistence/src/main/java/de/librecarsharing/DBCommunity.java
1630
package de.librecarsharing; import javax.persistence.*; import java.util.*; @Entity public class DBCommunity extends DBIdentified{ private String name; private Set<DBCar> cars; private Set<DBUser> users; private DBUser admin; public DBCommunity() { users= new HashSet<DBUser>(); cars = new HashSet<DBCar>(); } @ManyToOne public DBUser getAdmin() { return admin; } public void setAdmin(DBUser admin) { this.admin = admin; } @ManyToMany(mappedBy = "communities") public Set<DBUser> getUsers() { return users; } public void setUsers(Set<DBUser> users) { this.users = users; } public void addUser(DBUser user) { this.users.add(user); if (!user.getCommunities().contains(this)) { user.addCommunity(this); } } public void removeUser(DBUser user){ if(user.getCommunities().contains(this)) user.getCommunities().remove(this); this.users.remove(user); } @OneToMany(mappedBy ="community",cascade = CascadeType.REMOVE) public Set<DBCar> getCars() { return cars; } public void setCars(Set<DBCar> cars) { this.cars = cars; } public void addCar(DBCar car) { this.cars.add(car); if (car.getCommunity()!=this) { car.setCommunity(this); } } @Basic public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return this.getName(); } }
gpl-3.0
YiqunPeng/Leetcode-pyq
solutions/907SumOfSubarrayMinimums.py
1056
class Solution: def sumSubarrayMins(self, A): """ :type A: List[int] :rtype: int """ m = 10 ** 9 + 7 ans = 0 right = [0] * len(A) left = [0] * len(A) stack = [0] for i in range(1, len(A)): if A[i] <= A[stack[-1]]: while stack and A[i] <= A[stack[-1]]: right[stack[-1]] = i - stack[-1] stack.pop() stack.append(i) for i in range(len(stack)): right[stack[i]] = len(A) - stack[i] stack = [len(A)-1] for i in range(len(A)-2, -1, -1): if A[i] < A[stack[-1]]: while stack and A[i] < A[stack[-1]]: left[stack[-1]] = stack[-1] - i stack.pop() stack.append(i) for i in range(len(stack)): left[stack[i]] = stack[i] + 1 for i in range(len(right)): ans = ans + (right[i] * left[i] * A[i]) % m return ans % m
gpl-3.0
MarcinWieczorek/NovaGuilds
src/main/java/co/marcin/novaguilds/impl/versionimpl/v1_8_R3/TitleImpl.java
2868
/* * NovaGuilds - Bukkit plugin * Copyright (C) 2018 Marcin (CTRL) Wieczorek * * 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 co.marcin.novaguilds.impl.versionimpl.v1_8_R3; import co.marcin.novaguilds.api.util.Title; import co.marcin.novaguilds.impl.util.AbstractTitle; import co.marcin.novaguilds.impl.versionimpl.v1_8_R3.packet.PacketPlayOutTitle; import co.marcin.novaguilds.util.LoggerUtils; import co.marcin.novaguilds.util.StringUtils; import org.bukkit.entity.Player; public class TitleImpl extends AbstractTitle { public TitleImpl() { super(""); } public TitleImpl(String title) { super(title); } public TitleImpl(String title, String subtitle) { super(title, subtitle); } public TitleImpl(Title title) { super(title); } public TitleImpl(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { super(title, subtitle, fadeInTime, stayTime, fadeOutTime); } @Override public void send(Player player) { resetTitle(player); try { if(fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) { new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, null, fadeInTime * (ticks ? 1 : 20), stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20)).send(player); } String titleJson = "{text:\"" + StringUtils.fixColors(title) + "\",color:" + titleColor.name().toLowerCase() + "}"; new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, titleJson).send(player); if(subtitle != null) { String subTitleJson = "{text:\"" + StringUtils.fixColors(subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}"; new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, subTitleJson).send(player); } } catch(Exception e) { LoggerUtils.exception(e); } } @Override public void clearTitle(Player player) { try { new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.CLEAR, null).send(player); } catch(Exception e) { LoggerUtils.exception(e); } } @Override public void resetTitle(Player player) { try { new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.RESET, null).send(player); } catch(Exception e) { LoggerUtils.exception(e); } } }
gpl-3.0
Ostrich-Emulators/semtool
gui/src/main/java/com/ostrichemulators/semtool/ui/components/playsheets/graphsupport/NodeInfoPopup.java
3134
/** * ***************************************************************************** * Copyright 2013 SEMOSS.ORG * * This file is part of SEMOSS. * * SEMOSS 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. * * SEMOSS 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 * SEMOSS. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************** */ package com.ostrichemulators.semtool.ui.components.playsheets.graphsupport; import com.ostrichemulators.semtool.om.GraphElement; import com.ostrichemulators.semtool.ui.components.playsheets.GraphPlaySheet; import com.ostrichemulators.semtool.ui.components.playsheets.GridPlaySheet; import com.ostrichemulators.semtool.util.MultiMap; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; /** * This class is used to display information about a node in a popup window. */ public class NodeInfoPopup extends AbstractAction { private static final long serialVersionUID = -1859278887122010885L; private final GraphPlaySheet gps; private final Collection<GraphElement> pickedVertex; public NodeInfoPopup( GraphPlaySheet gps, Collection<GraphElement> picked ) { super( "Show Information about Selected Node(s)" ); this.putValue( Action.SHORT_DESCRIPTION, "Draw a box to select nodes, or hold Shift and click on nodes" ); this.gps = gps; pickedVertex = picked; } @Override public void actionPerformed( ActionEvent ae ) { MultiMap<IRI, GraphElement> typeCounts = new MultiMap<>(); for ( GraphElement v : pickedVertex ) { IRI vType = v.getType(); typeCounts.add( vType, v ); } ValueFactory vf = SimpleValueFactory.getInstance(); List<Value[]> data = new ArrayList<>(); int total = 0; for ( Map.Entry<IRI, List<GraphElement>> en : typeCounts.entrySet() ) { Value[] row = { en.getKey(), vf.createLiteral( en.getValue().size() ) }; data.add( row ); total += en.getValue().size(); } data.add( new Value[]{ vf.createLiteral( "Total Vertex Count" ), vf.createLiteral( total ) } ); GridPlaySheet grid = new GridPlaySheet(); grid.setTitle( "Selected Node/Edge Information" ); grid.create( data, Arrays.asList( "Property Name", "Value" ), gps.getEngine() ); gps.addSibling( grid ); } }
gpl-3.0