branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>TYPO3-svn-archive/jhe_esv2typo3<file_sep>/mod1/index.php
<?php
/***************************************************************
* Copyright notice
*
* (c) 2010 <NAME> <<EMAIL>>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* [CLASS/FUNCTION INDEX of SCRIPT]
*
*
*
* 57: class tx_jheesv2typo3_module1 extends t3lib_SCbase
* 65: function init()
* 82: function menuConfig()
* 100: function main()
* 119: function jumpToUrl(URL)
* 169: function printContent()
* 180: function moduleContent()
*
* TOTAL FUNCTIONS: 6
* (This index is automatically created/updated by the extension "extdeveval")
*
*/
$LANG->includeLLFile('EXT:jhe_esv2typo3/mod1/locallang.xml');
require_once(PATH_t3lib . 'class.t3lib_scbase.php');
$BE_USER->modAccess($MCONF, 1); // This checks permissions and exits if the users has no permission for entry.
// DEFAULT initialization of a module [END]
/**
* Module 'Erich Schmidt Verlag' for the 'jhe_esv2typo3' extension.
*
* @author <NAME> <<EMAIL>>
* @package TYPO3
* @subpackage tx_jheesv2typo3
*/
class tx_jheesv2typo3_module1 extends t3lib_SCbase {
var $pageinfo;
/**
* Initializes the Module
*
* @return void
*/
function init() {
global $BE_USER, $LANG, $BACK_PATH, $TCA_DESCR, $TCA, $CLIENT, $TYPO3_CONF_VARS;
parent::init();
/*
if (t3lib_div::_GP('clear_all_cache')) {
$this->include_once[] = PATH_t3lib.'class.t3lib_tcemain.php';
}
*/
}
/**
* Adds items to the->MOD_MENU array. Used for the function menu selector.
*
* @return void
*/
function menuConfig() {
global $LANG;
$this->MOD_MENU = Array (
'function' => Array (
'1' => $LANG->getLL('function1'),
'2' => $LANG->getLL('function2'),
'3' => $LANG->getLL('function3'),
)
);
parent::menuConfig();
}
/**
* Main function of the module. Write the content to $this->content
* If you chose "web" as main module, you will need to consider the $this->id parameter which will contain the uid-number of the page clicked in the page tree
*
* @return [type] ...
*/
function main() {
global $BE_USER, $LANG, $BACK_PATH, $TCA_DESCR, $TCA, $CLIENT, $TYPO3_CONF_VARS;
// Access check!
// The page will show only if there is a valid page and if this page may be viewed by the user
$this->pageinfo = t3lib_BEfunc::readPageAccess($this->id, $this->perms_clause);
$access = is_array($this->pageinfo) ? 1 : 0;
if (($this->id && $access) || ($BE_USER->user['admin'] && !$this->id)) {
// Draw the header.
$this->doc = t3lib_div::makeInstance('mediumDoc');
$this->doc->backPath = $BACK_PATH;
$this->doc->form = '<form action="" method="post" enctype="multipart/form-data" >';
// JavaScript
$this->doc->JScode = '
<script language="javascript" type="text/javascript">
script_ended = 0;
function jumpToUrl(URL) {
document.location = URL;
}
</script>
';
$this->doc->postCode = '
<script language="javascript" type="text/javascript">
script_ended = 1;
if (top.fsMod) top.fsMod.recentIds["web"] = 0;
</script>
';
$headerSection = $this->doc->getHeader('pages', $this->pageinfo, $this->pageinfo['_thePath']).'<br />'.$LANG->sL('LLL:EXT:lang/locallang_core.xml:labels.path').': '.t3lib_div::fixed_lgd_pre($this->pageinfo['_thePath'], 50);
$this->content .= $this->doc->startPage($LANG->getLL('title'));
$this->content .= $this->doc->header($LANG->getLL('title'));
$this->content .= $this->doc->spacer(5);
//$this->content.=$this->doc->section('',$this->doc->funcMenu($headerSection,t3lib_BEfunc::getFuncMenu($this->id,'SET[function]',$this->MOD_SETTINGS['function'],$this->MOD_MENU['function'])));
$this->content .= $this->doc->divider(5);
// Render content:
$this->moduleContent();
// ShortCut
if ($BE_USER->mayMakeShortcut()) {
$this->content .= $this->doc->spacer(20).$this->doc->section('', $this->doc->makeShortcutIcon('id', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name']));
}
$this->content .= $this->doc->spacer(10);
} else {
// If no access or if ID == zero
$this->doc = t3lib_div::makeInstance('mediumDoc');
$this->doc->backPath = $BACK_PATH;
$this->content .= $this->doc->startPage($LANG->getLL('title'));
$this->content .= $this->doc->header($LANG->getLL('title'));
$this->content .= $this->doc->spacer(5);
$this->content .= $this->doc->spacer(10);
}
}
/**
* Prints out the module HTML
*
* @return void
*/
function printContent() {
$this->content .= $this->doc->endPage();
echo $this->content;
}
/**
* Generates the module content
*
* @return void
*/
function moduleContent() {
global $GLOBALS, $LANG, $BACK_PATH;
$confArr = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['jhe_esv2typo3']);
$confArr['targetPath'] = t3lib_extMgm::extPath('jhe_esv2typo3'). 'data/';
$confArr['backupPath'] = t3lib_extMgm::extPath('jhe_esv2typo3'). 'data/backup/';
$confArr['donePath'] = t3lib_extMgm::extPath('jhe_esv2typo3'). 'data/done/';
$content .= '<input type="hidden" name="action" value="startImport">';
$content .= '<input type="submit" value="' . $LANG->getLL('startImport') . '" />';
$content .= '<br /><br /><br />';
if(t3lib_div::_POST('action') == 'startImport') {
$content .= 'Import geht los!<br />';
$content .= $this->getDataAndPutItToDB($confArr);
}
//$content .= '<br />GET:'.t3lib_div::view_array($_GET).'<br />'. 'POST:'.t3lib_div::view_array($_POST).'<br />'. '';
$this->content .= $this->doc->section('', $content, 0, 1);
}
public function getDataAndPutItToDB($confArr){
//Collect all existing ident numbers in DB
$identArr = $this->getIdentNoFromDBBeforeDBAction();
//Establishing the ftp connection
if(!$ftp_connection = $this->establishFTPConnection($confArr['ftpHost'], $confArr['ftpUser'], $confArr['ftpPassword'])) {
$return .= 'Es wurde keine FTP-Verbindung aufgebaut!<br />';
} else {
$return .= 'FTP-Verbindung steht!<br />';
}
//Try to change to the file directory
if (!ftp_chdir($ftp_connection, $confArr['ftpFolder'])) {
$return .= 'Could not change to the given file directory $ftp_path!<br />';
} else {
$return .= 'Das Arbeitsverzeichnis auf dem FTP-Server wurde gefunden!<br />';
}
//Get all files in data directory
$filesArr = ftp_nlist($ftp_connection, ".");
if(count($filesArr) == 0){
$return .= 'Es befinden sich zur Zeit keine Dateien im Arbeitsverzeichnis!<br />';
die;
}
//Identify zip files in the right format
$workingArr = $this->searchForFileWithSpecificFormat($filesArr);
if(count($workingArr) == 0){
$return .= 'Es befinden sich zur Zeit keine relevanten Dateien im Arbeitsverzeichnis!<br />';
die;
}
//Copy relevant file(s) to '/data'
foreach($workingArr as $file){
$res = $this->copyRelevantFilesFromFTP($ftp_connection, $confArr['targetPath'], $file);
}
if(!$res) {
$return .= 'Could not copy $file from $ftp_server!<br />';
} else {
$return .= 'Die Datei ' . $file . ' wurde erfolgreich vom FTP-Server heruntergeladen!<br />';
}
//Generates backup file(s)
foreach($workingArr as $file){
$success = $this->generateBackupFile($confArr['targetPath'], $confArr['backupPath'], $file);
}
if(!$success){
$return .= 'Backing up $file failed!<br />';
} else {
$return .= 'Backup von ' . $file . ' wurde erfolgreich angelegt!<br />';
}
//Extract zip file(s)
foreach($workingArr as $file){
$extract = $this->extractZipFile($confArr['targetPath'], $file);
}
if(!$extract){
$return .= 'Could not extract $targetFile!<br />';
} else {
$return .= 'Die Datei ' . $file . ' wurde erfolgreich entzipped!<br />';
}
//Delete the original file(s) from this server
foreach($workingArr as $file){
$delete = $this->deleteImportedFile($confArr['targetPath'], $file);
}
if(!$delete) {
$return .= 'Could not delete ' . $file . '!<br />';
} else {
$return .= 'Die importierte Datei ' . $file . ' wurde erfolreich wieder gelöscht!<br />';
}
//new array container for identifying all imported data for later purpose
$identImportArr = array();
$countUpdate = 0;
$countInsert = 0;
//für jede Datei im entzippten Ordner
//read in content of all files in newDir to array $xmlFiles
foreach($workingArr as $file){
$dir = $this->getDirNameFromZipFile($file);
$xmlFiles = t3lib_div::getFilesInDir($confArr['targetPath'] . $dir . '/');
sort($xmlFiles);
foreach($xmlFiles as $xmlFile){
//Check if filetype is xml
if(substr($xmlFile, -4) == '.xml'){
//Extract data from each xml file
$xmlArr = t3lib_div::xml2array(file_get_contents($confArr['targetPath'] . $dir . '/' . $xmlFile));
//Mapping xml structure <-> tx_dam fieldnames
$xml2dbMapping = array(
'esv.verlagsname' => 'tx_jheesv2typo3_publishing_house',
'esv.verlagsort' => 'tx_jheesv2typo3_place_publishing',
'esv.copyright' => 'copyright',
'esv.doipraefix' => 'tx_jheesv2typo3_doiprefix',
'esv.nodeid' => 'ident',
'esv.herausgeber' => 'publisher',
'esv.titel' => 'title',
'esv.doklink' => 'tx_dam.tx_jheesv2typo3_doklink',
'esv.inhaltstyp' => 'tx_jheesv2typo3_contenttype',
'esv.sachgebiet' => 'tx_jheesv2typo3_field_of_reference',
'esv.gesetzstatus' => 'tx_jheesv2typo3_state_of_law',
'esv.gesetzbereich' => 'tx_jheesv2typo3_field_of_law',
'esv.gesetzbezeichnung' => 'tx_jheesv2typo3_name_of_law',
'esv.gesetzkurzname' => 'tx_jheesv2typo3_short_name_of_law',
'esv.gesetzabkuerzung' => 'tx_jheesv2typo3_abbreviation_of_law',
'esv.rechtsgebiet' => 'tx_jheesv2typo3_field_of_law',
'esv.ausfertigungsdatum' => 'tx_jheesv2typo3_date_of_issue',
'esv.verkuendungsfundstelle' => 'tx_jheesv2typo3_source_of_proclamation',
'esv.aenderungsdatum' => 'tx_jheesv2typo3_modification_date',
'esv.aenderungfundstelle' => 'tx_jheesv2typo3_source_of_modification',
'esv.aenderungspublikationsdatum' => 'tx_jheesv2typo3_modification_publication_date',
'esv.inkrafttreten' => 'tx_jheesv2typo3_commencement'
);
//generate new array for db action
foreach($xmlArr as $subArr) {
foreach ($subArr as $k => $v) {
$i = str_replace(array_keys($xml2dbMapping), $xml2dbMapping, $k);
$xmlArrChanged[$i] = $v;
}
}
//get common t3 data for db action
$xmlArrT3 = array(
'pid' => $confArr['literatureMainFolder'] //@TODO: DATUMSFELDER ANPASSEN; CRDATE UND MODDATE ANPASSEN
);
//Merge arrays before db action
$xmlArrChanged = array_merge($xmlArrChanged, $xmlArrT3);
//check for db action
if(in_array($xmlArrChanged['ident'], $identArr)){
//Update data in db
if (!$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_dam','ident = ' .$xmlArrChanged['ident'], $xmlArrChanged )) {
die('DB-Update ' . $xmlArrChanged['ident'] . ' fehlgeschlagen');
}
////Collect ident numbers of all imported files for later purpose
$identImportArr[] = $xmlArrChanged['ident'];
//Copy xml file to done directory
$this->copyXmlFileToDone($confArr['targetPath'], $confArr['donePath'], $dir, $xmlFile);
//Delete extracted xml files
$this->deleteOriginalXmlFile($confArr['targetPath'], $dir, $xmlFile);
//Count Updates
$countUpdate++;
} else {
//Insert data to db
if (!$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dam',$xmlArrChanged )) {
die('DB-Insert ' . $xmlArrChanged['ident'] . ' fehlgeschlagen');
}
////Collect ident numbers of all imported files for later purpose
$identImportArr[] = $xmlArrChanged['ident'];
//Copy xml file to done directory
$this->copyXmlFileToDone($confArr['targetPath'], $confArr['donePath'], $dir, $xmlFile);
//Delete extracted xml files
$this->deleteOriginalXmlFile($confArr['targetPath'], $dir, $xmlFile);
//Count Inserts
$countInsert++;
}
} else {
//@TODO: Loggen)
}
}
$return .= $countUpdate . ' Updates / ' . $countInsert . ' Inserts<br />';
//Delete temporary directory if empty after db action
if(count(t3lib_div::getFilesInDir($confArr['targetPath'] . $dir)) == 0){
if(!$this->deleteTemporaryDirectory($confArr['targetPath'], $dir)) {
$return .= 'Arbeitsverzeichnis ' . $confArr['targetPath'] . $dir . ' konnte nicht gelöscht werden!<br />';
} else {
$return .= 'Arbeitsverzeichnis ' . $dir . ' wurde erfolgreich gelöscht!<br />';
}
}
}
//Get flag for delete action from configuration
if($confArr['delete'] == '1'){
$countDelete = 0;
//Mark all untouched records as deleted
$deleteArr = array_diff($identArr, $identImportArr);
foreach($deleteArr as $deleteFile){
if (!$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_dam','ident = ' .$deleteFile, array('deleted' => '1'))) {
die('DB-Update für Datensatz mit der IdentNo. ' . $deleteFile . ' fehlgeschlagen');
}
$countDelete++;
}
$return .= 'Es wurden ' . $countDelete . ' Datensätze gelöscht!<br />';
}
//Deletes used zip file from ftp server
foreach($workingArr as $remoteFile){
if(!ftp_delete($ftp_connection, $confArr['ftpFolder'].$remoteFile)){
$return .= 'Die Ursprungsdatei konnte auf dem FTP-Server nicht gelöscht werden!<br />';
} else {
$return .= 'Die Ursprungsdatei wurde auf dem FTP-Server gelöscht!<br />';
}
}
//Close ftp connectiom
if(!ftp_close($ftp_connection)) {
$return .= 'Die FTP-Verbindung konnte nicht geschlossen werden!<br />';
} else {
$return .= 'Die FTP-Verbindung wurde beendet!<br />';
}
return $return;
}
//get all ident numbers from actual tx_dam
private function getIdentNoFromDBBeforeDBAction() {
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'ident',
'tx_dam',
' deleted = 0 AND hidden = 0'
);
$identArr = array();
while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)){
$identArr[] = $row['ident'];
}
return $identArr;
}
// Search for files with specific names in $filesArr
// File name begins with 'bad_export', ends with '.zip'
private function searchForFileWithSpecificFormat($filesArr) {
$cleanedFilesArr = array();
foreach($filesArr as $file){
if(substr($file, -4) == '.zip'){
if (substr($file, 0, 10) == 'bad_export') {
$cleanedFilesArr[] = $file;
}
}
}
return $cleanedFilesArr;
}
//Get new directory name from filename for later file operations
private function getDirNameFromZipFile ($file) {
return substr($file, 0, -4);
}
private function copyRelevantFilesFromFTP($ftp_connection, $targetPath, $file){
$targetFile = $targetPath . $file;
if (!ftp_get($ftp_connection, $targetFile, $file, FTP_BINARY)) {
return false;
} else {
return true;
}
}
//Generate backup file
private function generateBackupFile($targetPath, $backupPath, $file){
$targetFile = $targetPath . $file;
$backupFile = $backupPath . $file;
if (!copy($targetFile, $backupFile)) {
return false;
} else {
return true;
}
}
//Extract zip file
private function extractZipFile($targetPath, $file){
$targetFile = $targetPath . $file;
//if(!system("unzip $targetFile -d $targetPath", $retVal)) {
if(!exec("unzip $targetFile -d $targetPath")) {
return false;
} else {
return true;
}
}
//Delete imported file
private function deleteImportedFile($targetPath, $file){
$targetFile = $targetPath . $file;
if(!unlink($targetFile)) {
return false;
} else {
return true;
}
}
function establishFTPConnection($server,$user, $pw){
// Connect to ftp server
$conn_id = ftp_connect($server);
// Login w/ given username and password
$login_result = ftp_login($conn_id, $user, $pw);
// Check connection to ftp server
if ((!$conn_id) || (!$login_result)) {
die('Establishing the connection to $server failed!');
}
return $conn_id;
}
private function copyXmlFileToDone($targetPath, $donePath, $dir, $file){
if(!is_dir($donePath . $dir . '/')){
if(!mkdir($donePath . $dir . '/')){
die('Kann das Verzeichnis ' . $donePath . $dir . '/ nicht anlegen!');
}
}
$source = $targetPath . $dir . '/' . $file;
$destination = $donePath . $dir . '/' . $file;
if(!copy($source, $destination)){
die('$file konnte nicht nach $destination verschoben werden!');
}
}
private function deleteOriginalXmlFile($targetPath, $dir, $file){
$targetFile = $targetPath . $dir . '/' . $file;
if(!unlink($targetFile)) {
return false;
} else {
return true;
}
}
private function deleteTemporaryDirectory($targetPath, $dir) {
$targetDir = $targetPath . $dir;
if(!rmdir($targetDir)) {
return false;
} else {
return true;
}
}
}
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/jhe_esv2typo3/mod1/index.php']) {
include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/jhe_esv2typo3/mod1/index.php']);
}
// Make instance:
$SOBE = t3lib_div::makeInstance('tx_jheesv2typo3_module1');
$SOBE->init();
// Include files?
foreach($SOBE->include_once as $INC_FILE) include_once($INC_FILE);
$SOBE->main();
$SOBE->printContent();
?><file_sep>/ext_tables.sql
#
# Table structure for table 'tx_dam'
#
CREATE TABLE tx_dam (
tx_jheesv2typo3_publishing_house varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_place_publishing varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_doiprefix varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_doklink tinytext,
tx_jheesv2typo3_contenttype varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_field_of_reference varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_state_of_law varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_area_of_validity varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_name_of_law varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_short_name_of_law varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_abbreviation_of_law varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_field_of_law varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_field_of_law varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_date_of_issue int(11) DEFAULT '0' NOT NULL,
tx_jheesv2typo3_source_of_proclamation varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_modification_date int(11) DEFAULT '0' NOT NULL,
tx_jheesv2typo3_source_of_modification varchar(255) DEFAULT '' NOT NULL,
tx_jheesv2typo3_modification_publication_date int(11) DEFAULT '0' NOT NULL,
tx_jheesv2typo3_commencement int(11) DEFAULT '0' NOT NULL
);<file_sep>/ext_tables.php
<?php
if (!defined('TYPO3_MODE')) {
die ('Access denied.');
}
$tempColumns = array (
'tx_jheesv2typo3_publishing_house' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_publishing_house',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_place_publishing' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_place_publishing',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_doiprefix' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_doiprefix',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_doklink' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_doklink',
'config' => array (
'type' => 'input',
'size' => '15',
'max' => '255',
'checkbox' => '',
'eval' => 'trim',
'wizards' => array(
'_PADDING' => 2,
'link' => array(
'type' => 'popup',
'title' => 'Link',
'icon' => 'link_popup.gif',
'script' => 'browse_links.php?mode=wizard',
'JSopenParams' => 'height=300,width=500,status=0,menubar=0,scrollbars=1'
)
)
)
),
'tx_jheesv2typo3_contenttype' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_contenttype',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_field_of_reference' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_field_of_reference',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_state_of_law' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_state_of_law',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_area_of_validity' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_area_of_validity',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_name_of_law' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_name_of_law',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_short_name_of_law' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_short_name_of_law',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_abbreviation_of_law' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_abbreviation_of_law',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_field_of_law' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_field_of_law',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_date_of_issue' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_date_of_issue',
'config' => array (
'type' => 'input',
'size' => '8',
'max' => '20',
'eval' => 'date',
'checkbox' => '0',
'default' => '0'
)
),
'tx_jheesv2typo3_source_of_proclamation' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_source_of_proclamation',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_modification_date' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_modification_date',
'config' => array (
'type' => 'input',
'size' => '8',
'max' => '20',
'eval' => 'date',
'checkbox' => '0',
'default' => '0'
)
),
'tx_jheesv2typo3_source_of_modification' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_source_of_modification',
'config' => array (
'type' => 'input',
'size' => '30',
'eval' => 'trim',
)
),
'tx_jheesv2typo3_modification_publication_date' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_modification_publication_date',
'config' => array (
'type' => 'input',
'size' => '8',
'max' => '20',
'eval' => 'date',
'checkbox' => '0',
'default' => '0'
)
),
'tx_jheesv2typo3_commencement' => array (
'exclude' => 0,
'label' => 'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tx_dam.tx_jheesv2typo3_commencement',
'config' => array (
'type' => 'input',
'size' => '8',
'max' => '20',
'eval' => 'date',
'checkbox' => '0',
'default' => '0'
)
),
);
t3lib_div::loadTCA('tx_dam');
t3lib_extMgm::addTCAcolumns('tx_dam',$tempColumns,1);
t3lib_extMgm::addToAllTCAtypes('tx_dam','tx_jheesv2typo3_publishing_house;;;;1-1-1, tx_jheesv2typo3_place_publishing, tx_jheesv2typo3_doiprefix, tx_jheesv2typo3_doklink, tx_jheesv2typo3_contenttype, tx_jheesv2typo3_field_of_reference, tx_jheesv2typo3_state_of_law, tx_jheesv2typo3_field_of_law, tx_jheesv2typo3_name_of_law, tx_jheesv2typo3_short_name_of_law, tx_jheesv2typo3_abbreviation_of_law, tx_jheesv2typo3_date_of_issue, tx_jheesv2typo3_source_of_proclamation, tx_jheesv2typo3_modification_date, tx_jheesv2typo3_source_of_modification, tx_jheesv2typo3_modification_publication_date, tx_jheesv2typo3_commencement');
t3lib_div::loadTCA('tt_content');
$TCA['tt_content']['types']['list']['subtypes_excludelist'][$_EXTKEY.'_pi1']='layout,select_key';
t3lib_extMgm::addPlugin(array(
'LLL:EXT:jhe_esv2typo3/locallang_db.xml:tt_content.list_type_pi1',
$_EXTKEY . '_pi1',
t3lib_extMgm::extRelPath($_EXTKEY) . 'ext_icon.gif'
),'list_type');
if (TYPO3_MODE == 'BE') {
t3lib_extMgm::addModulePath('web_txjheesv2typo3M1', t3lib_extMgm::extPath($_EXTKEY) . 'mod1/');
t3lib_extMgm::addModule('web', 'txjheesv2typo3M1', '', t3lib_extMgm::extPath($_EXTKEY) . 'mod1/');
}
?> | ce46b0239f3db15ada0f9cd8f822e6f4fb4e42a5 | [
"SQL",
"PHP"
] | 3 | PHP | TYPO3-svn-archive/jhe_esv2typo3 | be5db541fe40e2eaa8c80717b42d192522544a0e | dfae84c222a241e894f917cf2f1f8b7e839721be |
refs/heads/dev | <file_sep>FROM openjdk:alpine
ENV FIRESTORE_VERSION 1.4.0
ADD https://storage.googleapis.com/firebase-preview-drop/emulator/cloud-firestore-emulator-v$FIRESTORE_VERSION.jar ./cloud-firestore-emulator.jar
EXPOSE 5555
CMD ["java", "-jar", "./cloud-firestore-emulator.jar", "--host=0.0.0.0", "--port=5555"]<file_sep>const sendgrid = require('@sendgrid/mail')
const sendgridConfig = require('../config/sendgrid-config')
const logger = require('./logger-client')
module.exports = {
/**
* Envia email utilizando API do SendGrid
* https://github.com/sendgrid/sendgrid-nodejs
*
* @param {Object} opts Atributos para envio de e-mails
* @param {Array} opts.to Lista de e-mails de destino
* @param {string} opts.subject Título do e-mail
* @param {string} opts.content Conteúdo do e-mail representado em formato `text/html`
*/
sendMail({ to, subject, content }) {
sendgrid.setApiKey(sendgridConfig.apiKey)
const opts = {
from: sendgridConfig.fromEmail,
to,
subject,
html: content
}
logger.debug({
action: 'sendgrid-client.sendMail',
message: 'Sending mail',
meta: opts
})
return sendgrid.send(opts)
}
}
<file_sep># Orientações Idvogados
Guia para código fonte de backend do projeto Idvogados.
O objetivo desse documento é descrever as decisões tomadas para definição da estrutura do código e guiar os desenvolvedores
## Nomenclatura
A nomenclatura segue as seguintes regras:
- Arquivos: Nome em minúsculo, separado por `-`. `nome-de-arquivo.js`.
- Código: [CamelCase](https://pt.wikipedia.org/wiki/CamelCase). `minhaVariavel`.
- Objetos JSON: Nome das chaves em [snake_case](https://en.wikipedia.org/wiki/Snake_case).
```json
{
"campo_com_multiplas_palavras": "valor"
}
```
## Estrutura de pastas
```
.github/
ISSUE_TEMPLATES/
bin/
docs/
src/
api/
client/
config/
errors/
helpers/
middlewares/
models/
routes/
services/
test/
acceptance/
unit/
```
### Propósito de cada uma das pastas escolhidas
#### bin/
Scripts e arquivos binários
### docs/
Documentações importantes para o projeto, comumente escritas em arquivo [Markdown](https://en.wikipedia.org/wiki/Markdown)
### src/
Todo código relacionado a camada de negócio da API
### src/api/
Handlers (Controllers) para os endpoints da API
### src/client/
Clientes de serviços ou módulos externos (Banco de dados, Fila, Log, etc)
### src/config/
Definição dos objetos de configurações da API
### src/errors/
Classes customizadas de erro, geralmente extendendo da classe padrão `Error` do JavaScript
### src/helpers/
Funções auxiliares
### src/middlewares/
Middlewares para serem usados junto a Framework HTTP
### src/models/
Entidades para acesso e manipulação de dados (ORM)
### src/routes/
Definição de rotas da API
### src/services/
Definição das regras de negócio das entidades
### test/acceptance/
Testes de aceitação da API, executando o fluxo de request e response em um endpoint
### test/unit/
Testes unitários dos módulos
## Scripts
O projeto conta com vários scripts que irão auxiliar no desenvolvimento e podem ser utilizados das seguintes formas:
### Comandos Node.js
- `npm run deps`: Inicia as dependências do projeto configurados no arquivo [`docker-compose.test.yml`](https://github.com/idvogados/backend/blob/dev/docker-compose.test.yml)
- `npm run start`: Inicia a API
- `npm run start:docker`: Inicia a API utilizando Docker
- `npm run debug`: Inicia a API em modo Debug
- `npm run cli`: Acessa a API em modo terminal na pasta raiz do projeto
- `npm run test`: Executa todos os testes (Pasta `test/*`)
- `npm run test:acceptance`: Executa somente os testes de aceitação (Pasta `test/acceptance/*`)
- `npm run test:unit`: Executa somente os testes unitários (Pasta `test/unit/*`)
- `npm run style:check`: Verifica se o código fonte segue os padrões de estilo definidos nos arquivos `.eslintrc` e `.prettierrc`
- `npm run style:fix`: Formata o código fonte seguindo os estilos recomendados
### Comandos Docker
- `docker-compose up --build`: Inicia o projeto e suas dependências no Docker
- `docker-compose run idvogados_api npm run cli`: Acessa a API em modo terminal na pasta raiz do projeto
- `docker-compose run idvogados_api npm run test`: Executa todos os testes (Pasta `test/*`)
### Comandos Make
- `make build`: Faz build das imagens docker
- `make up`: Inicializa todos os serviços (é possível passar arugmentos extras utilizando `make up args='arg extra'`)
- `make up.detach`: Inicializa todos os serviços no modo detached e com outros parâmetros (é possível passar arugmentos extras utilizando `make up.detach args='arg extra'`)
- `make up.firebase`: Inicializa apenas o serviço do Firebase
- `make down`: Mata todos os serviços (é possível passar arugmentos extras utilizando `make down args='arg extra'`)
- `make down.volumes`: Mata todos os serviços e remove os volumes nomeados
- `make bash`: Inicia um bash/shell script no container do serviço Node
- `make cli`: Acessa a API em modo terminal na pasta raiz do projeto
- `make tests`: Executa todos os testes (Pasta `test/*`)
- `make coverage`: Executa os testes e gera o arquivo de coverage
- `make style.check`: Verifica se o código fonte segue os padrões de estilo definidos nos arquivos `.eslintrc` e `.prettierrc`
## Configurações do projeto
Para saber como configurar o projeto, clique [aqui](https://github.com/idvogados/backend/blob/dev/src/docs/configuracoes.md)<file_sep>const express = require('express')
const healthRoutes = require('./src/routes/health-route')
const errorsMiddleware = require('./src/middlewares/errors-middleware')
const app = express()
// Middlewares
app.use(express.json())
// Rotas
app.use(healthRoutes)
/**
* Captura de erros.
* Deve ser feito depois da definição das rotas,
* para garantir que todo handler de uma rota que
* lance um erro, tenha esse erro capturado pelo
* middleware.
*/
app.use(errorsMiddleware)
module.exports = app
<file_sep># 🚧 Trabalho em progresso.
Repositório para o projeto de back-end
## Como contribuir
Leia nosso guia de contribuição nesse [arquivo](https://github.com/idvogados/backend/blob/dev/CONTRIBUTING.md)<file_sep>const NotFoundError = require('../../../src/errors/not-found-error')
describe('[Unit] errors/not-found-error', () => {
const error = new NotFoundError()
it('should extends from Error class', () => {
expect(NotFoundError.prototype).to.be.instanceOf(Error)
})
it('should set name as NotFoundError', () => {
expect(error.name).to.be.eql('NotFoundError')
})
it('should use default error message', () => {
expect(error.message).to.be.eql('Not found')
})
context('when custom message was given', () => {
const errorWithCustomMessage = new NotFoundError('my custom message')
it('should use given message', () => {
expect(errorWithCustomMessage.message).to.be.eql('my custom message')
})
})
})
<file_sep>const sinon = require('sinon')
const sendgrid = require('@sendgrid/mail')
const logger = require('../../../src/client/logger-client')
const sendgridConfig = require('../../../src/config/sendgrid-config')
const sendgridClient = require('../../../src/client/sendgrid-client')
describe('[Unit] client/sendgrid-client', () => {
describe('.sendMail', () => {
const stubSend = sinon.stub()
const spySetApiKey = sinon.spy()
const spyLoggerDebug = sinon.spy()
const fixture = {
to: ['<EMAIL>'],
subject: 'A nice test email',
content: '<h1> Hello </h1>'
}
before(async () => {
sinon.replace(sendgrid, 'setApiKey', spySetApiKey)
sinon.replace(sendgrid, 'send', stubSend)
sinon.replace(logger, 'debug', spyLoggerDebug)
await sendgridClient.sendMail(fixture)
})
after(() => {
sinon.restore()
})
it('shoud setup client with API Key from config', () => {
const calledCorrectly = spySetApiKey.calledWith(sendgridConfig.apiKey)
expect(calledCorrectly).to.be.true
})
it('should log information in debug mode', () => {
const calledCorrectly = spyLoggerDebug.calledWith({
action: 'sendgrid-client.sendMail',
message: 'Sending mail',
meta: {
to: fixture.to,
from: sendgridConfig.fromEmail,
subject: fixture.subject,
html: fixture.content
}
})
expect(calledCorrectly).to.be.true
})
it('should send mail with param', () => {
const calledCorrectly = stubSend.calledWith({
to: fixture.to,
from: sendgridConfig.fromEmail,
subject: fixture.subject,
html: fixture.content
})
expect(calledCorrectly).to.be.true
})
})
})
<file_sep>const httpStatus = require('http-status')
const logger = require('../client/logger-client')
const NotFoundError = require('../errors/not-found-error')
/** Catálogo de erros conhecidos pela aplicação e seus respectivos statusCode */
const ERRORS_CATALOG = Object.freeze([{ error: NotFoundError, statusCode: httpStatus.NOT_FOUND }])
/**
* Middleware para capturar erros da aplicação
* e montar um retorno padrão para cada classe de erro mapeada.
* O erro também é logado no terminal.
*
* Caso `err` seja um erro não conhecido,
* retorna status code `INTERNAL_SERVER_ERROR`
*
* @param {Object} err Erro lançado pela aplicação
* @param {Express.Request} req Request
* @param {Express.Response} res Response
* @param {Function} next Função que leva para a próxima execução da stack
*/
module.exports = (err, req, res, next) => {
const errorMatched = ERRORS_CATALOG.find(e => e.error.name === err.name)
const statusCode = errorMatched ? errorMatched.statusCode : httpStatus.INTERNAL_SERVER_ERROR
const errorContent = {
error: err.name,
message: err.message
}
logger.error({
...errorContent,
statusCode,
stack: err.stack.split('\n'),
path: req.originalUrl,
query: req.query,
headers: req.headers
})
res.setHeader('x-error', true)
res.status(statusCode).json(errorContent)
next()
}
<file_sep># Configurações Idvogados
Nesse documento você irá encontrar todas as configurações do projeto de backend.
Além disso, você pode encontrar um guia na sessão [como rodar](#como-rodar), explicando as diferentes formas para inicializar o projeto.
## Como rodar
O projeto pode ser inicializado de várias formas:
### Rodando com Node.js
Instale o [Node.js](https://nodejs.org/en/download/) na sua versão mais recente (LTS), então execute:
```sh
npm start
```
Você irá ver uma mensagem semelhante a:
```sh
> {"level":"info" ... "msg":"Listening on port 3000"}
```
Então acesse [http://localhost:3000](http://localhost:3000)
### Rodando com nvm (Node Version Manager)
Instale o [nvm](https://github.com/nvm-sh/nvm), então execute:
```sh
nvm install
nvm use
```
Você irá ver uma mensagem semelhante a:
```sh
Now using node v12.16.3 (npm v6.14.4)
```
Execute o comando `npm start` para subir o projeto e acesse [http://localhost:3000](http://localhost:3000)
### Rodando com Docker
Instale o [Docker](https://docs.docker.com/get-docker/) e [docker-compose](https://docs.docker.com/compose/gettingstarted/) na suas versões mais recentes, então rode os seguintes comandos:
```sh
docker-compose up --build
```
Você irá ver a seguinte mensagem:
```sh
> idvogados_firebase | Dev App Server is now running.
> idvogados_api | {"level":"info" ... "msg":"Listening on port 3000"}
```
### Rodar com Make
Para inicializar o projeto com o comando `make`, utilize os seguintes comandos:
```sh
make build
make up
```
## Variáveis de ambiente
### Configurações do Node.js
- `NODE_ENV`: Determina o ambiente onde a API será executada; Possíveis valores: `production|test|development`
**Obs:** Ao usar `NODE_ENV=test` as demais variáveis de ambiente devem ser prefixadas com `TEST_*`
### Configurações da API
- `API_PORT`: Define a porta onde a API será inicializada. Padrão: `3000`.
### Configurações de Log
- `LOG_LEVEL`: Define nível de log usado pela API, determinando a quantidade de log que será gerada pela aplicação. Os níveis suportados são: `fatal|error|warn|info|debug|trace|silent`. Padrão: `debug`.
### Configurações do Firebase
As seguintes variáveis de ambiente são utilizadas para configurar a conexão com o Firebase. A referência completa para cada variável pode ser encontrada na documentação [Firebase#initializeApp](https://firebase.google.com/docs/reference/node/firebase?hl=pt-br#initializeapp)
- `FIREBASE_API_KEY`: Api Key para conexão com o Firebase Cloud, encontrada no painel de configuração do Firebase.
- `FIREBASE_PROJECT_ID`: ID do projeto no Firebase Cloud, encontrada no painel de configuração do Firebase.
- `FIREBASE_FIRESTORE_HOST`: Host do Firestore para conexão local. Padrão: `localhost:5555`
### Configurações do SendGrid
- `SENDGRID_API_KEY`: Api Key para conexão com o [SendGrid](sendgrid.com)
- `SENDGRID_FROM_EMAIL`: Email de origem padrão. Padrão: `<EMAIL>`
<file_sep>FROM node:12.16.3-alpine
RUN apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /var/app
COPY package.json .
RUN npm install --only=production
COPY . .
CMD ["npm", "start"]<file_sep>const firebase = require('firebase')
const apiConfig = require('../config/api-config')
const firebaseConfig = require('../config/firebase-config')
/** @type {firebase.firestore.Firestore} */
let firestoreInstance = null
module.exports = {
/**
* Inicializa uma App do Firebase e retorna a instancia
* do Firestore
*
* @returns {firebase.firestore.Firestore}
*/
_createConnection() {
const app = firebase.initializeApp({
apiKey: firebaseConfig.apiKey,
projectId: firebaseConfig.projectId
})
const firestore = app.firestore()
if (apiConfig.isDev) {
firestore.settings({
host: firebaseConfig.firestore.host,
ssl: false
})
}
return firestore
},
/**
* Conecta no Firebase
* @returns {firebase.firestore.Firestore}
*/
connect() {
firestoreInstance = firestoreInstance || this._createConnection()
return firestoreInstance
},
/**
* Desconecta do Firebase
*/
disconnect() {
firestoreInstance.terminate()
firestoreInstance = null
}
}
<file_sep>const logger = require('../client/logger-client')
module.exports = {
/**
* Verifica saúde da API
* @returns {Promise<Object>} Status da API
*/
async status() {
logger.debug({
action: 'health-service.status',
message: 'Checking API health'
})
return Promise.resolve({ status: 'ok' })
}
}
<file_sep>FROM node:12.16.3
WORKDIR /var/app
COPY package.json .
RUN npm install
COPY . .
CMD ["npm", "start"]
<file_sep>const sinon = require('sinon')
const firebase = require('firebase')
const apiConfig = require('../../../src/config/api-config')
const firebaseConfig = require('../../../src/config/firebase-config')
const firebaseClient = require('../../../src/client/firebase-client')
describe('[Unit] client/firebase-client', () => {
describe('._createConnection', () => {
let connection
const stubFirestoreSettings = sinon.stub()
const stubFirestore = sinon.fake.returns({ settings: stubFirestoreSettings })
const stubInitializeApp = sinon.fake.returns({ firestore: stubFirestore })
context('when runs in production', () => {
before(() => {
sinon.replace(firebase, 'initializeApp', stubInitializeApp)
sinon.replace(apiConfig, 'isDev', false)
connection = firebaseClient._createConnection()
})
after(() => {
sinon.restore()
})
it('should instantiate Firebase App using custom config', () => {
const calledCorrectly = stubInitializeApp.calledWith({
apiKey: firebaseConfig.apiKey,
projectId: firebaseConfig.projectId
})
expect(calledCorrectly).to.be.true
})
it('should NOT configure Firestore to local host', () => {
expect(stubFirestoreSettings.notCalled).to.be.true
})
it('should returns a Firestore instance', () => {
expect(connection).to.be.eql(stubFirestore.returnValues[0])
})
})
context('when runs in development', () => {
before(() => {
sinon.replace(firebase, 'initializeApp', stubInitializeApp)
sinon.replace(apiConfig, 'isDev', true)
connection = firebaseClient._createConnection()
})
after(() => {
sinon.restore()
})
it('should instantiate Firebase App using custom config', () => {
const calledCorrectly = stubInitializeApp.calledWith({
apiKey: firebaseConfig.apiKey,
projectId: firebaseConfig.projectId
})
expect(calledCorrectly).to.be.true
})
it('should configure Firestore to local host using custom config', () => {
const calledCorrectly = stubFirestoreSettings.calledWith({
host: firebaseConfig.firestore.host,
ssl: false
})
expect(calledCorrectly).to.be.true
})
it('should returns a Firestore instance', () => {
expect(connection).to.be.eql(stubFirestore.returnValues[0])
})
})
})
describe('.connect', () => {
let connection
before(() => {
const fakeFn = sinon.fake.returns({ projectId: firebaseConfig.projectId, terminate: sinon.stub() })
sinon.replace(firebaseClient, '_createConnection', fakeFn)
connection = firebaseClient.connect()
})
after(() => {
firebaseClient.disconnect()
sinon.restore()
})
it('should return a Firestore instance', () => {
expect(connection).to.have.property('projectId', firebaseConfig.projectId)
})
it('should create raw connection only one time', () => {
firebaseClient.connect()
firebaseClient.connect()
expect(firebaseClient._createConnection.calledOnce).to.be.true
})
})
describe('.disconnect', () => {
const spyTerminate = sinon.spy()
before(() => {
const fakeFn = sinon.fake.returns({ terminate: spyTerminate })
sinon.replace(firebaseClient, '_createConnection', fakeFn)
firebaseClient.connect()
firebaseClient.disconnect()
})
after(() => {
sinon.restore()
})
it('should close connection with Firestore', () => {
expect(spyTerminate.called).to.be.true
})
})
})
<file_sep>const envLoader = require('@b2wads/env-o-loader')
/**
* Configurações do Firebase
*/
module.exports = envLoader({
defaults: {
apiKey: 'dummy-api-key',
projectId: 'dummy-project-id',
firestore: {
host: 'localhost:5555'
}
},
test: {
apiKey: 'env:TEST_FIREBASE_API_KEY',
projectId: 'env:TEST_FIREBASE_PROJECT_ID',
firestore: {
host: 'env:TEST_FIREBASE_FIRESTORE_HOST'
}
},
development: {
apiKey: 'env:FIREBASE_API_KEY',
projectId: 'env:FIREBASE_PROJECT_ID',
firestore: {
host: 'env:FIREBASE_FIRESTORE_HOST'
}
},
production: {
apiKey: 'env:FIREBASE_API_KEY',
projectId: 'env:FIREBASE_PROJECT_ID',
firestore: {
host: 'env:FIREBASE_FIRESTORE_HOST'
}
}
})
<file_sep>const supertest = require('supertest')
const httpStatus = require('http-status')
const app = supertest(require('../../app'))
describe('[Acceptance] Healthcheck', () => {
describe('GET /health', () => {
let res
before(async () => {
res = await app.get('/health')
})
it('should return 200', () => {
expect(res.status).to.be.eql(httpStatus.OK)
})
it('should return API status', () => {
expect(res.body).to.have.property('status', 'ok')
})
})
})
<file_sep>const healthService = require('../../../src/services/health-service')
describe('[Unit] services/health-service', () => {
describe('.status', () => {
it('should return api status ', async () => {
const status = await healthService.status()
expect(status).to.have.property('status', 'ok')
})
})
})
<file_sep>build:
docker-compose build
up:
make up $(args)
up.detach:
docker-compose up --detach --force-recreate --renew-anon-volumes --remove-orphans $(args)
up.firebase:
docker-compose up --detach idvogados_firebase
down:
docker-compose down $(args)
down.volumes:
docker-compose down --volumes
bash:
docker-compose run idvogados_api bash
cli:
docker-compose run idvogados_api npm run cli
tests:
docker-compose run idvogados_api npm run test
coverage:
docker-compose run idvogados_api npm run coverage
style.check:
docker-compose run idvogados_api npm run style:check
<file_sep>const envLoader = require('@b2wads/env-o-loader')
/**
* Configurações do client de log
* Ref: `src/clients/logger-client.js`
*/
module.exports = envLoader({
defaults: {
level: 'debug'
},
test: {
level: 'env:TEST_LOG_LEVEL'
},
development: {
level: 'env:LOG_LEVEL'
},
production: {
level: 'env:LOG_LEVEL'
}
})
| 3f21cc6ce3b56e2cb61d31215fba28ac32dd196f | [
"JavaScript",
"Makefile",
"Dockerfile",
"Markdown"
] | 19 | Dockerfile | pabrrs/backend | e147bc665f17e579d4585c96dafcf2b912ae9ad1 | 0ec247277b6741dc8e188b84e4fbc12e807c480b |
refs/heads/master | <file_sep>require('./common/global.js');
const routes = require('./common/routes.js');
const restify = require('restify');
const server = restify.createServer();
server.use(restify.bodyParser());
server.use(restify.CORS());
/*server.use(function(){
"use strict";
var token = req.headers['authorization'];
var key = req.headers['key'];
if (token || key) {
try {
jwt.verify(token, require('secret')(), function (err, decoded) {
if (err) {
res.status(401);
return res.json({resTypeCode: "1", status: 401, resTypeMessage: 'Session Expired. Please login again to continue.'});
} else {
req.decoded = decoded;
next();
}
});
} catch (err) {
res.status(500);
res.json({
"status" : 500,
"resTypeMessage": "something went wrong",
"error" : err
});
}
} else {
res.status(401);
res.json({
"status" : 401,
"resTypeCode" : "1",
"resTypeMessage": "Please login to continue."
});
return;
}
});*/
server.opts(/.*/, function (req,res,next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
res.send(200);
return next();
});
// add routes
routes.applyRoutes(server);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
<file_sep>const util = include('common/utility.js');
const service = include('api/info/service.js');
function getUserInfo(req, res) {
//throw new error("explicit error");
const logId = util.getLogId();
const svc = new service.Info(logId);
svc.inquireUsers()
.then((userDetails) => {
res.send(userDetails);
})
.catch((error) => {
console.log("error occurred in controller - get shifts: ", error);
});
}
module.exports.getAllUserInfo = getUserInfo;
<file_sep>import shiftService from './../services/shiftService.js';
import loginService from './../services/loginService.js';
var curr = new Date;
var weekNumber = moment(curr).week();
var currentYear = moment(curr).year();
var currentMonday = moment(curr).startOf('week') + 7;
var self;
var ShiftNames;
var nextMonday=0;
var previousMonday=7;
export default class ShiftController {
constructor($http, $q, NgTableParams, $filter, ngTableDefaults,$cookies) {
self = this;
this.filter = $filter;
this.http = $http;
this.q = $q;
this.NgTableParams = NgTableParams;
this.isEditable = false;
this.showEdit=true;
this.cookies=$cookies;
this.message = "Hi";
this.messageResponse = "";
const curr = new Date;
const weekNo = moment(curr).week();
const year = moment(curr).year();
const monday = moment(curr).startOf('week') + 1;
this.message = "Shift Plan for ";
this.dateRange = moment(monday).add(1, 'days').format("YYYY-MM-DD") + " to " +
moment(monday).add(7, 'days').format("YYYY-MM-DD");
var days = [];
for (var i = 1; i < 8; i++) {
days.push({
id : "sday" + (i - 1).toString(),
date: moment(monday).add(i, 'days').format("YYYY-MM-DD")
});
}
if(this.cookies.get('token')){
var message=new loginService($http, $q,$cookies);
console.log("hello1",message);
var responseType=message.getResType();
console.log("hello",responseType);
if(responseType=="Success"){
this.showEdit=false;
}
}
this.days = days;
this.errors = [];
this.a = 5;
this.getShifts($http, $q,$cookies)
.then((result) => {
this.shifts = result;
ShiftNames=this.shifts;
return this.getEmployeeShifts($http, $q, weekNo, year,$cookies);
})
.then((result) => {
var response = _.map(result, (i) => {
var eo = {};
for(var j=0; j<7; j++){
var d = i["day"+j.toString()];
if(_.findWhere(this.shifts, {id: d})!=undefined){
var dname = _.findWhere(this.shifts, {id: d}).shiftname;
}
else{
break;
}
eo["sday"+j.toString()] = dname;
}
return _.extend(i, eo);
});
self.tableParams = new NgTableParams({},
{
getData: function () {
return response;
}
}
);
ngTableDefaults.settings.counts = [];
//this.tableParams = new NgTableParams({}, { dataset: response });
})
.catch((error) => {
this.errors.push("no dates were registered for current week");
});
}
getShifts($http, $q,$cookies) {
const svc = new shiftService($http, $q,$cookies);
console.log(svc);
return $q((resolve, reject) => {
svc.getShiftMaster()
.then((result) => {
return resolve(result);
})
.catch((err) => {
return reject(err);
});
})
}
getEmployeeShifts($http, $q, weekNo, year,$cookies) {
const svc = new shiftService($http, $q,$cookies);
return $q((resolve, reject) => {
svc.getEmployeeShifts(weekNo, year)
.then((result) => {
const newResponse = getImagePath(result);
return resolve(newResponse);
})
.catch((err) => {
return reject(err);
});
})
}
getNextShift() {
weekNumber += 1;
nextMonday += 7;
var $http = this.http;
this.dateRange = moment(currentMonday).add(1 + nextMonday, 'days').format("YYYY-MM-DD") + " to " +
moment(currentMonday).add(7 + nextMonday, 'days').format("YYYY-MM-DD");
var days = [];
for (var i = 1; i < 8; i++) {
days.push({
id : "sday" + (i - 1).toString(),
date: moment(currentMonday).add(i + nextMonday, 'days').format("YYYY-MM-DD")
});
}
self.days = days;
this.errors = [];
this.a = 5;
this.getEmployeeShifts($http, this.q, weekNumber, currentYear,this.cookies)
.then((result) => {
var response = _.map(result, (i) => {
var eo = {};
for (var j = 0; j < 7; j++) {
var d = i["day" + j.toString()];
var dname = _.findWhere(this.shifts, {id: d}).shiftname;
eo["sday" + j.toString()] = dname;
}
return _.extend(i, eo);
});
self.tableParams = {
reload : function () {
}, settings: function () {
return {}
}
};
self.tableParams = this.NgTableParams({}, {
getData: function () {
return response;
}
});
})
.catch((error) => {
this.errors.push("no dates were registered for current week");
});
}
getPreviousShift() {
weekNumber -= 1;
var $http = this.http;
this.dateRange = moment(currentMonday).add(1 + nextMonday, 'days').subtract(previousMonday, 'days').format("YYYY-MM-DD") + " to " +
moment(currentMonday).add(7 + nextMonday, 'days').subtract(previousMonday, 'days').format("YYYY-MM-DD");
var days = [];
for (var i = 1; i < 8; i++) {
days.push({
id : "sday" + (i - 1).toString(),
date: moment(currentMonday).add(i + nextMonday, 'days').subtract(previousMonday, 'days').format("YYYY-MM-DD")
});
}
nextMonday -= 7;
self.days = days;
this.errors = [];
this.a = 5;
this.getEmployeeShifts($http, this.q, weekNumber, currentYear,this.cookies)
.then((result) => {
var response = _.map(result, (i) => {
var eo = {};
for (var j = 0; j < 7; j++) {
var d = i["day" + j.toString()];
var dname = _.findWhere(this.shifts, {id: d}).shiftname;
eo["sday" + j.toString()] = dname;
}
return _.extend(i, eo);
});
self.tableParams = {
reload : function () {
}, settings: function () {
return {}
}
};
self.tableParams = this.NgTableParams({}, {
getData: function () {
return response;
}
});
})
.catch((error) => {
this.errors.push("no dates were registered for current week");
});
}
changeShift(value,name){
console.log(name)
self.changeValue=value;
}
}
function getImagePath(shiftDetails){
const newShiftDetails = shiftDetails;
_.each(newShiftDetails, (shift) => {
var randomNum = Math.floor((Math.random() * 16) + 1) + 10;
let imagePath = "./../../contents/images/Avatars/" + randomNum.toString() + ".png";
_.extend(shift, {imgPath: imagePath});
});
return newShiftDetails;
}<file_sep>const util = include('common/utility.js');
const service = include('api/shiftplan/service.js');
function getShift(req, res) {
console.log("shift request: ", JSON.stringify(req.body));
//throw new error("explicit error");
const logId = util.getLogId();
const svc = new service.ShiftInquiry(req, logId);
svc.inquireShifts()
.then((shiftDetails) => {
res.send(shiftDetails);
})
.catch((error) => {
console.log("error occurred in controller - get shifts: ", error);
});
}
function shiftMaster(req, res) {
console.log("shift master: ");
const logId = util.getLogId();
// FetchDetails - class without any request.
const svc = new service.FetchDetails(logId);
svc.fetchShiftMaster()
.then((shifts) => {
res.send(shifts);
})
.catch((error) => {
console.log("error occurred in controller - get shift master: ", error);
});
}
module.exports.getShift = getShift;
module.exports.shiftMaster = shiftMaster;
<file_sep>'use strict';
const squel = require('squel');
module.exports = {
userDetails(user) {
const query = squel.select({tableAliasQuoteCharacter: '', numberedParameters: true})
.field("passwordkey")
.field("isadmin")
.from("master.user")
.where("username = ?", user);
return {"key": "USERDETAILS", "value": query.toParam()};
}
};<file_sep>import callApi from './../common/callApi.js';
import constants from './../common/constants.js';
import shiftController from './../controller/shiftController.js';
var resType;
export default class loginService {
constructor($http, $q,$cookies) {
console.log("into service constructor: ");
this.http = $http;
this.promise = $q;
this.api = new callApi($http, $q,$cookies);
this.constants = new constants();
this.data=null;
this.cookies=$cookies;
console.log($cookies);
}
getLoginData(loginId, password) {
return this.promise((resolve, reject) => {
const data = {
"loginData": {
"loginId": loginId,
"psd" : <PASSWORD>
}
};
console.log(data)
const getLoginUrl = this.constants.baseUrl + constants.login().loginInfo;
console.log(getLoginUrl)
this.api.post(getLoginUrl, data)
.then((response) => {
// var a =new shiftController(this.http,this.promise);
// a.gotResponse(response);
console.log(response)
this.setLoginData(response);
return resolve(response);
})
.catch((err) => {
shiftController.messageResponse=err;
console.log("error occurred - post login loginService.js - line#26 ");
return reject(err);
});
})
}
urlBase64Decode(str) {
var output = str.replace('-', '+').replace('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
return window.atob(output);
}
setLoginData(response){
this.data=response;
console.log(this.data)
}
getData(){
var token = this.cookies.get('token')
var user = {};
if (typeof token !== 'undefined') {
var encoded = token.split('.')[1];
resType = JSON.parse(this.urlBase64Decode(encoded));
console.log(resType)
}
return resType;
}
getResType(){
var permissionList = (this.getData().resTypeMessage);
console.log(permissionList)
return permissionList;
}
}<file_sep>import shiftController from './controller/shiftController.js';
import infoController from './controller/infoController.js';
import loginController from './controller/loginController.js';
var sam = angular.module('sam', ['underscore', 'ngRoute', 'angularMoment','ngTable','ngCookies']);
sam.config(['$routeProvider', '$locationProvider','$httpProvider', function ($routeProvider, $locationProvider,$httpProvider) {
$locationProvider.html5Mode(true);
//$httpProvider.defaults.withCredentials = true;
}]);
sam.controller('shiftController', shiftController);
sam.controller('infoController', infoController);
sam.controller('loginController', loginController);
shiftController.$inject = ['$http', '$q',"NgTableParams",'$filter','ngTableDefaults','$cookies'];
infoController.$inject = ['$http', '$q','$cookies'];
loginController.$inject = ['$http', '$q','$cookies','$location'];
<file_sep>'use strict';
const squel = require('squel');
module.exports = {
getAllUsersQuery() {
const query = squel.select({tableAliasQuoteCharacter: '', numberedParameters: true})
.field('*')
.from("master.user", "u")
.join("transaction.userstreams", "us", "u.id = us.userid")
.join("master.streams", "s", "us.streamid = s.id")
.order('s.stream')
.order('u.username');
return {"key": "GETALLUSERSQUERY", "value": query.toParam()};
}
};
<file_sep>const Router = require('restify-router').Router;
const routerInstance = new Router();
routerInstance.post('/getShifts', respondShiftPlan);
routerInstance.get('/shiftMaster', respondShiftMaster);
routerInstance.get('/getAllUserInfo', respondGetAllUserInfo);
routerInstance.post('/getLoginInfo', respondGetLoginInfo);
function respondShiftPlan(req, res, next){
const shiftController = include('api/shiftplan/controller.js');
shiftController.getShift(req, res);
return next();
}
function respondShiftMaster(req, res, next){
const shiftController = include('api/shiftplan/controller.js');
shiftController.shiftMaster(req, res);
return next();
}
function respondGetAllUserInfo(req, res, next){
const infoController = include('api/info/controller.js');
infoController.getAllUserInfo(req, res);
return next();
}
function respondGetLoginInfo(req, res, next){
console.log("here");
const loginController = include('api/login/controller.js');
loginController.validateLogin(req, res);
return next();
}
module.exports = routerInstance;
<file_sep>function queryError() {
var statusCode = 422;
var message = 'Response Error';
return {success: false, data: message, status: statusCode};
}
function dbConnectionError() {
var statusCode = 503;
var message = 'Unable to connect to database!';
return {success: false, data: message, status: statusCode};
}
function responseError() {
var statusCode = 999;
var message = 'Unable to Fetch Data';
return {success: false, data: message, status: statusCode};
}
function headerError(message) {
return {success: false, data: message, status: 999}
}
function sizeExceedLimit(message) {
return {success: false, data: message, status: 999}
}
function invalidRequest(message) {
return {success: false, data: message, status: 999}
}
module.exports.queryError = queryError;
module.exports.dbConnectionError = dbConnectionError;
module.exports.responseError = responseError;
module.exports.headerError = headerError;
module.exports.sizeExceedLimit = sizeExceedLimit;
module.exports.invalidRequest = invalidRequest;<file_sep>export default class callApi{
constructor($http, $q,$cookies){
self=this;
this.http = $http;
this.promises = $q;
this.cookies = $cookies;
console.log("http: ",$cookies);
}
post(url, request){
if (self.cookies.get('token')) {
this.http.defaults.headers.common.Authorization = this.cookies.get('token');
}
return this.promises((resolve, reject) => {
this.http({
method: "POST",
url : url,
data : request
}).success(function (data,headers,config) {
return resolve(data);
}).error(function(error,headers,config){
return reject(error);
});
});
}
get(url){
console.log(self.cookies);
if (self.cookies.get('token')) {
this.http.defaults.headers.common.Authorization = self.cookies.get('token');
}
return this.promises((resolve, reject) => {
this.http({
method: "GET",
url : url
}).success(function (data,headers,config) {
return resolve(data);
}).error(function(error,headers,config){
return reject(error);
});
});
}
}
<file_sep>module.exports = function (req, res, next) {
//var token = req.headers['access-token'];
//var token = req.body.token || req.query.token || req.headers['authorization'];
var token = req.headers['authorization'];
var key = req.headers['key'];
//var token = req.body.token || req.query.token || req.headers['authorization'];
if (token || key) {
try {
//var decoded = jwt.decode(token, require('../config/secret.js')());
jwt.verify(token, require('secret')(), function (err, decoded) {
if (err) {
res.status(401);
return res.json({resTypeCode: "1", status: 401, resTypeMessage: 'Session Expired. Please login again to continue.'});
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} catch (err) {
res.status(500);
res.json({
"status" : 500,
"resTypeMessage": "something went wrong",
"error" : err
});
}
} else {
res.status(401);
res.json({
"status" : 401,
"resTypeCode" : "1",
"resTypeMessage": "Please login to continue."
});
return;
}
};<file_sep>'use strict'
const dbAccess = include('common/dataAccess.js');
const queries = include('api/shiftplan/queries.js');
const database = include('common/config.js');
class ShiftInquiry{
constructor(req, id){
this.weekNo = req.body.shiftInquiry.weekNo;
this.year = req.body.shiftInquiry.year;
console.log("id: ", id);
this.db = new dbAccess.Operations(id);
}
inquireShifts(){
const base = this;
return new Promises((resolve, reject) => {
console.log("getting shifts for the week ", base.weekNo, " and year: ", base.year);
const shiftQuery = queries.getShiftsQuery([base.weekNo, base.year]);
base.db.fetch(shiftQuery, database.samDb)
.then((shiftDetails) => {
resolve(shiftDetails);
})
.catch((error) => {
console.log("error in getting the shift details of the week ", error);
});
})
}
}
class FetchDetails{
constructor(id){
console.log("id: ", id);
this.db = new dbAccess.Operations(id);
}
fetchShiftMaster(){
const base = this;
return new Promises((resolve, reject) => {
console.log("getting shift master");
console.log("getting shift master 2");
const shiftMasterQuery = queries.getshiftsMaster();
base.db.fetch(shiftMasterQuery, database.samDb)
.then((shifts) => {
console.log("shifts: ", JSON.stringify(shifts));
return resolve(shifts);
})
.catch((error) => {
console.log("error in getting the shift master details, ", error);
return reject(error)
});
})
}
}
module.exports.ShiftInquiry = ShiftInquiry;
module.exports.FetchDetails = FetchDetails;
<file_sep>'use strict';
const squel = require('squel');
module.exports = {
getShiftsQuery(params) {
const query = squel.select({tableAliasQuoteCharacter: '', numberedParameters: true})
.from("crosstab('"
+ squel.select({tableAliasQuoteCharacter: '', numberedParameters: true})
.field('u.id').field('u.username').field('u.email').field('u.contact').field('u.employeeid')
.field('d.syear').field('d.weekno').field('d.weekday').field('sd.shiftid')
.from("transaction.shiftdetails", "sd")
.join("master.user", "u", "sd.userid = u.id")
.join("transaction.userstreams", "us", "us.userid = u.id")
.join("master.dates", "d", "sd.dateid = d.id")
.where("weekno = ?", params[0])
.where("syear = ?", params[1])
.order('1')
.order('2')
+ "','"
+ squel.select({tableAliasQuoteCharacter: '', numberedParameters: true})
.field('weekday')
.from('master.dates')
.distinct()
.order('1')
+ "') as ct(userid int, username text, email text, contact text, employeeid text, year int, weekno int, day0 int, day1 int, day2 int, day3 int, day4 int, day5 int, day6 int)"
)
.field('*');
return {"key": "GETSHIFTSQUERY", "value": query.toParam()};
},
getshiftsMaster() {
const query = squel.select({tableAliasQuoteCharacter: '', numberedParameters: true})
.field('*')
.from("master.shift");
console.log("shift master query: ", query.toString());
return {"key": "GETSHIFTMASTERQUERY", "value": query.toParam()};
}
};
<file_sep>'use strict'
const dbAccess = include('common/dataAccess.js');
const queries = include('api/info/queries.js');
const database = include('common/config.js');
class Info{
constructor(id){
console.log("id: ", id);
this.db = new dbAccess.Operations(id);
}
inquireUsers(){
const base = this;
return new Promises((resolve, reject) => {
console.log("getting all users information ");
const allUsersQuery = queries.getAllUsersQuery();
base.db.fetch(allUsersQuery, database.samDb)
.then((userDetails) => {
resolve(userDetails);
})
.catch((error) => {
console.log("error in getting the shift details of the week ", error);
});
})
}
}
module.exports.Info = Info;
<file_sep>import callApi from './../common/callApi.js';
import constants from './../common/constants.js';
export default class shiftService{
constructor($http, $q,$cookies){
console.log("into service constructor: ");
this.http = $http;
this.promise = $q;
this.api = new callApi($http, $q,$cookies);
this.constants = new constants();
}
getShiftMaster(){
return this.promise((resolve, reject) =>{
const shiftMasterUrl = this.constants.baseUrl + constants.shift().shiftMaster;
console.log(shiftMasterUrl);
this.api.get(shiftMasterUrl)
.then((response) => {
return resolve(response);
})
.catch((err) => {
console.log("error occurred - get shift master shiftService.js - line#21 ");
return reject(err);
});
})
}
getEmployeeShifts(weekNo, year){
return this.promise((resolve, reject) => {
const data = {
"shiftInquiry":{
"weekNo": weekNo,
"year": year
}
};
const getShiftsUrl = this.constants.baseUrl + constants.shift().getShifts;
this.api.post(getShiftsUrl, data)
.then((response) => {
return resolve(response);
})
.catch((err) => {
console.log("error occurred - post employee shifts shiftService.js - line#26 ");
return reject(err);
});
})
}
}
<file_sep>import loginService from './../services/loginService.js';
export default class LoginController {
constructor($http, $q,$cookies,$location) {
this.http=$http;
this.q=$q;
this.cookies=$cookies;
this.message="";
this.location=$location;
}
checkLogin(Id, password) {
if (Id == undefined && (password == undefined || password == "")) {
$("#ErrorListForLogin").text("Please enter username and password");
$("#ErrorListForLogin").css('display', 'block');
}
else if (Id == undefined || Id == "") {
$("#ErrorListForLogin").text("Please enter username");
$("#ErrorListForLogin").css('display', 'block');
}
else if (password == undefined || password == "") {
$("#ErrorListForLogin").text("Please enter password");
$("#ErrorListForLogin").css('display', 'block');
}
else {
password = password.trim(" ");
if (password.length == 0) {
$("#ErrorListForLogin").text("Please enter valid password");
$("#ErrorListForLogin").css('display', 'block');
}
else {
const svc = new loginService(this.http,this.q,this.cookies);
return this.q((resolve, reject) => {
svc.getLoginData(Id, password)
.then((result) => {
if (result.resTypeMessage == "Success") {
this.message=result.resTypeMessage;
$(".btn-default").click();
// this.location.path("./views/admin");
}
else {
$("#ErrorListForLogin").text(result.resTypeMessage);
$("#ErrorListForLogin").css('display', 'block');
}
console.log("response shift master: ", JSON.stringify(result));
this.cookies.put('token', result.token);
console.log(this.cookies)
return resolve(result);
})
.catch((err) => {
console.log("response err shift master: ", JSON.stringify(err));
return reject(err);
});
})
}
}
}
}
<file_sep>const base_dir = __dirname + '/../';
global._ = require('underscore');
global.Promises = require('bluebird');
global.jwt = require('jsonwebtoken');
/**
* include - get the relative path for the required modules.
* @param file - file name
* @returns {*} - file as a required module
*/
global.include = function (file) {
var includePath = base_dir.concat(file);
return require(includePath);
};
<file_sep>// sam.factory('constants', function(){
// return {
// btnType: {
// LINK: "LINK",
// FN: "FUNCTION",
// METHOD: "METHOD"
// }
// }
// });
export default class constants{
constructor(){
this.baseUrl = "http://localhost:8080/"
}
static shift(){
return {
getShifts: "getShifts",
shiftMaster: "shiftMaster"
}
}
static info(){
return {
allUserInfo: "getAllUserInfo"
}
}
static login(){
return {
loginInfo: "getLoginInfo"
}
}
}
| 289ab120f989074512c38fd59865150064563d12 | [
"JavaScript"
] | 19 | JavaScript | shreyasbande/frsam | ce5e1c5e08fa275b105eb6436c2fb3b966f0b8e2 | 62f6260aafc9530caa568a4c962d1a5b833920af |
refs/heads/master | <repo_name>singh-j/django-login_and_registration-<file_sep>/apps/accounts/urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^register/$', views.Register.as_view(), name='accounts-register'),
url(r'^login/$', views.Login.as_view(), name='accounts-login'),
url(r'^success/$', views.Success.as_view()),
)
| 73e3587f76f1bb99577f0826034d7a6156b13925 | [
"Python"
] | 1 | Python | singh-j/django-login_and_registration- | 071e297e3357f5e4e6ade120bc5c52b3dd1fe94c | 32d08804a60d57e4c08c68e30c2f1517f151ea42 |
refs/heads/master | <file_sep>import numpy as np
import tensorflow as tf
import re
import time
#DATA PREPROCESSING
lines= open('movie_lines.txt', encoding='utf-8', errors= 'ignore').read().split('\n')
conversations= open('movie_conversations.txt', encoding='utf-8', errors= 'ignore').read().split('\n')
id2line={}
for line in lines:
_line=line.split(' +++$+++ ')
if len(_line)==5:
id2line[_line[0]]= _line[4]
conversations_ids=[]
for conversation in conversations[:-1]:
_conversation=conversation.split(' +++$+++ ')[-1][1:-1].replace("'","").replace(" ","")
conversations_ids.append(_conversation.split(','))
questions=[]
answers=[]
for conversation in conversations_ids:
for i in range(len(conversation) -1):
questions.append(id2line[conversation[i]])
answers.append(id2line[conversation[i+1]])
def cleantext(text):
text=text.lower()
text=re.sub(r"i'm", "i am" ,text)
text=re.sub(r"he's", "he is" ,text)
text=re.sub(r"she's", "she is" ,text)
text=re.sub(r"that's", "that is" ,text)
text=re.sub(r"what's", "what is" ,text)
text=re.sub(r"where's", "where is" ,text)
text=re.sub(r"\'ll", " will" ,text)
text=re.sub(r"\'ve", " have" ,text)
text=re.sub(r"\'re", " are" ,text)
text=re.sub(r"\'d", " would" ,text)
text=re.sub(r"won't", "will not" ,text)
text=re.sub(r"can't", "cannot" ,text)
text=re.sub(r"[!@#$%^&*_+-=\"\'?><,;]", "" ,text)
return text
clean_questions=[]
for question in questions:
clean_questions.append(cleantext(question))
clean_answers=[]
for answer in answers:
clean_answers.append(cleantext(answer))
#creating dict to map num of occurences so we can remove rarely used words
word2count={}
for question in questions:
for word in question.split():
if word not in word2count:
word2count[word]=1
else:
word2count[word]+=1
for answer in answers:
for word in answer.split():
if word not in word2count:
word2count[word]=1
else:
word2count[word]+=1
threshold=20
questionsword2int={}
word_count=0
for word,count in word2count.items():
if count >= threshold:
questionsword2int[word]= word_count
word_count +=1
answersword2int={}
word_count=0
for word,count in word2count.items():
if count >= threshold:
answersword2int[word]= word_count
word_count +=1
tokens=["<PAD>","<EOS>","<OUT>","<SOS>"]
for token in tokens:
questionsword2int[token]= len(questionsword2int) +1
for token in tokens:
answersword2int[token]= len(answersword2int) +1
answersint2word= {w_i:w for w,w_i in answersword2int.items() }
for i in range(len(clean_answers)):
clean_answers[i] += " <EOS>"
#translating all the words into integers
#and filter all the least frequently used words by <OUT>
question_into_int=[]
for question in clean_questions:
ints=[]
for word in question.split():
if word not in questionsword2int:
ints.append(questionsword2int["<OUT>"])
else:
ints.append(questionsword2int[word])
question_into_int.append(ints)
answer_into_int=[]
for answer in clean_answers:
ints=[]
for word in answer.split():
if word not in answersword2int:
ints.append(answersword2int["<OUT>"])
else:
ints.append(answersword2int[word])
answer_into_int.append(ints)
#sorting ques and ans by length as it will speed and optimise training by reducing the length of padding
sorted_clean_questions=[]
sorted_clean_answers=[]
for length in range(1, 25 + 1):
#adding +1 coz upper bound in python in not included
for i in enumerate(question_into_int):
#print(i)
#gives a couple of index num and the question
if len(i[1]) == length:
sorted_clean_questions.append(question_into_int[i[0]])
sorted_clean_answers.append(answer_into_int[i[0]])
#Building Seq2seq model
def model_inputs():
inputs= tf.placeholder(tf.int32, [None][None], name="input")
targets= tf.placeholder(tf.int32, [None][None], name="target")
lr= tf.placeholder(tf.float32, name="learning_rate")
keep_prob= tf.placeholder(tf.float32, name="keep_prob")
return inputs, targets, lr, keep_prob
#preprocessing placeholders because decoder accepts data only in batches
def preprocess_targets(targets, word2int, batchsize):
left_side= tf.fill([batchsize,1], word2int['<SOS>'])
right_side= tf.strided_slice(targets, [0,0], [batchsize, -1], [1,1])
preprocessed_targets= tf.concat([left_side, right_side], 1)
return preprocessed_targets
def encoder_rnn(rnn_inputs, rnn_size, num_layers, keep_prob, sequence_length):
lstm= tf.contrib.rnn.BasicLSTMCell(rnn_size)
lstm_dropout= tf.contrib.rnn.DropoutWrapper(lstm, input_keep_prob= keep_prob)
encoder_cell= tf.contrib.rnn.MultiRNNCell([lstm_dropout] * num_layers)
encoder_output, encoder_state= tf.nn.bidirectional_dynamic_rnn(cell_fw= encoder_cell,
cell_bw= encoder_cell,
sequence_length= sequence_length,
inputs= rnn_inputs,
dtype= tf.float32)
return encoder_state
#decoding training set
def decode_training_set(encoder_state, decoder_cell, decoder_embedded_input, sequence_length, decoding_scope, output_function, keep_prob, batch_size):
attention_states= tf.zeroes([batchsize, 1, decoder_cell.output_size])
attention_keys, attention_values, attention_score_function, attention_construct_function= tf.contrib.seq2seq.prepare_attention(attention_states, attention_option= 'bahdanau', num_units= decoder_cell.output_size)
training_decoder_function= tf.contrib.seq2seq.attention_decoder_fn_train(encoder_state[0],
attention_keys,
attention_values,
attention_score_function,
attention_construct_function,
name= 'attn_doc_train')
decoder_output, decoder_final_state, decoder_final_context_state= tf.contrib.seq2seq.dynamic_rnn_decoder(decoder_cell,
training_decoder_function,
decoder_embedded_input,
sequence_length,
scope= decoding_scope)
decoder_output_dropout= tf.nn.dropout(decoder_output, keep_prob)
return output_function(decoder_output_dropout)
#decoding test/validation set
def decode_test_set(encoder_state, decoder_cell, decoder_embeddings_matrix, sos_id, eos_id, maximum_length, num_words, sequence_length, decoding_scope, output_function, keep_prob, batch_size):
attention_states= tf.zeroes([batchsize, 1, decoder_cell.output_size])
attention_keys, attention_values, attention_score_function, attention_construct_function= tf.contrib.seq2seq.prepare_attention(attention_states, attention_option= 'bahdanau', num_units= decoder_cell.output_size)
test_decoder_function= tf.contrib.seq2seq.attention_decoder_fn_inference(output_function,
encoder_state[0],
attention_keys,
attention_values,
attention_score_function,
attention_construct_function,
decoder_embeddings_matrix,
sos_id,
eos_id,
maximum_length,
num_words,
name= 'attn_doc_inf') #inf=inference
test_predictions, decoder_final_state, decoder_final_context_state= tf.contrib.seq2seq.dynamic_rnn_decoder(decoder_cell,
test_decoder_function,
scope= decoding_scope)
return test_predictions
| 06fa9d8ac82ce3041ea3d94c41de676725ef1e3a | [
"Python"
] | 1 | Python | pheobe15/ChatBot | 5332a44d348186103a8ef823ae14ef874d21c17b | 533f81fd938450aefa9a8c9588b38542a3ae85cd |
refs/heads/master | <repo_name>BLRussell-09/jsStrings<file_sep>/strings.js
// Challenge 1
var numOfSandwiches = 4*2
console.log('numOfSanswiches', numOfSandwiches); //Should print the number 8
// Challenge 2
var name = "Barry"
var string = "Hello, " + name + " how are you doing today?";
console.log('string' + string);
// Challenge 3
var dna = "GCAT";
var rna = dna.replace(/T/, "U");
console.log("RNA", rna);
// Challenge 4
var animal = "ALLigator"
// var animal = "bear"
// var animal = "rhino"
if(animal.toLowerCase() === "alligator"){
// console.log("small");
}else {console.log("wide");}
//
var yarn = "Text here"
var domString = "<h4>" + yarn + "</h4>"
var myDiv = document.getElementById('yarn-holder');
myDiv.innerHTML = domString;
// Challenge 4
var str = "IBMWLOVEbmcatsbmw";
var newStr = str.replace(/[bmw]/gi, "").toLowerCase();
var cats = "<h1>" + newStr + "</h1>"
var kittenDiv = document.getElementById('cat-holder');
kittenDiv.innerHTML = cats;
| cc6781a936263396d4b4f82e2c25630b1dda2af8 | [
"JavaScript"
] | 1 | JavaScript | BLRussell-09/jsStrings | 16280333e227bfaf040154ff9a233406cd8ca850 | 9ba9651e165328ec09e09a74c17e2460425ab862 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-body">
<section>
<div class="step-three" style="">
<h2><b>Login To Your Account</b></h2>
<form id="user-login" action="login" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<div class="col-md-6 col-sm-12">
<div class="row">
<div class="col-md-12">
<i class="glyphicon glyphicon-user" style="font-size: 150px;margin-left: 125px;"></i>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" class="form-control" placeholder="Email" id="User_email" name="User_email" required="required">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="<PASSWORD>" placeholder="<PASSWORD>" id="User_password" name="User_password" class="form-control" required="required">
</div>
</div>
<div class="form-group">
<button class="btn btn-default login" style="text-align: center;">Let me in</button>
</div>
<div class="form-group">
<span><a href="signup">Create account </a> or forgot password</span>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="confirm">
<div class="header">
<h2 style="line-height:1;color:white">CONFIRM YOUR <br> REQUEST WITH</h2>
</div>
<div class="body">
<button class="btn btn-default google"><span style="padding-right: 25px"><i class="fa fa-google" aria-hidden="true"></i></span> Google</button>
<p>This is just to confirm your request. We will never post anything without your premission.</p>
</div>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
</div>
</div>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-body">
<button style="width:220px; background-color: #5cb85c; border-color: #4cae4c;" class="btn btn-success pull-right"><i class="fa fa-plus"></i><a href="<?php echo base_url()?>Vendor/addpackage" style="color: white"> Add Package</a></button>
<h2><strong>My Packages</strong></h2>
<div class="content">
<? if(isset($get_all_package) && count($get_all_package) >0)
{?>
<div class="col-md-12" style="margin-bottom: 25px;">
<h3 class="vendor_name"><?php echo count($get_all_package); ?> record found.</h3>
</div>
<?
foreach($get_all_package as $package)
{
?>
<div class="col-md-12 package-box">
<div class="col-md-4">
<img style="height:170px;" src="<?php echo base_url() ; ?>images/packagetesting/<?php echo $package['package_picture_path']; ?>" class="img-responsive" alt="">
</div>
<div class="col-md-4">
<h3 class="vendor_name" style="font-size: 25px"><b><?php echo $package['Package_title']; ?></b></h3>
<div class="col-xs-12">
<span style="font-size:15px; padding-left:15px; color:#aa6708;"><b><?php echo $package['Package_description'] ; ?></b></span>
</div>
<hr>
</div>
<div class="col-md-2">
<div class="row">
<div class="pull-right starring_price">Rs <? echo $package['Package_price']?></div>
</div>
</div>
<div class="col-md-2" style="margin-top: 10px;">
<a href="<?php echo base_url()?>Vendor/editpackage/<?php echo $package['Package_id']; ?>" style="color: grey ; padding-left: 40px;"><i class="fa fa-edit"></i> <strong>Edit</strong></a>
</div>
</div>
<?
}
}
else {
?>
<div class="col-md-12">
<h3 class="vendor_name">0 record found.</h3>
</div>
<?
}?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedishedi</title>
</head>
<body>
<!--Header Starts
==================-->
<header>
<!--Navbar Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<!--Header Image
=================-->
<div class="header-image">
<div class="bg-color">
<div class="content">
<div class="container">
<h2 style="font-size: 45px;font-weight: bold;">Things you need to done for your wedding<br><span>Find it on wedishedi</span></h2>
<!---<div class="row">
<div class="col-md-12 nav-search nav-search-margin">
<form method="post" action="Vendor/search">
<select required="required" name="vendor_type" class="vendor_search magnifying select-left">
<option value="">Select Category</option>
<?php if(isset($get_all_vendor_type) && count($get_all_vendor_type) > 0)
{
foreach ($get_all_vendor_type as $vendor_type)
{
?><option value="<?php echo $vendor_type['Vendor_type_id']; ?>"><?php echo $vendor_type['Vendor_type_name']; ?></option>
<?php
}
}?>
</select>
<select class="vendor_search magnifying select-left" required="required" style="margin-left:20px;" name="city" >
<option value="">Select City</option>
<?php if(isset($get_all_city) && count($get_all_city)>0){
foreach ($get_all_city as $city) {
?>
<option value="<?php echo $city['city_id']?>"><?php echo $city['city_name']?></option>
<?
}
} ?>
</select>
<input type="submit" value="Find Suppliers" class="btn btn-success" style="font-size:20px; margin-left:150px;">
</form>
</div>
<!--<div class="col-md-12" style="padding-top: 100px;">
<h1><span>Memorable </span>Moments</h1>
</div>--->
<!-- </div>--->
</div>
</div>
</div>
</div>
</header>
<!--Services
==============-->
<section>
<div class="services">
<div class="container">
<h2>It’s Simple. You Have An Event To Plan And <br><span> We Have The Solution</span></h2>
<div class="owl-carousel" id="service-slider">
<div class="item">
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/bangles.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=1">
<img src="images/food.png" alt="">
<div class="content">
<h1>Banquet Hall</h1>
</div>
</a>
</div>
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/decorators.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=2">
<img src="images/flags.png" alt="">
<div class="content">
<h1>Decorators</h1>
</div>
</a>
</div>
</div>
<div class="item">
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/Dj.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=3">
<img src="images/dj.png" alt="">
<div class="content">
<h1>DJ</h1>
</div>
</a>
</div>
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/bakery.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=6">
<img src="images/bakery.png" alt="">
<div class="content">
<h1>Bakery</h1>
</div>
</a>
</div>
</div>
<div class="item">
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/photographer.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=5">
<img src="images/camera.png" alt="">
<div class="content">
<h1>Photography</h1>
</div>
</a>
</div>
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/catering.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=4">
<img src="images/catering.png" alt="">
<div class="content">
<h1>Catering</h1>
</div>
</a>
</div>
</div>
<div class="item">
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/Invitation.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=8">
<img src="images/note.png" alt="">
<div class="content">
<h1>Invitation</h1>
</div>
</a>
</div>
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/limousine.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=9">
<img src="images/tool.png" alt="">
<div class="content">
<h1>Limousine</h1>
</div>
</a>
</div>
</div>
<div class="item">
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/bridal_saloon.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=7">
<img src="images/salon.png" alt="">
<div class="content">
<h1>Bridal Salon</h1>
</div>
</a>
</div>
<div class="row" style="background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)),url(images/florist.jpg);background-size: cover; border-radius:50%; width:300px; display:inline-block; height:300px;">
<a href="Vendor/search/?vendor_type=10">
<img src="images/florist.png" alt="">
<div class="content">
<h1>Florist</h1>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</section>
<!--WedingCost-->
<section>
<div class="weddingcost">
<div class="content" style="">
<div class="container">
<h1><span>Wedding Cost Savings</span><br>
How much others couples in your area spent on wedding </h1>
<button class="btn btn-default">Wedding Cost</button>
</div>
</div>
</div>
</section>
<!--Latest News
=====================-->
<section>
<div class="blog">
<div class="container">
<h1>LATEST NEWS</h1>
<h4>Whether planning an intimate gathering or a wedding for hundreds, <br> learn the details on how to make your event successful.</h4>
<div class="col-md-4 col-sm-6">
<img src="images/blog1.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>January 12, 2016</p></div>
<h3>Sed Tristique Urna Ut Nibh</h3>
<p class="blog-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
<a href="">Read More</a>
</div>
</div>
<div class="col-md-4 col-sm-6">
<img src="images/blog2.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>December 05, 2015</p></div>
<h3>De Finibus Bonorum Et Malorum</h3>
<p class="blog-content">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore.</p>
<a href="">Read More</a>
</div>
</div>
<div class="col-md-4 col-sm-6">
<img src="images/blog3.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>October 18, 2015</p></div>
<h3>Vero Eos Et Accusamus Et Iusto</h3>
<p class="blog-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
<a href="">Read More</a>
</div>
</div>
</div>
</div>
</section>
<!--Footer
=============-->
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-body">
<form id="packagesave" class="dropzone" action="../Vendor/packagesave" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<!--STEP ONE
==============-->
<section>
<div class="step-one">
<h2>Add a new<strong> Package</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<div class="panel-body">
<div class="form-group" >
<div class="col-md-12 col-xs-12">
<input type="text" id="Package_title" placeholder="Package Headline" name="Package_title" required="required" class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group" >
<div class="col-md-8 col-xs-12">
<select required="required" name="Package_category" class="form-control col-md-7 col-xs-12">
<option value="">Select Category</option>
<?php if(isset($get_all_vendor_type) && count($get_all_vendor_type) > 0)
{
foreach ($get_all_vendor_type as $vendor_type)
{
?><option value="<?php echo $vendor_type['Vendor_type_id']; ?>"><?php echo $vendor_type['Vendor_type_name']; ?></option>
<?php
}
}?>
</select>
</div>
</div>
<div class="form-group" >
<div class="col-md-12 col-xs-12">
<textarea class="form-control resizable_textarea" data-parsley-trigger="keyup" data-parsley-minlength="50" data-parsley-maxlength="500" data-parsley-minlength-message="Come on! You need to enter at least a 100 caracters long description.." data-parsley-validation-threshold="10" id="Package_description" name="Package_description" required="required" class="form-control col-md-7 col-xs-12" placeholder="Briefly describe your package" style="height:150px;"></textarea>
</div>
</div>
<div class="form-group" >
<div class="col-md-6 col-xs-12 input-group mb-2 mr-sm-2 mb-sm-0" style="padding-left: 15px;">
<div class="input-group-addon">Rs:</div>
<input type="text" id="Package_price" placeholder="Price" name="Package_price" required="required" class="form-control col-md-7 col-xs-12">
<div class="input-group-addon">Per head</div>
</div>
</div>
</div>
</div>
<h2>Upload max 3<strong> Images</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<div class="panel-body">
</div>
</div>
<input type="hidden" name="User_id" value="<?php echo $this->session->userdata('User_id'); ?>">
<input type="hidden" name="vendor_id" value="<?php echo $vendor_data['Vendor_id']; ?>">
<button type="button" style="margin-top: 100px;" id="img_upload" class="btn btn-success pull-right" >Save</button>
</div>
</section>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<script type="text/javascript">
var myDropzone = new Dropzone('#packagesave', {
autoProcessQueue:false,
paramName: "myFiles",
uploadMultiple: true,
addRemoveLinks: true,
maxFiles: 3,
acceptedFiles: "image/jpeg,image/jpg,image/png,image/gif",
parallelUploads: 3,
init: function() {
var myDropzone = this;
$("#img_upload").click(function() {
$('#packagesave').bootstrapValidator('validate');
setTimeout(function(){
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
}
debugger;
myDropzone.on('sending', function(file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $('#packagesave').serializeArray();
$.each(data, function(key, el) {
formData.append(el.name, el.value);
});
});
}, 500);
myDropzone.on("success", function(files,response) {
window.location.href = 'http://localhost:8080/Wedishedi/Vendor/package';
console.log(response);
});
});
ValidateIt();
}
});
</script>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><?php
class vendor_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function get_all_vendor_type()
{
$query = $this->db->query("SELECT * from vendor_type");
$result_array = $query->result_array();
return $result_array;
}
public function get_all_vendor_by_type_city($vendor_type,$vendor_city)
{
$query = $this->db->query("SELECT *,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v WHERE v.City =".$this->db->escape($vendor_city)."");
$result_array = $query->result_array();
return $result_array;
}
public function get_all_vendors()
{
$query = $this->db->query("SELECT *,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v ");
$result_array = $query->result_array();
return $result_array;
}
public function get_all_vendor_by_type($vendor_type)
{
if($vendor_type == 1)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isBanquetHall = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 2)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isDecorators = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 3)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isDj = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 4)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isPhotographer = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 5)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isBakeries = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 6)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isBridalSaloon = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 7)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isInvitation = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 8)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isLimousine = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 9)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isFlorist = 1 ");
$result_array = $query->result_array();
}
elseif($vendor_type == 10)
{
$query = $this->db->query("SELECT * ,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path FROM vendors v where isBanquetHall = 1 ");
$result_array = $query->result_array();
}
return $result_array;
}
public function get_vendor_by_id($vendor_id)
{
$vendor_id = $this->db->escape($vendor_id);
$query = $this->db->query("SELECT *,(SELECT Vendor_picture_path FROM vendor_pictures vp WHERE vp.Vendor_id = v.Vendor_id LIMIT 1)AS Vendor_picture_path from vendors v where v.vendor_id = ".$vendor_id."");
$result_array = $query->row_array();
return $result_array;
}
public function get_service_by_vendor_type($vendor_type_id)
{
$service_list = $this->get_service($vendor_type_id);
$get_vendor_title = $this->get_vendor_title($vendor_type_id);
$out_put ='';
$count = 0;
if(isset($service_list) && $service_list != "")
{
$out_put.='<div class="row '.$vendor_type_id.'" >';
$out_put.='<h3 style="background-color: #3F729B;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">'.$get_vendor_title['Vendor_type_name'].'</h3>';
foreach($service_list as $ser)
{
$count = $count + 1;
$out_put.='<div class="col-md-6">';
$out_put.='<label class="control-label col-md-6 col-sm-6 col-xs-12" for="vendor-name">'.$ser['Service_title'].'';
$out_put.='</label>';
$out_put.='<div class="col-md-3 col-sm-3 col-xs-12">';
$out_put.='<input type="checkbox" style="width: 33px;" id="Service_id_'.$ser['Service_id'].'" name="Service_'.$ser['Service_id'].'" class="form-control col-md-7 col-xs-6 input_validator">';
$out_put.=' </div>';
$out_put.='</div>';
}
$out_put.='</div>';
}
return $out_put;
}
public function get_faq_by_vendor_type($vendor_type_id)
{
$faq_list = $this->get_faq($vendor_type_id);
$get_vendor_title = $this->get_vendor_title($vendor_type_id);
$out_put ='';
$count = 0;
if(isset($faq_list) && $faq_list != "")
{
$out_put.='<div class="row '.$vendor_type_id.'">';
$out_put.='<h3 style="background-color: #9a4364;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">'.$get_vendor_title['Vendor_type_name'].'</h3>';
foreach($faq_list as $faq)
{
$count = $count + 1;
$out_put.='<div class="form-group">';
$out_put.='<label class="control-label col-md-6 col-sm-6 col-xs-12" for="vendor-name">'.$faq['faq_title'].' <span class="required" style="color:red;">*</span>';
$out_put.='</label>';
$out_put.='<div class="col-md-3 col-sm-3 col-xs-12">';
$out_put.='<input type="text" id="faq_id_'.$faq['faq_id'].'" name="faq_id_'.$faq['faq_id'].'" required="required" class="form-control col-md-7 col-xs-6 input_validator">';
$out_put.=' </div>';
$out_put.='</div>';
}
$out_put.='</div>';
}
return $out_put;
}
public function get_min_max_faq_id()
{
$query = $this->db->query("SELECT MIN(faq_id) AS min_serive_id , MAX(faq_id) AS max_serive_id FROM faq ");
$result_array = $query->row_array();
return $result_array;
}
public function get_service($vendor_type_id)
{
$query = $this->db->query("SELECT * FROM service WHERE Vendor_type_id = ".$vendor_type_id."");
$result_array = $query->result_array();
return $result_array;
}
public function get_faq($vendor_type_id)
{
$query = $this->db->query("SELECT * FROM faq WHERE Vendor_type_id = ".$vendor_type_id."");
$result_array = $query->result_array();
return $result_array;
}
public function get_vendor_title($vendor_type_id)
{
$query = $this->db->query("SELECT * FROM vendor_type WHERE Vendor_type_id = ".$vendor_type_id."");
$result_array = $query->row_array();
return $result_array;
}
public function get_vendor_faq($vendor_type)
{
$query = $this->db->query("SELECT * FROM faq where Vendor_type_id = ".$vendor_type." ");
$result_array = $query->result_array();
return $result_array;
}
public function get_vendor_service_by_id($vendor_id,$vendor_type_id)
{
$service_list = $this->get_service($vendor_type_id);
$get_vendor_title = $this->get_vendor_title($vendor_type_id);
$query1 = $this->db->query("SELECT Services FROM vendors where Vendor_id = ".$vendor_id." ");
$services = $query1->row_array();
$out_put ='';
$count = 0;
if(isset($service_list) && $service_list != "")
{
$out_put.='<div class="row" id="'.$vendor_type_id.'">';
$out_put.='<h3 style="background-color: #3F729B;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">'.$get_vendor_title['Vendor_type_name'].'</h3>';
foreach($service_list as $ser)
{
$count = $count + 1;
$out_put.='<div class="col-md-6">';
$out_put.='<label class="control-label col-md-6 col-sm-6 col-xs-12" for="vendor-name">'.$ser['Service_title'].'';
$out_put.='</label>';
$out_put.='<div class="col-md-3 col-sm-3 col-xs-12">';
if(strpos($services['Services'], $ser['Service_id']) !== false)
{
$out_put.='<input type="checkbox" style="width: 33px;" checked="checked" id="Service_id_'.$ser['Service_id'].'" name="Service_'.$ser['Service_id'].'" class="form-control col-md-7 col-xs-6 input_validator">';
}
else {
$out_put.='<input type="checkbox" style="width: 33px;" id="Service_id_'.$ser['Service_id'].'" name="Service_'.$ser['Service_id'].'" class="form-control col-md-7 col-xs-6 input_validator">';
}
$out_put.=' </div>';
$out_put.='</div>';
}
$out_put.='</div>';
}
return $out_put;
}
public function get_vendor_faq_by_id($vendor_id,$vendor_type_id)
{
$query = $this->db->query("SELECT *,(SELECT s.faq_title FROM faq s WHERE s.faq_id = vs.faq_id)AS faq_title FROM vendor_faq vs JOIN faq s ON s.faq_id = vs.faq_id JOIN vendor_type vt ON s.Vendor_type_id = vt.Vendor_type_id where vs.Vendor_id = ".$vendor_id." and vt.Vendor_type_id = ".$vendor_type_id."");
$faq_list = $query->result_array();
$get_vendor_title = $this->get_vendor_title($vendor_type_id);
$out_put ='';
$count = 0;
if(isset($faq_list) && $faq_list != "")
{
$out_put.='<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">'.$get_vendor_title['Vendor_type_name'].'</h3>';
foreach($faq_list as $faq)
{
$count = $count + 1;
$out_put.='<div class="form-group" >';
$out_put.='<label class="control-label col-md-6 col-sm-6 col-xs-12" for="vendor-name">'.$faq['faq_title'].' <span class="required" style="color:red;">*</span>';
$out_put.='</label>';
$out_put.='<div class="col-md-3 col-sm-3 col-xs-12">';
$out_put.='<input type="text" id="faq_id_'.$faq['faq_id'].'" name="faq_id_'.$faq['faq_id'].'" value="'.$faq['result'].'" required="required" class="form-control col-md-7 col-xs-6">';
$out_put.=' </div>';
$out_put.='</div>';
}
}
return $out_put;
}
public function get_all_vendor_faq($vendor_id)
{
$query = $this->db->query("SELECT *,(SELECT s.faq_title FROM faq s WHERE s.faq_id = vs.faq_id)AS title FROM vendor_faq vs WHERE vs.vendor_id = ".$vendor_id."");
$result_array = $query->result_array();
return $result_array;
}
public function vendor_faq($vendor_id)
{
$query = $this->db->query("SELECT *
FROM vendor_faq vs
JOIN faq s ON s.faq_id = vs.faq_id
JOIN vendor_type vt ON s.Vendor_type_id = vt.Vendor_type_id
WHERE vs.Vendor_id = ".$vendor_id."");
$result_array = $query->result_array();
return $result_array;
}
public function add($data)
{
$date = date('Y-m-d H:i:s');
$sql = 'insert into vendors(Vendor_name,Vendor_description,Vendor_starting_price,Vendor_address,User_id,City,CreatedOn,Vendor_lat,Vendor_long,Services) VALUES("'.$data['Vendor_name'].'","'.$data['Vendor_description'].'","'.$data['Vendor_starting_price'].'","'.$data['Vendor_address'].'","'.$data['User_id'].'","'.$data['city'].'","'.$date.'","'.$data['Vendor_lat'].'","'.$data['Vendor_long'].'","'.$data['serlist'].'")';
$this->db->query($sql);
$lastid = $this->db->insert_id();
if(isset($data['Vendor_type']))
{
foreach ($data['Vendor_type'] as $type) {
if($type == 1)
{
$sql = 'UPDATE vendors SET isBanquetHall = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 2)
{
$sql = 'UPDATE vendors SET isDecorators = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 3)
{
$sql = 'UPDATE vendors SET isDj = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 4)
{
$sql = 'UPDATE vendors SET isCatering = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 5)
{
$sql = 'UPDATE vendors SET isPhotographer = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 6)
{
$sql = 'UPDATE vendors SET isBakeries = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 7)
{
$sql = 'UPDATE vendors SET isBridalSaloon = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 8)
{
$sql = 'UPDATE vendors SET isInvitation = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 9)
{
$sql = 'UPDATE vendors SET isLimousine = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 10)
{
$sql = 'UPDATE vendors SET isFlorist = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
}
}
return $lastid;
}
public function edit($data)
{
$date = date('Y-m-d H:i:s');
$sql = 'update vendors Set Vendor_name = "'.$data['Vendor_name'].'" ,Vendor_description = "'.$data['Vendor_description'].'" , Vendor_starting_price = "'.$data['Vendor_starting_price'].'", Vendor_address = "'.$data['Vendor_address'].'", Services = "'.$data['serlist'].'", User_id = "'.$data['User_id'].'",City = "'.$data['city'].'",ModifiedOn = "'.$date.'" WHERE Vendor_id = "'.$data['vendor_id'].'"';
$this->db->query($sql);
if(isset($data['Vendor_type']))
{
foreach ($data['Vendor_type'] as $type) {
if($type == 1)
{
$sql = 'UPDATE vendors SET isBanquetHall = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 2)
{
$sql = 'UPDATE vendors SET isDecorators = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 3)
{
$sql = 'UPDATE vendors SET isDj = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 4)
{
$sql = 'UPDATE vendors SET isCatering = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 5)
{
$sql = 'UPDATE vendors SET isPhotographer = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 6)
{
$sql = 'UPDATE vendors SET isBakeries = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 7)
{
$sql = 'UPDATE vendors SET isBridalSaloon = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 8)
{
$sql = 'UPDATE vendors SET isInvitation = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 9)
{
$sql = 'UPDATE vendors SET isLimousine = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
elseif($type == 10)
{
$sql = 'UPDATE vendors SET isFlorist = 1 WHERE Vendor_id = '.$lastid.'';
$this->db->query($sql);
}
}
}
}
public function get_vendor_images($vendor_id)
{
$query = $this->db->query("SELECT Vendor_picture_path FROM vendor_pictures WHERE Vendor_id = ".$vendor_id." AND Is_Deleted = 0");
$result_array = $query->result_array();
return $result_array;
}
public function get_package_images($package_id)
{
$query = $this->db->query("SELECT package_picture_path FROM package_picture WHERE package_id = ".$package_id." AND Is_Deleted = 0");
$result_array = $query->result_array();
return $result_array;
}
public function add_vendor_faq($vendor_id,$faq_id,$resut)
{
$date = date('Y-m-d H:i:s');
$sql = 'insert into vendor_faq(Vendor_id,faq_id,creation_date,result) VALUES("'.$vendor_id.'","'.$faq_id.'","'.$date.'","'.$resut.'")';
$this->db->query($sql);
$lastid = $this->db->insert_id();
return $lastid;
}
public function edit_vendor_faq($vendor_id,$faq_id,$resut)
{
$sql = 'update vendor_faq set result = "'.$resut.'" where Vendor_id="'.$vendor_id.'" and faq_id="'.$faq_id.'"';
return $this->db->query($sql);
}
public function add_image_path($vendor_id,$path,$is_pp)
{
$sql = 'insert into vendor_pictures(Vendor_id,Vendor_picture_path,Is_profile_pic) VALUES("'.$vendor_id.'","'.$path.'","'.$is_pp.'")';
return $this->db->query($sql);
}
public function delete_image_path($path)
{
$sql = 'update vendor_pictures set Is_Deleted = 1 where Vendor_picture_path = "'.$path.'"';
return $this->db->query($sql);
}
public function get_vendor_picture_by_id($vendor_id)
{
$query = $this->db->query("SELECT * FROM vendor_pictures vp where vp.Vendor_id = ".$vendor_id." AND Is_Deleted = 0");
$result_array = $query->result_array();
return $result_array;
}
public function get_vendor_id_by_user_id($User_id)
{
$sql = 'Select * from vendors where User_id = '.$User_id.'';
$query = $this->db->query($sql);
$result_array = $query->row_array();
return $result_array;
}
public function packageadd($data)
{
$date = date('Y-m-d H:i:s');
$sql = 'insert into package(Package_title,Package_description,Package_category,Package_price,Vendor_id,CreatedOn) VALUES("'.$data['Package_title'].'","'.$data['Package_description'].'","'.$data['Package_category'].'","'.$data['Package_price'].'","'.$data['vendor_id'].'","'.$date.'")';
$this->db->query($sql);
$lastid = $this->db->insert_id();
return $lastid;
}
public function packageedit($data)
{
$sql = 'update package set Package_title = "'.$data['Package_title'].'", Package_description = "'.$data['Package_description'].'", Package_category = "'.$data['Package_category'].'", Package_price ="'.$data['Package_price'].'" where Package_id= "'.$data['Package_id'].'" ';
return $this->db->query($sql);
}
public function add_package_image_path($package_id,$path)
{
$sql = 'insert into package_picture(package_id,package_picture_path) VALUES("'.$package_id.'","'.$path.'")';
return $this->db->query($sql);
}
public function get_all_package($vendor_id)
{
$query = $this->db->query("SELECT *,(SELECT pp.package_picture_path FROM package_picture pp WHERE pp.package_id = p.Package_id LIMIT 1) AS package_picture_path
FROM package p
WHERE p.Vendor_id =".$vendor_id."");
$result_array = $query->result_array();
return $result_array;
}
public function get_package_by_id($package_id)
{
$query = $this->db->query("SELECT *,(select Vendor_type_name from vendor_type vt where vt.Vendor_type_id = p.Package_category) as type
FROM package p
WHERE p.Package_id =".$package_id."");
$result_array = $query->row_array();
return $result_array;
}
public function delete_package_picture($filepath)
{
$sql = 'update package_picture set Is_Deleted = 1 where package_picture_path = "'.$filepath.'"';
return $this->db->query($sql);
}
public function delete_vendor_picture($filepath)
{
$sql = 'update vendor_pictures set Is_Deleted = 1 where vendor_picture_path = "'.$filepath.'"';
return $this->db->query($sql);
}
public function get_all_city()
{
$query = $this->db->query("SELECT *
FROM city
");
$result_array = $query->result_array();
return $result_array;
}
public function get_min_max_service_id()
{
$query = $this->db->query("SELECT MIN(Service_id) AS min_serive_id , MAX(Service_id) AS max_serive_id FROM service ");
$result_array = $query->row_array();
return $result_array;
}
public function get_vendor_services($serlist)
{
$sql = "SELECT *
FROM service s
WHERE s.Service_id IN (".$serlist.")";
$query = $this->db->query($sql);
$result_array = $query->result_array();
return $result_array;
}
}
?>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-body">
<section>
<div class="step-three" style="">
<h2><b>Register Your Account</b></h2>
<hr>
<form id="user_signup" action="save" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<div class="col-sm-12">
<div class="form-group">
<div class="col-sm-6">
<input type="text" required class="form-control" placeholder="First Name" name="User_fname" id="User_fname" required="required">
</div>
<div class="col-sm-6">
<input type="text" required class="form-control" placeholder="Last Name" name="User_lname" id="User_lname" required="required">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" required class="form-control" placeholder="Email" name="User_email" id="User_email" data-fv-remote-name="User_email" required="required">
<span id='message_phone'></span>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<input type="text" required id="phoneNumber" class="form-control" placeholder="Contact Number" name="User_phone_no" id="User_phone_no" required="required">
</div>
<div class="col-sm-6">
<select name="User_contact_preference" id="User_contact_preference" class="form-control" required="required">
<option>Select Contact Preference</option>
<option value="1">Phone and Email</option>
<option value="2">Phone</option>
<option value="3">Email</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<input type="<PASSWORD>" required id="User_password" class="form-control" placeholder="<PASSWORD>" name="User_password" required="required">
</div>
<div class="col-sm-6">
<input type="<PASSWORD>" required id="confirm_password" placeholder="Confirm Password" class="form-control" name="confirm_password" required="required">
<span id='message_pass'></span>
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<input type="checkbox" name="IsVendor" style="height:30px; width:30px;" data-label="Supplier" >
</div>
<label for="preference" class="col-sm-4 control-label">Are You Supplier ?</label>
</div>
<div class="form-group">
<div class="col-sm-7">
<button class="btn btn-warning pull-left signup" style="width: 150px;margin-left: 268px;">Register</button>
</div>
</div>
<div class="form-group">
<span class="pull-right col-sm-8"><a href="login">Login Existing Account </a> or forgot password</span>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
</div>
</div>
<script type="text/javascript">
</script>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.20&sensor=true&key=<KEY>"></script>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="container">
<h1><span>Find The Best Suppliers In Your Area</span></h1>
<div id="map" style="height:300px; width:100%; "></div>
<hr>
<!---<div class="col-md-12 nav-search">
<form method="post" action="search">
<select required="required" name="vendor_type" class="vendor_search select-left">
<option value="">Select Category</option>
<?php if(isset($get_all_vendor_type) && count($get_all_vendor_type) > 0)
{
foreach ($get_all_vendor_type as $vendor_type)
{
$type_id = $vendor_type['Vendor_type_id'];
?><option <?php if ((int)$vendor_type == $type_id){ ?>selected<?php }?> value="<?php echo $vendor_type['Vendor_type_id']; ?>"><?php echo $vendor_type['Vendor_type_name']; ?></option>
<?php
}
}?>
</select>
<select required="required" name="city" class="vendor_search select-left" style="margin-left:20px;">
<option value="">Select City</option>
<option <?php if (isset($city) && $city == "Lahore"){ ?>selected<?php }?> value="Lahore">Lahore</option>
<option <?php if (isset($city) && $city == "Karachi"){ ?>selected<?php }?> value="Karachi">Karachi</option>
<option <?php if (isset($city) && $city == "Islamabad"){ ?>selected<?php }?> value="Islamabad">Islamabad</option>
</select>
<input type="submit" value="Find Suppliers" class="btn btn-success" style="font-size:20px; margin-left:150px;">
</form>
</div>--->
</div>
<div class="container">
<div class="col-md-12">
<h3 class="vendor_name"><?php echo count($listing); ?> Records Found.</h3>
</div>
<hr>
<div class="col-md-12" style="margin-top:40px; margin-bottom:40px; z-index:1;">
<?php if (isset($listing) && count($listing) > 0)
{
foreach ($listing as $dat)
{
?>
<a href="<?php echo base_url()?>Vendor/detail/<?php echo $dat['Vendor_id']; ?>">
<div class="col-md-12 vendor-box">
<div class="col-md-4">
<img style="height:250px;" src="<?php echo base_url() ; ?>images/vendortesting/<?php echo $dat['Vendor_picture_path']; ?>" class="img-responsive" alt="">
</div>
<div class="col-md-4">
<div class="content">
<h3 class="vendor_name" style="font-size: 25px"><b><?php echo $dat['Vendor_name']; ?></b></h3>
<div class="col-xs-12">
<i class="glyphicon glyphicon-map-marker" style="font-size:20px;"></i>
<span style="font-size:15px; padding-left:15px; color:#aa6708;"><b><?php echo $dat['Vendor_address'] ; ?></b></span>
</div>
<hr>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="pull-right starring_price">Starring Price - Rs <?php echo $dat['Vendor_starting_price'] ; ?></div>
</div>
<div class="row" style="margin-top: 10px;">
<button class="btn btn-info pull-right"><i class="fa fa-edit"></i> Request Quote</button>
</div>
<div class="row" style="margin-top: 10px;">
<button style="width: 140px;" class="btn btn-warning pull-right"><i class="fa fa-heart"></i> Favourite</button>
</div>
</div>
</div></a>
<?php
}
} ?>
<!--<div class="col-md-4 col-sm-6 vendor-box">
<img src="images/blog2.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>December 05, 2015</p></div>
<h3>De Finibus Bonorum Et Malorum</h3>
<p class="blog-content">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore.</p>
<a href="">Read More</a>
</div>
</div>
<div class="col-md-4 col-sm-6 vendor-box">
<img src="images/blog3.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>October 18, 2015</p></div>
<h3>Vero Eos Et Accusamus Et Iusto</h3>
<p class="blog-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
<a href="">Read More</a>
</div>
</div>-->
</div>
<!--<div class="col-md-12" style="margin-top:40px;">
<div class="col-md-4 col-sm-6 vendor-box">
<img src="images/blog1.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>January 12, 2016</p></div>
<h3>Sed Tristique Urna Ut Nibh</h3>
<p class="blog-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
<a href="">Read More</a>
</div>
</div>
<div class="col-md-4 col-sm-6 vendor-box">
<img src="images/blog2.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>December 05, 2015</p></div>
<h3>De Finibus Bonorum Et Malorum</h3>
<p class="blog-content">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore.</p>
<a href="">Read More</a>
</div>
</div>
<div class="col-md-4 col-sm-6 vendor-box">
<img src="images/blog3.jpg" class="img-responsive" alt="">
<div class="content">
<div class="date"><p>October 18, 2015</p></div>
<h3>Vero Eos Et Accusamus Et Iusto</h3>
<p class="blog-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
<a href="">Read More</a>
</div>
</div>
</div>-->
</div>
</div>
</div>
</section>
<script>
$(document).ready(function(){
initmap();
});
function initmap() {
debugger;
var lat;
var long;
var mapCanvas = document.getElementById("map");
var locations = <?php echo json_encode($listing); ?>;
// Initialize the Geocoder
lat = 31.504214566890944;
long = 74.33143593652346;
var mapOptions = {
center: new google.maps.LatLng(lat, long),
zoom: 11
}
var map = new google.maps.Map(mapCanvas, mapOptions);
for(var i =0 ; i < locations.length ;i++)
{
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['Vendor_lat'], locations[i]['Vendor_long']),
map: map,
title: locations[i]['Vendor_name']+' - '+locations[i]['Vendor_address']
});
}
}
</script>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quotation</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header-calendar.php'); ?>
<!-- form part
=================-->
<div class="main-form">
<div class="content">
<div class="container">
<div id='loading' style="display:none;">loading...</div>
<div id='calendar'></div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New Events</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary popsubmit">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Footer
=============-->
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
//This is the Book Model for CodeIgniter CRUD using Ajax Application.
class Events_model extends CI_Model
{
var $table = 'events';
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_events($start, $end)
{
return $this->db->where("Event_start_date >=", $start)->where("Event_end_date <=", $end)->get($this->table);
}
public function add_event($data)
{
$this->db->insert($this->table, $data);
}
public function get_event($id)
{
return $this->db->where("Event_id", $id)->get($this->table);
}
public function update_event($id, $data)
{
$this->db->where("Event_id", $id)->update($this->table, $data);
}
public function delete_event($id)
{
$this->db->where("Event_id", $id)->delete($this->table);
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
//define('STDIN',fopen("php://stdin","r"));
class Events extends CI_Controller {
/**
* Index Page for this controller.
*
* This page contain event calendar based google calendar
* author: <NAME>
* email: <EMAIL>
*/
public function __construct()
{
parent::__construct();
require FCPATH.'vendor/autoload.php';
$this->load->helper('url');
$this->load->model('events_model');
}
public function get_events()
{
// Our Start and End Dates
$start = $this->input->get("start");
$end = $this->input->get("end");
$startdt = new DateTime('now'); // setup a local datetime
$startdt->setTimestamp($start); // Set the date based on timestamp
$start_format = $startdt->format('Y-m-d H:i:s');
$enddt = new DateTime('now'); // setup a local datetime
$enddt->setTimestamp($end); // Set the date based on timestamp
$end_format = $enddt->format('Y-m-d H:i:s');
$events = $this->events_model->get_events($start_format, $end_format);
$data_events = array();
foreach($events->result() as $r) {
$data_events[] = array(
"Id" => $r->Event_id,
"title" => $r->Event_title,
"desc" => $r->Event_desc,
"end" => $r->Event_end_date,
"start" => $r->Event_start_date
);
}
echo json_encode(array("events" => $data_events));
exit();
}
public function add_event()
{
/* Our calendar data */
$name = $this->input->post("title", TRUE);
$desc = $this->input->post("content_event", TRUE);
$start_date = $this->input->post("start", TRUE);
$end_date = $this->input->post("end", TRUE);
$event_type = $this->input->post("event_type", TRUE);
$guest_name = $this->input->post("guest_name", TRUE);
if(!empty($start_date)) {
$sd = DateTime::createFromFormat("Y-m-d", $start_date);
$start_date = $sd->format('Y-m-d H:i:s');
$start_date_timestamp = $sd->getTimestamp();
} else {
$start_date = date("Y-m-d H:i:s", time());
$start_date_timestamp = time();
}
if(!empty($end_date)) {
$ed = DateTime::createFromFormat("Y-m-d", $end_date);
$end_date = $ed->format('Y-m-d H:i:s');
$end_date_timestamp = $ed->getTimestamp();
} else {
$end_date = date("Y-m-d H:i:s", time());
$end_date_timestamp = time();
}
$this->events_model->add_event(array(
"Event_title" => $name,
"Event_desc" => $desc,
"Event_start_date" => $start_date,
"Event_end_date" => $end_date,
'Event_type' => $event_type,
'Event_expected_guest' => $guest_name,
'CreatedBy' => 1,
'Created_datetime' => date("Y-m-d H:i:s", time()),
'Is_Active' => 1,
'User_id' => 1,
'Vendor_id' => 1,
)
);
}
public function update_event()
{
/* Our calendar data */
$name = $this->input->post("title", TRUE);
$desc = $this->input->post("content_event", TRUE);
$start_date = $this->input->post("start", TRUE);
$end_date = $this->input->post("end", TRUE);
$event_type = $this->input->post("event_type", TRUE);
$guest_name = $this->input->post("guest_name", TRUE);
$id = $this->input->post("id", TRUE);
// if(!empty($start_date)) {
// $sd = DateTime::createFromFormat("Y-m-d", $start_date);
// $start_date = $sd->format('Y-m-d H:i:s');
// $start_date_timestamp = $sd->getTimestamp();
// } else {
// $start_date = date("Y-m-d H:i:s", time());
// $start_date_timestamp = time();
// }
// if(!empty($end_date)) {
// $ed = DateTime::createFromFormat("Y-m-d", $end_date);
// $end_date = $ed->format('Y-m-d H:i:s');
// $end_date_timestamp = $ed->getTimestamp();
// } else {
// $end_date = date("Y-m-d H:i:s", time());
// $end_date_timestamp = time();
// }
// $this->events_model->update_event($id, array(
// "title" => $name,
// "description" => $desc,
// "start" => $start_date,
// "end" => $end_date,
// 'event_type' => $event_type,
// 'event_expected_guest' => $guest_name,
// 'modified_by' => 2,
// 'modified_date' => date("Y-m-d H:i:s", time()),,
// )
// );
$this->events_model->update_event($id, array(
"title" => $name,
"description" => $desc,
// "start" => $start_date,
// "end" => $end_date,
// 'event_type' => $event_type,
'event_expected_guest' => $guest_name,
'modified_by' => 2,
'modified_date' => date("Y-m-d H:i:s", time()),
)
);
}
public function index()
{
//var_dump($this->session->userdata());
//exit();
$this->load->view('events/index.php');
}
public function save(){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$title = isset($request->title) ? strip_tags($request->title) : '';
$place = isset($request->place) ? strip_tags($request->place) : '';
$content_event = isset($request->content_event) ? strip_tags($request->content_event) : '';
$start = isset($request->start) ? strip_tags($request->start) : '';
$end = isset($request->end) ? strip_tags($request->end) : '';
/*
$insert = $this->book_model->book_add($data);
$data = array(
'book_isbn' => $title,
'book_title' => $content_event,
'book_author' => $start,
'book_category' => $end,
);
echo json_encode(array("status" => TRUE));
*/
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("<KEY>");
$client = $this->getClient();
print_r($client);
try {
if ($client) {
throw new Exception('Test error', 123);
}
echo json_encode(array(
'result' => 'vanilla!',
));
}catch (Exception $e) {
print_r($e->getMessage());
$client_id = '12345467-123azer123aze123aze.apps.googleusercontent.com'; // YOUR Client ID
$service_account_name = '12345467-<EMAIL>'; // Email Address in the console account
$key_file_location = 'fullcalendar/google-api-php-client-master/API_Project-35c93db58757.p12'; // key.p12 to create in the Google API console
if (strpos($client_id, "googleusercontent") == false || !strlen($service_account_name) || !strlen($key_file_location)) {
echo "no credentials were set.";
exit;
}
echo json_encode(array(
'error' => array(
'msg' => $e->getMessage(),
'code' => $e->getCode(),
),
));
}
die();
/** We create service access ***/
$client = new Google_Client();
/************************************************
If we have an access token, we can carry on. (Otherwise, we'll get one with the help of an assertion credential.)
Here we have to list the scopes manually. We also supply the service account
************************************************/
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'), // ou calendar_readonly
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Calendar($client);
$calendarId = '<EMAIL>';
$event = new Google_Service_Calendar_Event(array(
'summary' => $title,
'location' => $place,
'description' => $content_event,
'start' => array(
'dateTime' => $start, //'2015-06-08T15:00:00Z'
'timeZone' => 'Europe/Paris',
),
'end' => array(
'dateTime' => $end,
'timeZone' => 'Europe/Paris',
),
/* in case you need that :
'attendees' => array(
array('email' => '<EMAIL>'),
array('email' => '<EMAIL>'),
),*/
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 20)
),
),
));
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s', $event->htmlLink);
}
public function update(){
$postdata = file_get_contents("php://input");
print_r($this->input->post('content_event'));
}
public function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig(FCPATH.'google/credentials.json');
$client->setAccessType('offline');
$client->setPrompt('force');
// Load previously authorized token from a file, if it exists.
$tokenPath = FCPATH.'google/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="container">
<!---<h1><span>Find The Best Suppliers In Your Area</span></h1>
<div class="col-md-12 nav-search">
<form method="post" action="../search">
<select required="required" name="vendor_type" class="vendor_search magnifying select-left">
<option value="">Select Category</option>
<?php if(isset($get_all_vendor_type) && count($get_all_vendor_type) > 0)
{
foreach ($get_all_vendor_type as $vendor_type)
{
?><option value="<?php echo $vendor_type['Vendor_type_id']; ?>"><?php echo $vendor_type['Vendor_type_name']; ?></option>
<?php
}
}?>
</select>
<select required="required" name="city" class="vendor_search magnifying select-left" style="margin-left:20px;">
<option value="">Select City</option>
<option value="Lahore">Lahore</option>
<option value="Karachi">Karachi</option>
<option value="Islamabad">Islamabad</option>
</select>
<input type="submit" value="Find Vendors" class="btn btn-success" style="font-size:20px; margin-left:150px">
</form>
</div>--->
</div>
<section>
<div class="container" style="margin-top: 50px;margin-bottom: 30px;background-image: url('../../images/vendortesting/<?php echo $get_vendor_by_id['Vendor_picture_path']; ?>');height: 250px !important;background-repeat: round;background-size: cover;background-attachment: fixed;">
<h2 style="/* padding-left:15px; */font-size: 45px;font-weight: bold;text-align: center;color: white;padding-top: 100px;padding-bottom: 65px;background-color: rgba(0,0,0,0.3);"><?php echo $get_vendor_by_id['Vendor_name']; ?></h2>
<!--<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-3">
<button class="btn btn-warning" data-toggle="modal" data-target="#Quote">Request Quote</button>
</div>
<div class="col-md-3">
<button class="btn btn-success" data-toggle="modal" data-target="#ContactInfo"><i class="glyphicon glyphicon-earphone" style="font-size: 20px;margin-right: 10px;"></i>View Contact Info</button>
</div>
</div>-->
<div>
</section>
<div class="modal fade" id="Quote" role="dialog">
</div>
<div class="modal fade" id="ContactInfo" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1 class="modal-title vendor_contact_header"><b>Contact Info</b></h4>
</div>
<div class="modal-body" style="background-color:#F4F496">
<div style="min-height:700px;">
<div class="col-md-6">
<div class="row">
<span class="vendor_name"><?php echo $get_vendor_by_id['Vendor_name']; ?>.</span>
</div>
</div>
<div class="col-md-6">
<div class="row">
<i class="glyphicon glyphicon-earphone" style="font-size:20px;"></i>
<span class="vendor_name" style="padding-left:15px"><?php echo $get_vendor_by_id['Vendor_contact_no']; ?>.</span>
</div>
</div>
<div class="col-md-12">
<div class="row">
<i class="glyphicon glyphicon-map-marker" style="font-size:20px;"></i>
<span style="font-size:20px; padding-left:15px; color:#aa6708;"><b><?php echo $get_vendor_by_id['Vendor_address']; ?>.</b></span>
</div>
</div>
<div class="row" >
<div class="col-md-12" style="padding-top:50px;">
<span class="vendor_name">Question You Should Ask</span>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>1</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>HOW MANY EVENTS DO YOU DO PER YEAR (HOW MUCH EXPERIENCE DO YOU HAVE)?</b></h3>
<p>This is probably THE most important question you will ask. Ideally, the professional you are interviewing should have ample experience (specifically with weddings if you are getting married).</p>
<p><b>Why it's Important:</b> Not only will an experienced vendor be obviously more skilled in their profession, it also ensures that they have a track record on working with other vendors and handling matters if something goes wrong.</p>
</div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>2</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>DO YOU USE ANY CONTRACT?</b></h3>
<p><b>The hiring or retaining of the majority of professional services found on Wedishedi will absolutely merit a contract.</b> Remember that a contract is designed to protect both you and the business, and virtually all reputable vendors will have one available for your review. If the vendor you are interviewing does not use contracts, you should seriously consider moving on to the next one on your list. The exception to this rule is if it is not standard practice for that type of service to use contracts (such as when buying wedding/party invitations or favors).</p>
</div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>3</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>DO YOU HAVE ANY REVIEWS ON Wedishedi.COM?</b></h3>
<p>Real referrals from satisfied clients are hard to fake. Decidio verifies the customer contact information for each posted review for authenticity. <b>If they do not have any reviews posted from previous customers, ask why not.</b> With up to ten thousand brides and party planners using our site every day (including yourself), most reputable businesses will have at least a few reviews regarding the quality of their service. Before hiring, call and ask questions to both previous customers and professional references.</p>
</div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>4</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>HOW MUCH DO YOU COST (INCLUDING PACKAGE PRICING)?</b></h3>
<p>After you are satisfied with the vendor's qualifications, price will naturally be the next highest concern when making your final determination on which professional you hire. <b>Remember that pricing for professional services is relative,</b> especially when you factor in experience, skill level, and reputation. The better quality (most talented/experienced/sought after) professionals will naturally cost more because their reputation and level of skill justify their rate.</p></div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>5</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>WHAT SPECIFICALLY IS INCLUDED IN THAT COST?</b></h3>
<p>What is included in specific packages will vary from vendor to vendor, so it's likely that you won't be able to compare which best suits you without first doing a little figuring. <b>Don't make the common mistake in assuming that the lowest cost package will automatically be the best deal.</b> Take into account that higher quotes may include services you want or are considered "must haves", but are not included in lower priced packages.</p></div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>6</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>ARE THERE ANY ADDITIONAL FEES/TAXES?</b></h3>
<p>Make sure you ask what (or if) additional costs such as travel fees, setup fees, taxes, service charges, etc will be included in the final price. These costs should be itemized and clearly defined in your contract before you sign, which leads to our next question.</p></div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>7</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>WHAT IS YOUR CANCELLATION POLICY IF EITHER YOU OR I CANCEL?</b></h3>
<p>Sometimes life does not go as planned, and a cancellation of services is needed. Ask if the contract has a provision for cancellations. Also ask if part of your deposit is refundable if you cancel before a certain date. Finally, ask if the vendor has a back up plan if something happens to them and they unexpectedly cancel.</p>
</div>
</div>
<div style="padding-top:20px;">
<div class="col-md-2">
<div class="serial-num"><span>8</span></div>
</div>
<div class="col-md-10">
<h3 class="qust"><b>DO YOU HAVE A SOCIAL MEDIA PRESENCE ONLINE?</b></h3>
<p>Just like with liability insurance, reputable businesses will appear online in various ways, including Facebook, Twitter, and other forums. Less reputable businesses will tend not to participate in social media, as new customers will be able to quickly learn from the feedback posted by previous unhappy customers and stay away.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<section>
<div class="container" style="margin-top: 30px;margin-bottom: 30px;">
<div class="row">
<!--<div class="container col-md-8">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<?php if(isset($get_all_vendor_pictures) && count($get_all_vendor_pictures)>0)
{
$count = 0;
foreach ($get_all_vendor_pictures as $key) {
$count = $count + 1;
?>
<div class="item <? if($count == 1){?>active <?}?>">
<img class="img-responsive" src="../../images/vendortesting/<?php echo $key['Vendor_picture_path']; ?>" alt="Los Angeles" style="width:100%; height: 400px; max-height:400px;">
</div>
<?
}
} ?>
</div>
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" style="color:red;"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" style="color:red;"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="row">
<ul class="carousel-indicators">
<?php if(isset($get_all_vendor_pictures) && count($get_all_vendor_pictures)>0)
{
$count = 0;
foreach ($get_all_vendor_pictures as $key) {
$count = $count + 1;
?>
<li data-target="#myCarousel" data-slide-to="<? echo $count - 1; ?>" class="<? if($count == 1){?>active <?}?>"><img src="../../images/vendortesting/<?php echo $key['Vendor_picture_path']; ?>" ></li>
<?
}
} ?>
</ul>
</div>
<!--<img style="width:100%;" src="../../images/vendortesting/<?php echo $get_vendor_by_id['Vendor_picture_path']; ?>" class="img-responsive" alt=""> -->
<!--</div> -->
<div class="col-md-4" >
<div style="">
<i class="glyphicon glyphicon-map-marker" style="font-size:20px;"></i>
<span style="font-size:20px; padding-left:15px; color:#aa6708;"><b><?php echo $get_vendor_by_id['Vendor_address']; ?>.</b></span>
<hr></hr>
<!---<span><i class="glyphicon glyphicon-thumbs-up" style="font-size:25px; color:darkgray;">20</i><span>
<span><i class="glyphicon glyphicon-thumbs-down" style="font-size:25px;margin-left:50px; margin-right:50px; color:darkgray;">10</i><span>
<button class="btn btn-info" data-toggle="modal" data-target="#feedback">Leave Feedback</button>
<hr></hr>--->
<div class="col-md-12" >
<div id="map" style="height:300px; width:100%;"></div>
</div>
</div>
<div>
<div class="col-md-12" style="">
<h1 style="margin-top: 30px;"><span>Services Included</span></h1>
<div class="tab-content" style="margin-top:20px;">
<div id="Overview12" class="tab-pane fade in active">
<div class="table-responsive">
<table class="table">
<tbody>
<?php foreach ($get_services as $service) {
?>
<tr>
<td style="font-size:20px;"><?php echo $service['Service_title'];?></td>
<th style="font-size:20px; color: green"><i class="glyphicon glyphicon-ok"></i></th>
</tr>
<?
} ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-md-12" style="">
<!--<ul class="nav nav-pills nav-justified">
<li class="active"><a data-toggle="tab" href="#Overview">Frequently Asked Questions</a></li>
<li><a data-toggle="tab" href="#Avalaiblity">Avalaiblity</a></li>
</ul>-->
<h1 style="margin-top: 30px;"><span>Frequently Asked Questions</span></h1>
<div class="tab-content" style="margin-top:20px;">
<div id="Overview" class="tab-pane fade in active">
<div class="table-responsive">
<table class="table">
<tbody>
<?php if(isset($get_all_vendor_faq) && count($get_all_vendor_faq)>0)
{
$prev = 0;
$new = 0;
foreach ($get_all_vendor_faq as $vendor_faq) {
$new = $vendor_faq['Vendor_type_id'];
?>
<?
if($new != $prev)
{
?>
<tr><td style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;"><? echo $vendor_faq['Vendor_type_name']; ?></td><td style="background-color: #ff7043"></td></tr>
<? } ?>
<tr>
<td><?php echo $vendor_faq['faq_title'];?></td>
<th><?php echo $vendor_faq['result'];?></th>
</tr>
<?php
$prev = $vendor_faq['Vendor_type_id'];
}
}?>
</tbody>
</table>
</div>
</div>
<div id="Avalaiblity" class="tab-pane fade">
<h3>Avalaiblity</h3>
<p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-md-offset-1" style="">
<span class="vendor_name container" style="padding-left:15px;">Vendor Packages<span>
<hr></hr>
<div class="content">
<? if(isset($get_all_package) && count($get_all_package) >0)
{?>
<?
foreach($get_all_package as $package)
{
?>
<a href="<?php echo base_url()?>Vendor/packagedetail/?id=<?php echo $package['Package_id']; ?>">
<div class="col-md-12 package-box" style="background: #f7f7f7;">
<div class="row">
<div class="col-md-4">
<img class="img-responsive" src="<?php echo base_url() ; ?>images/packagetesting/<?php echo $package['package_picture_path']; ?>" class="img-responsive" alt="">
</div>
<div class="col-md-8">
<h3 class="" style="color: #FCB41E;font-size: 15px"><b><?php echo $package['Package_title']; ?></b></h3>
</div>
<div class="col-md-2">
</div>
</div>
<div class="row col-md-12">
<div class="col-md-6 starring_price" style="font-size: 14px;">STARTING AT <b>Rs:<? echo $package['Package_price']?></b></div>
<div class="col-md-6 " style="font-size: 15px;">
<span class="col-md-3"><i class="fa fa-heart-o" style=""></i>
</span>
<span class="col-md-8"><i class="glyphicon glyphicon-star-empty" style=""></i><i class="glyphicon glyphicon-star-empty" style=""></i><i class="glyphicon glyphicon-star-empty" style=""></i><i class="glyphicon glyphicon-star-empty" style=""></i><i class="glyphicon glyphicon-star-empty" style=""></i>
</span>
</div>
</div>
</div>
</a>
<?
}
}
else {
?>
<div class="col-md-12">
<h3 class="vendor_name">0 Active Package.</h3>
</div>
<?
}?>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</section>
<script>
google.maps.event.addDomListener(window, "load", initmap);
function initmap() {
var latLng = new google.maps.LatLng(<?php echo $get_vendor_by_id['Vendor_lat']?>, <?php echo $get_vendor_by_id['Vendor_long']?>
);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: "<?php echo $get_vendor_by_id['Vendor_name'].' - '.$get_vendor_by_id['Vendor_address'] ;?>",
map: map
});
}
</script>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<?php $IsVendor = $this->session->userdata('IsVendor');
if($IsVendor==1 && count($vendor_id) == 0 ){ ?>
<div class="main-form">
<div id="msg"></div>
<div class="content">
<div class="container">
<div class="form-body">
<form id="vendor_add" action="save" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<!--STEP ONE
==============-->
<section>
<div class="step-one">
<h2>Tell Us About Your <br><strong>Business</strong></h2>
<div class="panel panel-primary" style="border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">Vendor General Information</h3>
<div class="panel-body">
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name">Business Name <span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<input type="text" id="Vendor_name" name="Vendor_name" required="required" class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Describe your business<span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<textarea type="text" id="Vendor_description" name="Vendor_description" required="required" style="min-height: 150px;" class="form-control col-md-7 col-xs-12"></textarea>
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Cover Photo<span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<!-- <img id="blah" class="img-responsive img-circle" src="../images/avatar.png" alt="your image" /> -->
<input type="file" id="Vendor_picture" name="Vendor_picture" required="required" onchange="readURL(this);">
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name">Category<span class="required">*</span>
</label>
<div class="col-md-9 col-xs-12">
<div class="col-md-6 col-sm-12">
<input type="checkbox" class="switch" name="Vendor_type[]" value="1" data-label="Banquet Hall" required>
<input type="checkbox" class="switch" name="Vendor_type[]" value="2" data-label="Decorators" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="3" data-label="Dj" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="4" data-label="Catering" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="5" data-label="Photographer" >
</div>
<div class="col-md-6 col-sm-12">
<input type="checkbox" class="switch" name="Vendor_type[]" value="6" data-label="Bakeries" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="7" data-label="Bridal Saloon" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="8" data-label="Invitation" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="9" data-label="Limousine" >
<input type="checkbox" class="switch" name="Vendor_type[]" value="10" data-label="Florist" >
</div>
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Starting Price<span class="required">*</span>
</label>
<div class="col-md-6 col-xs-12 input-group mb-2 mr-sm-2 mb-sm-0" style="padding-left: 15px;">
<div class="input-group-addon">Rs:</div>
<input type="number" id="Vendor_starting_price" placeholder="Price" name="Vendor_starting_price" required="required" class="form-control col-md-7 col-xs-12">
<div class="input-group-addon">Per Event</div>
</div>
</div>
</div>
</div>
<div class="panel panel-primary" style="border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">Vendor Location</h3>
<div class="panel-body">
<div class="warning">
<p><strong>Note!</strong> First pin your address. Secondly change your address with the <strong>Postal address</strong>.</p>
</div>
<div class="form-group ">
<label class="control-label form-control-sm col-md-3 col-sm-3 col-xs-12" for="product-name"></label>
<div class="col-md-5 col-xs-12">
<input type="button" id="btnloc" name="" required="required" class="form-control btn btn-warning" data-toggle="modal" data-target="#setLoc" value="Pin Your Address">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Address <span class="required">*</span>
</label>
<div class="col-md-8">
<input type="text" id="Vendor_address" name="Vendor_address" required="required" class="form-control col-md-7 col-xs-12">
<input type="hidden" id="Vendor_lat" name="Vendor_lat" value="0">
<input type="hidden" id="Vendor_long" name="Vendor_long" value="0">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">City<span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<select class="form-control col-md-7 col-xs-12" required="required" name="city" >
<option value="">Select City</option>
<?php if(isset($get_all_city) && count($get_all_city)>0){
foreach ($get_all_city as $city) {
?>
<option value="<?php echo $city['city_id']?>"><?php echo $city['city_name']?></option>
<?
}
} ?>
</select>
</div>
</div>
</div>
</div>
<div >
<h2>Tell Us About Your <br><strong>Services</strong></h2>
<div class="panel panel-primary" style="border-color: transparent;">
<div class="panel-body" id="panel-body-vendor-service">
</div>
</div>
</div>
<div >
<h2>Frequently Asked <br><strong>Questions</strong></h2>
<div class="panel panel-primary" style="border-color: transparent;">
<div class="panel-body" id="panel-body-service">
</div>
</div>
</div>
<input type="hidden" name="User_id" value="<?php echo $this->session->userdata('User_id') ?>">
<button class="btn btn-default pull-right next-2" >Save & Continue.</button>
</div>
</section>
</form>
<section>
<div class="step-three" style="display:none">
<h2>Upload Your <br><strong>Images</strong></h2>
<form id="vendor_pic" class="dropzone" action="../Vendor/file_upload" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<input type="hidden" id="vendor_id" name="vendor_id" value="">
</form>
<button id="img_upload" class="btn btn-default pull-right next-3">Save & Finish</button>
<button id="sbmtbtn" class="btn btn-default pull-left prev-2">Previous Step</button>
</div>
</section>
</div>
</div>
</div>
</div>
<?php }
elseif($IsVendor==1 && isset($vendor_id) && count($vendor_id)>0 ) {
?>
<div class="container">
<div class="row tile_count">
<div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count">
<span class="count_top"><i class="fa fa-calendar-o"></i> Total Events</span>
<div class="count">10</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count">
<span class="count_top"><i class="fa fa-calendar-o"></i> Booked Events</span>
<div class="count">123.50</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count">
<span class="count_top"><i class="fa fa-calendar-o"></i> Pending Events</span>
<div class="count green">2,500</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count">
<span class="count_top"><i class="fa fa-user"></i> Total Packages</span>
<div class="count">4,567</div>
</div>
<div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count">
<span class="count_top"><i class="fa fa-user"></i> Active Packages</span>
<div class="count">4,567</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<?php
}
else {
?>
<div class="container">
<div class="alert alert-info">
Please <a data-toggle="modal" data-target="#eventdetail"><strong>click here</strong></a> to provide information about your event.
</div>
<div id="timecounter" class="col-md-12 clock"></div>
<h1><span>Plan your event with us</span></h1>
<div>
<div class="col-md-12" style="margin-top:30px;">
<ul class="nav nav-tabs nav-justified">
<li class="active"><a data-toggle="tab" href="#home"><b>Dashboard</b></a></li>
<li><a data-toggle="tab" href="#menu1"><b>Budget Calculator</b></a></li>
<li><a data-toggle="tab" href="#menu2"><b>Guest List</b></a></li>
<li><a data-toggle="tab" href="#menu3"><b>Todo's</b></a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade in active">
<h3>Wedding Planning</h3>
Planning a wedding involves endless details, deadlines, family drama, and far too often enough stress to make you want to just elope. Use our planning checklist, read our budgeting tips, and look into a wedding planner to help you pull it all together.
</div>
<div id="menu1" class="tab-pane fade">
<h3>Budget Calculator</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div id="menu2" class="tab-pane fade">
<h3>Guest List</h3>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p>
</div>
<div id="menu3" class="tab-pane fade">
<h3>Todo's</h3>
<p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
</div>
</div>
</div>
</div>
<div class="modal fade" id="eventdetail" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1 class="modal-title vendor_contact_header" style="margin:0px;"><b>Tell Us About Your Event</b></h4>
</div>
<div class="modal-body">
<div class="main-form">
<div class="content" style="padding:0px;">
<div class="container" style="width:100%;" >
<div class="form-body">
<form action="#">
<div class="form-group">
<label for="eventtype" class="col-sm-5 control-label">Event Type</label>
<div class="col-sm-7">
<select name="eventtype" class="form-control" required>
<option value="">Select Event</option>
<option value="">Wedding</option>
<option value="">Corporate Function</option>
<option value="">Birthday</option>
<option value="">Anniversary</option>
<option value="">Holiday Party</option>
</select>
</div>
</div>
<div class="form-group">
<label for="zip" class="col-sm-5 control-label">Event City</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="City" name="city" required>
</div>
</div>
<div class="form-group">
<label for="zip" class="col-sm-5 control-label">Event Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Address" name="address" required>
</div>
</div>
<div class="form-group">
<label for="guestexpect" class="col-sm-5 control-label">Guest Expected</label>
<div class="col-sm-7">
<select name="guesexpected" class="form-control" required>
<option value="">How Many</option>
<option value="">Less Than 10</option>
<option value="">10 - 50</option>
<option value="">50 - 100</option>
<option value="">100 - 200</option>
<option value="">200 - 300</option>
<option value="">300 - 400</option>
<option value="">400 - 500</option>
<option value="">500 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="eventdate" class="col-sm-5 control-label">Event Date</label>
<div class="col-sm-7">
<input type="text" class="form-control datepicker" required name="eventdate" placeholder="MM-DD-YYYY">
</div>
</div>
<div class="form-group">
<div class="col-sm-7">
<button style="padding:0px" class="form-control" name="Submit">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}?>
</div>
</section>
<div id="setLoc" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please drag the pointer to your address.</h4>
</div>
<div class="modal-body">
<div id="mapCanvas"></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var myDropzone = new Dropzone('#vendor_pic', {
autoProcessQueue:false,
paramName: "myFiles",
uploadMultiple: true,
addRemoveLinks: true,
maxFiles: 6,
acceptedFiles: "image/jpeg,image/jpg,image/png,image/gif",
parallelUploads: 6,
init: function() {
var myDropzone = this;
$("#img_upload").click(function() {
setTimeout(function(){
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
}
}, 500);
});
myDropzone.on("success", function(files,response) {
window.location.href = '';
console.log(response);
});
}
});
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
debugger;
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address,responses[4].formatted_address.split(',')[0]);
} else {
updateMarkerAddress('Cannot determine address at this location.','');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('Vendor_address').value = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('Vendor_lat').value = latLng.lat();
document.getElementById('Vendor_long').value = latLng.lng();
}
function updateMarkerAddress(str,city) {
document.getElementById('Vendor_address').value = str;
document.getElementById('city').value = city;
}
function initialize() {
var latLng = new google.maps.LatLng(31.504214566890944, 74.33143593652346
);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 11,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
icon:{path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,scale:7},
title: 'Your Location',
map: map,
draggable: true
});
// Update current position info.
//debugger;
//google.maps.event.trigger(map,'resize');
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
// /google.maps.event.trigger(map,'resize');
}
// Onload handler to fire off the app.
$('#setLoc').on('shown.bs.modal', function(){
debugger;
initialize();
});
//google.maps.event.addDomListener(window, 'load', initialize);
/*$(document).ready(function() {
$('#btnloc').click(function() {
debugger;
//$('#mapCanvas').height('300px');
google.maps.event.trigger(mapCanvas,'resize');
});
});*/
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-body">
<form id="vendor_add" action="save" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<!--STEP ONE
==============-->
<section>
<div class="step-one">
<h2>Your <br><strong>Business</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">Vendor General Information</h3>
<div class="panel-body">
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name">Vendor Types <span class="required">*</span>
</label>
<div class="col-md-9 col-xs-12">
<div class="col-md-6 col-sm-12">
<input type="checkbox" disabled name="Vendor_type[]" value="1" <? if($vendor_detail['isBanquetHall'] == 1){?> checked<? }?> required>Banquet Hall<br>
<input type="checkbox" disabled name="Vendor_type[]" value="2" <? if($vendor_detail['isDecorators'] == 1){?> checked<? }?> required >Decorators<br>
<input type="checkbox" disabled name="Vendor_type[]" value="3" <? if($vendor_detail['isDj'] == 1){?> checked<? }?> required >Dj<br>
<input type="checkbox" disabled name="Vendor_type[]" value="4" <? if($vendor_detail['isCatering'] == 1){?> checked<? }?> required>Catering<br>
<input type="checkbox" disabled name="Vendor_type[]" value="5" <? if($vendor_detail['isPhotographer'] == 1){?> checked<? }?> required >Photographer<br>
</div>
<div class="col-md-6 col-sm-12">
<input type="checkbox" disabled name="Vendor_type[]" value="6" <? if($vendor_detail['isBakeries'] == 1){?> checked<? }?> required>Bakeries<br>
<input type="checkbox" disabled name="Vendor_type[]" value="7" <? if($vendor_detail['isBridalSaloon'] == 1){?> checked<? }?> required>Bridal Saloon<br>
<input type="checkbox" disabled name="Vendor_type[]" value="8" <? if($vendor_detail['isInvitation'] == 1){?> checked<? }?> required>Invitation<br>
<input type="checkbox" disabled name="Vendor_type[]" value="9" <? if($vendor_detail['isLimousine'] == 1){?> checked<? }?> required>Limousine<br>
<input type="checkbox" disabled name="Vendor_type[]" value="10" <? if($vendor_detail['isFlorist'] == 1){?> checked<? }?> required>Florist<br>
</div>
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name">Name <span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<input type="text" id="Vendor_name" name="Vendor_name" value="<?php echo $vendor_detail['Vendor_name']; ?>" required="required" class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Description<span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<textarea type="text" id="Vendor_description" name="Vendor_description" style="min-height:150px;" required="required" class="form-control col-md-7 col-xs-12"><?php echo $vendor_detail['Vendor_description']; ?></textarea>
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Logo / Profile Picture<span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<img id="blah" class="img-responsive img-circle" style="max-height: 110px !important; max-width: 110px !important;" src="../images/vendortesting/<?php echo $vendor_detail['Vendor_picture_path']; ?>" alt="your image" />
<a id="remove_file" title="Remove file X">Remove file</a>
<input type="hidden" id="remove_file_name" value="<?php echo $vendor_detail['Vendor_picture_path']; ?>">
<input type="file" id="Vendor_picture" name="Vendor_picture" onchange="readURL(this);">
</div>
</div>
</div>
</div>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">Vendor Location</h3>
<div class="panel-body">
<div class="form-group ">
<label class="control-label form-control-sm col-md-3 col-sm-3 col-xs-12" for="product-name"></label>
<div class="col-md-5 col-xs-12">
<input type="button" id="btnloc" name="" required="required" class="form-control btn btn-warning" data-toggle="modal" data-target="#setLoc" value="Point Your Location">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">Vendor Address <span class="required">*</span>
</label>
<div class="col-md-8">
<input type="text" id="Vendor_address" name="Vendor_address" required="required" value="<?php echo $vendor_detail['Vendor_address']; ?>" class="form-control col-md-7 col-xs-12">
<input type="hidden" id="Vendor_lat" name="Vendor_lat" value="0">
<input type="hidden" id="Vendor_long" name="Vendor_long" value="0">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name">City <span class="required">*</span>
</label>
<div class="col-md-8 col-xs-12">
<select class="form-control col-md-7 col-xs-12" required="required" name="city" >
<option value="">Select City</option>
<?php if(isset($get_all_city) && count($get_all_city)>0){
foreach ($get_all_city as $city) {
?>
<option <?php if($vendor_detail['City'] == $city['city_id'] ){?> selected="selected" <?} ?> value="<?php echo $city['city_id']?>"><?php echo $city['city_name']?></option>
<?
}
} ?>
</select>
</div>
</div>
</div>
</div>
<div >
<h2>Tell Us About Your <br><strong>Services</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<div class="panel-body" id="panel-body-vendor-service">
</div>
</div>
</div>
<div >
<h2>Frequently Asked <br><strong>Questions</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<div class="panel-body" id="panel-body-service">
</div>
</div>
</div>
<input type="hidden" name="User_id" value="<?php echo $this->session->userdata('User_id') ?>">
<input type="hidden" id="vendor_id" name="vendor_id" value="<?php echo $vendor_detail['Vendor_id']?>">
<button class="btn btn-default pull-right next-2" >Save & Continue.</button>
</div>
</section>
</form>
<section>
<div class="step-three" style="display:none">
<h2>Upload Your <br><strong>Images</strong></h2>
<form id="my-dropzone" class="dropzone" action="file_upload" method="post" enctype="multipart/form-data" role="form" data-toggle="validator">
<input type="hidden" id="vendor_id" name="vendor_id" value="<?php echo $vendor_detail['Vendor_id']?>">
</form>
<button id="img_upload" class="btn btn-default pull-right next-3">Save & Finish</button>
<button id="sbmtbtn" class="btn btn-default pull-left prev-2">Previous Step</button>
</div>
</section>
</div>
</div>
</div></div>
</div>
</div>
<div id="setLoc" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please drag the pointer to your address.</h4>
</div>
<div class="modal-body">
<div id="mapCanvas"></div>
</div>
</div>
</div>
</div>
<script>
$(window).bind("load", function() {
$.each($("input[name='Vendor_type[]']:checked"), function(){
debugger;
$.ajax({ url: "get_vendor_service_by_id", data:"vendor_id=<?php echo $vendor_detail['Vendor_id']?>&vendor_type_id="+$(this).val()+"", success: function(result){
$("#panel-body-vendor-service").append(result);
}});
$.ajax({ url: "get_vendor_faq_by_id", data:"vendor_id=<?php echo $vendor_detail['Vendor_id']?>&vendor_type_id="+$(this).val()+"", success: function(result){
$("#panel-body-service").append(result);
}});
});
});
$('#remove_file').click(function(){
var name = $('#remove_file_name').val();
$.ajax({
type: 'POST',
url: '../Vendor/delete_vendor_picture',
data: "name="+name,
dataType: 'html'
});
$('#blah').attr('src','../images/avatar.png');
$('#remove_file').hide();
});
Dropzone.options.myDropzone = {
autoProcessQueue:false,
paramName: "myFiles",
uploadMultiple: true,
addRemoveLinks: true,
maxFiles: 6,
acceptedFiles: "image/jpeg,image/jpg,image/png,image/gif",
parallelUploads: 6,
removedfile: function(file) {
var name = file.name;
debugger;
$.ajax({
type: 'POST',
url: 'delete_file',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
thisDropzone = this;
$.get('get_vendor_images?vendor_id=<?php echo $vendor_detail['Vendor_id']?>', function(data) {
$.each(data, function(key,value){
debugger;
var filepath = "<?php echo str_replace('\\', '/',FCPATH);?>images/vendortesting/";
var mockFile = { name: value.name, size: value.size,status: Dropzone.ADDED,accepted: true };
thisDropzone.files.push(mockFile); // add to files array
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, '../images/vendortesting/'+value.name);
thisDropzone.emit("complete", mockFile);
});
});
$("#img_upload").click(function() {
debugger;
setTimeout(function(){
if (thisDropzone.getQueuedFiles().length > 0) {
thisDropzone.processQueue();
}
}, 500);
window.location.href = '<?php echo site_url('vendor') ?>';
});
thisDropzone.on("success", function(files,response) {
window.location.href = 'www.google.com';
console.log(response);
});
}
};
</script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
debugger;
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address,responses[4].formatted_address.split(',')[0]);
} else {
updateMarkerAddress('Cannot determine address at this location.','');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('Vendor_address').value = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('Vendor_lat').value = latLng.lat();
document.getElementById('Vendor_long').value = latLng.lng();
}
function updateMarkerAddress(str,city) {
document.getElementById('Vendor_address').value = str;
document.getElementById('city').value = city;
}
function initialize() {
var latLng = new google.maps.LatLng(<?php echo $vendor_detail['Vendor_lat']?>, <?php echo $vendor_detail['Vendor_long']?>
);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 11,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
icon:{path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,scale:7},
title: "<?php echo $vendor_detail['Vendor_name'].' - '.$vendor_detail['Vendor_address'] ;?>",
map: map,
draggable: true
});
// Update current position info.
//debugger;
//google.maps.event.trigger(map,'resize');
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
// /google.maps.event.trigger(map,'resize');
}
// Onload handler to fire off the app.
$('#setLoc').on('shown.bs.modal', function(){
debugger;
initialize();
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('vendor_model');
$this->load->model('user_model');
$this->load->library('session');
}
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$data['get_all_city'] = $this->vendor_model->get_all_city();
$this->load->helper('url');
$this->load->view('welcome_message.php',$data);
}
public function logout()
{
$this->session->unset_userdata('User_id');
$this->session->unset_userdata('IsVendor');
$this->session->unset_userdata('vendor_id');
redirect('Welcome/login');
}
public function login()
{
$this->load->helper('url');
$this->load->view('planningtool/login.php');
}
public function signup()
{
$this->load->helper('url');
$this->load->view('planningtool/signup.php');
}
public function profile()
{
$User_id = $this->session->userdata('User_id');
if(isset($User_id) && count($User_id)>0)
{
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$vendor_id = $this->vendor_model->get_vendor_id_by_user_id($User_id);
$data['user_detail'] = $this->user_model->get_user_by_id($User_id);
$data['vendor_id'] = $vendor_id['Vendor_id'];
if(isset($data['vendor_id']) && count($data['vendor_id'])>0)
{
$data['vendor_detail'] = $this->vendor_model->get_vendor_by_id($data['vendor_id']);
$data['vendor_picture'] = $this->vendor_model->get_vendor_picture_by_id($data['vendor_id']);
$data['vendor_faq'] = $this->vendor_model->vendor_faq($data['vendor_id']);
$this->load->helper('url');
$this->load->view('planningtool/profile.php',$data);
}
else {
redirect('Welcome/dashboard');
}
}
else {
redirect('Welcome/login');
}
}
public function dologin()
{
$User_email = $this->input->post('User_email');
if(isset($User_email) && count($User_email)>0)
{
$data['User_email'] = $User_email;
$data['User_password'] = $this->input->post('<PASSWORD>');
$user = $this->user_model->dologin($data);
if(isset($user) && count($user) > 0)
{
$this->session->set_userdata('User_id',$user['User_id']);
$this->session->set_userdata('IsVendor',$user['IsVendor']);
echo 'true';
}
else {
echo 'false';
}
}
}
public function dashboard()
{
$User_id = $this->session->userdata('User_id');
if(isset($User_id) && count($User_id)>0)
{
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$data['get_all_city'] = $this->vendor_model->get_all_city();
$vendor_id = $this->vendor_model->get_vendor_id_by_user_id($User_id);
if(isset($vendor_id) && count($vendor_id)>0)
{
$this->session->set_userdata('vendor_id',$vendor_id);
}
$data['vendor_id'] = $vendor_id['Vendor_id'];
$this->load->helper('url');
$this->load->view('planningtool/dashboard.php',$data);
}
else {
redirect('Welcome/login');
}
}
public function save()
{
$User_fname = $this->input->post('User_fname');
if(isset($User_fname) && count($User_fname)>0)
{
$data['User_fname'] = $this->input->post('User_fname');
$data['User_lname'] = $this->input->post('User_lname');
$data['User_email'] = $this->input->post('User_email');
$data['User_phone_no'] = $this->input->post('User_phone_no');
$data['User_contact_preference'] = $this->input->post('User_contact_preference');
$data['User_password'] = $this->input->post('User_password');
$data['IsVendor'] = $this->input->post('IsVendor');
If(isset($data['IsVendor']) && count($data['IsVendor'])>0)
{
$data['IsVendor'] = 1;
}
else {
$data['IsVendor'] = 0;
}
$User_id = $this->user_model->add($data);
echo true;
}
}
public function chk_email()
{
$User_email = $this->input->post('User_email');
if(isset($User_email) && count($User_email)>0)
{
$do_exist = $this->user_model->chk_email($User_email);
if($do_exist > 0)
{
echo 'false';
}
else {
echo 'true';
}
}
}
}
<file_sep><header>
<link rel="stylesheet" href="<?php echo base_url('/css/bootstrap.min.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/font-awesome.min.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/animate.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/hamburgers.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/creativelink/demo.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/creativelink/component.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/creativelink/normalize.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/switchable.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/datepicker.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/style.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/owl.carousel.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/owl.theme.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/flipclock.css');?>">
<link rel="stylesheet" href="<?php echo base_url('/css/dropzone.min.css');?>">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css"/>
<link rel="stylesheet" href="<?php echo base_url('/css/bootstrap-select.min.css');?>">
<script src="<?php echo base_url('js/dropzone.min.js');?>"></script>
<script src="<?php echo base_url('js/jquery.min.js');?>"></script>
<script src="<?php echo base_url('js/bootstrap.min.js');?>"></script>
<script src="<?php echo base_url('js/linkhover.js');?>"></script>
<script src="<?php echo base_url('js/owl.carousel.min.js');?>"></script>
<script src="<?php echo base_url('js/waypoint.min.js');?>"></script>
<script src="<?php echo base_url('js/jquery.counterup.min.js');?>"></script>
<script src="<?php echo base_url('js/script.js');?>"></script>
<script src="<?php echo base_url('js/bootstrapvalidator.js');?>"></script>
<script src="<?php echo base_url('js/flipclock.min.js');?>"></script>
<script src="<?php echo base_url('js/flipclock.js');?>"></script>
<script src="<?php echo base_url('js/bootstrap-select.min.js');?>"></script>
<script src="<?php echo base_url('js/switchable.min.js');?>"></script>
<!--start script added faysal mahamud -->
<link href='<?php echo base_url('css/fullcalendar.min.css');?>' rel='stylesheet' />
<link href='<?php echo base_url('css/fullcalendar.print.min.css');?>' rel='stylesheet' media='print' />
<script src="<?php echo base_url('js/moment.min.js');?>"></script>
<script src="<?php echo base_url('js/fullcalendar.min.js');?>"></script>
<script src="<?php echo base_url('js/gcal.min.js');?>"></script>
<!-- end script added faysal mahamud -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.20&sensor=true&key=<KEY>"></script>
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<style>
#calendar {
max-width: 900px;
margin: 0 auto;
}
</style>
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
selectable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
select: function (startDate, endDate) {
modalbox('create', startDate.format(), endDate.format());
},
eventClick: function (event) {
console.log(event);
modalbox('updated', event);
// if (event.url) {
//
// // opens events in a popup window
// //window.open(event.url, 'gcalevent', 'width=700,height=600');
// return false;
// }
},
eventSources: [{
events: function (start, end, timezone, callback) {
$.ajax({
url: '<?php echo base_url() ?>events/get_events',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function (msg) {
var events = msg.events;
callback(events);
}
});
}
}, ]
});
function modalbox(type = "", start = '', endDate = '') {
if (type == 'create') {
var pop_content = '<form id="popup">' +
'<div class="form-group">' +
'<label for="recipient-name" class="col-form-label">Title:</label>' +
'<input type="text" name="title" class="form-control" id="recipient-name">' +
'</div>' +
'<div class="form-group">' +
'<label for="recipient-name" class="col-form-label">Event Type:</label>' +
'<input type="text" name="event_type" class="form-control" id="recipient-name" value="">' +
'</div>' +
'<div class="form-group">' +
'<label for="recipient-name" class="col-form-label">Guest Name:</label>' +
'<input type="text" name="guest_name" class="form-control" id="recipient-name" value="">' +
'</div>' +
'<div class="form-group">' +
'<label for="message-text" class="col-form-label">Description:</label>' +
'<textarea name="content_event" class="form-control" id="message-text"></textarea>' +
'</div>' +
'<input type="hidden" id="start" name="start" value="' + start + '"><input type="hidden" id="end" name="end" value="' + endDate + '"><input type="hidden" id="save_method" name="method" value="add">' +
'</form>';
} else {
var start_date = start.start.format();
if (start.end != '') {
var end_date = start.end.format();
} else {
end_date = '';
}
var title = start.title;
var description = start.description;
$('#exampleModalLabel').html('Update Events');
var pop_content = '<form id="popup">' +
'<div class="form-group">' +
'<label for="recipient-name" class="col-form-label">Place:</label>' +
'<input type="text" name="title" class="form-control" id="recipient-name" value="' + title + '">' +
'</div>' +
'<div class="form-group">' +
'<label for="message-text" class="col-form-label">Description:</label>' +
'<textarea name="content_event" class="form-control" id="message-text">' + description + '</textarea>' +
'</div>' +
'<input type="hidden" id="id" name="id" value="' + start.id + '">'+
'<input type="hidden" id="start" name="start" value="' + start_date + '">'+
'<input type="hidden" id="end" name="end" value="' + end_date + '">' +
'<input type="hidden" id="save_method" name="method" value="update">' +
'</form>';
}
$('#exampleModal .modal-body').html(pop_content);
$('#exampleModal').modal('show');
}
$('.popsubmit').on('click', function (event) {
debugger;
event.preventDefault(); // on stop le submit
var title = $('#recipient-name').val();
var start = $('#start').val();
var end = $('#end').val();
var where_event = $('#where_event').val();
var content_event = $('#message-text').val();
var save_method = $('#save_method').val();
if (title) {
$('#calendar').fullCalendar('renderEvent', {
title: title,
start: start,
end: end
},
true // make the event "stick"
);
// Now we push it to Google also :
//add_event_gcal(title,start,end,where_event,content_event);
}
// Wether we had the form fulfilled or not, we clean FullCalendar and close the popup
$('#calendar').fullCalendar('unselect');
var url;
if (save_method == 'add') {
url = "<?php echo site_url('events/add_event')?>";
} else {
url = "<?php echo site_url('events/update_event')?>";
}
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#popup').serialize(),
dataType: "JSON",
success: function (data) {
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload(); // for reload a page
},
error: function (jqXHR, textStatus, errorThrown) {
location.reload();
}
});
});
});
</script>
<!--Navbar Starts
==================-->
<nav class="navbar navbar-default">
<div class="logo12">
<a href="<?php echo base_url()?>" class="pull-left" style="margin-left: 25px;margin-top: 5px;margin-bottom: 5px"><img style="height:60px;" src="<?php echo base_url('/images/logo.png');?>" alt="logo">
</a>
</div>
<div class="container"><?php $User_id = $this->session->userdata('User_id'); ?>
<div class="col-sm-8 col-md-8">
<form class="navbar-form" action="<?php echo base_url('Vendor/search');?>" role="search">
<div class="input-group" style=" margin-top: 10px;">
<div class="col-sm-6 col-md-6">
<select class="form-control" required="required" id="vendor_type" name="vendor_type" style="width: 240px;">
<option value="">Select Vendor Type</option>
</select>
</div>
<div class="col-sm-6 col-md-6">
<select class="form-control" required="required" id="vendor_city" name="city" style="width: 180px;">
<option value="">Select City</option>
</select>
<div class="input-group-btn">
<button class="btn btn-warning" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</div>
</form>
</div>
<ul class="nav navbar-nav navbar-right header-menu hidden-xs" style="height: 70px;">
<li><a style="padding: 10px 0px 0px 0px;" href="<?php echo base_url()?>"><b><span style="color:white;font-size: 12px;">Home</span></b></a></li>
<li><a style="padding: 10px 0px 0px 0px;" href="#"><b><span style="color:white;font-size: 12px;">Suppliers</span></b></a></li>
<li><a style="padding: 10px 0px 0px 0px;" href="<?php echo base_url()?>WeddingCost"><b><span style="color:white;font-size: 12px;">Cost</span></b></a></li>
<!--<li><a href="#"><b><span style="color:white">News</span></b></a></li>-->
<li><?php if(isset($User_id) && count($User_id)>0)
{?>
<a style="padding: 10px 0px 0px 0px;" href="<?php echo base_url()?>Welcome/logout"><b><span style="color:white;font-size: 12px;">LogOut</span></b></a>
<?php
}
else
{?>
<a style="padding: 10px 0px 0px 0px;" href="<?php echo base_url()?>Welcome/login"><b><span style="color:white;font-size: 12px;">Login</span></b></a>
<?php }?>
</li>
</ul>
</div>
</nav>
<?php if(isset($User_id) && count($User_id)>0)
{?>
<div>
<nav class="bellow-navbar navbar-default">
<div class="container">
<ul class="nav navbar-nav">
<li ><a class="subheader" href="#"><i class="fa fa-align-justify"></i><b><span style="font-size: 12px;">Dashboard</span></b></a></li>
<li ><a class="subheader" href="<?php echo base_url()?>Events"><i class="glyphicon glyphicon-floppy-saved"></i><b><span style="font-size: 12px;" >Events</span></b></a></li>
<li ><a class="subheader" href="<?php echo base_url()?>Vendor/package"><i class=" glyphicon glyphicon-edit"></i><b><span style="font-size: 12px;">Packages</span></b></a></li>
<li ><a class="subheader" href="#"><i class=" glyphicon glyphicon-edit"></i><b><span style="font-size: 12px;">Quote Request</span></b></a></li>
<li ><a class="subheader" href="<?php echo base_url()?>Welcome/profile"><i class="fa fa-user"></i><b><span style="font-size: 12px;">Profile</span></b></a></li>
</ul>
</div>
</nav>
</div>
<?php }?>
</header>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="container">
<div class="row">
<div class="col-md-6 weddingcost1">
<h1><span>The Average Cost Of A Wedding</span></h1>
<p>
In each of the past few years, Pakistani's have spent an average of almost Rs1,500,000 on weddings. To help you get an idea of what other real life couples in your area have spent over the last year, we at Planiology have gathered data from around the country to help you budget for your own wedding.
</p>
<p>To see what other couples in your area have actually spent on their weddings, enter your city and state into the field below.
</p>
<div class="form-group">
<div class="col-sm-5">
<input type="text" class="form-control" placeholder="City" name="city">
</div>
<div class="col-sm-5 ">
<button class="weddingcostbutton btn">See Wedding Cost</button>
</div>
</div>
<div class="info-sec-inner">
<h3><b>HOW TO KEEP YOUR BUDGET UNDER CONTROL</b></h3>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Vendor extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('vendor_model');
$this->load->model('user_model');
}
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->helper('url');
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$data['listing'] = $this->vendor_model->get_all_vendors();
$this->load->view('vendor/index.php',$data);
}
public function detail()
{
$vendor_id = $this->uri->segment(3);
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$get_vendor_by_id = $this->vendor_model->get_vendor_by_id($vendor_id);
if(isset($get_vendor_by_id['Services']) && count($get_vendor_by_id['Services'])>0)
{
$data['get_services'] = $this->vendor_model->get_vendor_services($get_vendor_by_id['Services']);
}
$data['get_vendor_by_id'] = $get_vendor_by_id;
$vendor_type = $data['get_vendor_by_id']['Vendor_type'];
$data['get_all_vendor_faq'] = $this->vendor_model->vendor_faq($vendor_id);
$data['get_all_vendor_pictures'] = $this->vendor_model->get_vendor_images($vendor_id);
$data['get_all_package'] = $this->vendor_model->get_all_package($vendor_id);
//$vendor_type =
$this->load->helper('url');
$this->load->view('vendor/detail.php',$data);
}
public function search()
{
$vendor_type = $this->input->post('vendor_type');
$vendor_city = $this->input->post('city');
if(isset($vendor_type) && count($vendor_type)>0 && isset($vendor_city) && count($vendor_city) > 0)
{
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$data['listing'] = $this->vendor_model->get_all_vendor_by_type_city($vendor_type,$vendor_city);
$data['vendor_type'] = $vendor_type;
$data['city'] = $vendor_city;
$this->load->view('vendor/index.php',$data);
//var_dump($listing);
//exit();
}
else {
$vendor_type = $this->input->get('vendor_type');
if(isset($vendor_type) && count($vendor_type)>0)
{
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$data['listing'] = $this->vendor_model->get_all_vendor_by_type($vendor_type);
$data['vendor_type'] = $vendor_type;
$this->load->view('vendor/index.php',$data);
//var_dump($listing);
//exit();
}
else {
redirect('welcome');
}
}
}
public function get_service_by_vendor_type()
{
$vendor_type_id = $this->input->get('vendor_type_id');
$vendor_service_list = $this->vendor_model->get_service_by_vendor_type($vendor_type_id);
echo $vendor_service_list;
}
public function get_faq_by_vendor_type()
{
$vendor_type_id = $this->input->get('vendor_type_id');
$vendor_faq_list = $this->vendor_model->get_faq_by_vendor_type($vendor_type_id);
echo $vendor_faq_list;
}
public function get_vendor_faq_by_id()
{
$vendor_id = $this->input->get('vendor_id');
$vendor_type_id = $this->input->get('vendor_type_id');
$vendor_faq_list = $this->vendor_model->get_vendor_faq_by_id($vendor_id,$vendor_type_id);
echo $vendor_faq_list;
}
public function get_vendor_service_by_id()
{
$vendor_id = $this->input->get('vendor_id');
$vendor_type_id = $this->input->get('vendor_type_id');
$vendor_service_list = $this->vendor_model->get_vendor_service_by_id($vendor_id,$vendor_type_id);
echo $vendor_service_list;
}
public function get_vendor_images()
{
$vendor_id = $this->input->get('vendor_id');
$vendor_images = $this->vendor_model->get_vendor_images($vendor_id);
$filepath = ''.str_replace('\\', '/',FCPATH).'images/vendortesting/';
foreach($vendor_images as $file){ //get an array which has the names of all the files and loop through it
$obj['name'] = $file['Vendor_picture_path']; //get the filename in array
$obj['size'] = filesize(''.$filepath.$file['Vendor_picture_path'].''); //get the flesize in array
$result[] = $obj; // copy it to another array
}
header('Content-Type: application/json');
echo json_encode($result);
}
public function get_package_images()
{
$package_id = $this->input->get('package_id');
$vendor_images = $this->vendor_model->get_package_images($package_id);
$filepath = ''.str_replace('\\', '/',FCPATH).'images/packagetesting/';
foreach($vendor_images as $file){ //get an array which has the names of all the files and loop through it
$obj['name'] = $file['package_picture_path']; //get the filename in array
$obj['size'] = filesize(''.$filepath.$file['package_picture_path'].''); //get the flesize in array
$result[] = $obj; // copy it to another array
}
header('Content-Type: application/json');
echo json_encode($result);
}
public function get_vendor_faq()
{
$vendor_type = $this->input->post('vendor_type_id');
echo json_encode($this->vendor_model->get_vendor_faq($vendor_type));
}
public function edit()
{
$User_id = $this->session->userdata('User_id');
if(isset($User_id) && count($User_id)>0)
{
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$vendor_id = $this->vendor_model->get_vendor_id_by_user_id($User_id);
$data['user_detail'] = $this->user_model->get_user_by_id($User_id);
$data['get_all_city'] = $this->vendor_model->get_all_city();
$data['vendor_id'] = $vendor_id['Vendor_id'];
$data['vendor_detail'] = $this->vendor_model->get_vendor_by_id($data['vendor_id']);
$data['vendor_picture'] = $this->vendor_model->get_vendor_picture_by_id($data['vendor_id']);
$data['vendor_faq'] = $this->vendor_model->vendor_faq($data['vendor_id']);
$this->load->helper('url');
$this->load->view('vendor/edit.php',$data);
}
else {
redirect('Welcome/login');
}
}
public function save()
{
$Vendor_name = $this->input->post('Vendor_name');
if(isset($Vendor_name) && count($Vendor_name) > 0 )
{
$data['Vendor_name'] = $Vendor_name;
$data['Vendor_type'] = $this->input->post('Vendor_type');
$data['Vendor_description'] = $this->input->post('Vendor_description');
$data['Vendor_starting_price'] = $this->input->post('Vendor_starting_price');
$data['Vendor_address'] = $this->input->post('Vendor_address');
$data['User_id'] = $this->input->post('User_id');
$data['city'] = $this->input->post('city');
$data['Vendor_lat'] = $this->input->post('Vendor_lat');
$data['Vendor_long'] = $this->input->post('Vendor_long');
$data['vendor_id'] = $this->input->post('vendor_id');
$min_max_service_id = $this->vendor_model->get_min_max_service_id();
$prefix = $serlist = '';
for($x = $min_max_service_id['min_serive_id'];$x<=$min_max_service_id['max_serive_id'];$x++)
{
$result = $this->input->post('Service_'.$x.'');
if(isset($result) && $result == "on")
{
$serlist .= $prefix . '' . $x . '';
$prefix = ', ';
}
}
$data['serlist'] = rtrim($serlist,', ');
if(isset($data['vendor_id']) && $data['vendor_id'] > 0)
{
$vendor_id = $data['vendor_id'];
$this->vendor_model->edit($data);
}
else {
$vendor_id = $this->vendor_model->add($data);
}
$min_max_faq_id = $this->vendor_model->get_min_max_faq_id();
for($x = $min_max_faq_id['min_serive_id'];$x<=$min_max_faq_id['max_serive_id'];$x++)
{
$result = $this->input->post('faq_id_'.$x.'');
if(isset($result) && count($result)>0)
{
$faq_id = $x;
if(isset($data['vendor_id']) && $data['vendor_id'] > 0)
{
$vendor_faq_id = $this->vendor_model->edit_vendor_faq($vendor_id,$faq_id,$result);
}
else {
$vendor_faq_id = $this->vendor_model->add_vendor_faq($vendor_id,$faq_id,$result);
}
}
}
$config['upload_path'] = FCPATH.'images\vendortesting';
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['max_size'] = 400000000000;
$config['max_width'] = 3260;
$config['max_height'] = 1600;
$this->load->library('upload', $config);
$config['file_name'] = 'vendor_'.$vendor_id.'' ;
$this->upload->initialize($config);
//$this->upload->do_upload('vendor_img');
//$data = $this->upload->data();
if ( ! $this->upload->do_upload('Vendor_picture')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
exit();
}
else {
$data = $this->upload->data();
//$path = $data['full_path'].'/'.$config['file_name'];
$profile_pic = 1;
$this->vendor_model->add_image_path($vendor_id,$data['file_name'],$profile_pic);
}
echo $vendor_id;
}
else {
redirect('vendor');
}
}
public function file_upload()
{
$vendor_id = $this->input->POST('vendor_id');
if(isset($vendor_id) && $vendor_id > 0)
{
$filesCount = count($_FILES['myFiles']['name']);
$config['upload_path'] = FCPATH.'images\vendortesting';
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['max_size'] = 400000000000;
$config['max_width'] = 3260;
$config['max_height'] = 1600;
$this->load->library('upload', $config);
$files = $_FILES;
for ($i = 0; $i < $filesCount; $i++) {
$_FILES['myFiles']['name']= $files['myFiles']['name'][$i];
$_FILES['myFiles']['type']= $files['myFiles']['type'][$i];
$_FILES['myFiles']['tmp_name']= $files['myFiles']['tmp_name'][$i];
$_FILES['myFiles']['error']= $files['myFiles']['error'][$i];
$_FILES['myFiles']['size']= $files['myFiles']['size'][$i];
$config['file_name'] = 'vendor_'.$vendor_id.'_'.$i.'' ;
$this->upload->initialize($config);
//$this->upload->do_upload('vendor_img');
//$data = $this->upload->data();
if ( ! $this->upload->do_upload('myFiles')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
exit();
}
else {
$data = $this->upload->data();
//$path = $data['full_path'].'/'.$config['file_name'];
if($i == 0)
{
$profile_pic = 1;
}
else {
$profile_pic = 0;
}
$this->vendor_model->add_image_path($vendor_id,$data['file_name'],$profile_pic);
}
}
}
}
public function package()
{
$User_id = $this->session->userdata('User_id');
if(isset($User_id) && count($User_id)>0)
{
$this->load->helper('url');
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$user_id = $this->session->userdata('User_id');
$vendor_id = $this->vendor_model->get_vendor_id_by_user_id($user_id);
if(isset($vendor_id) && count($vendor_id)>0)
{
$data['get_all_package'] = $this->vendor_model->get_all_package($vendor_id['Vendor_id']);
$this->load->view('vendor/package.php',$data);
}
else {
redirect('Welcome/dashboard');
}
}
else {
redirect('Welcome/login');
}
}
public function addpackage()
{
$User_id = $this->session->userdata('User_id');
if(isset($User_id) && count($User_id)>0)
{
$this->load->helper('url');
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
$user_id = $this->session->userdata('User_id');
$data['vendor_data'] = $this->vendor_model->get_vendor_id_by_user_id($user_id);
$this->load->view('vendor/addpackage.php',$data);
}
else {
redirect('Welcome/login');
}
}
public function editpackage()
{
$User_id = $this->session->userdata('User_id');
if(isset($User_id) && count($User_id)>0)
{
$this->load->helper('url');
$package_id = $this->uri->segment(3);
$data['get_all_vendor_type'] = $this->vendor_model->get_all_vendor_type();
//$user_id = $this->session->userdata('User_id');
$data['Vendor_id'] = $this->vendor_model->get_vendor_id_by_user_id($User_id);
$data['User_id'] = $User_id;
$data['get_package_by_id'] = $this->vendor_model->get_package_by_id($package_id);
$this->load->view('vendor/editpackage.php',$data);
}
else {
redirect('Welcome/login');
}
}
public function delete_package_picture()
{
$pic_name = $this->input->POST('name');
$file_path= FCPATH.'images\packagetesting\\'.$pic_name;
if(is_file($file_path))
{
unlink($file_path);
$this->vendor_model->delete_package_picture($pic_name);
}
}
public function delete_vendor_picture()
{
$pic_name = $this->input->POST('name');
$file_path= FCPATH.'images\vendortesting\\'.$pic_name;
if(is_file($file_path))
{
unlink($file_path);
$this->vendor_model->delete_vendor_picture($pic_name);
}
}
public function packagesave()
{
$vendor_id = $this->input->POST('vendor_id');
$user_id = $this->input->POST('User_id');
if(isset($vendor_id) && $vendor_id > 0 && isset($user_id) && $user_id > 0)
{
$data['Package_title'] = $this->input->POST('Package_title');
$data['Package_category'] = $this->input->POST('Package_category');
$data['Package_description'] = $this->input->POST('Package_description');
$data['Package_price'] = $this->input->POST('Package_price');
$data['vendor_id'] = $this->input->POST('vendor_id');
$Package_id = $this->input->POST('Package_id');
if(isset($Package_id) && $Package_id > 0)
{
$data['Package_id'] = $this->input->POST('Package_id');
$this->vendor_model->packageedit($data);
}
else {
$Package_id = $this->vendor_model->packageadd($data);
}
if(isset($Package_id) && count($Package_id)>0)
{
$filesCount = count($_FILES['myFiles']['name']);
$config['upload_path'] = FCPATH.'images\packagetesting';
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['max_size'] = 400000000000;
$config['max_width'] = 3260;
$config['max_height'] = 1600;
$this->load->library('upload', $config);
$files = $_FILES;
for ($i = 0; $i < $filesCount; $i++) {
$_FILES['myFiles']['name']= $files['myFiles']['name'][$i];
$_FILES['myFiles']['type']= $files['myFiles']['type'][$i];
$_FILES['myFiles']['tmp_name']= $files['myFiles']['tmp_name'][$i];
$_FILES['myFiles']['error']= $files['myFiles']['error'][$i];
$_FILES['myFiles']['size']= $files['myFiles']['size'][$i];
$config['file_name'] = 'package_'.$Package_id.'_'.$i.'' ;
$this->upload->initialize($config);
//$this->upload->do_upload('vendor_img');
//$data = $this->upload->data();
if ( ! $this->upload->do_upload('myFiles')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
exit();
}
else {
$data = $this->upload->data();
$this->vendor_model->add_package_image_path($Package_id,$data['file_name']);
}
}
}
}
}
public function packagedetail()
{
$package_id = $this->input->get('id');
$data['get_package_by_id'] = $this->vendor_model->get_package_by_id($package_id);
$data['get_package_images'] = $this->vendor_model->get_package_images($package_id);
$data['get_vendor_by_id'] = $this->vendor_model->get_vendor_by_id($data['get_package_by_id']['Vendor_id']);
$this->load->view('vendor/pdetail.php',$data);
}
public function get_all_vendor_type()
{
echo json_encode($this->vendor_model->get_all_vendor_type());
}
public function get_all_city()
{
echo json_encode($this->vendor_model->get_all_city());
}
}
<file_sep><?php
class user_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function dologin($data)
{
$sql = 'select * from users where User_email = "'.$data['User_email'].'" and User_password = "'.md5($data['User_password']).'"';
$query = $this->db->query($sql);
$result_array = $query->row_array();
return $result_array;
}
public function get_user_by_id($User_id)
{
$sql = 'select * from users where User_id = "'.$User_id.'"';
$query = $this->db->query($sql);
$result_array = $query->row_array();
return $result_array;
}
public function add($data)
{
$date = date('Y-m-d H:i:s');
$sql = 'insert into users(User_fname,User_lname,User_email,User_phone_no,User_password,User_contact_preference,CreatedOn,IsVendor) VALUES("'.$data['User_fname'].'","'.$data['User_lname'].'","'.$data['User_email'].'","'.$data['User_phone_no'].'","'.md5($data['User_password']).'","'.$data['User_contact_preference'].'","'.$date.'","'.$data['IsVendor'].'")';
$this->db->query($sql);
return TRUE;
}
public function chk_email($User_email)
{
$sql = 'select count(*) as count from users where User_email = "'.$User_email.'"';
$query = $this->db->query($sql);
$result_array = $query->row_array();
if($result_array['count'] > 0)
{
return 1;
}
else {
return 0;
}
}
}
?>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="container" style="margin-top: 50px;margin-bottom: 30px;background-image: url('../../images/vendortesting/<?php echo $get_vendor_by_id['Vendor_picture_path']; ?>');height: 250px !important;background-repeat: round;background-size: cover;background-attachment: fixed;">
<h2 style="/* padding-left:15px; */font-size: 45px;font-weight: bold;text-align: center;color: white;padding-top: 100px;padding-bottom: 65px;background-color: rgba(0,0,0,0.3);"><?php echo $get_vendor_by_id['Vendor_name']; ?></h2>
<div>
</div>
</div>
</section>
<div class="vendor">
<div class="container">
<h1><span style="color: #FCB41E;font-size: 40px;font-weight: bold;"><?php echo $get_package_by_id['Package_title'];?></span></h1>
<div class="col-md-7" style="padding-bottom: 200px;">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<?php $count = 0;
foreach ($get_package_images as $key) {
?>
<li data-target="#myCarousel" data-slide-to="<?php echo $count; ?>" class="<?php if($count == 0){?> active <?}?>"><img src="<?php echo base_url(); ?>images/packagetesting/<? echo $key['package_picture_path'] ?>" alt="..."></li>
<?
$count++;
}?>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<?php $count = 0;
foreach ($get_package_images as $key) {
?>
<div class="item <?php if($count == 0){?> active <?}?>">
<img src="<?php echo base_url(); ?>images/packagetesting/<? echo $key['package_picture_path'] ?>" >
</div>
<?
$count++;
}?>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="col-md-4">
<span class="starring_price">Starting At RS: <?php echo $get_package_by_id['Package_price'] ?></span>
<hr>
<span class="starring_price">Category: <?php echo $get_package_by_id['type'] ?></span>
<hr>
<span><?php echo $get_package_by_id['Package_description'] ?>
</span>
</div>
</div>
</div>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quotation</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<!-- form part
=================-->
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-header">
<div class="col-md-4 col-sm-12 active" id="step1">
<h4>STEP ONE</h4>
</div>
<div class="col-md-4 col-sm-12" id="step2">
<h4>STEP TWO</h4>
</div>
<div class="col-md-4 col-sm-12" id="step3">
<h4>STEP THREE</h4>
</div>
</div>
<div class="form-body">
<!--STEP ONE
==============-->
<section>
<div class="step-one">
<form action="#">
<h2>Tell Us About Your Event</h2>
<div class="form-group">
<label for="eventtype" class="col-sm-5 control-label">Event Type</label>
<div class="col-sm-7">
<select name="eventtype" class="form-control">
<option value="">Select Event</option>
<option value="">Wedding</option>
<option value="">Corporate Function</option>
<option value="">Birthday</option>
<option value="">Anniversary</option>
<option value="">Holiday Party</option>
</select>
</div>
</div>
<div class="form-group">
<label for="zip" class="col-sm-5 control-label">Event Zone</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="5 Digit ZIP" name="zip">
</div>
</div>
<div class="form-group">
<label for="guestexpect" class="col-sm-5 control-label">Guest Expected</label>
<div class="col-sm-7">
<select name="guesexpected" class="form-control">
<option value="">How Many</option>
<option value="">Less Than 10</option>
<option value="">10 - 50</option>
<option value="">50 - 100</option>
<option value="">100 - 200</option>
<option value="">200 - 300</option>
<option value="">300 - 400</option>
<option value="">400 - 500</option>
<option value="">500 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="eventdate" class="col-sm-5 control-label">Event Date</label>
<div class="col-sm-7">
<input type="text" class="form-control datepicker" name="eventdate" placeholder="MM-DD-YYYY">
</div>
</div>
<h2 style="margin-top: 80px;">Do You Also Need Quotes <br> For Other Services?</h2>
<div class="col-md-6 col-sm-12">
<input type="checkbox" class="switch" data-label="Bakeries" >
<input type="checkbox" class="switch" data-label="Beauty Salons And Spas" >
<input type="checkbox" class="switch" data-label="Bridal Salons" >
<input type="checkbox" class="switch" data-label="Catering" >
<input type="checkbox" class="switch" data-label="Decorations" >
<input type="checkbox" class="switch" data-label="DJ" >
<input type="checkbox" class="switch" data-label="Favors" >
<input type="checkbox" class="switch" data-label="Florists" >
<input type="checkbox" class="switch" data-label="Invitations" >
</div>
<div class="col-md-6 col-sm-12">
<input type="checkbox" class="switch" data-label="Limousine" >
<input type="checkbox" class="switch" data-label="Musician" >
<input type="checkbox" class="switch" data-label="Novelty Entertainment" >
<input type="checkbox" class="switch" data-label="Officiants" >
<input type="checkbox" class="switch" data-label="Party Rentals" >
<input type="checkbox" class="switch" data-label="Tuxedos" >
<input type="checkbox" class="switch" data-label="Photographers" >
<input type="checkbox" class="switch" data-label="Videographers" >
<input type="checkbox" class="switch" data-label="Wedding Event Planners" >
</div>
</form>
<button class="btn btn-default pull-right next-2">Next Step</button>
</div>
</section>
<!--STEP TWO
===============-->
<section>
<div class="step-two" style="display:none">
<h2>Tell Us About Your Needs</h2>
<form action="#">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Banquet Facilites
</a>
<i class="fa fa-times-circle-o closebutton pull-right" aria-hidden="true" style="pointer: cursor"></i>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<div class="form-group">
<label for="banquet-budget" class="col-sm-5 control-label">Budget</label>
<div class="col-sm-7">
<select name="banquet-budget" class="form-control">
<option value="">Select Budget</option>
<option value="">Less Than $500</option>
<option value="">$500 - $1000</option>
<option value="">$1000 - $2000</option>
<option value="">$2000 - $3000</option>
<option value="">$3000 - $4000</option>
<option value="">$4000 - $5000</option>
<option value="">$5000 - $6000</option>
<option value="">$6000 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="banquet-time" class="col-sm-5 control-label">Time Needed</label>
<div class="col-sm-7">
<select name="banquet-time" class="form-control">
<option value="">--Start Time--</option>
<option value="">7:00 AM</option>
<option value="">8:00 AM</option>
<option value="">10:00 AM</option>
<option value="">11:00 AM</option>
<option value="">1:00 PM</option>
<option value="">2:00 PM</option>
<option value="">4:00 PM</option>
<option value="">5:00 PM</option>
<option value="">7:00 PM</option>
</select>
<select name="banquet-duration" class="form-control">
<option value="">--How Long--</option>
<option value="">1 Hour</option>
<option value="">2 Hours</option>
<option value="">3 Hours</option>
<option value="">4 Hours</option>
<option value="">5 Hours</option>
<option value="">6 Hours</option>
<option value="">6 Hours or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-5 control-label">Type of Venue</label>
<div class="col-sm-7">
<input type="checkbox" class="switch" data-label="Banquet Hall" >
<input type="checkbox" class="switch" data-label="Hotel or Resort" >
<input type="checkbox" class="switch" data-label="Country Club" >
<input type="checkbox" class="switch" data-label="Restaurant" >
<input type="checkbox" class="switch" data-label="Mansion" >
<input type="checkbox" class="switch" data-label="Yacht" >
<input type="checkbox" class="switch" data-label="Limousine" >
</div>
</div>
<div class="form-group">
<label for="banquet-guest" class="col-sm-5 control-label">Number of Guests</label>
<div class="col-sm-7">
<select name="banquet-guest" class="form-control">
<option value="">How Many</option>
<option value="">Less Than 10</option>
<option value="">10 - 50</option>
<option value="">50 - 100</option>
<option value="">100 - 200</option>
<option value="">200 - 300</option>
<option value="">300 - 400</option>
<option value="">400 - 500</option>
<option value="">500 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="banquet-comment" class="col-sm-5 control-label">Comments</label>
<div class="col-sm-7">
<textarea name="banquet-comment" cols="20" rows="5" placeholder="Any Special Requests or Needs..."></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
Catering
</a>
<i class="fa fa-times-circle-o closebutton pull-right" aria-hidden="true" style="pointer: cursor"></i>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
<div class="panel-body">
<div class="form-group">
<label for="banquet-budget" class="col-sm-5 control-label">Budget</label>
<div class="col-sm-7">
<select name="banquet-budget" class="form-control">
<option value="">Select Budget</option>
<option value="">Less Than $500</option>
<option value="">$500 - $1000</option>
<option value="">$1000 - $2000</option>
<option value="">$2000 - $3000</option>
<option value="">$3000 - $4000</option>
<option value="">$4000 - $5000</option>
<option value="">$5000 - $6000</option>
<option value="">$6000 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="banquet-time" class="col-sm-5 control-label">Time Needed</label>
<div class="col-sm-7">
<select name="banquet-time" class="form-control">
<option value="">--Start Time--</option>
<option value="">7:00 AM</option>
<option value="">8:00 AM</option>
<option value="">10:00 AM</option>
<option value="">11:00 AM</option>
<option value="">1:00 PM</option>
<option value="">2:00 PM</option>
<option value="">4:00 PM</option>
<option value="">5:00 PM</option>
<option value="">7:00 PM</option>
</select>
<select name="banquet-duration" class="form-control">
<option value="">--How Long--</option>
<option value="">1 Hour</option>
<option value="">2 Hours</option>
<option value="">3 Hours</option>
<option value="">4 Hours</option>
<option value="">5 Hours</option>
<option value="">6 Hours</option>
<option value="">6 Hours or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-5 control-label">Type of Venue</label>
<div class="col-sm-7">
<input type="checkbox" class="switch" data-label="Banquet Hall" >
<input type="checkbox" class="switch" data-label="Hotel or Resort" >
<input type="checkbox" class="switch" data-label="Country Club" >
<input type="checkbox" class="switch" data-label="Restaurant" >
<input type="checkbox" class="switch" data-label="Mansion" >
<input type="checkbox" class="switch" data-label="Yacht" >
<input type="checkbox" class="switch" data-label="Limousine" >
</div>
</div>
<div class="form-group">
<label for="banquet-guest" class="col-sm-5 control-label">Number of Guests</label>
<div class="col-sm-7">
<select name="banquet-guest" class="form-control">
<option value="">How Many</option>
<option value="">Less Than 10</option>
<option value="">10 - 50</option>
<option value="">50 - 100</option>
<option value="">100 - 200</option>
<option value="">200 - 300</option>
<option value="">300 - 400</option>
<option value="">400 - 500</option>
<option value="">500 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="banquet-guest" class="col-sm-5 control-label">Number of Guests</label>
<div class="col-sm-7 radiocheck">
<div class="radio">
<label>
Yes
</label>
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
</div>
<div class="radio">
<label>
No
</label>
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
</div>
</div>
</div>
<div class="form-group">
<label for="banquet-comment" class="col-sm-5 control-label">Comments</label>
<div class="col-sm-7">
<textarea name="banquet-comment" cols="20" rows="5" placeholder="Any Special Requests or Needs..."></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
Bakeries
</a>
<i class="fa fa-times-circle-o closebutton pull-right" aria-hidden="true" style="pointer: cursor"></i>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">
<div class="form-group">
<label for="banquet-budget" class="col-sm-5 control-label">Budget</label>
<div class="col-sm-7">
<select name="banquet-budget" class="form-control">
<option value="">Select Budget</option>
<option value="">Less Than $500</option>
<option value="">$500 - $1000</option>
<option value="">$1000 - $2000</option>
<option value="">$2000 - $3000</option>
<option value="">$3000 - $4000</option>
<option value="">$4000 - $5000</option>
<option value="">$5000 - $6000</option>
<option value="">$6000 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="banquet-time" class="col-sm-5 control-label">Time Needed</label>
<div class="col-sm-7">
<select name="banquet-time" class="form-control">
<option value="">--Start Time--</option>
<option value="">7:00 AM</option>
<option value="">8:00 AM</option>
<option value="">10:00 AM</option>
<option value="">11:00 AM</option>
<option value="">1:00 PM</option>
<option value="">2:00 PM</option>
<option value="">4:00 PM</option>
<option value="">5:00 PM</option>
<option value="">7:00 PM</option>
</select>
<select name="banquet-duration" class="form-control">
<option value="">--How Long--</option>
<option value="">1 Hour</option>
<option value="">2 Hours</option>
<option value="">3 Hours</option>
<option value="">4 Hours</option>
<option value="">5 Hours</option>
<option value="">6 Hours</option>
<option value="">6 Hours or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-5 control-label">Type of Venue</label>
<div class="col-sm-7">
<input type="checkbox" class="switch" data-label="Banquet Hall" >
<input type="checkbox" class="switch" data-label="Hotel or Resort" >
<input type="checkbox" class="switch" data-label="Country Club" >
<input type="checkbox" class="switch" data-label="Restaurant" >
<input type="checkbox" class="switch" data-label="Mansion" >
<input type="checkbox" class="switch" data-label="Yacht" >
<input type="checkbox" class="switch" data-label="Limousine" >
</div>
</div>
<div class="form-group">
<label for="banquet-guest" class="col-sm-5 control-label">Number of Guests</label>
<div class="col-sm-7">
<select name="banquet-guest" class="form-control">
<option value="">How Many</option>
<option value="">Less Than 10</option>
<option value="">10 - 50</option>
<option value="">50 - 100</option>
<option value="">100 - 200</option>
<option value="">200 - 300</option>
<option value="">300 - 400</option>
<option value="">400 - 500</option>
<option value="">500 or More</option>
</select>
</div>
</div>
<div class="form-group">
<label for="banquet-guest" class="col-sm-5 control-label">Number of Guests</label>
<div class="col-sm-7 radiocheck">
<div class="radio">
<label>
Yes
</label>
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
</div>
<div class="radio">
<label>
No
</label>
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
</div>
</div>
</div>
<div class="form-group">
<label for="banquet-comment" class="col-sm-5 control-label">Comments</label>
<div class="col-sm-7">
<textarea name="banquet-comment" cols="20" rows="5" placeholder="Any Special Requests or Needs..."></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<button class="btn btn-default pull-right next-3">Next Step</button>
<button class="btn btn-default pull-left prev-1" style="width: 140px; margin-left: 3%">Previous Step</button>
</div>
</section>
<!--STEP THREE
=======================-->
<section>
<div class="step-three" style="display:none">
<h2>Tell Us About Your Needs</h2>
<form action="">
<div class="col-md-6 col-sm-12">
<div class="form-group">
<label for="name1" class="col-sm-5 control-label">First Name</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="<NAME>" name="name1">
</div>
</div>
<div class="form-group">
<label for="name2" class="col-sm-5 control-label">Last Name</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="<NAME>" name="name2">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-5 control-label">Email</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Email" name="email">
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-5 control-label">Phone Number</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Phone Number" name="phone">
</div>
</div>
<div class="form-group">
<label for="preference" class="col-sm-5 control-label">Contact Prefences</label>
<div class="col-sm-7">
<select name="preference" class="form-control">
<option value="">--SELECT--</option>
<option value="">Telephone</option>
<option value="">Email</option>
<option value="">Telephone or Email</option>
</select>
</div>
</div>
<div class="form-group">
<label for="time" class="col-sm-5 control-label">Best Time to Call</label>
<div class="col-sm-7">
<select name="time" class="form-control">
<option value="">--SELECT--</option>
<option value="">Morning</option>
<option value="">Afternoon</option>
<option value="">Evening</option>
<option value="">Weekend</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="confirm">
<div class="header">
<h2 style="line-height:1">CONFIRM YOUR <br> REQUEST WITH</h2>
</div>
<div class="body">
<button class="btn btn-default facebook"><span style="padding-right: 30px"><i class="fa fa-facebook" aria-hidden="true"></i></span>FACEBOOK</button>
<button class="btn btn-default twitter"><span style="padding-right: 25px"><i class="fa fa-twitter" aria-hidden="true"></i></span> TWITTER</button>
<button class="btn btn-default google"><span><i class="fa fa-google-plus" aria-hidden="true"></i></span> GOOGLE+</button>
<p>This is just to confirm your request. We will never post anything without your premission.</p>
</div>
</div>
</div>
</form>
<button class="btn btn-default pull-left prev-2" style="width: 150px;margin-left: 40px;">Previous Step</button>
</div>
</section>
</div>
</div>
</div>
</div>
<!--Footer
=============-->
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wedding Manager</title>
</head>
<body>
<!--Header Starts
==================-->
<?php include_once('application/views/header.php'); ?>
<section>
<div class="vendor">
<div class="content">
<div class="main-form">
<div class="content">
<div class="container">
<div class="form-body">
<!--STEP ONE
==============-->
<section>
<div class="step-one">
<h2>Your <br><strong>Profile Information</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">User Information</h3>
<div class="panel-body">
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name"><b>Name</b></div>
<div class="col-md-8 col-xs-12"><?php echo ''.$user_detail['User_fname'].' '.$user_detail['User_lname'].''; ?></div>
</div>
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name"><b>Email</b></div>
<div class="col-md-8 col-xs-12"><?php echo $user_detail['User_email']; ?></div>
</div>
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name"><b>Phone number</b></div>
<div class="col-md-8 col-xs-12"><?php echo $user_detail['User_phone_no']; ?></div>
</div>
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name"><b>Contact Preference</b></div>
<div class="col-md-8 col-xs-12"><?php if($user_detail['User_contact_preference'] == 1){ echo 'Phone and Email';}elseif($user_detail['User_contact_preference'] == 2){echo 'Phone';}elseif($user_detail['User_contact_preference'] == 3){echo 'Email';}?></div>
</div>
</div>
</div>
<h2>Your <br><strong>Business Details</strong></h2>
<button class="btn btn-success pull-left" style="width:220px; " ><a href="../Vendor/detail/<?php echo $vendor_id;?>" style="color: white"><span>Preview Vendor Details</span></a></button>
<button class="btn btn-success pull-right" style="width:220px; background-color: #5cb85c; border-color: #4cae4c;" ><i class="fa fa-edit"></i><a href="../Vendor/edit" style="color: white"><span>Edit Vendor Details</span></a></button>
<!---<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">Vendor General Information</h3>
<div class="panel-body">
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name"><b>Vendor Types</b><span class="required">*</span>
</div>
<div class="col-md-9 col-xs-12">
<div class="col-md-6 col-sm-12">
<?php
if($vendor_detail['isBanquetHall'] == 1)
{
echo 'Banquet Hall';
}
if($vendor_detail['isDecorators'] == 1)
{
echo '<br>'.'Decorators';
}
if($vendor_detail['isCatering'] == 1)
{
echo '<br>'.'Catering';
}
if($vendor_detail['isPhotographer'] == 1)
{
echo '<br>'.'Photographer';
}
if($vendor_detail['isBakeries'] == 1)
{
echo '<br>'.'Bakeries';
}
if($vendor_detail['isBridalSaloon'] == 1)
{
echo '<br>'.'BridalSaloon';
}
if($vendor_detail['isInvitation'] == 1)
{
echo '<br>'.'Card Invitation';
}
if($vendor_detail['isLimousine'] == 1)
{
echo '<br>'.'Limousine';
}
if($vendor_detail['isFlorist'] == 1)
{
echo '<br>'.'Florist';
}
?>
</div>
</div>
</div>
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="vendor-name"><b>Vendor Name</b>
</div>
<div class="col-md-8 col-xs-12">
<?php echo $vendor_detail['Vendor_name']; ?>
</div>
</div>
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name"><b>Vendor Contact #</b><span class="required">*</span>
</div>
<div class="col-md-8 col-xs-12">
<?php echo $vendor_detail['Vendor_contact_no']; ?>
</div>
</div>
<div class="form-group" >
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name"><b>Vendor Email</b><span class="required">*</span>
</div>
<div class="col-md-8 col-xs-12">
<?php echo $vendor_detail['Vendor_email_address']; ?>
</div>
</div>
</div>
</div>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;">Vendor Location</h3>
<div class="panel-body">
<div class="form-group">
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name"><b>Vendor Address</b>
</div>
<div class="col-md-8">
<?php echo $vendor_detail['Vendor_address']; ?>
</div>
</div>
<div class="form-group">
<div class="control-label col-md-3 col-sm-3 col-xs-12" for="product-name"><b>City</b>
</div>
<div class="col-md-8 col-xs-12">
<?php echo $vendor_detail['City']; ?>
</div>
</div>
</div>
</div>
<div >
<h2>Your <br><strong>Services</strong></h2>
<div class="panel panel-primary" style="background-color: #F4F496;border-color: transparent;">
<div class="panel-body" id="panel-body-service">
<?php
if(isset($vendor_services) && count($vendor_services) > 0)
{
$prev = 0;
$new = 0;
foreach ($vendor_services as $key) {
$new = $key['Vendor_type_id'];
if($new != $prev)
{
?>
<h3 style="background-color: #ff7043;padding: 15px 0px 15px 0px;text-align: center;font-weight: bold;color: white;"><? echo $key['Vendor_type_name']; ?></h3>
<? } ?>
<div class="form-group">
<div class="control-label col-md-6 col-sm-6 col-xs-12" for="product-name"><b><? echo $key['Service_title']; ?></b>
</div>
<div class="col-md-3 col-sm-3 col-xs-12">
<? echo $key['result']; ?>
</div>
</div>
<?
$prev = $key['Vendor_type_id'];
}
}
?>
</div>
</div>
</div>
<div >
<h2>Your <br><strong>Images</strong></h2>
<div class="">
<?php foreach ($vendor_picture as $key) {
?>
<div class="col-md-4">
<img style="width:250px; height:200px;" src="../images/vendortesting/<?php echo $key['Vendor_picture_path']; ?>" class="img-responsive" alt="">
</div>
<? } ?>
</div>
</div>--->
<input type="hidden" name="User_id" value="<?php echo $this->session->userdata('User_id') ?>">
</div>
</section>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<?php include_once('application/views/footer.php'); ?>
</body>
</html>
| 5dbbc66607873d650b5efe390c76182b992f2a40 | [
"PHP"
] | 21 | PHP | tayyab9ahmed/Wedishedi | 9247fbdd798dcbc7176f2fc599341120c6f202dd | 360844c323728597adbf0af1eeb9919566d2f6f1 |
refs/heads/master | <file_sep>/*
** EPITECH PROJECT, 2020
** Untitled project
** File description:
** smart.h -- No description
*/
#ifndef SMART_H
#define SMART_H
// Smart pointers
#include <malloc.h>
#define __getp(p) (* (void **) (p))
__nonnull() static inline void free_ptr(void *p)
{
if (__getp(p) != NULL) {
free(__getp(p));
__getp(p) = NULL;
}
}
#undef __getp
#define __smart __attribute__((cleanup(free_ptr)))
// Smart FILE streams
#include <stdio.h>
__nonnull() static inline void close_fp(FILE **fpp)
{
if (*fpp != NULL) {
fclose(*fpp);
*fpp = NULL;
}
}
#define autofp_t __attribute__((cleanup(close_fp))) FILE *
#endif /* !SMART_H */
<file_sep>/*
** EPITECH PROJECT, 2020
** Dante's Star (solver)
** File description:
** maze_make_charmtx.c -- No description
*/
#include <errno.h>
#include <malloc.h>
#include <stdbool.h>
#include <string.h>
#include <sys/cdefs.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "smart.h"
#include "solver.h"
static bool make_matrix_step2(cmtx_t *cmtx)
{
char *tmp = cmtx->buff;
cmtx->c = calloc(cmtx->y, sizeof(*cmtx->c));
for (int y = 0; y < cmtx->y; y += 1)
cmtx->c[y] = strtok_r(tmp, "\n", &tmp);
return false;
}
static size_t count_lines(char const *maze1d)
{
size_t n = 1;
for (;;) {
maze1d = strchr(maze1d, '\n');
if (maze1d == NULL || *++maze1d == '\0')
break;
n += 1;
}
return n;
}
bool maze_make_charmtx(const char *const path, cmtx_t *cmtx)
{
struct stat sb;
autofp_t fp = fopen(path, "r");
char wrongc;
if (fp == NULL)
return !!dprintf(2, "%s: %s\n", path, strerror(errno));
stat(path, &sb);
cmtx->buff = malloc(sb.st_size / sizeof(*cmtx->buff));
if (cmtx->buff == NULL)
return !!dprintf(2, "%s: %s\n", __func__, strerror(errno));
while (fread(cmtx->buff, sizeof(*cmtx->buff), sb.st_size, fp)) {}
wrongc = cmtx->buff[strspn(cmtx->buff, "X*\n")];
if (wrongc)
return !!dprintf(2, "Forbidden character '%c' in %s\n", wrongc, path);
cmtx->y = count_lines(cmtx->buff);
cmtx->x = strcspn(cmtx->buff, "\n");
return make_matrix_step2(cmtx);
}
<file_sep>##
## EPITECH PROJECT, 2019
## <project>
## File description:
## [file description]
##
### SOURCES ###
#----c_sources----#
SRC := main.c
SRC +=
SRC +=
#----tests_sources----#
UT_SRC := test_main.c
UT_SRC +=
### SOURCES ###
### DIRECTORIES ###
#----c_sources_dir----#
SRC_DIR := ./src/
#----unit_tests_sources_dir----#
UT_DIR := ./tests/
#----headers_sources_dir----#
INC_DIR := ./include/
### DIRECTORIES ###
### COMPILE_USEFULL ###
#----project_usefull----#
NAME = generator
DEBUG_NAME = debug
CFLAGS := -Wall -Wextra
CFLAGS += -Werror
CFLAGS += -iquote $(INC_DIR)
SRC_PATH = $(addprefix $(SRC_DIR), $(SRC))
#----unit_test_usefull----#
UT_NAME = testbin
UT_FLAGS = --coverage -lcriterion
UT_PATH = $(addprefix $(UT_DIR), $(UT_SRC))
#----general_usefull----#
CC = gcc
OBJ = $(SRC_PATH:.c=.o)
### COMPILE_USEFULL ###
### COLOURS ###
CRESET := $$'\033[0m'
#----\033[38;2;<R>;<G>;<B>m----#
CLIGHTGREEN := $$'\033[38;2;190;255;200m'
#----format----#
CBOLD := $$'\033[1m'
### COLOURS ###
### RULES_USEFULL ###
RM = rm -f
### RULES_USEFULL ###
#------------------------------------------------------------#
.PHONY: all
all: $(NAME)
$(NAME): $(OBJ)
$(CC) $(CFLAGS) -o $(NAME) $(OBJ)
@ echo $(CLIGHTGREEN) $(CBOLD) "# COMPILE SUCCESSFULL #"$(CRESET)
#------------------------------------------------------------#
.PHONY: debug
debug: $(DEBUG_NAME)
$(DEBUG_NAME): $(OBJ)
$(CC) -g3 $(CFLAGS) -o $(DEBUG_NAME) $(OBJ)
@ echo $(CLIGHTGREEN) $(CBOLD) "# COMPILE SUCCESSFULL #"$(CRESET)
#------------------------------------------------------------#
.PHONY: clean
clean:
$(RM) $(OBJ)
$(RM) *.gc*
#------------------------------------------------------------#
.PHONY: fclean
fclean: clean
$(RM) $(NAME)
$(RM) $(DEBUG_NAME)
$(RM) $(UT_NAME)
#------------------------------------------------------------#
.PHONY: re
re: fclean all
<file_sep>/*
** EPITECH PROJECT, 2019
** <Project_name>
** File description:
** [test_ft_revstr.c]--No description
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
char *ft_revstr(char *str);
Test(ft_revstr, test_ft_revstr_with_expected_result)
{
char *nullstr = NULL;
char s1[7] = {"543210"};
char s2[2] = {"1"};
char s3[2] = {""};
cr_expect_str_eq(ft_revstr(s1), "012345", "F1T1");
cr_expect_str_eq(ft_revstr(s2), "1", "F1T2");
cr_expect_str_eq(ft_revstr(s3), "", "F1T3");
cr_expect_null(ft_revstr(nullstr), "F1T4");
}
<file_sep>/*
** EPITECH PROJECT, 2020
** Dante's Star (solver)
** File description:
** astar_neighbours.c -- No description
*/
#include <limits.h>
#include <stddef.h>
#include "solver.h"
static int get_y(direction_t dir, anode_t *parent)
{
switch (dir) {
case LEFT:
case RIGHT: return parent->y;
case DOWN: return parent->y + 1;
case UP: return parent->y - 1;
default: return -1;
}
}
static int get_x(direction_t dir, anode_t *parent)
{
switch (dir) {
case DOWN:
case UP: return parent->x;
case LEFT: return parent->x - 1;
case RIGHT: return parent->x + 1;
default: return -1;
}
}
void astar_search_neighbour(
direction_t dir, bool clist[YMAX][XMAX], cell_t cell[YMAX][XMAX])
{
unsigned long cnew = ADATA->parent.c + 1;
int y = get_y(dir, &ADATA->parent);
int x = get_x(dir, &ADATA->parent);
cell_t *neighbour = NULL;
if (!is_valid(y, x))
return;
neighbour = &cell[y][x];
if (is_dest(y, x)) {
neighbour->parent.y = ADATA->parent.y;
neighbour->parent.x = ADATA->parent.x;
ADATA->done = true;
} else if (clist[y][x] && is_path(y, x) && neighbour->c > cnew) {
astack_push(&ADATA->olist, cnew, y, x);
neighbour->c = cnew;
neighbour->parent.y = ADATA->parent.y;
neighbour->parent.x = ADATA->parent.x;
}
}
<file_sep>##
## EPITECH PROJECT, 2019
## Dante
## File description:
## Root Makefile
##
#------------------------------------------------------------#
.PHONY: all
all:
make -C generator/ all
#make -C solver/ all
#------------------------------------------------------------#
.PHONY: tests_run
tests_run:
#------------------------------------------------------------#
.PHONY: clean
clean:
make -C generator/ clean
#make -C solver/ clean
$(RM) *.gc*
#------------------------------------------------------------#
.PHONY: fclean
fclean: clean
make -C generator/ fclean
#make -C solver/ fclean
$(RM) $(UT_NAME)
#------------------------------------------------------------#
.PHONY: re
re: fclean all
<file_sep>/*
** EPITECH PROJECT, 2019
** <Project_name>
** File description:
** [test_main.c]--No description
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
int main(int ac, char **av);
Test(main, test_main_with_expected_result)
{
char *av1[2] = {"a.out", "foo"};
char *av2[3] = {"a.out", "foo", "bar"};
cr_expect_eq(main(2, av1), 0, "F1T1");
cr_expect_eq(main(3, av2), 84, "F1T2");
}
<file_sep>/*
** EPITECH PROJECT, 2020
** Dante's Star (solver)
** File description:
** astar_search.c -- No description
*/
#include <limits.h>
#include <stdbool.h>
#include <string.h>
#include "solver.h"
const adata_t *ADATA_CONTAINER = NULL;
static void draw_path(cell_t cell[YMAX][XMAX])
{
int row = YMAX - 1;
int col = XMAX - 1;
while (row || col) {
MTX->c[row][col] = 'o';
row = cell[row][col].parent.y;
col = cell[row][col].parent.x;
}
}
static void astar_init(cell_t cell[YMAX][XMAX], bool clist[YMAX][XMAX])
{
memset(clist, false, YMAX * XMAX * sizeof(**clist));
for (int y = 0; y < YMAX; y += 1)
for (int x = 0; x < XMAX; x += 1) {
cell[y][x].parent.x = -1;
cell[y][x].parent.y = -1;
cell[y][x].c = ULONG_MAX;
}
}
bool astar_search(void)
{
bool clist[YMAX][XMAX];
cell_t cell[YMAX][XMAX];
adata_t data = {.olist = {0}, .parent = {0}, .done = false};
astar_init(cell, clist);
ADATA_CONTAINER = &data;
astack_push(&data.olist, 0, 0, 0);
while (data.olist.top != NULL) {
astack_pop_into(&data.olist, &data.parent);
clist[data.parent.y][data.parent.x] = true;
for (direction_t dir = 0; dir < 4 && data.done == false; dir += 1)
astar_search_neighbour(dir, clist, cell);
if (data.done) {
draw_path(cell);
break;
}
}
return data.done;
}
<file_sep>/*
** EPITECH PROJECT, 2019
** <Project_name>
** File description:
** [test_ft_strcat.c]--No description
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
char *ft_strcat(char *src, char *dest);
char *ft_strcpy(char *src, char *dest);
Test(ft_strcat, test_ft_strcat_with_expected_result)
{
char t1[] = "1";
cr_expect_str_eq(ft_strcat("1", t1), "11", "F1T1");
char t2[] = "12345";
cr_expect_str_eq(ft_strcat("67890", t2), "1234567890", "F1T2");
char t3[] = "";
cr_expect_str_eq(ft_strcat("1234567890", t3), "1234567890", "F1T3");
char t4[] = "1234567890";
cr_expect_str_eq(ft_strcat("", t4), "1234567890", "F1T4");
char t6[] = "";
cr_expect_str_eq(ft_strcat("", t6), "", "F1T6");
char t7[] = "0987654321";
cr_expect_str_eq(ft_strcat(NULL, t7), t7, "F1T7");
}
<file_sep>/*
** EPITECH PROJECT, 2020
** Dante - Generator
** File description:
** Dante - Generator header
*/
#ifndef DANGEN_H
#define DANGEN_H
#endif /* !DANGEN_H */
<file_sep>##
## EPITECH PROJECT, 2019
## Multipart Makefile
## File description:
## Automatic detection of libfox module usage
##
ifndef FOXAUTOCONFIG
ifeq ($(find libs/ -type d -name 'libfox' -exec echo true \;),"true")
define FOXAUTOCONFIG
#!$(SHELL)
#
# .foxconfig.sh
# Copyright (C) 2019 renard <<EMAIL>>
#
# Distributed under terms of the MIT license.
#
grep -qRE 'wrap_(close|malloc|open|read|write)\.h' \
src/ tests/ \
&& echo -n "wrap_libc "
grep -qRE 'fox_(list|stack|tree)\.h' \
src/ tests/ \
&& echo -n "datastruct "
for mod in $$(ls ./lib/libfox | grep -ve 'Makefile');
do
grep -qR "fox_$$mod.h" \
src/ tests/ \
&& echo -n "$$mod "
done
endef
else
define FOXAUTOCONFIG
#!$(SHELL)
#
# .foxconfig.sh
# Copyright (C) 2019 renard <<EMAIL>>
#
# Distributed under terms of the MIT license.
#
# Libfox directory has not been found.
# This script won't do anything.
endef
endif
#
# Write the script in its file
#########################################################
FOXSCRIPT := .foxconfig
$(call export FOXAUTOCONFIG) $(file >$(FOXSCRIPT),$(FOXAUTOCONFIG))
#########################################################
#
# Check what module is used in the project
#########################################################
FOXMODULES := $(strip $(shell $(SHELL) $(FOXSCRIPT)))
#########################################################
#
# If no libfox module is used, get the coverage at least.
#########################################################
ifneq "$(strip $(FOXMODULES))" ""
FOXRULE = $(FOXMODULES)
else
FOXRULE = tests
endif
#########################################################
endif
<file_sep>/*
** EPITECH PROJECT, 2019
** Untitled project
** File description:
** Main source
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "smart.h"
#include "solver.h"
const cmtx_t *MTX = NULL;
int main(int ac, char **av)
{
cmtx_t cmtx = {0};
if (ac != 2)
return 84 | !dprintf(2, "Wrong argument count: %d\n", ac);
MTX = &cmtx;
if (maze_make_charmtx(av[1], &cmtx))
return 84;
if (!is_path(0, 0) || !is_path(cmtx.y - 1, cmtx.x - 1))
return 84 | !dprintf(2, "Invalid entry or exit point.\n");
if (astar_search()) {
print_matrix();
return EXIT_SUCCESS;
} else
return 84 | !dprintf(2, "Maze is not solvable.\n");
}
<file_sep>/*
** EPITECH PROJECT, 2019
** <Project_name>
** File description:
** [test_ft_strcat.c]--No description
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
char *ft_strcpy(char *src, char *dest);
Test(ft_strcpy, test_ft_strcpy_with_expected_result)
{
char t1[10];
cr_expect_str_eq(ft_strcpy("123456789", t1), "123456789", "T3");
char t2[1];
cr_expect_str_eq(ft_strcpy("", t2), "", "T2");
char t3[3];
cr_expect_str_eq(ft_strcpy("1", t3), "1", "T3");
char t4[30];
cr_expect_str_eq(ft_strcpy("12345", t4), "12345", "T4");
char t5[10];
cr_expect_null(ft_strcpy(NULL, t5), "T5");
}
<file_sep>/*
** EPITECH PROJECT, 2019
** <Project_name>
** File description:
** [test_ft_strlen.c]--No description
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include <string.h>
//#include "libft.h"
size_t ft_strlen(char const *str);
Test(ft_strlen, test_ft_strlen_with_real_strlen)
{
cr_expect_eq(ft_strlen("1"), strlen("1"), "F1T1");
cr_expect_eq(ft_strlen("12"), strlen("12"), "F1T2");
cr_expect_eq(ft_strlen("123"), strlen("123"), "F1T3");
cr_expect_eq(ft_strlen(""), strlen(""), "F1T4");
cr_expect_eq(ft_strlen("1234567890"), strlen("1234567890"), "F1T5");
cr_expect_eq(ft_strlen("0987654321"), strlen("1234567890"), "F1T8");
cr_expect_eq(ft_strlen("ft_strlen"), strlen("my_strlen"), "F1T9");
cr_expect_eq(ft_strlen("Luc, je sui"), strlen("s ton pere!"), "F1T10");
}
<file_sep>/*
** EPITECH PROJECT, 2019
** Dante generator
** File description:
** Main source
*/
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
void free_maze(char **mz)
{
int i;
for (i = 0 ; mz[i + 1] ; i++) {
printf("%s\n", mz[i]);
}
printf("%s", mz[i]);
for (i = 0 ; mz[i] ; i++) {
free(mz[i]);
}
free(mz);
}
char **create_maze(int x, int y)
{
char **mz = NULL;
mz = malloc((x + 1) * sizeof(char *));
if (mz == NULL)
return (NULL);
mz[x] = NULL;
for (int i = 0 ; i < x ; i++) {
mz[i] = malloc(y * sizeof(char) + 1);
if (mz[i] == NULL)
return (NULL);
mz[i][y] = '\0';
for (int j = 0 ; j < y ; j++)
mz[i][j] = '*';
}
return (mz);
}
char **generate_maze(char **mz, int x, int y)
{
int rdx = 0;
int rdy = 0;
srandom(time(NULL));
while (rdy < 1)
rdy = random() % y;
rdx = random() % x;
for (int i = 0 ; mz[i] ; i++) {
if (i != rdx)
mz[i][rdy] = 'X';
}
return (mz);
}
int main(int ac, char **av)
{
char **mz = NULL;
int x = 0;
int y = 0;
if (ac < 3 || ac > 4) {
return (84);
} else if (ac == 4 && strcmp("[perfect]", av[3])) {
return (84);
} else {
x = atoi(av[2]);
y = atoi(av[1]);
}
if (x <= 1 || y <= 1)
return (84);
mz = create_maze(x, y);
if (mz == NULL)
return (84);
mz = generate_maze(mz, x - 1, y - 1);
free_maze(mz);
return (0);
}
<file_sep>/*
** EPITECH PROJECT, 2020
** Dante's Star (solver)
** File description:
** astack_push.c -- No description
*/
#include <malloc.h>
#include <stdbool.h>
#include <string.h>
#include "solver.h"
void astack_pop_into(astack_t *stack, anode_t *container)
{
anode_t *top = stack->top;
if (top != NULL) {
memcpy(container, stack->top, sizeof(*container));
container->next = NULL;
stack->top = top->next;
free(top);
}
}
bool astack_push(astack_t *stack, cost_t c, int row, int col)
{
anode_t *node = malloc(sizeof(*node));
if (node != NULL) {
node->c = c;
node->y = row;
node->x = col;
node->next = stack->top;
stack->top = node;
}
return !(node != NULL);
}
<file_sep>/*
** EPITECH PROJECT, 2020
** Untitled project
** File description:
** solver.h -- No description
*/
#ifndef SOLVER_H
#define SOLVER_H
#include <stdbool.h>
#include <stdio.h>
#include <sys/cdefs.h>
#include <sys/types.h>
typedef unsigned long cost_t;
typedef enum { UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3 } direction_t;
typedef struct {
struct {
int x;
int y;
} parent;
cost_t c;
} cell_t;
typedef struct {
// Size
int x;
int y;
// 2D matrix
char **c;
// Origin buffer pointer (to free at the end)
char *buff;
} cmtx_t;
typedef struct anode_s {
int x;
int y;
cost_t c;
struct anode_s *next;
} anode_t;
typedef struct {
anode_t *top;
} astack_t;
typedef struct astar_data_s {
astack_t olist;
anode_t parent;
bool done;
} adata_t;
extern const adata_t *ADATA_CONTAINER;
#define ADATA ((adata_t *) ADATA_CONTAINER)
extern const cmtx_t *MTX;
#define XMAX (MTX->x)
#define YMAX (MTX->y)
bool astack_push(astack_t *stack, cost_t c, int row, int col);
void astack_pop_into(astack_t *stack, anode_t *container);
bool maze_make_charmtx(const char *const path, cmtx_t *cmtx);
static inline bool is_valid(int row, int col)
{
return (row >= 0 && row < MTX->y) && (col >= 0 && col < MTX->x);
}
static inline bool is_path(int row, int col)
{
return MTX->c[row][col] == '*';
}
static inline bool is_dest(int row, int col)
{
return (row == MTX->x - 1) && (col == MTX->y - 1);
}
static inline void print_matrix()
{
for (int y = 0; y < YMAX; y += 1)
for (int x = 0; x < XMAX; x += 1)
printf("%s\n", MTX->c[y]);
}
bool astar_search(void);
void astar_search_neighbour(
direction_t dir, bool clist[YMAX][XMAX], cell_t cell[YMAX][XMAX]);
#endif /* !SOLVER_H */
<file_sep>##
## EPITECH PROJECT, 2019
## <project>
## File description:
## [file description]
##
### SOURCES ###
#----c_sources----#
SRC := ft_revstr.c
SRC += ft_strlen.c
#----tests_sources----#
UT_SRC := test_ft_revstr.c
UT_SRC += test_ft_strlen.c
### SOURCES ###
### DIRECTORIES ###
#----c_sources_dir----#
SRC_DIR := ../lib/src/
#----unit_tests_sources_dir----#
UT_DIR := ./lib_tests/
#----headers_sources_dir----#
INC_DIR := ../lib/include/
### DIRECTORIES ###
### COMPILE_USEFULL ###
#----project_usefull----#
NAME = lib_tbin
CFLAGS := -Wall -Wextra -Werror
CFLAGS += -iquote $(INC_DIR)
SRC_PATH = $(addprefix $(SRC_DIR), $(SRC))
#----unit_test_usefull----#
UT_FLAGS = --coverage -lcriterion
UT_PATH = $(addprefix $(UT_DIR), $(UT_SRC))
#----general_usefull----#
CC = gcc
OBJ = $(SRC_PATH:.c=.o)
### COMPILE_USEFULL ###
### RULES_USEFULL ###
RM = rm -f
### RULES_USEFULL ###
#------------------------------------------------------------#
.PHONY: all
all: $(NAME)
$(NAME):
$(CC) $(CFLAGS) -o $(NAME) $(SRC_PATH) $(UT_PATH) $(UT_FLAGS)
mv $(NAME) ../
../$(NAME) --always-succeed
mv *.gc* ../
$(RM) ../$(NAME)
| 2e7755f37e74f8a12801f90be011f08f2d12fe20 | [
"C",
"Makefile"
] | 18 | C | SirWrexes/CPE_dante_2019 | cac5d88a4a3e00b5ad7ecb4ca72c4555ed9d8184 | 7af3bb9b1a4e3807c8e38591cfbc60e2c7e4fe01 |
refs/heads/master | <file_sep><?php
class Home extends Controller
{
public function index()
{
$data['title'] = 'Home';
$data['cm'] = $this->model('CharityModel')->getAllCharity();
$this->view('home/index', $data);
}
}
<file_sep><?php
class Form extends Controller
{
public function index()
{
$data['title'] = 'Donasi Sekarang';
$this->view('form/index', $data);
}
public function add()
{
$server = "localhost";
$dbuser = "root";
$dbpass = "";
$database = "donatur";
$conn = mysqli_connect($server, $dbuser, $dbpass, $database);
if (!$conn) {
die("<script>alert('Connection Failed.')</script>");
}
if (isset($_POST['submit'])) {
$location = "../public/uploads/bukti";
$nama = $_POST["namaLengkap"];
$kode = $_POST["kodeDonasi"];
$nomer = $_POST["nomerHP"];
$nominal = $_POST["nominal"];
$file_new_name = date("dmy") . time() . $_FILES["file"]["name"];
$file_name = $_FILES["file"]["name"];
$file_temp = $_FILES["file"]["tmp_name"];
$file_size = $_FILES["file"]["size"];
if ($file_size > 10485760) {
echo "<script>alert('Woops! File is too big. Maximum file size allowed for upload 10 MB.')</script>";
} else {
$sql = "INSERT INTO contributor (namaLengkap, kodeDonasi, nomerHP, nominal, bukti)
VALUES ('$nama', '$kode', '$nomer', '$nominal', '$file_name')";
$result = mysqli_query($conn, $sql);
if ($result) {
move_uploaded_file($file_temp, $location . $file_new_name);
echo "<script>alert('Form berhasil disubmit!')</script>";
} else {
echo "<script>alert('Woops! Sepertinya foto anda bermasalah.')</script>";
}
}
}
return $this->view('form/index');
}
}
<file_sep><?php
class Incoming extends Controller
{
public function index()
{
$data['title'] = 'Detail Page';
$data['cm'] = $this->model('CharityModel')->getAllCharity();
$this->view('incoming/index', $data);
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 18 Jun 2021 pada 07.42
-- Versi server: 10.4.19-MariaDB
-- Versi PHP: 8.0.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `donatur`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `contributor`
--
CREATE TABLE `contributor` (
`id` int(11) NOT NULL,
`namaLengkap` varchar(35) NOT NULL,
`kodeDonasi` varchar(4) NOT NULL,
`nomerHP` bigint(12) NOT NULL,
`nominal` int(11) NOT NULL,
`bukti` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `contributor`
--
ALTER TABLE `contributor`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `contributor`
--
ALTER TABLE `contributor`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Charity of Humanity - COH</title>
<meta content="" name="description">
<meta content="" name="keywords">
<!-- Favicons -->
<link href="<?= BASEURL; ?>/img/favicon.png" rel="icon">
<link href="<?= BASEURL; ?>/img/apple-touch-icon.png" rel="apple-touch-icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href="<?= BASEURL; ?>/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="<?= BASEURL; ?>/vendor/icofont/icofont.min.css" rel="stylesheet">
<link href="<?= BASEURL; ?>/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
<link href="<?= BASEURL; ?>/vendor/venobox/venobox.css" rel="stylesheet">
<link href="<?= BASEURL; ?>/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">
<link href="<?= BASEURL; ?>/vendor/aos/aos.css" rel="stylesheet">
<!-- Template Main CSS File -->
<link href="<?= BASEURL; ?>/css/style.css" rel="stylesheet">
<!-- =======================================================
* Template Name: Day - v2.2.1
* Template URL: https://bootstrapmade.com/day-multipurpose-html-template-for-free/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>
<body>
<!-- ======= Top Bar ======= -->
<div id="topbar" class="d-none d-lg-flex align-items-center fixed-top ">
<div class="container d-flex">
<div class="contact-info mr-auto">
<i class="icofont-envelope"></i> <a href="<EMAIL>"><EMAIL></a>
<i class="icofont-phone"></i> +62 812 3223 0090
</div>
<div class="social-links">
<a href="#" class="twitter"><i class="icofont-twitter"></i></a>
<a href="#" class="facebook"><i class="icofont-facebook"></i></a>
<a href="#" class="instagram"><i class="icofont-instagram"></i></a>
</div>
</div>
</div>
<!-- ======= Header ======= -->
<header id="header" class="fixed-top ">
<div class="container d-flex align-items-center">
<h1 class="logo mr-auto"><a href="index.php">COH</a></h1>
<!-- Uncomment below if you prefer to use an image logo -->
<!-- <a href="index.html" class="logo mr-auto"><img src="assets/img/logo.png" alt="" class="img-fluid"></a>-->
<nav class="nav-menu d-none d-lg-block">
<ul>
<li class="active"><a href="index.php">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Charity</a></li>
<li><a href="#team">Team</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<!-- .nav-menu -->
</div>
</header>
<!-- End Header -->
<!-- ======= Hero Section ======= -->
<section id="hero" class="d-flex align-items-center">
<div class="container position-relative" data-aos="fade-up" data-aos-delay="500">
<h1>Welcome to COH</h1>
<h1>Charity of Humanity</h1>
<h2>We are charity volunteers for those in need.</h2>
<a href="#about" class="btn-get-started scrollto">Get Started</a>
</div>
</section>
<!-- End Hero -->
<main id="main">
<!-- ======= About Section ======= -->
<section id="about" class="about">
<div class="container">
<div class="row">
<div class="col-lg-6 order-1 order-lg-2" data-aos="fade-left">
<img src="<?= BASEURL; ?>/img/about.jpg" class="img-fluid" alt="">
</div>
<div class="col-lg-6 pt-4 pt-lg-0 order-2 order-lg-1 content" data-aos="fade-right">
<h2>Donasi untuk Kemanusiaan</h2> <br>
<p style="text-align: justify;">
Charity of Humanity merupakan website yang kami buat sebagai sarana untuk mengumpulkan dana amal, yang akan digunakan untuk membantu saudara kita yang membutuhkan. Harapannya dengan adanya website ini akan memberi kemudahan untuk orang orang yang ingin
beramal, dan bisa sedikit membantu mereka yang sedang kesusahan.
</p>
</div>
</div>
</div>
</section>
<!-- End About Section -->
<!-- ======= Services Section ======= -->
<section id="services" class="services">
<div class="container">
<div class="section-title">
<span>Ongoing Charity</span>
<h2>Ongoing Charity</h2>
<p>Merupakan pengumpulan dana amal yang sedang berlangsung.</p>
</div>
<div class="row">
<?php foreach ($data['cm'] as $cm) : ?>
<?php if ($cm['id'] < 4) { ?>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="fade-up" data-aos-delay="450">
<div class="card">
<img src="<?= BASEURL; ?><?= $cm['img']; ?>" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title"><a href="<?= BASEURL; ?>/ongoing"><?= $cm['judul']; ?></a></h5>
<p class="card-text mb-2">
<small class="text-muted"><?= $cm['tanggal']; ?></small>
</p>
<b>
<p class="card-text mb-2">
KODE AMAL : <?= $cm['kode']; ?>
</p>
</b>
<p class="card-text mb-3"><?= $cm['subTittle']; ?></p>
<a class="btn btn-danger" href="<?= BASEURL; ?>/form" role="button">Donasi Sekarang</a>
</div>
</div>
</div>
<?php } ?>
<?php endforeach ?>
</div>
</div>
</section>
<!-- End Services Section -->
<!-- ======= Services Section ======= -->
<section id="services" class="services">
<div class="container">
<div class="section-title">
<span>Upcoming Charity</span>
<h2>Upcoming Charity</h2>
<p>Merupakan pengumpulan dana amal yang akan segera kami laksanakan.</p>
</div>
<div class="row">
<?php foreach ($data['cm'] as $cm) : ?>
<?php if ($cm['id'] > 3) { ?>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="fade-up" data-aos-delay="450">
<div class="card">
<img src="<?= BASEURL; ?><?= $cm['img']; ?>" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title"><a href="<?= BASEURL; ?>/incoming"><?= $cm['judul']; ?></a></h5>
<b>
<p class="card-text mb-2">
KODE AMAL : <?= $cm['kode']; ?>
</p>
</b>
<p class="card-text mb-3"><?= $cm['subTittle']; ?></p>
</div>
</div>
</div>
<?php } ?>
<?php endforeach ?>
</div>
</div>
</section>
<!-- End Services Section -->
<!-- ======= Cta Section ======= -->
<section id="cta" class="cta">
<div class="container" data-aos="zoom-in">
<div class="text-center">
<h3>Donasi Sekarang</h3>
<p> Jika kita masih menganggap kemanusiaan itu berharga, maka bantulah saudara kita yang memmbutuhkan bantuan di luar sana.</p>
<a class="cta-btn" href="<?= BASEURL; ?>/form">Klik untuk Berdonasi!</a>
</div>
</div>
</section>
<!-- End Cta Section -->
<!-- ======= Team Section ======= -->
<section id="team" class="team">
<div class="container">
<div class="section-title">
<span>Team</span>
<h2>Team</h2>
<p>The following are our team members</p>
</div>
<div class="row">
<div class="col-lg-6 col-md-8 d-flex align-items-stretch" data-aos="zoom-in">
<div class="member">
<img src="<?= BASEURL; ?>/img/team/team-1.jpg" alt="">
<h4>Fathorrosi</h4>
<span>College Student</span>
<p>
Mahasiswa semester 4 prodi Sistem Informasi, Fakultas Ilmu Komputer, Unniversitas Jember
</p>
<div class="social">
<a href=""><i class="icofont-twitter"></i></a>
<a href=""><i class="icofont-facebook"></i></a>
<a href=""><i class="icofont-instagram"></i></a>
<a href=""><i class="icofont-linkedin"></i></a>
</div>
</div>
</div>
<div class="col-lg-6 col-md-8 d-flex align-items-stretch" data-aos="zoom-in">
<div class="member">
<img src="<?= BASEURL; ?>/img/team/team-3.jpg" alt="">
<h4><NAME></h4>
<span>College Student</span>
<p>
Mahasiswa semester 4 prodi Sistem Informasi, Fakultas Ilmu Komputer, Unniversitas Jember
</p>
<div class="social">
<a href=""><i class="icofont-twitter"></i></a>
<a href=""><i class="icofont-facebook"></i></a>
<a href=""><i class="icofont-instagram"></i></a>
<a href=""><i class="icofont-linkedin"></i></a>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Team Section -->
<!-- ======= Contact Section ======= -->
<section id="contact" class="contact">
<div class="container">
<div class="section-title">
<span>Contact</span>
<h2>Contact</h2>
<p>Sit sint consectetur velit quisquam cupiditate impedit suscipit alias</p>
</div>
<div class="row" data-aos="fade-up">
<div class="col-lg-6">
<div class="info-box mb-4">
<i class="bx bx-map"></i>
<h3>Our Address</h3>
<p>A108 Adam Street, New York, NY 535022</p>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="info-box mb-4">
<i class="bx bx-envelope"></i>
<h3>Email Us</h3>
<p><EMAIL></p>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="info-box mb-4">
<i class="bx bx-phone-call"></i>
<h3>Call Us</h3>
<p>+1 5589 55488 55</p>
</div>
</div>
</div>
<div class="row" data-aos="fade-up">
<div class="col-lg-6 ">
<iframe class="mb-4 mb-lg-0" src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d12097.433213460943!2d-74.0062269!3d40.7101282!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xb89d1fe6bc499443!2sDowntown+Conference+Center!5e0!3m2!1smk!2sbg!4v1539943755621" frameborder="0" style="border:0; width: 100%; height: 384px;" allowfullscreen></iframe>
</div>
<div class="col-lg-6">
<form action="../form/contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="<NAME>" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
</div>
</div>
</section>
<!-- End Contact Section -->
</main>
<!-- End #main -->
<!-- ======= Footer ======= -->
<footer id="footer">
<div class="footer-top">
<div class="container">
<div class="row">
<div class="col-lg-4 col-md-6">
<div class="footer-info">
<h3>COH</h3>
<p>
J<NAME> 99 Tangerang <br> 98128, Indonesia<br><br>
<strong>Phone:</strong> +62 812 3223 0090<br>
<strong>Email:</strong> <EMAIL><br>
</p>
<div class="social-links mt-3">
<a href="#" class="twitter"><i class="bx bxl-twitter"></i></a>
<a href="#" class="facebook"><i class="bx bxl-facebook"></i></a>
<a href="#" class="instagram"><i class="bx bxl-instagram"></i></a>
</div>
</div>
</div>
<div class="col-lg-2 col-md-6 footer-links">
<h4>Useful Links</h4>
<ul>
<li><i class="bx bx-chevron-right"></i> <a href="#">Home</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#">About us</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Services</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Terms of service</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Privacy policy</a></li>
</ul>
</div>
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Kritik dan Saran</h4>
<p>Silahkan beri kami kritik maupun saran. Kami akan menerimanya dengan senang hati</p>
<form action="" method="post">
<input type="email" name="email"><input type="submit" value="Subscribe">
</form>
</div>
</div>
</div>
</div>
<div class="container">
<div class="copyright">
© Copyright <strong><span>Day</span></strong>. All Rights Reserved
</div>
<div class="credits">
<!-- All the links in the footer should remain intact. -->
<!-- You can delete the links only if you purchased the pro version. -->
<!-- Licensing information: https://bootstrapmade.com/license/ -->
<!-- Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/day-multipurpose-html-template-for-free/ -->
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
</footer>
<!-- End Footer -->
<a href="#" class="back-to-top"><i class="icofont-simple-up"></i></a>
<div id="preloader"></div>
<!-- Vendor JS Files -->
<script src="<?= BASEURL; ?>/vendor/jquery/jquery.min.js"></script>
<script src="<?= BASEURL; ?>/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="<?= BASEURL; ?>/vendor/jquery.easing/jquery.easing.min.js"></script>
<script src="<?= BASEURL; ?>/vendor/php-email-form/validate.js"></script>
<script src="<?= BASEURL; ?>/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="<?= BASEURL; ?>/vendor/venobox/venobox.min.js"></script>
<script src="<?= BASEURL; ?>/vendor/owl.carousel/owl.carousel.min.js"></script>
<script src="<?= BASEURL; ?>/vendor/aos/aos.js"></script>
<!-- Template Main JS File -->
<script src="<?= BASEURL; ?>/js/main.js"></script>
</body>
</html><file_sep># Repositori for project Pweb
Projek kami tentang relawan amal
<file_sep><?php
class Ongoing extends Controller
{
public function index()
{
$data['title'] = 'Detail Page';
$data['cm'] = $this->model('CharityModel')->getAllCharity();
$this->view('ongoing/index', $data);
}
}
<file_sep><?php
define('BASEURL', 'http://localhost/SDGS/public');
| 05859b3f6c0212ba88857723db935b5594ab6521 | [
"Markdown",
"SQL",
"PHP"
] | 8 | PHP | micdavid/projek_SDGS | 16f1f3c5ed0df5fb2d311a0d8a4d42e782467781 | ee6c9d1010fb034a047948443d7a729df379c61d |
refs/heads/master | <file_sep><?
# *******************************************************************
# class.hodinky.php-------------------------------------WebWorks.cz--
# ------------------------- trida pro praci s databazi --------------
#
# *******************************************************************
class Database {
var $user, $password, $database, $server, $result, $db;
var $messages = array (); # debug informace
# ...................................................................
# KONSTRUKTOR
# bool Database ( string server, string database, string user, string pass )
function Database ($server, $database, $user, $password) {
# kontrola predanych hodnot
if (!$server || !$database || !$user)
return (false);
$this->server = $server;
$this->database = $database;
$this->user = $user;
$this->password = $<PASSWORD>;
return (true);
}
# ...................................................................
# bool _connect ( )
# pripoji se k databazi
function _connect () {
# pripojeni MySQL databaze
if ($this->db = mysql_pconnect ($this->server, $this->user, $this->password)) {
if (!mysql_select_db ($this->database, $this->db)) {
$this->messages['system'] = 'DB connected but wrong database name "' . $this->database . '"!';
return (false);
}
}
else {
$this->messages['system'] = 'DB not connected!';
return (false);
}
$this->messages['system'] = 'DB connected.';
$this->messages['total_time'] = 0;
$this->messages['total_queries'] = 0;
return ($this->db);
}
# ...................................................................
# resource query ( string query [. string query_name)
# pozadavek na databazi
# dopsat moznost INSERT, DELETE a UPDATE
function query ($query, $query_name = '') {
unset ($this->result);
# pokud neni pripojena databaze, pripoj
if (!$this->db)
$this->_connect ();
if ($this->db) {
# spusteni mereni
list($usec, $sec) = explode(" ",microtime());
$time_start = (float) $usec + (float) $sec;
# vlastni dotaz
$this->result = mysql_query($query, $this->db);
#konec mereni a zapsani do $messages
list($usec, $sec) = explode(" ",microtime());
$elapsed = round (((float) $usec + (float) $sec) - $time_start, 5);
$this->messages['total_time'] += $elapsed;
$this->messages['total_queries']++;
if ($query_name && $query_name != '') {
$this->messages['queries_summary'][$query_name]++;
$this->messages['queries'][] = array ('name' => $query_name, 'time' => (string) $elapsed, 'query' => $query);
}
else {
$this->messages['queries_summary']['undefined']++;
$this->messages['queries'][] = array ('time' => (string) $elapsed, 'query' => $query);
}
}
return ($this->result);
}
# ...................................................................
# int numRows ( )
# vrati pocet radek dotazu
# dopsat moznost INSERT, DELETE a UPDATE
function numRows () {
if (!$this->db)
return (false);
$output = @mysql_num_rows ($this->result);
if ($output)
return ($output);
else
return (mysql_affected_rows ());
}
# ...................................................................
# mixed getRow ( [resource result] )
# vrati radku (jako asociativni pole) vysledku query (posledniho nebo predaneho) dotazu
# dopsat moznost INSERT, DELETE a UPDATE
function getRow ($result = null) {
if (!$this->db)
return (false);
if ($result)
$radka = mysql_fetch_assoc ($result);
else
$radka = mysql_fetch_assoc ($this->result);
if (is_array ($radka))
return ($radka);
else
return (false);
}
# ...................................................................
# array getAllRows ( [resource result] [, string index] )
# vrati array array - kompletni vysledek z DB
# dopsat moznost INSERT, DELETE a UPDATE - blbost?
function getAllRows ($result = null, $indexby = null) {
if (!$this->db)
return (false);
while ($row = $this->getRow ($result)) {
if ($indexby)
$output[$row[$indexby]] = $row;
else
$output[] = $row;
}
return ($output);
}
# ...................................................................
# string getResult ( [resource result] )
# vrati 1 sloupec prvni radky vysledku, hodi se pro jednoduche dotazy
# dopsat moznost INSERT, DELETE a UPDATE - blbost?
function getResult ($result = null) {
if (!$this->db)
return (false);
if ($result)
return (mysql_result ($result, 0, 0));
else
return (mysql_result ($this->result, 0, 0));
}
# ...................................................................
# string getRowsCount ( [resource result] )
# vrati celkovy pocet vysledku, kdyby nebylo pouzito LIMIT (musi byt predtim specialni volaniSELECT SQL_...)
function getRowsCount () {
if (!$this->db)
return (false);
return ($this->getResult ($this->query ('SELECT FOUND_ROWS();', 'FOUND ROWS')));
}
# ...................................................................
# string getNumAffected ( [resource result] )
# vrati celkovy pocet radku, ktere byly ovlivneny
function getNumAffected () {
if (!$this->db)
return (false);
return (mysql_affected_rows ());
}
# ...................................................................
# string getId ( )
# vrati ID posledni pridane polozky
# dopsat moznost INSERT, DELETE a UPDATE - blbost?
function getId () {
if (!$this->db)
return (false);
return (mysql_insert_id ($this->db));
}
# ...................................................................
function freeResult ($result = null) {
if (!$this->db)
return (false);
if ($result)
return (mysql_free_result ($result));
else
return (mysql_free_result ($this->result));
}
}
?><file_sep><?
class Modul {
var $cache; # cache soubor
var $DB; # globalni objekt pro praci s databazi
var $cachetotal; # cache s pocet celkovych radek odpovidajicich poslednimu getu
var $cachesql; # cache sql query posledniho getu
var $sqlbase; # zaklad SQL dotazu
var $sqlupdate; # zaklad SQL dotazu - UPDATE
var $sqlinsert; # zaklad SQL dotazu - INSERT
var $sqltable;
var $idformat = 'id';
var $sqlgrouptotal;
var $order = -6;
var $limit = 20;
var $sync = array ();
var $fulltextcolumns; # zakladni sloupce pro hledani
# ...................................................................
# KONSTRUKTOR
function Modul (& $database) {
$this->DB = & $database; # globalni objekt pro praci s databazi
$this->cache = array ();
if (!is_object ($this->DB))
return (false);
return (true);
}
# ...................................................................
function getLimit () {
return ($this->limit);
}
# ...................................................................
function setLimit ($limit = null) {
if (is_numeric ($limit) && $limit > 0)
$this->limit = (int) $limit;
return ($this->limit);
}
# ...................................................................
function getNoCalcRows ($where = null, $order = null, $limit = null, $limit_from = null) {
return ($this->get ($where, $order, $limit, $limit_from, true));
}
# ...................................................................
function get ($where = null, $order = null, $limit = null, $limit_from = null, $nocalcrows = false) {
if (!$this->sqlbase)
return (false);
# zaklad sql dotazu
$sql = $this->sqlbase;
# pokud je v sqlbase obsazen GROUP BY, musim to rozdel (mozna i neco dalsiho)
if (function_exists("strripos")) {
$posgroupby = strripos ($sql, 'GROUP BY ');
$lastfrom = strripos ($sql, 'FROM ');
if ($posgroupby>$lastfrom) {
$sql_groupby = substr ($sql,$posgroupby);
$sql = substr ($sql, 0, $posgroupby);
}
}
elseif (strpos (strtolower ($sql), 'group by')) {
$sql_groupby = stristr ($sql, 'group by');
$sql = substr ($sql, 0, strpos (strtolower ($sql), 'group by'));
}
# pokud je v sqlbase obsazen WHERE, musim to rozdelit
if (function_exists("strripos")) {
$poswhere = strripos ($sql, 'WHERE ');
if ($poswhere>$lastfrom) {
$sql_where = substr ($sql,$poswhere+6);
$sql = substr ($sql, 0, $poswhere);
}
}
elseif (strpos (strtolower ($sql), 'where')) {
$sql_where = substr (stristr ($sql, 'where'),6);
$sql = substr ($sql, 0, strpos (strtolower ($sql), 'where'));
}
# WHERE - pridani podminky
if (!is_array ($where) && isset ($where))
$where = array ($where);
if ($sql_where)
$where[] = $sql_where;
if ($where)
$sql .= ' WHERE ' . implode (' AND ', $where);
# pokud je v sqlbase GROUP BY, musis odriznutou cast pridat (zde)
if ($sql_groupby)
$sql .= ' ' .$sql_groupby;
# ORDER BY - pridani trideni
if (!$order)
$order = $this->order;
foreach (explode (',', $order) as $partorder) {
if (is_numeric ($partorder)) {
if ($partorder < 0)
$orders[] = (-1 * $partorder) . ' DESC';
else
$orders[] = $partorder;
}
}
if (is_array ($orders))
$sql .= ' ORDER BY ' . implode (', ', $orders);
# LIMIT
if ($limit != -1) {
if (!is_numeric ($limit) || (int) $limit < 1)
$limit = $this->limit;
if ($limit != -1) {
$sql .= ' LIMIT ';
if (is_numeric ($limit_from) && (int) $limit_from > 1)
$sql .= ($limit_from-1) * $limit . ', ';
$sql .= $limit;
}
}
$sql .= ';';
# nechci pocet vsech radek - zdrzuje
if ($nocalcrows)
$sql = str_replace (' SQL_CALC_FOUND_ROWS', '', $sql);
$this->cachesql = $sql;
# SQL dotaz
$this->DB->query ($sql, get_class ($this) . ' -> get');
while ($radka = $this->DB->getRow ()) {
$data[] = $radka;
$this->cache[$radka['id']] = $radka;
}
# nactu si kolik by bylo celkove radek (pro lister)
if (strpos ($this->sqlbase, 'SQL_CALC_FOUND_ROWS') && !$nocalcrows)
$this->cachetotal = $this->DB->getRowsCount ();
return ($data);
}
# ...................................................................
function getCustom ($custom_sql = null, $where = null, $order = null, $limit = null, $limit_from = null) {
$temp = $this->sqlbase;
if ($custom_sql)
$this->sqlbase = $custom_sql;
$data = $this->get ($where, $order, $limit, $limit_from);
$this->sqlbase = $temp;
return ($data);
}
# ...................................................................
# vrati definovane agregovane vysledky, tedy soucet, prumer, pocet atd vsech vysledku bez ohledu na limit
function getGroupTotal ($where = null) {
if (!$this->sqlgrouptotal)
return (false);
if (!is_array ($where) && isset ($where))
$where = array ($where);
$sql = substr ($this->sqlbase, strpos (strtoupper ($this->sqlbase), ' FROM'));
# pokud je v sqlbase obsazen GROUP BY, musim to rozdel (mozna i neco dalsiho)
if (strpos (strtoupper ($sql), 'GROUP BY'))
$sql = substr ($sql, 0, strpos (strtoupper ($sql), 'GROUP BY'));
# pokud je v sqlbase obsazen WHERE, musim to rozdelit
if (strpos (strtolower ($sql), 'where')) {
$where[] = substr (stristr ($sql, 'where'),6);
$sql = substr ($sql, 0, strpos (strtolower ($sql), 'where'));
}
# pokud je v sqlgrouptotal obsazen GROUP BY, musim to rozdelit
if (strpos (strtoupper ($this->sqlgrouptotal), 'GROUP BY')) {
$sql_groupby = ' ' . stristr ($this->sqlgrouptotal, 'GROUP BY');
$sql_gt = substr ($this->sqlgrouptotal, 0, strpos (strtoupper ($this->sqlgrouptotal), 'GROUP BY'));
}
else {
$sql_groupby = ' GROUP BY ' . $this->sqltable . '.id';
$sql_gt = $this->sqlgrouptotal;
}
# WHERE - pridani podminky
if (!is_array ($where) && isset ($where))
$where = array ($where);
if ($sql_where)
$where[] = $sql_where;
if ($where)
$sql_where .= ' WHERE ' . implode (' AND ', $where) . ' ';
# finalni dotaz
$sql = $sql_gt . $sql . $sql_where . $sql_groupby;
# SQL dotaz
$this->DB->query ($sql, get_class ($this) . ' -> getGroupTotal');
return ($this->DB->getRow ());
}
# ...................................................................
# stejne jako get (), ale vrati 1-n (parametr $count) nahodnych zaznamu
function getRandom ($where = null, $order = null, $limit = null, $limit_from = null, $count = 1) {
$data = $this->get ($where, $order, $limit, $limit_from);
# chci cislo
$count = 1 * (int) $count;
# pokud mam dostatecny pocet zaznamu
if ($this->cachetotal >= 1 && $this->cachetotal > $count) {
# vyberu klice nahodnych polozek
srand ();
$keys = array_rand ($data, $count);
if ($count > 1) {
foreach ($keys as $value)
$output[] = $data[$value];
return ($output);
}
else
return (array ($data[$keys]));
}
# zadny vysledek nebo chci stejny pocet jako mam = vyber vseho
else
return ($data);
}
# ...................................................................
# vrati informace o aktualnim trideni
function getExtra ($order = null) {
# budu pracovat jen s prvni hodnotou trideni z retezce "3, -5, 2, 11"
if (strpos ($order, ',')) {
$firstorder = substr ($order, 0, strpos ($order, ','));
$restorder = substr ($order, strpos ($order, ',') );
}
else
$firstorder = $order;
if (!is_numeric ($firstorder))
$firstorder = $this->order;
# ORDER BY - pridani trideni
if ($order < 0) {
$output['order'] = -1*$firstorder;
$output['order_type'] = 'down';
$output['order_minus'] = 1;
$output['order_other'] = $firstorder;
$output['orderfull'] = (-1*$firstorder) . $restorder;
$output['orderfull_other'] = $firstorder . $restorder;
}
else {
$output['order'] = $firstorder;
$output['order_type'] = 'up';
$output['order_plus'] = 1;
$output['order_other'] = -1*$firstorder;
$output['orderfull'] = $firstorder . $restorder;
$output['orderfull_other'] = (-1*$firstorder) . $restorder;
}
return ($output);
}
# ...................................................................
function getTotal ($dataset = null, $values = null) {
if (!is_array ($values))
return (false);
if (!is_array ($dataset))
return (false);
foreach ($dataset as $row)
foreach ($values as $key=>$funct) {
if ($funct == 'count' && isset ($row[$key]))
$output[$key]++;
if ($funct == 'sum' && isset ($row[$key]))
$output[$key] += $row[$key];
if ($funct == 'avg' && isset ($row[$key])) {
$output[$key] += ((int) $row['id'] && $values['id']=='sum') ? $row['id'] * $row[$key] : $row[$key];
$counter[$key]++;
}
}
foreach ($values as $key=>$funct) {
if ($funct=='avg' && $output[$key]) {
$output[$key] = $output[$key] / (((int)$output['id'] && $values['id']=='sum') ? $output['id'] : $counter[$key]);
}
}
return ($output);
}
# ...................................................................
function getRowsCount ($result = null) {
return ($this->cachetotal);
}
# ...................................................................
function set ($set, $ids = null) {
if (!is_array ($set))
return (false);
# priprava pro UDATE
foreach ($set as $key=>$value)
$sqltemp[] = $this->sqltable . '.' . $key . ' = ' . $value;
# MULTI UPDATE
if (is_array ($ids) && count ($ids)) {
$sql = $this->sqlupdate . ' SET ' . implode (', ', $sqltemp) . ' WHERE ' . $this->sqltable . '.' . $this->idformat . ' IN ("' . implode ('", "', $ids) . '");';
}
# SINGLE UPDATE
elseif (is_numeric ($ids)) {
$sql = $this->sqlupdate . ' SET ' . implode (', ', $sqltemp) . ' WHERE ' . $this->sqltable . '.' . $this->idformat . ' = "' . $ids . '";';
}
# INSERT
else {
$sql = $this->sqlinsert . ' (' . implode (', ', array_keys ($set)) . ') VALUES (' . implode (', ', $set) . ');';
$insert = true;
}
//$this->DB->query ('START TRANSACTION;');
$go = $this->DB->getNumAffected ($this->DB->query ($sql));
# kdyz byl insert, jeste nactu nove id
if ($insert)
$ids = $this->DB->getId ();
# musim volat sync()?
if ($go)
foreach (array_keys ($set) as $key=>$value)
if (in_array ($key, $this->sync)) {
if ($insert)
$go = $this->syncInsert ($set, $ids);
else
$go = $this->syncUpdate ($set, $ids);
break;
}
if ($go) {
//$this->DB->query ('COMMIT;');
# smazu si cache
unset ($this->cache);
unset ($this->cachetotal);
return ($ids);
}
//else
//$this->DB->query ('ROLLBACK;');
return (false);
}
# ...................................................................
function syncInsert ($set, $id) {
return (true);
}
# ...................................................................
function syncUpdate ($set, $oldata) {
return (true);
}
# ...................................................................
# $retunarray znaci ze vysledek bude pole [] = data, pri false se vrati jen 1. vysledek data
function getId ($ids = null, $returnarray = true) {
# prohledam cache, budu nacitat jen nove potrebne
if (is_array ($ids))
foreach ($ids as $key=>$id) {
if ($this->cache[$id]) {
$output[] = $this->cache[$id];
unset ($ids[$key]);
}
}
elseif ($ids) {
if ($this->cache[$ids])
$output[] = $this->cache[$ids];
else
$ids = array ($ids);
}
# nenasel jsem (vse), doctu potrebne
if (count ($ids) && is_array ($ids)) {
$data = $this->get ($this->sqltable . '.' . $this->idformat . ' IN("' . implode ('", "', $ids) . '")');
$cache[$data[$this->idformat]] = $data;
if (is_array ($data) && is_array ($output))
$output = array_merge ($data, $output);
elseif (is_array ($data))
$output = $data;
}
# pripadne vratim i castecny vysledek
if (is_array ($output)) {
if ($returnarray)
return ($output);
else
return ($output[0]);
}
return (false);
}
# ...................................................................
function findId ($where, $returnonlyfirst = true) {
if (!$where)
return (null);
$data = $this->get ($where);
if ($data && $returnonlyfirst) {
$data = reset ($data);
return ($data['id']);
}
elseif (is_array ($data)) {
foreach ($data as $key=>$value)
$output[] = $value['id'];
return ($output);
}
else
return (null);
}
# ...................................................................
function findIds ($where, $returnonlyfirst = true) {
return ($this->findId ($where, false));
}
# ...................................................................
function createFulltextSubquery ($input = '', $columns = null, $separator_or = false) {
# kdyz nemam vstup nebo hledane sloupce, konec
if (!$input || (!$columns && !is_array ($this->fulltextcolumns)))
return (null);
# prevedu si seznam sloupcu na pole, pripadne nactu defaultni
if ($columns && !is_array ($columns))
$columns[] = $columns;
elseif (!is_array ($columns)) {
$columns = $this->fulltextcolumns;
}
# vytvorim si subquery aplikovane na kazde hledane slovo
foreach ($columns as $value) {
$sub[] = 'CAST(' . $value . ' AS CHAR)';
}
$word_query = 'CONCAT_WS(" ",' . implode (',', $sub) . ')';
//$word_query = 'z.nazev';
# vytvorim si pole hledanych slov
$input = mb_strtolower (eregi_replace ('[^a-ž0-9 ]+', ' ', $input));
$input = eregi_replace (' +', ' ', $input);
$words = explode (' ', $input);
# vytvoreni dotazu
if (!is_array ($words))
return (null);
foreach ($words as $word)
$query[] = $word_query . ' COLLATE utf8_general_ci LIKE "%' . $word . '%"';
if ($separator_or)
$output = '(' . implode (' OR ', $query) . ')';
else
$output = '(' . implode (' AND ', $query) . ')';
return ($output);
}
}
?> | b7b9dbdc5038ef1f08db3b1a1faeeafef121fe0c | [
"PHP"
] | 2 | PHP | janmensik/Modul.class | dbeb775bb54c878ae0723c6883c749dace481a10 | 0d5e4d36f6c6d988c19b764df917bbc2f46740c3 |
refs/heads/master | <repo_name>kftsc/AndroidStudio-CustomerInfo<file_sep>/src/main/java/kftsc/custapp/PurchaseDataProvider.java
package kftsc.custapp;
import android.support.annotation.NonNull;
/**
* Created by kftsc on 1/16/2019.
*/
public class PurchaseDataProvider implements Comparable<PurchaseDataProvider> {
private String type;
private String category;
private String amount;
private String time;
public PurchaseDataProvider(String type, String category, String amount, String time) {
this.type = type;
this.category = category;
this.amount = amount;
this.time = time;
}
public String getType() {
return type;
}
public String getCategory() {
return category;
}
public String getAmount() {
return amount;
}
public String getTime() {
return time;
}
public void setType(String type) {
this.type = type;
}
public void setCategory(String category) {
this.category = category;
}
public void setAmount(String amount) {
this.amount = amount;
}
public void setTime(String time) {
this.time = time;
}
public int compareTo (PurchaseDataProvider other) {
if (Integer.valueOf(this.getTime()).compareTo(Integer.valueOf(other.getTime())) < 0) {
return 1;
}
else if (Integer.valueOf(this.getTime()).compareTo(Integer.valueOf(other.getTime())) > 0) {
return -1;
}
else {
return 0;
}
}
}
<file_sep>/src/main/java/kftsc/custapp/MainActivity.java
package kftsc.custapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("客户档案");
final Button setNewButton = (Button) findViewById(R.id.setNewBtn);
setNewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setNewAct(setNewButton);
}
});
final Button searchButton = (Button) findViewById(R.id.searchBtn);
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchAct(searchButton);
}
});
}
public void setNewAct (View view) {
Intent setNewIntent = new Intent(this,SetNewActivity.class);
startActivity(setNewIntent);
}
public void searchAct (View view) {
Intent searchIntent = new Intent(this, SearchActivity.class);
startActivity(searchIntent);
}
}
<file_sep>/src/main/java/kftsc/custapp/ListDataAdapter.java
package kftsc.custapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by kftsc on 1/17/2019.
*/
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(@NonNull Context context, int resource) {
super(context, resource);
}
static class LayoutHandler {
TextView type, category, amount, time;
}
@Override
public void add(Object object) {
super.add(object);
list.add(object);
Collections.sort(list);
}
@Override
public int getCount() {
return list.size();
}
@Nullable
@Override
public Object getItem(int position) {
return list.get(position);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater =
(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.type = (TextView) row.findViewById(R.id.text_type);
layoutHandler.category = (TextView) row.findViewById(R.id.text_category);
layoutHandler.amount = (TextView) row.findViewById(R.id.text_amount);
layoutHandler.time = (TextView) row.findViewById(R.id.text_time);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
//origin
PurchaseDataProvider provider = (PurchaseDataProvider) this.getItem(position);
layoutHandler.type.setText(provider.getType());
layoutHandler.category.setText(provider.getCategory());
layoutHandler.amount.setText(provider.getAmount());
layoutHandler.time.setText(displayTimeForm(provider.getTime()));
/*
if (SearchActivity.flag ) {
for (int i = position; i < list.size(); ) {
PurchaseDataProvider provider = (PurchaseDataProvider) this.getItem(i);
if (Integer.valueOf(provider.getTime()) >= timeCalculator(SearchActivity.current_time , SearchActivity.duration_time)
&& Integer.valueOf(provider.getTime()) <= SearchActivity.current_time ) {
layoutHandler.type.setText(provider.getType());
layoutHandler.category.setText(provider.getCategory());
layoutHandler.amount.setText(provider.getAmount());
layoutHandler.time.setText(displayTimeForm(provider.getTime()));
break;
} else {
i++;
}
}
}
else {
PurchaseDataProvider provider = (PurchaseDataProvider) this.getItem(position);
layoutHandler.type.setText(provider.getType());
layoutHandler.category.setText(provider.getCategory());
layoutHandler.amount.setText(provider.getAmount());
layoutHandler.time.setText(displayTimeForm(provider.getTime()));
}
*/
return row;
}
public String displayTimeForm(String time) {
if(time.length() == 8) {
return time.substring(0, 4) + "/" + time.substring(4, 6) + "/" + time.substring(6, 8);
}
else {
return time;
}
}
/*
public Integer timeCalculator(Long curr, Long dur) {
// System.out.println(curr);
// System.out.println(dur);
// System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
int currMon = Integer.valueOf(curr.toString().substring(4,6));
int currYear = Integer.valueOf(curr.toString().substring(0,4));
String date= curr.toString().substring(6,8);
Long durNum = dur / 100;
while (durNum >= currMon) {
durNum = durNum - currMon;
currYear--;
currMon = 12;
}
durNum = currMon - durNum;
String month;
if (durNum < 10) {
month = "0" + String.valueOf(durNum);
}
else {
month = String.valueOf(durNum);
}
String result = String.valueOf(currYear) + month + date;
return Integer.valueOf(result);
}
*/
}
<file_sep>/src/main/java/kftsc/custapp/PurchaseDbHelper.java
package kftsc.custapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by kftsc on 1/17/2019.
*/
public class PurchaseDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "PURCHASEINFO.DB";
private static final int DATABASE_VERSION = 1;
public static final String CREATE_QUERY =
"CREATE TABLE " + Customer.GasPurchase.TABLE_NAME + "(" + Customer.GasPurchase.Buyer + " TEXT," +
Customer.GasPurchase.GAS_TYPE + " TEXT,"
+ Customer.GasPurchase.GAS_CATEGORY + " TEXT," + Customer.GasPurchase.AMOOUNT + " TEXT," +
Customer.GasPurchase.TIME + " TEXT);";
public PurchaseDbHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DATABASE OPERATION", "Database created / opened...");
}
public String getCreateQuery() {
return this.CREATE_QUERY;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATION", "Table created...");
}
public void addPurchaseInfo (String buyerName, String gasType, String gasCategory, String amount, String time,
SQLiteDatabase sqLiteDatabase) {
ContentValues contentValues = new ContentValues();
contentValues.put(Customer.GasPurchase.Buyer, buyerName);
contentValues.put(Customer.GasPurchase.GAS_TYPE, gasType);
contentValues.put(Customer.GasPurchase.GAS_CATEGORY, gasCategory);
contentValues.put(Customer.GasPurchase.AMOOUNT, amount);
contentValues.put(Customer.GasPurchase.TIME, time);
sqLiteDatabase.insert(Customer.GasPurchase.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATION", "One row is inserted...");
}
public Cursor searchInformation (String buyerName, SQLiteDatabase sqLiteDatabase) {
String[] projections = {
Customer.GasPurchase.Buyer,
Customer.GasPurchase.GAS_TYPE,
Customer.GasPurchase.GAS_CATEGORY,
Customer.GasPurchase.AMOOUNT,
Customer.GasPurchase.TIME
};
String selection = Customer.GasPurchase.Buyer + " LIKE ?";
String[] selection_args = {buyerName};
Cursor cursor = sqLiteDatabase.query(Customer.GasPurchase.TABLE_NAME, projections,
selection, selection_args,null, null, null);
return cursor;
}
public void deletePurchase (String buyerName, SQLiteDatabase sqLiteDatabase) {
String selection = Customer.GasPurchase.Buyer + " LIKE ?";
String[] selection_args = {buyerName};
sqLiteDatabase.delete(Customer.GasPurchase.TABLE_NAME, selection, selection_args);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
<file_sep>/src/main/java/kftsc/custapp/SumActivity.java
package kftsc.custapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class SumActivity extends AppCompatActivity {
private String buyerName;
private PurchaseDbHelper purchaseDbHelper;
private SQLiteDatabase sqLiteDatabase;
TextView output;
private PurchaseList purchaseList;
private boolean qi, chai;
CheckBox checkQi, checkChai, cQi93, cQi98, cChai0, cChai_10;
private String qi93, qi98, chai0, chai_10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sum);
this.setTitle("统计");
Intent name = getIntent();
buyerName = name.getStringExtra(SearchActivity.EXTRA_MESSAGE2);
output = (TextView) findViewById(R.id.output);
final Button backBtn = (Button) findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack(backBtn);
}
});
checkQi = (CheckBox) findViewById(R.id.checkQi);
checkQi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkQi.isChecked()) {
qi = true;
}
else {
qi = false;
}
}
});
checkChai = (CheckBox) findViewById(R.id.checkChai);
checkChai.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkChai.isChecked()) {
chai = true;
}
else {
chai = false;
}
}
});
cQi93 = (CheckBox) findViewById(R.id.cQi93);
cQi93.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cQi93.isChecked()) {
qi93 = "93";
}
else {
qi93 = "";
}
}
});
cQi98 = (CheckBox) findViewById(R.id.cQi98);
cQi98.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cQi98.isChecked()) {
qi98 = "98";
}
else {
qi98 = "";
}
}
});
cChai0 = (CheckBox) findViewById(R.id.cChai0);
cChai0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cChai0.isChecked()) {
chai0 = "0";
}
else {
chai0 = "";
}
}
});
cChai_10 = (CheckBox) findViewById(R.id.cChai_10);
cChai_10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cChai_10.isChecked()) {
chai_10 = "-10";
}
else {
chai_10 = "";
}
}
});
final Button doSum = (Button) findViewById(R.id.doSumBtn);
doSum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSum(doSum);
}
});
}
public void goBack(View v) {
// Intent back = new Intent(this, SearchActivity.class);
//startActivity(back);
}
public void getSum(View v) {
purchaseDbHelper = new PurchaseDbHelper(getApplicationContext());
sqLiteDatabase = purchaseDbHelper.getWritableDatabase();
Cursor cursor = purchaseDbHelper.searchInformation(buyerName, sqLiteDatabase);
purchaseList = new PurchaseList();
if(cursor.moveToFirst()) {
while(cursor.moveToNext()) {
String type, category, amount, time;
type = cursor.getString(1);
category = cursor.getString(2);
amount = cursor.getString(3);
time = cursor.getString(4);
if (SearchActivity.flag) {
if (Integer.valueOf(time) >= timeCalculator(SearchActivity.current_time, SearchActivity.duration_time)
&& Integer.valueOf(time) <= SearchActivity.current_time ) {
PurchaseDataProvider provider = new PurchaseDataProvider(type, category, amount, time);
purchaseList.addOne(provider);
}
}
else {
PurchaseDataProvider provider = new PurchaseDataProvider(type, category, amount, time);
purchaseList.addOne(provider);
}
}
}
if (qi93 == null && qi98 == null && chai0 == null && chai_10 == null && !qi && !chai) {
Toast.makeText(this, "请选择统计条件", Toast.LENGTH_SHORT).show();
}
else {
output.setText(String.valueOf(purchaseList.advanceSum(qi, chai, qi93, qi98, chai0, chai_10)));
}
}
public Integer timeCalculator(Long curr, Long dur) {
// System.out.println(curr);
// System.out.println(dur);
// System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
int currMon = Integer.valueOf(curr.toString().substring(4,6));
int currYear = Integer.valueOf(curr.toString().substring(0,4));
String date= curr.toString().substring(6,8);
Long durNum = dur / 100;
while (durNum >= currMon) {
durNum = durNum - currMon;
currYear--;
currMon = 12;
}
durNum = currMon - durNum;
String month;
if (durNum < 10) {
month = "0" + String.valueOf(durNum);
}
else {
month = String.valueOf(durNum);
}
String result = String.valueOf(currYear) + month + date;
return Integer.valueOf(result);
}
}
| 6c1fd427415b21efcae0de4867ee5dc06a57f172 | [
"Java"
] | 5 | Java | kftsc/AndroidStudio-CustomerInfo | c88a881a42d935ae07e1afd94fede6382048ee45 | 585f8bd92c36f0b27f60804af205f79524597328 |
refs/heads/master | <file_sep>#include <boost/predef.h>
#include "../../executerwithscript.h"
const char m_szPerlScript[] = \
"" "\n"
"#-----------------" "\n"
"#!/usr/bin/env /usr/bin/perl -X" "\n"
"#-----------------" "\n"
"" "\n"
"use strict;" "\n"
"" "\n"
"print '$0 = \"'.\"$0\".'\"';" "\n"
"print \"\\n\";" "\n"
"" "\n"
"{" "\n"
" my $ver = $];" "\n"
" $ver *= 1000;" "\n"
" my $ver_maj = int($ver / 1000);" "\n"
" my $ver_min = int($ver % 1000);" "\n"
" print 'PERL version major = '.$ver_maj.', minor = '.$ver_min;" "\n"
" print \"\\n\";" "\n"
"}" "\n"
"" "\n"
"print \"DEBUGGING = \".$^D;" "\n"
"print \"\\n\";" "\n"
"" "\n"
"foreach (0..@ARGV)" "\n"
"{" "\n"
" last if $_ == @ARGV;" "\n"
" print '$ARGV['.$_.'] = \"'.$ARGV[$_].'\"';" "\n"
" print \"\\n\";" "\n"
"}" "\n"
"" "\n"
"print 'Input: ';" "\n"
"chomp(my $input = <STDIN>);" "\n"
"print 'You entered = \"'.\"$input\".'\"';" "\n"
"print \"\\n\";" "\n"
"" "\n"
"print \"End of test\\n\";" "\n"
;
bool testExecuteScript0()
{
WalterTools::CExecuterWithScript perl(m_szPerlScript, 0, true);
if (!perl.execute())
return false;
return true;
}
bool testExecuteScriptWithArgs()
{
WalterTools::CExecuterWithScript perl(m_szPerlScript, 0, true);
WalterTools::ArgListType lst;
lst.push_back("1");
lst.push_back("2");
return perl.execute(lst);
}
bool testExecuteScriptWithArgs2(int argc, char *argv[])
{
try
{
WalterTools::CExecuterWithScript perl(m_szPerlScript, 0, true);
if (!perl.execute(argc, argv))
return false;
}catch(const std::exception &e)
{
fprintf(stderr, "Error: %s\n", e.what());
throw;
}
return true;
}
#include <stdio.h>
//BOOST_AUTO_TEST_CASE(test1)
//{
// BOOST_CHECK(testExecuteScript0());
// BOOST_CHECK(testExecuteScriptWithArgs());
// BOOST_CHECK(testExecuteScriptWithArgs2(boost::unit_test::framework::master_test_suite().argc,
// boost::unit_test::framework::master_test_suite().argv));
//}
BOOST_AUTO_TEST_CASE(test2)
{
//pwd > *
{
WalterTools::CExecuter shell;
BOOST_CHECK(shell.setExecuter("pwd"));
WalterTools::CExecuterData data;
BOOST_CHECK(shell.attachToOutput(data));
BOOST_CHECK(shell.execute());
std::string sOut;
data.getString(sOut);
fwrite(sOut.c_str(), sizeof(char), sOut.length(), stdout);
}
//find /usr/local/include -name "noncopyable.hpp" > /tmp/list.txt
{
WalterTools::CExecuter shell;
BOOST_CHECK(shell.setExecuter("find"));
WalterTools::ArgListType lst;
lst.push_back("/usr/local/include");
lst.push_back("-name");
lst.push_back("noncopyable.hpp"); //'"' must be removed!
BOOST_CHECK(shell.attachToOutput("/tmp/list.txt"));
BOOST_CHECK(shell.execute(lst));
}
//cat < /tmp/list.txt > /tmp/list2.txt
{
WalterTools::CExecuter shell;
BOOST_CHECK(shell.setExecuter("cat"));
BOOST_CHECK(shell.attachToInput("/tmp/list.txt"));
BOOST_CHECK(shell.attachToOutput("/tmp/list2.txt"));
BOOST_CHECK(shell.execute());
}
//grep "noncopyable" < /tmp/list2.txt
{
WalterTools::CExecuter shell;
BOOST_CHECK(shell.setExecuter("grep"));
WalterTools::ArgListType lst;
lst.push_back("noncopyable"); //'"' must be removed!
BOOST_CHECK(shell.attachToInput("/tmp/list2.txt"));
WalterTools::CExecuterData data;
BOOST_CHECK(shell.attachToOutput(data));
BOOST_REQUIRE(shell.execute(lst));
printf("%s\n", data.getData());
}
}
<file_sep># lib-wt-executer
Walter Tool for execution external process (execve in POSIX)
<file_sep>#ifndef _EXECUTER_H_
#define _EXECUTER_H_
#include <stdlib.h>
#include <string>
#include <list>
#include "executerdata.h"
namespace WalterTools
{
typedef std::string ArgType;
typedef std::list<ArgType> ArgListType;
class CExecuterPin;
class CExecuter
{
public:
explicit CExecuter(
const char *pszExecuter = NULL);
virtual ~CExecuter();
bool setExecuter(const char *pszExecuter);
const char *executer() const
{
return m_sExecuter.c_str();
}
virtual bool execute(const int &argc, char const * const * argv,
const size_t &nPassArgs = 1);
virtual bool execute();
virtual bool execute(const ArgListType &);
bool attachToInput(int fd);
bool attachToOutput(int fd);
bool attachToInput(CExecuterData &);
bool attachToOutput(CExecuterData &);
bool attachToInput(const char *pszFilePath);
bool attachToOutput(const char *pszFilePath);
protected:
bool executeI(ArgListType &);
int isInput() const
{
return m_pInput != NULL;
}
int isOutput() const
{
return m_pOutput != NULL;
}
virtual bool setupSignalsImpl(bool /*bSet*/){ return true; }
virtual bool setupSignalsForChildImpl(){ return true; }
private:
bool processInputForChild();
bool processOutputForChild();
bool processInput(bool bCloseOnly = false);
bool processOutput(bool bCloseOnly = false);
bool executeImpl(char ** ppszArgs);
std::string m_sExecuter;
CExecuterPin *m_pInput;
CExecuterPin *m_pOutput;
};
}
#endif //_EXECUTER_H_
<file_sep>#ifndef _EXECUTERWITHSCRIPT_H_
#define _EXECUTERWITHSCRIPT_H_
#include "executer.h"
#include "common/noncopyable.h"
namespace WalterTools
{
enum ScriptType
{
enScriptType_Unknown = 0,
enScriptType_Perl,
enScriptType_Shell,
};
class CExecuterWithScript: public CExecuter,
public boost::noncopyable
{
public:
explicit CExecuterWithScript(
const char *pScript, const size_t &sz = 0,
bool bReff2Data = false);
~CExecuterWithScript();
static ScriptType getScriptType(const unsigned char *pScript, const size_t &sz);
static ScriptType getScriptType(const char *pszPathToScript);
bool setScriptType(const ScriptType &);
const ScriptType &getScriptType() const
{
return m_nType;
}
bool setSeparatorForScriptArgs(const char *pszSeparatorForScriptArgs);
virtual bool execute(const int &argc, char const * const * argv,
const size_t &nPassArgs = 1);
virtual bool execute();
virtual bool execute(const ArgListType &);
protected:
virtual bool setupSignalsImpl(bool bSet);
virtual bool setupSignalsForChildImpl();
private:
static ScriptType getScriptType(std::string * pstrExecuter,
const char *pScript, const size_t &sz = 0);
bool execute2(const ArgListType &lstInArgs = ArgListType(),
const size_t &nArgc = 0, char const * const * pArgv = NULL,
const size_t &nPassArgs = 1, bool bParseArgsFromScript = true);
ScriptType m_nType;
std::string m_sSeparatorForScriptArgs;
CExecuterData *m_pInputScript;
};
}
#endif //_EXECUTERWITHSCRIPT_H_
<file_sep>#include "../executerdata.h"
#include <stdexcept>
#include <memory.h>
#include <assert.h>
namespace WalterTools
{
CExecuterData::CExecuterData(
unsigned char *pData /*= NULL*/,
const size_t &sz /*= 0*/,
bool bReff2Data /*= false*/):
m_pData(NULL),
m_sz(0),
m_bReff2Data(bReff2Data)
{
if (pData && sz)
{
if (!bReff2Data)
{
assert(sizeof(unsigned char) == 1);
m_pData = (unsigned char *)malloc(sz);
if (!m_pData)
throw std::bad_alloc();
memcpy(m_pData, pData, sz);
}else
{
m_pData = pData;
}
m_sz = sz;
}
}
CExecuterData::~CExecuterData()
{
if (!m_bReff2Data && m_pData)
free(m_pData);
}
bool CExecuterData::getString(std::string &strOut)
{
if (!m_pData || !m_sz)
return false;
strOut.assign((char *)m_pData, m_sz);
return !strOut.empty();
}
bool CExecuterData::getData(unsigned char *&pDataOut, size_t &szOut,
bool bCopy /*= false*/)
{
if (!m_pData || !m_sz)
return false;
if (bCopy)
{
assert(sizeof(unsigned char) == 1);
pDataOut = (unsigned char *)malloc(m_sz);
if (!pDataOut)
return false;
memcpy(m_pData, pDataOut, m_sz);
}else
{
pDataOut = m_pData;
}
szOut = m_sz;
return true;
}
}
<file_sep>#include "executer_p.h"
#include <stdexcept>
#include <memory.h>
#include <unistd.h>
#include <cstdio> //
#include <assert.h>
namespace WalterTools
{
char *copyStr(const char *pszData, const size_t &sz /*= 0*/)
{
if (!pszData)
return NULL;
size_t nSz = sz;
if (!nSz)
nSz = strlen(pszData);
if (!nSz)
return NULL;
char *pCopy = (char *)malloc(sizeof(char)*(nSz + 1));
if (!pCopy)
throw std::bad_alloc();
strncpy(pCopy, pszData, nSz);
pCopy[nSz] = 0;
return pCopy;
}
void copyStr(ArgType &str, const char *pszData, const size_t &sz /*= 0*/)
{
if (!pszData)
return;
size_t nSz = sz;
if (!nSz)
nSz = strlen(pszData);
if (!nSz)
return;
str.assign(pszData, nSz); //throw
}
bool saveArg(ArgListType &lst, const char *pszData, const size_t &sz /*= 0*/)
{
try
{
ArgType str;
copyStr(str, pszData, sz);
lst.push_back(str);
}catch(...)
{
return false;
}
return true;
}
/**
* @brief Convert list of argument to string array for 'exec(v)'.
* @warning Result array must be released by 'freeArgsArray' function
* @param[in] lst Input list
* @param[out] ppArray Output string array
* @return Return 'true' if success
*/
bool convertArgs2Array(ArgListType &lst, char **&ppArray)
{
if (lst.empty())
return false;
try
{
ppArray = (char **)malloc(sizeof(char*)*lst.size());
if (!ppArray)
throw std::bad_alloc();
char **ppArrayCur = ppArray;
for(auto it = lst.begin(); it != lst.end(); ++it)
{
(*ppArrayCur) = copyStr((*it).c_str());
ppArrayCur++;
}
}catch(...)
{
return false;
}
return true;
}
/**
* @brief Release string array created by 'convertArgs2Array'
* @param ppArray
*/
void freeArgsArray(char **&ppArray)
{
char **ppArrayCur = ppArray;
while(*ppArrayCur) free(*ppArrayCur++);
free(ppArray);
}
/**
* @brief Create list of arguments from command line arguments
* @param[in,out] lst
* @param[in] argc
* @param[in] argv
* @param[in] nPassArgs Add to list only the arguments after nPassArgs
* @return Return 'true' if success
*/
bool saveArgs(ArgListType &lst,
const int &argc, char const * const * argv,
const size_t &nPassArgs)
{
if (argc > 0 && argv)
{
for(int cArg = nPassArgs; cArg < argc; ++cArg)
{
if (!saveArg(lst, argv[cArg]))
return false;
}
}
return true;
}
/**
* @brief Find position in string following the set of characters
* A string which is searched is limited limited to fixed size
* (and standart end of C-string)
* @param[in] pData Input string
* @param[in] pArrayToNext Set of characters
* @param[in] sz Limit size
* @param[in] szToFind Size of the set of characters.
* If 0 uses 'strlen' to determinate size
* @return Found position or last character or 'NULL' (if error)
*/
const char *strNextAny(const char *pData, const char *pArrayToNext,
const size_t &sz, const size_t &szToFind /*= 0*/)
{
if (!pData || !*pData)
return NULL;
if (!pArrayToNext || !*pArrayToNext)
return NULL;
size_t szToFind2 = szToFind;
if (1 == szToFind2)
return NULL;
else if (szToFind2 > 0)
--szToFind2;
else if (!szToFind2)
szToFind2 = strlen(pArrayToNext);
size_t cCheckSZ = 0;
const char *pch = pData;
while(*pch &&
cCheckSZ++ < sz)
{
bool bFound = false;
size_t cNext = 0;
const char *pszCurr = pArrayToNext;
while(*pszCurr &&
cNext < szToFind2)
{
if (*pszCurr == *pch)
{
bFound = true;
break;
}
++pszCurr, ++cNext;
}
if (!bFound)
break;
++pch;
}
return pch;
}
const char *strStrAny(const char *pData, const char *pArrayToFind,
const size_t &sz, const size_t &szToFind /*= 0*/)
{
if (!pData || !*pData)
return NULL;
if (!pArrayToFind || !*pArrayToFind)
return NULL;
size_t szToFind2 = szToFind;
if (1 == szToFind2)
return NULL;
else if (szToFind2 > 0)
--szToFind2;
else if (!szToFind2)
szToFind2 = strlen(pArrayToFind);
bool bFound = false;
size_t cCheckSZ = 0;
const char *pch = pData;
while(*pch &&
cCheckSZ++ < sz)
{
size_t cNext = 0;
const char *pszCurr = pArrayToFind;
while(*pszCurr &&
cNext < szToFind2)
{
if (*pszCurr == *pch)
{
bFound = true;
break;
}
++pszCurr, ++cNext;
}
if (bFound)
break;
++pch;
}
if (!bFound)
return NULL;
return pch;
}
const char *strStr(const char *pData, const char *pToFind,
const size_t &sz, const size_t &szToFind /*= 0*/)
{
if (!pData || !*pData)
return NULL;
if (!pToFind || !*pToFind)
return NULL;
size_t szToFind2 = szToFind;
if (1 == szToFind2)
return NULL;
else if (szToFind2 > 0)
--szToFind2;
else if (!szToFind2)
szToFind2 = strlen(pToFind);
bool bFound = false;
size_t cCheckSZ = 0;
const char *pch = pData;
while(*pch &&
cCheckSZ++ < sz)
{
size_t cNext = 0;
const char *pszCurr = pch;
do
{
if (*pszCurr != pToFind[cNext])
break;
++cNext, ++pszCurr;
}while(*pszCurr &&
cCheckSZ++ < sz &&
cNext < szToFind2);
pch = pszCurr;
if(cNext == szToFind2)
{
bFound = true;
break;
}
++pch;
}
if (!bFound)
return NULL;
return pch;
}
const char *_szBinMark = "#!";
bool saveArgsFromScriptData(
ArgListType &lst,
const char *pszExecuter,
const char *pData, const size_t &sz)
{
if (!pszExecuter || !pData || !sz)
return false;
assert(sizeof(char) == 1);
size_t szOfBinMark = strlen(_szBinMark) + 1;
const char *pch = strStr (pData, _szBinMark, sz, szOfBinMark);
if (!pch)
return false;
pch = strStr (pch, pszExecuter, sz - (pch - pData));
if (!pch)
return false;
const char szDelimeters[] = " \t\n";
const char *pFStart = strNextAny (pch, szDelimeters, sz - (pch - pData), sizeof(szDelimeters)-1);
if (!pFStart)
return false;
while(NULL !=
(pch = strStrAny (pFStart, szDelimeters, sz - (pFStart - pData), sizeof(szDelimeters))))
{
const char *pFEnd = pch;
std::string strArg(pFStart, pFEnd-pFStart);
if (strArg.empty())
break;
lst.push_back(strArg);
pFStart = strNextAny (pFEnd, szDelimeters, sz - (pFEnd - pData), sizeof(szDelimeters)-1);
if (!pFStart)
return false;
if (*(pFStart) == '\n')
break;
}
return true;
}
}
<file_sep>#ifndef EXECUTERPIPE_H
#define EXECUTERPIPE_H
#include "executerpin.h"
namespace WalterTools
{
class CExecuterPipe: public CExecuterPin
{
protected:
explicit CExecuterPipe(int hFD0 = -1, int hFD1 = -1):
CExecuterPin(hFD0)
{
if (-1 != hFD1 && !initPipePin(hFD1))
throw std::logic_error("Invalid handle");
}
public:
bool initPipePin(int hFD)
{
if (hFD < 0)
return false;
m_hPipePin = hFD;
return true;
}
virtual bool isValid() const
{
return CExecuterPin::isValid() && m_hPipePin >= 0;
}
int hPipe() const
{
return m_hPipePin;
}
private:
int m_hPipePin;
};
}
#endif // EXECUTERPIPE_H
<file_sep>#ifndef _EXECUTER_P_H_
#define _EXECUTER_P_H_
#include "../executer_types.h"
namespace WalterTools
{
char *copyStr(const char *pszData, const size_t &sz = 0);
void copyStr(ArgType &str, const char *pszData, const size_t &sz = 0);
bool saveArg(ArgListType &lst, const char *pszData, const size_t &sz = 0);
bool convertArgs2Array(ArgListType &lst, char **&ppArray);
void freeArgsArray(char **&ppArray);
bool saveArgs(
ArgListType &lst,
const int &argc, char const * const * argv,
const size_t &nPassArgs);
const char *strStr(const char *pData, const char *pToFind,
const size_t &sz, const size_t &szToFind = 0);
const char *strStrAny(const char *pData, const char *pArrayToFind,
const size_t &sz, const size_t &szToFind = 0);
const char *strNextAny(const char *pData, const char *pArrayToNext,
const size_t &sz, const size_t &szToFind = 0);
extern const char *_szBinMark;
bool saveArgsFromScriptData(
ArgListType &lst,
const char *pszExecuter,
const char *pData, const size_t &sz);
bool writeAllTo(const int &hPipe, const unsigned char *pData, const size_t &sz,
const size_t &szOfChunk = 512);
bool readAllFrom(const int &hPipe, unsigned char *&pData, size_t &sz,
const size_t &szOfChunk = 512);
}
#endif //_EXECUTER_P_H_
<file_sep>#include "../executerwithscript.h"
#include <stdexcept>
#include <memory.h>
#include "executer_p.h"
#include <unistd.h>
#include <cstdio> //
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/types.h>
namespace WalterTools
{
CExecuterWithScript::CExecuterWithScript(
const char *pScript,
const size_t &sz /*= 0*/,
bool bReff2Data /*= false*/): CExecuter(),
m_nType(enScriptType_Unknown),
m_pInputScript(NULL)
{
if (!pScript || !*pScript)
throw std::logic_error("Invalid data 'script' for executer");
size_t szL = sz;
if (!szL)
szL = strlen(pScript);
std::string strExecuter;
m_nType = getScriptType(&strExecuter, pScript, szL);
if (!setExecuter(strExecuter.c_str()))
throw std::logic_error("Invalid executer from script");
if (enScriptType_Perl == m_nType)
{
if (!setSeparatorForScriptArgs("-"))
{
assert(false);
}
}
CExecuterData *pInput = new CExecuterData(
(unsigned char *)pScript, szL, bReff2Data);
if (!pInput)
throw std::bad_alloc();
if (!attachToInput(*pInput))
{
delete pInput;
throw std::logic_error("Can't attach to script data");
}
m_pInputScript = pInput;
}
CExecuterWithScript::~CExecuterWithScript()
{
if (m_pInputScript)
delete m_pInputScript;
}
ScriptType CExecuterWithScript::getScriptType(const unsigned char *pScript, const size_t &sz)
{
return getScriptType(NULL, (const char *)pScript, sz);
}
ScriptType CExecuterWithScript::getScriptType(const char *pszPathToScript)
{
assert(sizeof(char) == 1);
int fd = open(pszPathToScript, O_RDONLY);
if (-1 == fd)
{
perror("Can't open file.");
return enScriptType_Unknown;
}
const size_t nChunkBuffSz = 512;
char *pChunkBuff = (char *)malloc(nChunkBuffSz);
if (!pChunkBuff)
{
close(fd);
return enScriptType_Unknown;
}
size_t nBuffSz = nChunkBuffSz;
char *pBuff = pChunkBuff;
const char *pMarkStart = pBuff;
size_t nBinMarkSz = strlen(_szBinMark) + 1;
bool bFound = false;
int nCurr = 0;
size_t nReadSz = (size_t)nCurr;
do
{
nCurr = read(fd, pChunkBuff, nChunkBuffSz);
if (-1 == nCurr)
{
free(pChunkBuff);
break;
}else if (nCurr)
{
nReadSz += (size_t)nCurr;
size_t nTmp = nBuffSz - nChunkBuffSz + nReadSz;
const char *pch = pMarkStart;
pch = strStr (pch, _szBinMark, nTmp - (pch - pBuff), nBinMarkSz);
if (pch)
{
pMarkStart = pch;
pch = strStr (pch, "\n", nTmp - (pch - pBuff), 2);
if (pch)
{
bFound = true;
break;
}
}else
{
do
{
pch = strStr (pMarkStart, "\n", nTmp - (pch - pBuff), 2);
if (pch)
{
pMarkStart = pch;
}
}while(pch);
}
if (nReadSz >= nChunkBuffSz)
{
nReadSz = 0;
nBuffSz += nChunkBuffSz;
pBuff = (char *)realloc(pBuff, nBuffSz);
if (!pBuff)
{
free(pChunkBuff);
break;
}
}
pChunkBuff += nCurr;
}
}while(nCurr);
close(fd);
ScriptType nRet = enScriptType_Unknown;
if (bFound)
{
if (nReadSz > 0)
{
nReadSz = nBuffSz - nChunkBuffSz + nReadSz;
pBuff = (char *)realloc(pBuff, nReadSz);
if (!pBuff)
{
free(pChunkBuff);
return enScriptType_Unknown;
}
}else
{
nReadSz = nBuffSz;
}
nRet = getScriptType(NULL, pBuff, nReadSz);
}
free(pBuff);
return nRet;
}
ScriptType CExecuterWithScript::getScriptType(std::string * pstrExecuter,
const char *pScript, const size_t &sz /*= 0*/)
{
assert(sizeof(char) == 1);
if (!pScript || !*pScript)
return enScriptType_Unknown;
size_t szL = sz;
if (!szL)
szL = strlen(pScript);
size_t szOfBinMark = strlen(_szBinMark) + 1;
const char *pch = strStr (pScript, _szBinMark, szL, szOfBinMark);
if (!pch)
return enScriptType_Unknown;
const char szDelimeters[] = " \t\n";
const char *pFStart = pch;
const char *pFEnd = strStrAny (pch, szDelimeters, szL - (pch - pScript), sizeof(szDelimeters));
if (!pFEnd)
return enScriptType_Unknown;
std::string strExecuter;
strExecuter.assign(pFStart, pFEnd-pFStart);
assert(!strExecuter.empty());
if (pstrExecuter)
(*pstrExecuter) = strExecuter;
std::string strFilename;
std::string::size_type found = strExecuter.find_last_of("/");
if (std::string::npos != found)
{
strFilename = strExecuter.substr(found+1);
}else
{
strFilename = strExecuter;
}
if (!strFilename.compare("env"))
{
pFStart = strNextAny (pFEnd, szDelimeters, szL - (pFEnd - pScript), sizeof(szDelimeters)-1);
if (!pFStart)
return enScriptType_Unknown;
pFEnd = strStrAny (pFStart, szDelimeters, szL - (pFStart - pScript), sizeof(szDelimeters));
if (!pFEnd)
return enScriptType_Unknown;
strExecuter.assign(pFStart, pFEnd-pFStart);
assert(!strExecuter.empty());
if (pstrExecuter)
(*pstrExecuter) = strExecuter;
std::string::size_type found = strExecuter.find_last_of("/");
if (std::string::npos != found)
{
strFilename = strExecuter.substr(found+1);
}else
{
strFilename = strExecuter;
}
}
if (!strFilename.compare("bash") ||
!strFilename.compare("sh"))
{
return enScriptType_Shell;
}else if(!strFilename.find("perl"))
{
return enScriptType_Perl;
}
return enScriptType_Unknown;
}
bool CExecuterWithScript::setScriptType(const ScriptType &nType)
{
if (enScriptType_Unknown == nType)
return false;
m_nType = nType;
return true;
}
bool CExecuterWithScript::setSeparatorForScriptArgs(const char *pszSeparatorForScriptArgs)
{
if (!pszSeparatorForScriptArgs || !*pszSeparatorForScriptArgs)
return false;
m_sSeparatorForScriptArgs.assign(pszSeparatorForScriptArgs);
return true;
}
bool CExecuterWithScript::execute(
const int &argc, char const * const * argv,
const size_t &nPassArgs /*= 1*/)
{
if (enScriptType_Unknown == getScriptType())
return false;
if (!isInput() && m_pInputScript)
{
if (!attachToInput(*m_pInputScript))
return false;
}
return execute2(ArgListType(), argc, argv, nPassArgs);
}
bool CExecuterWithScript::execute()
{
if (enScriptType_Unknown == getScriptType())
return false;
if (!isInput() && m_pInputScript)
{
if (!attachToInput(*m_pInputScript))
return false;
}
return execute2();
}
bool CExecuterWithScript::execute(const ArgListType &lstExportArgs)
{
if (enScriptType_Unknown == getScriptType())
return false;
if (!isInput() && m_pInputScript)
{
if (!attachToInput(*m_pInputScript))
return false;
}
return execute2(lstExportArgs);
}
bool CExecuterWithScript::execute2(
const ArgListType &lstExportArgs /*= ArgListType()*/,
const size_t &nArgc /* = 0*/, char const * const * pArgv /*= NULL*/,
const size_t &nPassArgs /*= 1*/, bool bParseArgsFromScript /*= true*/)
{
ArgListType lstArgs;
if (!saveArg(lstArgs, executer()))
return false;
if (bParseArgsFromScript)
{
const size_t HEADER_MAX_SIZE = 1024;
assert(m_pInputScript != NULL);
if (!saveArgsFromScriptData(
lstArgs,
executer(),
m_pInputScript->getData(),
(m_pInputScript->getSize() > HEADER_MAX_SIZE)?HEADER_MAX_SIZE:m_pInputScript->getSize()))
return false;
}
auto itInsert = lstArgs.begin();
for(auto it = lstExportArgs.begin(); it != lstExportArgs.end(); ++it)
{
lstArgs.push_back(*it);
if (lstArgs.begin() == itInsert)
itInsert = --(lstArgs.end());
}
if (nArgc > 0 && pArgv &&
nArgc > nPassArgs)
{
if (lstArgs.begin() == itInsert)
itInsert = --(lstArgs.end());
if (!saveArgs(lstArgs,
nArgc, pArgv, nPassArgs))
return false;
++itInsert;
}
if (lstArgs.begin() != itInsert &&
!m_sSeparatorForScriptArgs.empty())
{
lstArgs.insert(itInsert, m_sSeparatorForScriptArgs);
}
return CExecuter::executeI(lstArgs);
}
bool CExecuterWithScript::setupSignalsImpl(bool bSet)
{
// if (SIG_ERR == signal(SIGINT, (bSet)?SIG_IGN:SIG_DFL))
// {
// perror("While setup SIGINT");
// return false;
// }
// if (SIG_ERR == signal(SIGQUIT, (bSet)?SIG_IGN:SIG_DFL))
// {
// perror("While setup SIGQUIT");
// return false;
// }
if (SIG_ERR == signal(SIGPIPE, (bSet)?SIG_IGN:SIG_DFL))
{
perror("While setup SIGPIPE");
return false;
}
return true;
}
bool CExecuterWithScript::setupSignalsForChildImpl() //child inherit signal processors?
{
// if (SIG_ERR == signal(SIGINT, SIG_DFL))
// {
// perror("While setup SIGINT");
// return false;
// }
// if (SIG_ERR == signal(SIGQUIT, SIG_DFL))
// {
// perror("While setup SIGQUIT");
// return false;
// }
return true;
}
}
<file_sep>#include "executerpipedata.h"
#include <stdexcept>
#include <memory.h>
#include <assert.h>
#include <unistd.h>
#include <cstdio> //
namespace WalterTools
{
CExecuterPipeData::CExecuterPipeData(
CExecuterData &data,
int hFD0 /*= -1*/,
int hFD1 /*= -1*/): CExecuterPipe(hFD0, hFD1),
m_rData(data)
{
}
bool CExecuterPipeData::writeAllToPipe(
const size_t &szOfChunk /*= 512*/)
{
if (!isValid())
return false;
if (!data().m_pData || !data().m_sz)
return false;
int nCurr = 0;
int nChunk = szOfChunk;
while(nCurr < (int)data().m_sz)
{
if (nCurr + nChunk > (int)data().m_sz)
nChunk = data().m_sz - nCurr;
int nCurrChunk = write(hPipe(), data().m_pData, nChunk);
if (-1 == nCurrChunk)
return false;
nCurr += nCurrChunk;
data().m_pData += nCurrChunk;
}
return true;
}
bool CExecuterPipeData::readAllFromPipe(
const size_t &szOfChunk /*= 512*/)
{
if (!isValid())
return false;
assert(sizeof(unsigned char) == 1);
size_t nBuffSz = szOfChunk;
unsigned char *pBuffData = (unsigned char *)malloc(nBuffSz);
if (!pBuffData)
return false;
data().m_pData = pBuffData;
int nCurr = 0;
size_t nSz = (size_t)nCurr;
do
{
nCurr = read(hPipe(), pBuffData, szOfChunk);
if (-1 == nCurr)
{
free(pBuffData);
return false;
}else if (nCurr)
{
nSz += (size_t)nCurr;
if (nSz >= nBuffSz)
{
nBuffSz += szOfChunk;
data().m_pData = (unsigned char *)realloc(data().m_pData, nBuffSz);
if (!data().m_pData)
{
free(pBuffData);
return false;
}
}
pBuffData += nCurr;
}
}while(nCurr);
if (nSz > 0)
{
data().m_pData = (unsigned char *)realloc(data().m_pData, nSz);
if (!data().m_pData)
{
free(pBuffData);
return false;
}
data().m_sz = nSz;
}else /*No data*/
{
free(data().m_pData);
data().m_pData = NULL;
data().m_sz = 0;
}
return true;
}
}
<file_sep>#ifndef _EXECUTER_TYPES_H_
#define _EXECUTER_TYPES_H_
#include <string>
#include <list>
namespace WalterTools
{
typedef std::string ArgType;
typedef std::list<ArgType> ArgListType;
}
#endif //_EXECUTER_TYPES_H_
<file_sep>#ifndef _EXECUTEPIPEDATA_H_
#define _EXECUTEPIPEDATA_H_
#include "executerpipe.h"
#include "../executerdata.h"
namespace WalterTools
{
class CExecuterPipeData:
public CExecuterPipe,
public boost::noncopyable
{
public:
explicit CExecuterPipeData(
CExecuterData &,
int hFD0 = -1, int hFD1 = -1);
const CExecuterData &data() const
{
return m_rData;
}
bool writeAllToPipe(const size_t &szOfChunk = 512);
bool readAllFromPipe(const size_t &szOfChunk = 512);
private:
CExecuterData &data()
{
return m_rData;
}
CExecuterData &m_rData;
};
}
#endif //_EXECUTEPIPEDATA_H_
<file_sep>#ifndef EXECUTERPIPEFILE_H
#define EXECUTERPIPEFILE_H
#include "executerpipe.h"
namespace WalterTools
{
class CExecuterPipeFile: public CExecuterPipe
{
public:
explicit CExecuterPipeFile(int hFile,
int hFD0 = -1, int hFD1 = -1);
virtual ~CExecuterPipeFile();
bool writeFileToPipe(const size_t &szOfChunk = 512);
bool readFileFromPipe(const size_t &szOfChunk = 512);
private:
bool readFrom_writeTo(int h0, int h1,
const size_t &szOfChunk);
int m_hFile;
};
}
#endif // EXECUTERPIPEFILE_H
<file_sep>#ifndef EXECUTERPIN_H
#define EXECUTERPIN_H
#include <stdexcept>
namespace WalterTools
{
class CExecuterPin
{
public:
explicit CExecuterPin(int hFD = -1)
{
if (-1 != hFD && !initPin(hFD))
throw std::logic_error("Invalid handle");
}
virtual ~CExecuterPin(){}
bool initPin(int hFD)
{
if (hFD < 0)
return false;
m_hPin = hFD;
return true;
}
virtual bool isValid() const
{
return m_hPin >=0;
}
int hPin() const
{
return m_hPin;
}
private:
int m_hPin;
};
}
#endif // EXECUTERPIN_H
<file_sep>#ifndef EXECUTERDATA_H
#define EXECUTERDATA_H
#include <stdlib.h>
#include "common/noncopyable.h"
#include <string>
namespace WalterTools
{
class CExecuterPipeData;
class CExecuterData:
public boost::noncopyable
{
friend class CExecuterPipeData;
public:
explicit CExecuterData(
unsigned char *pData = NULL,
const size_t &sz = 0,
bool bReff2Data = false);
virtual ~CExecuterData();
bool getData(unsigned char *&pDataOut, size_t &szOut,
bool bCopy = false);
bool getString(std::string &);
const char *getData() const
{
return (const char *)m_pData;
}
size_t getSize() const
{
return m_sz;
}
private:
unsigned char *m_pData;
size_t m_sz;
bool m_bReff2Data;
};
}
#endif // EXECUTERDATA_H
<file_sep>#include "executerpipefile.h"
#include <stdexcept>
#include <memory.h>
#include <assert.h>
#include <unistd.h>
#include <cstdio> //
namespace WalterTools
{
CExecuterPipeFile::CExecuterPipeFile(int hFile,
int hFD0 /*= -1*/, int hFD1 /*= -1*/):
CExecuterPipe(hFD0, hFD1), m_hFile(hFile)
{
if (-1 == hFile)
throw std::logic_error("Invalid handle");
}
CExecuterPipeFile::~CExecuterPipeFile()
{
close(m_hFile);
}
bool CExecuterPipeFile::writeFileToPipe(const size_t &szOfChunk /*= 512*/)
{
return readFrom_writeTo(m_hFile, hPipe(), szOfChunk);
}
bool CExecuterPipeFile::readFileFromPipe(const size_t &szOfChunk /*= 512*/)
{
return readFrom_writeTo(hPipe(), m_hFile, szOfChunk);
}
bool CExecuterPipeFile::readFrom_writeTo(int h0, int h1,
const size_t &szOfChunk)
{
if (!isValid())
return false;
unsigned char *pBuffData = (unsigned char *)malloc(szOfChunk);
if (!pBuffData)
return false;
int nCurrRD = 0;
do
{
nCurrRD = read(h0, pBuffData, szOfChunk);
if (-1 == nCurrRD)
{
free(pBuffData);
return false;
}else if (nCurrRD)
{
if (nCurrRD < (int)szOfChunk)
{
unsigned char *pData = (unsigned char *)realloc(pBuffData, nCurrRD);
if (!pData)
{
free(pBuffData);
return false;
}else
pBuffData = pData;
}
int nCurrWD = write(h1, pBuffData, nCurrRD);
if (-1 == nCurrWD)
{
free(pBuffData);
return false;
}
}
}while(nCurrRD);
free(pBuffData);
return true;
}
}
<file_sep>#include "../executer.h"
#include <stdexcept>
#include <memory.h>
#include "executer_p.h"
#include <unistd.h>
#include <cstdio>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h> //stderr
#include "executerpin.h"
#include "executerpipe.h"
#include "executerpipedata.h"
#include "executerpipefile.h"
namespace WalterTools
{
CExecuter::CExecuter(const char *pszExecuter /* = NULL*/):
m_pInput(NULL),
m_pOutput(NULL)
{
if (pszExecuter && *pszExecuter)
m_sExecuter.assign(pszExecuter);
}
CExecuter::~CExecuter()
{
if (m_pInput)
{
delete m_pInput;
m_pInput = NULL;
}
if (m_pOutput)
{
delete m_pOutput;
m_pOutput = NULL;
}
}
bool CExecuter::setExecuter(const char *pszExecuter)
{
if (!pszExecuter || !*pszExecuter)
return false;
m_sExecuter.assign(pszExecuter);
return true;
}
bool CExecuter::execute(
const int &argc, char const * const * argv,
const size_t &nPassArgs /*= 1*/)
{
ArgListType lstArgs;
lstArgs.push_back(m_sExecuter);
if (!saveArgs(lstArgs, argc, argv, nPassArgs))
return false;
return executeI(lstArgs);
}
bool CExecuter::execute()
{
ArgListType lstArgs;
lstArgs.push_back(m_sExecuter);
return executeI(lstArgs);
}
bool CExecuter::execute(const ArgListType &lstInArgs)
{
if (lstInArgs.empty())
return execute();
ArgListType lstArgs(lstInArgs);
lstArgs.push_front(m_sExecuter);
return executeI(lstArgs);
}
bool CExecuter::attachToInput(int fd)
{
if (fd < 0 ||
isInput())
return false;
int aH[2];
if (-1 == pipe(aH))
{
perror("Error");
return false;
}
CExecuterPipeFile *pImpl = NULL;
try
{
pImpl = new CExecuterPipeFile(fd, aH[0], aH[1]);
if (!pImpl)
throw std::bad_alloc();
}
catch(const std::exception &err)
{
close(aH[0]);
close(aH[1]);
fprintf(stderr, "%s", err.what());
return false;
}
m_pInput = pImpl;
return true;
}
bool CExecuter::attachToOutput(int fd)
{
if (fd < 0 ||
isOutput())
return false;
CExecuterPin *pImpl = NULL;
try
{
pImpl = new CExecuterPin(fd);
if (!pImpl)
throw std::bad_alloc();
}
catch(const std::exception &err)
{
fprintf(stderr, "%s", err.what());
return false;
}
m_pOutput = pImpl;
return true;
}
bool CExecuter::attachToInput(const char *pszFilePath)
{
if (!pszFilePath || !*pszFilePath)
return false;
int fd = open(pszFilePath, O_RDONLY);
if (-1 == fd)
{
perror("Can't open file.");
return false;
}
if (!attachToInput(fd))
{
close(fd);
return false;
}else
{
return true;
}
}
bool CExecuter::attachToOutput(const char *pszFilePath)
{
if (!pszFilePath || !*pszFilePath)
return false;
int fd = creat(pszFilePath, 0644);
if (-1 == fd)
{
perror("Can't create file.");
return false;
}
if (!attachToOutput(fd))
{
close(fd);
return false;
}else
{
return true;
}
}
bool CExecuter::attachToInput(CExecuterData &objInput)
{
if (isInput())
return false;
int aH[2];
if (-1 == pipe(aH))
{
perror("Error");
return false;
}
CExecuterPipeData *pImpl = NULL;
try
{
pImpl = new CExecuterPipeData(objInput, aH[0], aH[1]);
if (!pImpl)
throw std::bad_alloc();
}
catch(const std::exception &err)
{
close(aH[0]);
close(aH[1]);
fprintf(stderr, "%s", err.what());
return false;
}
m_pInput = pImpl;
return true;
}
bool CExecuter::attachToOutput(CExecuterData &objOutput)
{
if (isOutput())
return false;
int aH[2];
if (-1 == pipe(aH))
{
perror("Error");
return false;
}
CExecuterPipeData *pImpl = NULL;
try
{
pImpl = new CExecuterPipeData(objOutput, aH[1], aH[0]);
if (!pImpl)
throw std::bad_alloc();
}
catch(const std::exception &err)
{
close(aH[0]);
close(aH[1]);
fprintf(stderr, "%s", err.what());
return false;
}
m_pOutput = pImpl;
return true;
}
bool CExecuter::executeI(ArgListType &lstArgs)
{
if (lstArgs.empty())
return false;
if (!saveArg(lstArgs, NULL))
return false;
char **ppArgs = NULL;
if (!convertArgs2Array(lstArgs, ppArgs))
return false;
if (!setupSignalsImpl(true))
{
freeArgsArray(ppArgs);
setupSignalsImpl(false);
return false;
}
bool bResult = executeImpl(ppArgs);
freeArgsArray(ppArgs);
setupSignalsImpl(false);
return bResult;
}
bool CExecuter::processInputForChild()
{
if (!m_pInput)
return true;
if (!m_pInput->isValid())
return false;
bool bRet = true;
CExecuterPipe *pInputPipe = dynamic_cast<CExecuterPipe *>(m_pInput);
if (pInputPipe)
{
close(pInputPipe->hPipe());
}
if (-1 == dup2(m_pInput->hPin(), 0))
{
perror("Error");
bRet = false;
}
close(m_pInput->hPin());
return bRet;
}
bool CExecuter::processOutputForChild()
{
if (!m_pOutput)
return true;
if (!m_pOutput->isValid())
return false;
bool bRet = true;
CExecuterPipe *pOutputPipe = dynamic_cast<CExecuterPipe *>(m_pOutput);
if (pOutputPipe)
{
close(pOutputPipe->hPipe());
}
if (-1 == dup2(m_pOutput->hPin(), 1))
{
perror("Error");
bRet = false;
}
close(m_pOutput->hPin());
return bRet;
}
bool CExecuter::processInput(bool bCloseOnly /*= false*/)
{
if (!m_pInput)
return true;
if (!m_pInput->isValid())
return false;
close(m_pInput->hPin());
bool bRet = true;
CExecuterPipe *pInputPipe = dynamic_cast<CExecuterPipe *>(m_pInput);
if (pInputPipe)
{
if (!bCloseOnly)
{
CExecuterPipeData *pInputPipeData = dynamic_cast<CExecuterPipeData *>(pInputPipe);
if (pInputPipeData)
{
if (!pInputPipeData->writeAllToPipe())
{
perror("Can't write data to pipe");
bRet = false;
}
}else
{
CExecuterPipeFile *pInputPipeFile = dynamic_cast<CExecuterPipeFile *>(pInputPipe);
if (pInputPipeFile &&
!pInputPipeFile->writeFileToPipe())
{
perror("Can't read file to pipe");
bRet = false;
}
}
}
close(pInputPipe->hPipe());
}
return bRet;
}
bool CExecuter::processOutput(bool bCloseOnly /*= false*/)
{
if (!m_pOutput)
return true;
if (!m_pOutput->isValid())
return false;
close(m_pOutput->hPin());
bool bRet = true;
CExecuterPipe *pOutputPipe = dynamic_cast<CExecuterPipe *>(m_pOutput);
if (pOutputPipe)
{
if (!bCloseOnly)
{
CExecuterPipeData *pOutputPipeData = dynamic_cast<CExecuterPipeData *>(pOutputPipe);
if (pOutputPipeData &&
!pOutputPipeData->readAllFromPipe())
{
perror("Can't read data from pipe");
bRet = false;
}
}
close(pOutputPipe->hPipe());
}
return bRet;
}
bool CExecuter::executeImpl(char ** ppszArgs)
{
if (!ppszArgs)
return false;
enum
{
enChildRetCode_InitializeSignal = 1,
enChildRetCode_ErrorInput,
enChildRetCode_ErrorOutput,
enChildRetCode_ErrorExecute,
};
int pid = fork();
switch(pid)
{
case -1:
{
perror("Error");
return false;
}
case 0:
{
if (!setupSignalsForChildImpl())
exit((int)enChildRetCode_InitializeSignal);
if (!processInputForChild())
exit((int)enChildRetCode_ErrorInput);
if (!processOutputForChild())
exit((int)enChildRetCode_ErrorOutput);
if (-1 == execvp(ppszArgs[0], ppszArgs))
{
perror("Error");
}
exit((int)enChildRetCode_ErrorExecute);
}
default:;
}
bool bRet = true;
if (!processInput(!bRet))
{
kill(pid, SIGKILL);
bRet = false;
}
if (!processOutput(!bRet))
{
kill(pid, SIGKILL);
bRet = false;
}
if (m_pInput)
{
delete m_pInput;
m_pInput = NULL;
}
if (m_pOutput)
{
delete m_pOutput;
m_pOutput = NULL;
}
int statusPID = 0;
if (-1 == waitpid(pid, &statusPID, 0) && bRet)
{
perror("Error");
kill(pid, SIGKILL);
bRet = false;
}
int nRet = 0;
if (bRet)
{
if (WIFEXITED(statusPID))
{
nRet = WEXITSTATUS(statusPID);
if (nRet)
fprintf(stderr, "Executer exited by %d", nRet);
}else
{
bRet = false;
nRet = WTERMSIG(statusPID);
if (nRet)
fprintf(stderr, "Executer terminated by %d", nRet);
else
fprintf(stderr, "Executer terminated");
}
}
return bRet && !nRet;
}
}
<file_sep>/* C includes here */
#include <stdlib.h>
#include <string.h>
#if defined __cplusplus
/* C++ includes here */
#include <string>
#define BOOST_TEST_MODULE WTExecuter
#include <boost/test/included/unit_test.hpp>
#endif
| 74213ae78e4b536ff242c4e913d65a5e6337cd3f | [
"Markdown",
"C++"
] | 18 | C++ | Andrei-Masilevich/wt-executer | 98d14602837a8508b88fb0e764eadb60c8494e38 | a02bccc666b89a700e913927e4eae07cbd72465d |
refs/heads/master | <file_sep><?php
error_reporting (E_ALL & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if(isset($_SESSION['id'])){
ECHO "<script language=JavaScript>window.location='index.php';</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ##########universales###### -->
<meta charset="UTF-8">
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- ######Propios########3 -->
<title>Crear Cuenta</title>
</head>
<body>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////MENU///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.php">lOGO</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="../index.php"><span class="glyphicon glyphicon-home"></span> Inicio</a></li>
<li><a href="#">Productos</a></li>
<li><a href="#">Servicios</a></li>
<li><a href="#">Conocenos</a></li>
<li><a href="contacto.php">Contacto</a></li>
<!-- ###################Sessiones################### -->
<?php
if(!isset($_SESSION['id'])){
echo '<li><a href="login.php">Iniciar Sesion</a></li>';
echo '<li><a href="cuenta.php">Crear Cuenta</a></li>';
}else{
echo '<li class="dropdown">';
echo '<a href="#" id="sesionuser"class="dropdown-toggle" data-toggle="dropdown" role="button">';
echo $_SESSION['nombre']." ";
echo '<span class="caret"></span>';
echo '</a>';
echo '<ul class="dropdown-menu">';
echo '<li><a href="#">Cerrar Sesion</a></li>';
echo '</ul>';
echo '</li>';
}
?>
<!--################### Sesiones ################-->
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////FIN-MENU///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////BODY///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="row" id="txt">
</div>
<form id="cliente" >
<div class="form-group row">
<div class="col-md-3">
<label for="correo">Correo</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" name="correo" id="correo" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="contrasena">Contraseña</label>
</div>
<div class="col-md-9">
<input type="password" class="form-control" name="contrasena" id="contrasena" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="confirm-contrasena">Confirmar Contraseña</label>
</div>
<div class="col-md-9">
<input type="password" class="form-control" name="contrasena1" id="confirm_contrasena" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="nombres">Nombre(s)</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" name="nombres" id="nombres" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="apellidos">Apellidos</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" name="apellidos" id="apellidos" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="telefono">Telefono</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" name="telefono" id="telefono" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="telefono_adicional">Tel. Adicional</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" name="telefono_adicional" id="telefono_adicional" required>
</div>
</div>
</form>
<div class="form-group row">
<div class="checkbox col-md-8">
<label>
<input type="checkbox" value="1" id="terminos_y_condiciones">
Acepto los termino y condiciones
</label>
</div>
<div class="col-xs-4">
<button class="btn btn-primary pull-right" id="cliente_nuevo">Crear Cuenta</button>
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</div>
<!-- ##################################################################################### -->
<!-- //////////////////////////////////FIN-BODY/////////////////////////////////////////// -->
<!-- ##################################################################################### -->
<!-- ##################################################################################### -->
<!-- ////////////////////////////MODAL CREAR CUENTA/////////////////////////////////////// -->
<!-- ##################################################################################### -->
<div class="modal fade" id="ModalCuentaNueva" role="dialog" >
<div class="modal-dialog modal-md" id="contenido">
<div class="modal-content">
<div class="modal-header">
<!-- <button type="button" class="close" data-dismiss="modal">×</button> -->
<h4 class="modal-title">Felicidades</h4>
<br>
<div></div>
</div>
<div class="modal-body">
<p>
Se te ha enviado un correo, por favor verificalo para confirmar la cuenta.
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="index" data-dismiss="modal" onclick="index();">Aceptar</button>
</div>
</div>
</div>
</div>
<!-- ###################################################################################### -->
<!-- //////////////////////// FIN MODAL CREAR CUENTA/////////////////////////////////////// -->
<!-- ###################################################################################### -->
<script src="../jquery/jquery-2.1.3.min.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>
<script src="../jquery/abc.js"></script>
</body>
</html><file_sep># MacroSign
Desarrollo del software Web para la empresa MAcroSing Version 1
<file_sep>$(document).ready(function(){
$('#sing').click(function(){
var user = $("#usuario").val();
var pass = $("#password").val();
if( user =="" || pass =="" ){
// alert("hola");
$("div#txt").html("Todos los datos son requeridos.");
}else{
var datos = $("form#formSesion").serialize();
$.ajax({ //inicio ajax
url: "../PHP/modInSesion.php",
type: "POST",
data: datos,
dataType: "json",
success: function(cJson){
if(cJson.id == "no"){
$("div#txt").html("Usuario o Contraseña incorrecto.");
}else{
console.log(cJson)
$('#ModalIndex').modal('show'); // Hace que el modal aparesca
$('#nombreuser').html('<h4>'+ cJson.nombre +' '+ cJson.apellido +'</h4>');
}
},
}); // fin ajax
}
});
$('#aceptar').click(function(){
window.location='../index.php';
});
});
<file_sep><?php
error_reporting (E_ALL & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if(isset($_SESSION['id'])){
ECHO "<script language=JavaScript>window.location='index.php';</script>";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<!-- ##########universales###### -->
<meta charset="UTF-8">
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- #########´propios########### -->
<!-- <link rel="stylesheet" type="text/css" href="css/login.css"> -->
<title>Inicio de Usuarios</title>
</head>
<body>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////MENU///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.php">lOGO</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="../index.php"><span class="glyphicon glyphicon-home"></span> Inicio</a></li>
<li><a href="#">Productos</a></li>
<li><a href="#">Servicios</a></li>
<li><a href="#">Conocenos</a></li>
<li><a href="contacto.php">Contacto</a></li>
<!-- ###################Sessiones################### -->
<?php
if(!isset($_SESSION['id'])){
echo '<li><a href="login.php">Iniciar Sesion</a></li>';
echo '<li><a href="cuenta.php">Crear Cuenta</a></li>';
}else{
echo '<li class="dropdown">';
echo '<a href="#" id="sesionuser"class="dropdown-toggle" data-toggle="dropdown" role="button">';
echo $_SESSION['nombre']." ";
echo '<span class="caret"></span>';
echo '</a>';
echo '<ul class="dropdown-menu">';
echo '<li><a href="#">Cerrar Sesion</a></li>';
echo '</ul>';
echo '</li>';
}
?>
<!--################### Sesiones ################-->
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////FIN-MENU///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////BODY///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<div class="container">
<p><br/></p>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="panel panel-info">
<div class="panel-body">
<div class="page-header">
<h3>Bienvenido</h3>
</div>
<div id="txt"></div>
<form role="form" id="formSesion">
<div class="form-group">
<label for="usuario">Correo</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="usuario" name="correo" placeholder="Correo">
</div>
</div>
<div class="form-group">
<label for="password">Contraseña</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" name="pass" id="password" placeholder="<PASSWORD>">
</div>
</div>
<hr/>
</form>
<button class="btn btn-primary" id="sing" ><span class=""></span>Ingresar</button>
</div>
</div>
</div>
</div>
</div>
<!-- modal index -->
<div class="modal fade" id="ModalIndex" role="dialog" >
<div class="modal-dialog modal-sm" id="contenido">
<div class="modal-content">
<div class="modal-header">
<!-- <button type="button" class="close" data-dismiss="modal">×</button> -->
<h4 class="modal-title">Bienvenido</h4>
<br>
<div id="nombreuser"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="aceptar" data-dismiss="modal">Aceptar</button>
</div>
</div>
</div>
</div>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////FIN-BODY///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<script src="../jquery/jquery-2.1.3.min.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>
<script src="../jquery/login.js"></script>
</body>
</html><file_sep><?php
include("conexion.php");
$conn = conectar();
$nombre = $_POST['nombre'];
$imagen = $_POST['imagen'];
$descripcion = $_POST['descripcion'];
$estado = $_POST['estado'];
if($estado!="1"){
$estado =2;
}else{
$estado =1;
}
$sql = "INSERT INTO productos VALUES ('','$nombre','$imagen','$descripcion','$estado')";
$result = @mysql_query($sql,$conn) or die(mysql_error());
if (!$result) {
echo "Fallo al insertar datos: (" . $mysqli->errno . ") " . $mysqli->error;
}else{
echo "Guardado Exitosamente";
//echo "<script language=JavaScript>window.location='../../contrato/nuevocontrato.php?id_cliente=".$id."';</script>";
}
mysql_close($conn);
?><file_sep><?php
error_reporting (E_ALL & ~E_NOTICE & ~E_DEPRECATED);
session_start();
session_unset();
session_destroy();
echo "<script language='javascript'>alert('Sesion Cerrada.')</script>";
echo "<script language=JavaScript>window.location='../index.php'</script>";
?><file_sep>$(document).ready(function(){
///Dirigir al index///
////Alta de usuario Cliente
$('#cliente_nuevo').click(function(){
var correo = $("#correo").val();
var pass = $("#contrasena").val();
var pass2 = $("#confirm_contrasena").val();
var nombres = $("#nombres").val();
var apellidos = $("#apellidos").val();
var telefono = $("#telefono").val();
var telefono2 = $("#telefono_adicional").val();
if( correo =="" || pass =="" || pass2=="" || nombres=="" || apellidos =="" || telefono =="" || telefono2=="" ){
$("div#txt").html("<div class='alert alert-danger'>Todos los campos son requeridos</div>");
return false;
}else{
if (pass != pass2) {
$("div#txt").html("<div class='alert alert-danger'>Las Contraseña no coinciden</div>");
return false;
}else{
if(correo.indexOf('@', 0) == -1 || correo.indexOf('.', 0) == -1){
$("div#txt").html("<div class='alert alert-danger'>Ingresa un correo valido</div>");
return false;
}else{
var datos = $("form#cliente").serialize();
$.ajax({ //inicio ajax
url: "../PHP/ModInsertCliente.php",
type: "POST",
data: datos,
success: function(data){
console.log("Se esta generando la consulta");
$('#ModalCuentaNueva').modal('show');
},
}); // fin ajax
}
}
}
});
});
//////Alta de producto////////////
function altaproducto(){
var datos = $("form#producto").serialize();
$.ajax({ //inicio ajax
url: "../PHP/ModInsertProducto.php",
type: "POST",
data: datos,
success: function(data){
console.log("Se esta generando la consulta");
$('#ModalGuardardo').modal('show');
// mostrarproducto();
// $('#Modal1').modal('hide');
// $("#producto").val("");
// $("#precio").val("");
},
}); // fin ajax
};
function index(){
window.location='../index.php';
}<file_sep><?php
error_reporting (E_ALL & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if(!isset($_SESSION['id'])){
//mostrar modal
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ##########universales###### -->
<meta charset="UTF-8">
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- ##########Propios############ -->
<link rel="stylesheet" type="text/css" href="../css/login.css">
<link rel="stylesheet" href="../css/contacto.css">
<title>MacroSign</title>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.php">lOGO</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="../index.php"><span class="glyphicon glyphicon-home"></span> Inicio</a></li>
<li><a href="#">Productos</a></li>
<li><a href="#">Servicios</a></li>
<li><a href="#">Conocenos</a></li>
<li><a href="contacto.php">Contacto</a></li>
<!-- ###################Sessiones################### -->
<?php
if(!isset($_SESSION['id'])){
echo '<li><a href="login.php">Iniciar Sesion</a></li>';
echo '<li><a href="cuenta.php">Crear Cuenta</a></li>';
}else{
echo '<li class="dropdown">';
echo '<a href="#" id="sesionuser"class="dropdown-toggle" data-toggle="dropdown" role="button">';
echo $_SESSION['nombre']." ";
echo '<span class="caret"></span>';
echo '</a>';
echo '<ul class="dropdown-menu">';
echo '<li><a href="#">Cerrar Sesion</a></li>';
echo '</ul>';
echo '</li>';
}
?>
<!--################### Sesiones ################-->
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////FIN-MENU///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////BODY///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<div class="container">
<div class="page-header" id="encabezado">
<h1>Contacto.</h1>
</div>
<!-- ############################################################ -->
<!-- #########################Datos############################## -->
<!-- ############################################################ -->
<div class="row" id="datosgen">
<div id="datostd">
<div class="row" id="id">
<div class="col-md-9" id="datos1">
<div class="row" id="id1">
<div class="col-md-4 col-sm-4 col-xs-4" >
<ul id="lista1">
<li><p><strong>MacroSign</strong></p></li>
<li><p><strong>Direccion</strong></p></li>
<li><p><strong>Telefonos</strong></p></li>
<li><p><strong>Horario de<br>atencion</strong></p></li>
</ul>
</div>
<div class="col-md-8 col-sm-8 col-xs-8" id="id2">
<ul id="lista2">
<li><p>Creamos Infinidad de Ideas</p></li>
<li><p>Calle 105 #443D x 52A y 54 Col. Dolores Otero</p></li>
<li><p>Tel. (992)2-72-04-74, (999)2-74-38-29</p></li>
<li><p>Lunes a Sabado de 8:00 am a 9:00 pm</p></li>
</ul>
</div>
</div>
</div>
<div class="col-md-3 hidden-xs">
<a href="#mapa" >
<div id="vermapa">
<span class="glyphicon glyphicon-map-marker"></span><br><br>
<strong>Ver mapa</strong>
</div>
</a>
</div>
</div>
</div>
</div>
<!-- ############################################################ -->
<!-- #########################Fin Datos########################## -->
<!-- ############################################################ -->
<div class="row" id="martop30">
<div class="col-md-2"></div>
<div class="col-md-8">
<p>Por favor escribe tus datos en los espacios correspondientes, nos comunicaremos lo más pronto posible.</p>
<p>Los espacios con (*) son obligatorios.</p><br>
<p>¡Gracias por su Preferencia!</p>
<hr>
</div>
<div class="col-md-2"></div>
</div>
<!-- ############################################################ -->
<!-- #########################FORMULARIO######################### -->
<!-- ############################################################ -->
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-6">
<form action="">
<div class="form-group row">
<div class="col-md-4">
<label for="">*Nombre completo:</label>
</div>
<div class="col-md-8">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<label for="">*Correo:</label>
</div>
<div class="col-md-8">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<label for="">Empresa:</label>
</div>
<div class="col-md-8">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<label for="">*Telefono:</label>
</div>
<div class="col-md-8">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<label for="">*Servicio de interes:</label>
</div>
<div class="col-md-8">
<input type="text" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<label for="">Empresa:</label>
</div>
<div class="col-md-8">
<textarea type="text" class="form-control"></textarea>
</div>
</div>
</form>
<div class="pull-right">
<button class="btn btn-default">Limpiar</button>
<button class="btn btn-primary">Enviar</button>
</div>
</div>
<div class="col-md-2"></div>
</div>
<!-- ############################################################ -->
<!-- #####################FIN FORMULARIO######################### -->
<!-- ############################################################ -->
<!-- ############################################################ -->
<!-- #########################MAPA############################### -->
<!-- ############################################################ -->
<section id="mapa" class="row">
<div class="divmapa">
<div class="row">
<div class="col-md-12">
<iframe src="https://www.google.com/maps/embed?pb=!1m21!1m12!1m3!1d3726.3131902836267!2d-89.62382789267879!3d20.939934238385995!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m6!3e0!4m0!4m3!3m2!1d20.9404503!2d-89.6232271!5e0!3m2!1ses-419!2smx!4v1448859126159" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</div>
</div>
</section>
<!-- ############################################################ -->
<!-- #########################FIN MAPA############################### -->
<!-- ############################################################ -->
</div>
<!-- ##################################################################################### -->
<!-- ////////////////////////////////////////FIN-BODY///////////////////////////////////////// -->
<!-- ##################################################################################### -->
<script src="../jquery/jquery-2.1.3.min.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>
</body>
</html><file_sep><?php
function conectar(){
//Conexión a DB mysql
$conexi = @mysql_connect('localhost','root','');
@mysql_select_db('macrosign',$conexi);
if (!$conexi){
echo "No se pudo conectar a la BD. Favor de verificar";
return;
}
return $conexi;
}
?><file_sep><?php
include("conexion.php");
$conn = conectar();
$arr = array();
$correo = $_POST['correo'];
$pass = $_POST['pass'];
$sql = "SELECT id_usuario,correo,nombres,apellidos,id_tipo_usuario FROM usuarios WHERE correo = '".$correo."' && password ='".$pass."'";
$result = @mysql_query($sql,$conn) or die(mysql_error());
$row = mysql_fetch_array($result);
if($row==0){
$arr = array('id'=>"no");
}else{
$arr = array('id'=>$row[0],
'correo'=>$row[1],
'nombre'=>$row[2],
'apellido'=>$row[3],
'tipo'=>$row[4]);
session_start();
$_SESSION['id'] = $row[0];
$_SESSION['correo'] = $row[1];
$_SESSION['nombre'] = $row[2];
$_SESSION['apellido'] = $row[3];
$_SESSION['tipo'] = $row[4];
};
mysql_close($conn);
echo json_encode($arr);
?><file_sep><?php
include("conexion.php");
$conn = conectar();
$correo = $_POST['correo'];
$contrasena = $_POST['contrasena'];
$nombres = $_POST['nombres'];
$apellidos = $_POST['apellidos'];
$telefono = $_POST['telefono'];
$telefono_adicional = $_POST['telefono_adicional'];
$sql = "INSERT INTO usuarios VALUES ('','$correo','$contrasena','$nombres','$apellidos','$telefono','$telefono_adicional','1')";
if (!$result) {
echo "Fallo al insertar datos: (" . $mysqli->errno . ") " . $mysqli->error;
}else{
echo "Guardado Exitosamente";
}
mysql_close($conn);
?> | 5b2d44bccb77617d4df753b3fdb90ce6be796091 | [
"Markdown",
"JavaScript",
"PHP"
] | 11 | PHP | IrvinAlbornoz1394/MacroSign | afbcf4e167c4f9cc534197d9d31825faaf06827c | 4994f285ebace1dfad201d27f685be3db241dd18 |
refs/heads/master | <file_sep>package com.colin.service.impl;
import com.colin.mapper.ForcusMapper;
import com.colin.service.ForcusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ForcusServiceImpl implements ForcusService {
@Autowired
ForcusMapper forcusMapper;
@Override
public int ifForcus(int authorid, int uid) {
return forcusMapper.ifForcus(authorid, uid);
}
@Override
public void addForcus(int microBlogId, int authorid, int userId) {
forcusMapper.addForcus(microBlogId, authorid, userId);
}
@Override
public void deleteForcus(int authorid, int userId) {
forcusMapper.deleteForcus(authorid, userId);
}
@Override
public int selectfansCount(int authorid) {
return forcusMapper.selectfansCount(authorid);
}
@Override
public int selectMicCount(int uid) {
return forcusMapper.selectMicCount(uid);
}
}
<file_sep>package com.colin.service;
import com.colin.bean.Discuss;
import com.colin.bean.Microblog;
import java.util.List;
import java.util.Map;
public interface MicroblogService {
Integer selectCount(int id);
//通过用户id查询所有文章
List<Microblog> selectAllArticleByUid(int i, int pageCount, int id);
//通过文章id删除文章
void deleteMicroblogByIDAjax(int id);
//插入文章
void insertByMicroblog(Microblog microblog);
//查询文章
Microblog select(Microblog microblog);
//更新文章
void uploadMicroblog(Microblog microblog1);
//查询点赞数
int selectLikesCount(int id);
//查询转发数
int selectForwardCount(int id);
void addLikeCount(int uid, int likecount);
//更新喜欢的数量
void updateLikeCount(int id, int likecount, int microblogid);
//转发
void transmit(Microblog microBlog);
//查询转发文章的具体信息
Microblog selectTransmit(Microblog microBlog);
//更新转发数量
void updateTransmitCount(int uid, int transmitCount, int microBlogId);
//通过文章id查询文章
Microblog selectById(int microblogid);
//查询所有文章
List<Microblog> selectAllMic();
//通过博文id查询所有该博文的评论和回复
List<Discuss> selectVblogDiscussByMicroblogId(int id);
//插入评论
void insertVblogDisuss(Discuss discuss);
//删除评论
void deleteDiscussByUserId(Discuss discuss);
//查询图片路径
String selectPictureUrl(int id);
//插入图片
void insertPicture(Microblog microblog);
//删除评论
void deleteCommentByUser(Map map);
List<Microblog> selectMyArticleByUid(int i, int pageCount, int id);
List<Microblog> selectHot(int i, int pageCount);
}
<file_sep>package com.colin.service;
import com.colin.bean.Label;
import java.util.List;
public interface LabelService {
List<Label> selectAll();
void addLabel(Label label);
}
<file_sep>jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/vblog
jdbc.username=root
jdbc.password=<PASSWORD><file_sep>package com.colin.bean;
public class Page {
private Integer pageNumber;
private Integer totalPage;
public Page() {
}
public Page(Integer pageNumber, Integer totalPage) {
this.pageNumber = pageNumber;
this.totalPage = totalPage;
}
@Override
public String toString() {
return "Page{" +
"pageNumber=" + pageNumber +
", totalPage=" + totalPage +
'}';
}
public Integer getPageNumber() {
return pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
}
<file_sep>package com.colin.controller;
import com.colin.bean.Discuss;
import com.colin.bean.Microblog;
import com.colin.bean.User;
import com.colin.service.MicroblogService;
import com.colin.service.UserService;
import com.colin.util.ParamCheck;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RequestMapping("/user")
@Controller
public class UserController {
@Autowired
UserService userService;
@Autowired
MicroblogService microblogService;
//跳转到登录页面
@RequestMapping("/login")
public String login() {
return "userLogin";
}
//进行登录 登陆成功进入主页 ok
@RequestMapping("/userLogin")
public String userLogin(User user, Model model, HttpSession httpSession) {
//判断是否非空
boolean b = ParamCheck.ParamCheck(user.getName(), user.getPassword());
if (b) {
String userName = user.getName();
String email = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
String telephone = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$";
/*java用验证手机号*/ /*测试用代码,前台输入手机号时测试,matches返回true/false*/
if (userName.matches(telephone)) { /*如果匹配上则将名字置空,并将Name中的值写到setTelephone()方法中*/
user.setName(null);
user.setTelephone(userName);/*代码测试用*/
System.out.println(user.getTelephone());
} else if (userName.matches(email)) {
user.setName(null);
user.setEmail(userName);
}
//通过用户输入信息进行查询,数据库有记录则正确登录,否则登陆失败
User userLogin = userService.userLogin(user);
if (userLogin == null) {
return "loginFalse";
}
httpSession.setAttribute("userLogin", userLogin);
model.addAttribute("user", userLogin);
return "first";
} else {
return "loginFalse";
}
}
@RequestMapping("/first")
public String first(HttpSession httpSession, Model model) {
User user = (User) httpSession.getAttribute("userLogin");
model.addAttribute("user", user);
return "first";
}
@RequestMapping(value = "/myMic")
public String myMic(HttpSession httpSession, Model model) {
User user = (User) httpSession.getAttribute("userLogin");
model.addAttribute("user", user);
return "myMic";
}
@RequestMapping(value = "/hot")
public String hot(HttpSession httpSession, Model model) {
User user = (User) httpSession.getAttribute("userLogin");
model.addAttribute("user", user);
return "hot";
}
//跳转到注册页面
@RequestMapping("/register")
public String register() {
return "userRegister";
}
//进行注册 注册成功跳转到登陆页面 ok
@RequestMapping("/userRegister")
public String userRegister(User user, Model model) {
User userLogin = userService.userRegister(user);
if (user.getName().equals(null) || user.getName().equals("")) {
model.addAttribute("result", "昵称不可为空!");
return "userRegister";
} else if (user.getEmail().equals("")) {
model.addAttribute("result", "邮箱不可为空!");
return "userRegister";
} else if (user.getPassword().equals("")) {
model.addAttribute("result", "密码不可为空!");
return "userRegister";
} else if (user.getTelephone().equals("")) {
model.addAttribute("result", "手机号不可为空!");
return "userRegister";
}
if (user.getSignature().equals("")) {
user.setSignature("这个人很懒,没留下任何信息哦!");
}
String email = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
String telephone = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$";
if (user.getName().length() > 10) {
model.addAttribute("result", "昵称不可过长!");
return "userRegister";
} else if (user.getEmail().matches(email)) {
model.addAttribute("result", "邮箱格式不正确!");
return "userRegister";
} else if (user.getPassword().length() < 6) {
model.addAttribute("result", "密码过短,不安全!");
return "userRegister";
} else if (user.getTelephone().matches(telephone)) {
model.addAttribute("result", "手机号格式不正确!");
return "userRegister";
}
if (userLogin == null) {
userService.insertUser(user);
return "redirect:/user/login";
} else {
model.addAttribute("result", "用户已存在!");
return "userRegister";
}
}
//跳转到用户信息界面 ok
@RequestMapping("/information")
public String userInformation(HttpSession httpSession, Model model) {
User userLogin = (User) httpSession.getAttribute("userLogin");
model.addAttribute("userLogin", userLogin);
return "userInformation";
}
//更新用户信息 ok
@RequestMapping("/updateInformation")
public String userUpdate(User user, HttpSession httpSession) {
userService.updateUser(user);
User userLogin = (User) httpSession.getAttribute("userLogin");
if (user.getPassword().equals(null) || user.getPassword().equals(userLogin.getPassword())) {
httpSession.setAttribute("userLogin", user);
return "first";
} else {
return "redirect:/user/login";
}
}
//上传用户头像 ok
@RequestMapping("/uploadAvatar")
public String uploadAvatar() {
return "userUploadAvatar";
}
@RequestMapping("/uploadAvatarOK")
public String doUpload(MultipartFile file, Model model, HttpSession session) throws IOException {
User userLogin = (User) session.getAttribute("userLogin");
String absolutePath = null;
if (file != null && !file.isEmpty()) {
String str = file.getOriginalFilename();
String str1 = str.substring(str.lastIndexOf(".") + 1);
File file1 = new File("D:/学习/编译器/文件/VBlog/out/artifacts/ssm_war_exploded/avatar", userLogin.getId() + "." + str1);
FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
String name = file1.getName();
absolutePath = "/avatar/" + name;
userLogin.setAvatar(absolutePath);
userService.updateUserAvatar(userLogin);
}
model.addAttribute("userLogin", userLogin);
return "userInformation";
}
//todo 未知方法
@RequestMapping("/Test2")
public String Test2(int id, HttpSession httpSession) {
httpSession.setAttribute("microbogid", id);
return "chp.comment";
}
//评论页面的加载
@RequestMapping("/ShowVblogDiscuss")
@ResponseBody
public List<Discuss> ShowVblogDiscuss(@RequestBody Microblog microblog) {
//通过博文id查询所有该博文的评论和回复
//todo 登录的用户
int microblogId = microblog.getId();
System.out.println("dsdsdsdsd");
System.out.println(microblogId);
List<Discuss> discusses = microblogService.selectVblogDiscussByMicroblogId(microblogId);
System.out.println(discusses);
return discusses;
}
//保存评论博文评论
@RequestMapping("/AcceptComments")
@ResponseBody
public Discuss AcceptComments(@RequestBody Discuss discuss) {
System.out.println(discuss);
User user = new User();
//todo
user.setId(2);
discuss.setCommentPerson(user);
System.out.println(discuss);
microblogService.insertVblogDisuss(discuss);
return discuss;
}
//保存回复评论
@RequestMapping("/AcceptResponds")
@ResponseBody
public Discuss AcceptResponds(@RequestBody Discuss discuss) {
User user = new User();
user.setId(1);
discuss.setCommentPerson(user);
System.out.println(discuss);
microblogService.insertVblogDisuss(discuss);
return discuss;
}
@RequestMapping("/deleteCommentByUser")
@ResponseBody
public Discuss deleteCommentByUser(@RequestBody Map map) {
//todo 再接受一个USer类,比较类里的名字与name是否相等
System.out.println(map);
microblogService.deleteCommentByUser(map);
return new Discuss();
}
@RequestMapping("/deleteAllCommentByUser")
@ResponseBody
public Discuss deleteAllCommentByUser(@RequestBody Map map) {
//todo 再接受一个USer类,比较类里的名字与name是否相等
System.out.println(map);
// microBlogService.deleteAllCommentByUserId(map);
return new Discuss();
}
}
<file_sep>package com.colin.service;
import com.colin.bean.User;
import java.util.List;
public interface UserService {
User userLogin(User user);
User userRegister(User user);
void insertUser(User user);
void updateUser(User user);
//插入用户头像
void updateUserAvatar(User user);
//更新博主用户表中的粉丝数
void updateFans(int uid1, int fansCount);
//更新当前用户表中的关注数
void updateForcus(int uid, int forcusCount);
List<User> selectAllUser();
User selectUserById(int id);
}
<file_sep>package com.colin.service.impl;
import com.colin.bean.Discuss;
import com.colin.bean.Microblog;
import com.colin.mapper.MicroblogMapper;
import com.colin.service.MicroblogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class MicroblogServiceImpl implements MicroblogService {
@Autowired
MicroblogMapper microblogMapper;
@Override
public Integer selectCount(int id) {
return microblogMapper.selectCount(id);
}
@Override
public List<Microblog> selectAllArticleByUid(int i, int pageCount, int id) {
return microblogMapper.selectAllArticleByUid(i, pageCount, id);
}
@Override
public void deleteMicroblogByIDAjax(int id) {
microblogMapper.deleteMicroblogByIDAjax(id);
}
@Override
public void insertByMicroblog(Microblog microblog) {
microblogMapper.insertByMicroblog(microblog);
}
@Override
public Microblog select(Microblog microblog) {
return microblogMapper.select(microblog);
}
@Override
public void uploadMicroblog(Microblog microblog1) {
microblogMapper.uploadMicroblog(microblog1);
}
@Override
public int selectLikesCount(int id) {
return microblogMapper.selectLikesCount(id);
}
@Override
public int selectForwardCount(int id) {
return microblogMapper.selectForwardCount(id);
}
@Override
public void addLikeCount(int uid, int likecount) {
microblogMapper.addLikeCount(uid, likecount);
}
@Override
public void transmit(Microblog microBlog) {
microblogMapper.transmit(microBlog);
}
@Override
public Microblog selectTransmit(Microblog microBlog) {
return microblogMapper.selectTransmit(microBlog);
}
public void updateTransmitCount(int uid, int transmitCount, int microBlogId) {
microblogMapper.updateTransmitCount(uid, transmitCount, microBlogId);
}
@Override
public Microblog selectById(int microblogid) {
return microblogMapper.selectById(microblogid);
}
@Override
public void updateLikeCount(int uid, int likecount, int microblogid) {
microblogMapper.updateLikeCount(uid, likecount, microblogid);
}
@Override
public List<Microblog> selectAllMic() {
return microblogMapper.selectAllMic();
}
//通过博文id查询所有该博文的评论和回复
@Override
public List<Discuss> selectVblogDiscussByMicroblogId(int microblogId) {
return microblogMapper.selectVblogDiscussByMicroblogId(microblogId);
}
@Override
public void insertVblogDisuss(Discuss discuss) {
microblogMapper.insertVblogDisuss(discuss);
}
@Override
public void deleteDiscussByUserId(Discuss discuss) {
microblogMapper.deleteDiscussByUserId(discuss);
}
@Override
public String selectPictureUrl(int id) {
return microblogMapper.selectPictureUrl(id);
}
@Override
public void insertPicture(Microblog microblog) {
microblogMapper.insertPicture(microblog);
}
@Override
public void deleteCommentByUser(Map map) {
String test = (String) map.get("time");
Date date = new Date(test);
Timestamp time = new Timestamp(date.getTime());
//todo 这里先写死
// User user1 = (User) map.get("user");
// String user = user1.getName();
String name = (String) map.get("name");
String user = (String) map.get("user");
microblogMapper.deleteCommentByUser(user, name, time);
}
@Override
public List<Microblog> selectMyArticleByUid(int i, int pageCount, int id) {
return microblogMapper.selectMyArticleByUid(i, pageCount, id);
}
@Override
public List<Microblog> selectHot(int i, int pageCount) {
return microblogMapper.selectHot(i, pageCount);
}
}
<file_sep>package com.colin.service.impl;
import com.colin.bean.User;
import com.colin.mapper.UserMapper;
import com.colin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User userLogin(User user) {
return userMapper.userLogin(user);
}
@Override
public User userRegister(User user) {
return userMapper.userRegister(user);
}
@Override
public void insertUser(User user) {
userMapper.insertUser(user);
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public void updateUserAvatar(User user) {
userMapper.updateUserAvatar(user);
}
@Override
public void updateFans(int uid1, int fansCount) {
userMapper.updateFans(uid1, fansCount);
}
@Override
public void updateForcus(int uid, int forcusCount) {
userMapper.updateForcus(uid, forcusCount);
}
@Override
public List<User> selectAllUser() {
return userMapper.selectAllUser();
}
@Override
public User selectUserById(int id) {
return userMapper.selectUserById(id);
}
}
<file_sep>CREATE DATABASE IF NOT EXISTS `vblog` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `vblog`;
-- MySQL dump 10.13 Distrib 5.7.25, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: vblog
-- ------------------------------------------------------
-- Server version 5.7.25
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `administrator`
--
DROP TABLE IF EXISTS `administrator`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `administrator` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '管理员名',
`name` varchar(45) NOT NULL COMMENT '管理员名',
`password` varchar(45) NOT NULL COMMENT '<PASSWORD>',
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='管理员';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `administrator`
--
LOCK TABLES `administrator` WRITE;
/*!40000 ALTER TABLE `administrator` DISABLE KEYS */;
/*!40000 ALTER TABLE `administrator` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `discuss`
--
DROP TABLE IF EXISTS `discuss`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `discuss` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`microblogid` int(11) NOT NULL COMMENT '博文的id',
`commentid` int(11) NOT NULL COMMENT '评论人的名字',
`respondentid` int(11) DEFAULT NULL COMMENT '被评论人的名字',
`discusstime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '用户给博文的评论时间',
`comment` varchar(100) NOT NULL COMMENT '评论内容',
`floor` int(255) NOT NULL COMMENT '评论语句所在楼层',
`like` int(255) NOT NULL DEFAULT '0' COMMENT '点赞数',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=167 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `discuss`
--
LOCK TABLES `discuss` WRITE;
/*!40000 ALTER TABLE `discuss` DISABLE KEYS */;
INSERT INTO `discuss` VALUES (165,245,2,NULL,'2020-06-20 14:08:54','好看吗',0,0),(166,245,1,1,'2020-06-20 14:09:04',' 还行啊',0,0);
/*!40000 ALTER TABLE `discuss` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `forcus`
--
DROP TABLE IF EXISTS `forcus`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `forcus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`microblogid` int(11) NOT NULL COMMENT '博主文章的id,根据文章id找到博主uid',
`authorid` int(11) NOT NULL COMMENT '博文作者的id',
`fansid` int(11) NOT NULL COMMENT '粉丝id',
`alias` varchar(45) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='关注';
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `forcus`
--
LOCK TABLES `forcus` WRITE;
/*!40000 ALTER TABLE `forcus` DISABLE KEYS */;
INSERT INTO `forcus` VALUES (4,251,8,1,NULL);
/*!40000 ALTER TABLE `forcus` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `group`
--
DROP TABLE IF EXISTS `group`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `group` (
`id` int(11) NOT NULL,
`name` varchar(45) NOT NULL COMMENT '分组名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `group`
--
LOCK TABLES `group` WRITE;
/*!40000 ALTER TABLE `group` DISABLE KEYS */;
/*!40000 ALTER TABLE `group` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `label`
--
DROP TABLE IF EXISTS `label`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `label` (
`id` int(11) NOT NULL COMMENT '标签id',
`name` varchar(45) NOT NULL COMMENT '标签名',
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `label`
--
LOCK TABLES `label` WRITE;
/*!40000 ALTER TABLE `label` DISABLE KEYS */;
INSERT INTO `label` VALUES (2,'小说'),(1,'明星');
/*!40000 ALTER TABLE `label` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `label_microblog`
--
DROP TABLE IF EXISTS `label_microblog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `label_microblog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`label_id` int(11) NOT NULL COMMENT '标签id',
`microblog_id` int(11) NOT NULL COMMENT '微博id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `label_microblog`
--
LOCK TABLES `label_microblog` WRITE;
/*!40000 ALTER TABLE `label_microblog` DISABLE KEYS */;
/*!40000 ALTER TABLE `label_microblog` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `likes`
--
DROP TABLE IF EXISTS `likes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `likes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`microblogid` int(11) NOT NULL COMMENT '微博id',
`uid` int(11) NOT NULL COMMENT '点赞用户id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `likes`
--
LOCK TABLES `likes` WRITE;
/*!40000 ALTER TABLE `likes` DISABLE KEYS */;
INSERT INTO `likes` VALUES (43,249,8),(44,248,8),(46,251,1),(47,249,1);
/*!40000 ALTER TABLE `likes` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `microblog`
--
DROP TABLE IF EXISTS `microblog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `microblog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL COMMENT '用户id',
`content` varchar(2000) NOT NULL COMMENT '微博内容',
`reason` varchar(2000) DEFAULT NULL COMMENT '转发理由',
`videourl` varchar(100) DEFAULT NULL COMMENT '视频地址',
`createtime` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '注册时间',
`likecount` int(11) DEFAULT '0' COMMENT '点赞数量',
`transmitcount` int(11) DEFAULT '0' COMMENT '转发数量',
`label` varchar(100) DEFAULT NULL COMMENT '标签',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=255 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `microblog`
--
LOCK TABLES `microblog` WRITE;
/*!40000 ALTER TABLE `microblog` DISABLE KEYS */;
INSERT INTO `microblog` VALUES (245,1,'这是第一条微博',NULL,NULL,'2020-06-20 08:40:32.000',0,0,NULL),(248,1,'[哈哈]',NULL,NULL,'2020-06-20 09:19:41.000',1,0,NULL),(249,1,'呵呵',NULL,NULL,'2020-06-20 09:20:13.000',2,0,NULL),(251,8,'小风的微博[哈哈]',NULL,NULL,'2020-06-20 14:23:20.000',1,3,NULL),(252,1,'小风的微博[哈哈]','挺有意思的',NULL,'2020-06-20 15:11:45.660',1,1,NULL),(254,1,'小风的微博[哈哈]','123',NULL,'2020-06-21 01:23:38.177',1,3,NULL);
/*!40000 ALTER TABLE `microblog` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `picture`
--
DROP TABLE IF EXISTS `picture`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `picture` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pictureurl` varchar(100) NOT NULL COMMENT '图片路径',
`microblogid` int(11) NOT NULL COMMENT '关联文章id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `picture`
--
LOCK TABLES `picture` WRITE;
/*!40000 ALTER TABLE `picture` DISABLE KEYS */;
INSERT INTO `picture` VALUES (44,'/picture/%E8%BF%98%E7%BB%8F%E5%B0%8F%E9%98%9F.jpg',243),(45,'/picture/-E5-85-AB-E6-88-92.jpg',244),(46,'/picture/b21c8701a18b87d608167af6050828381e30fd87.jpg',245),(47,'/picture/b21c8701a18b87d608167af6050828381e30fd87.jpg',251);
/*!40000 ALTER TABLE `picture` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `transmit`
--
DROP TABLE IF EXISTS `transmit`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `transmit` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`microblogid` int(11) NOT NULL COMMENT '博文的id',
`uid` int(11) NOT NULL COMMENT '转发用户的id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=156 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `transmit`
--
LOCK TABLES `transmit` WRITE;
/*!40000 ALTER TABLE `transmit` DISABLE KEYS */;
INSERT INTO `transmit` VALUES (153,251,1),(154,251,1),(155,251,1);
/*!40000 ALTER TABLE `transmit` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`name` varchar(45) NOT NULL COMMENT '用户名',
`sex` varchar(20) NOT NULL DEFAULT '男' COMMENT '用户性别',
`password` varchar(45) NOT NULL COMMENT '用户密码',
`avatar` varchar(100) DEFAULT NULL COMMENT '头像',
`telephone` char(11) DEFAULT NULL COMMENT '手机号',
`email` varchar(45) DEFAULT NULL COMMENT '邮箱',
`signature` varchar(45) DEFAULT '一句话介绍一下自己吧,让别人更了解你' COMMENT '个性签名',
`createtime` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '注册时间',
`address` varchar(100) DEFAULT NULL COMMENT '地址',
`relationship` varchar(45) DEFAULT NULL COMMENT '感情状况',
`forcuscount` int(11) DEFAULT '0' COMMENT '关注数量',
`fanscount` int(11) DEFAULT '0' COMMENT '粉丝数量',
`microblogcount` int(11) DEFAULT '0' COMMENT '微博数量',
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'小白','男','123456','/avatar/1.jpg','13948633624','<EMAIL>','这个人很懒,没留下任何信息哦!','2019-07-01 08:43:18.000',NULL,NULL,1,0,0),(8,'小风','男','123456','/avatar/8.jpg','19917563834','<EMAIL>','这个人很懒,没留下任何信息哦!','2020-06-20 05:15:35.304','','',1,0,0),(9,'1','男','1','/avatar/9.jpg',NULL,NULL,'一句话介绍一下自己吧,让别人更了解你','2020-06-20 05:47:36.759',NULL,NULL,0,0,0);
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping events for database 'vblog'
--
--
-- Dumping routines for database 'vblog'
--
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-07-26 15:56:12
<file_sep>package com.colin.service.impl;
import com.colin.bean.Label;
import com.colin.mapper.LabelMapper;
import com.colin.service.LabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class LabelServiceImpl implements LabelService {
@Autowired
LabelMapper labelMapper;
@Override
public List<Label> selectAll() {
return labelMapper.selectAll();
}
@Override
public void addLabel(Label label) {
labelMapper.addLabel(label);
}
}
<file_sep>package com.colin.mapper;
import com.colin.bean.Label;
import java.util.List;
public interface LabelMapper {
List<Label> selectAll();
void addLabel(Label label);
}
<file_sep>package com.colin.bean;
import java.sql.Timestamp;
import java.util.List;
public class Discuss {
//评论id
private int id;
//博文id
private int microblogId;
//评论人或回复人
private User commentPerson;
//被回复人
private User getCommentPerson;
//评论或回复时间
private Timestamp discussTime;
//评论内容
private String comment;
//别评论或回复的楼层
private Integer floor;
//拥有赞数
private int likeCount;
//点赞的人名单
private List<DiscussLikes> likesPerson;
public Discuss() {
}
public Discuss(int id, int microblogId, User commentPerson, User getCommentPerson, Timestamp discussTime, String comment, Integer floor, int likeCount, List<DiscussLikes> likesPerson) {
this.id = id;
this.microblogId = microblogId;
this.commentPerson = commentPerson;
this.getCommentPerson = getCommentPerson;
this.discussTime = discussTime;
this.comment = comment;
this.floor = floor;
this.likeCount = likeCount;
this.likesPerson = likesPerson;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMicroblogId() {
return microblogId;
}
public void setMicroblogId(int microblogId) {
this.microblogId = microblogId;
}
public User getCommentPerson() {
return commentPerson;
}
public void setCommentPerson(User commentPerson) {
this.commentPerson = commentPerson;
}
public User getGetCommentPerson() {
return getCommentPerson;
}
public void setGetCommentPerson(User getCommentPerson) {
this.getCommentPerson = getCommentPerson;
}
public Timestamp getDiscussTime() {
return discussTime;
}
public void setDiscussTime(Timestamp discussTime) {
this.discussTime = discussTime;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Integer getFloor() {
return floor;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public List<DiscussLikes> getLikesPerson() {
return likesPerson;
}
public void setLikesPerson(List<DiscussLikes> likesPerson) {
this.likesPerson = likesPerson;
}
@Override
public String toString() {
return "Discuss{" +
"id=" + id +
", microblogId=" + microblogId +
", commentPerson=" + commentPerson +
", getCommentPerson=" + getCommentPerson +
", discussTime=" + discussTime +
", comment='" + comment + '\'' +
", floor=" + floor +
", likeCount=" + likeCount +
", likesPerson=" + likesPerson +
'}';
}
}
<file_sep>package com.colin.service;
public interface ForcusService {
int ifForcus(int authorid, int uid);
void addForcus(int microBlogId, int authorid, int userId);
void deleteForcus(int authorid, int userId);
int selectfansCount(int authorid);
int selectMicCount(int uid);//关注数
}
| 6abb2b15528bf7fe7bd73720085a4a4993d51ac3 | [
"Java",
"SQL",
"INI"
] | 14 | Java | cyl-GitHub/VBlog | 57d3654c48c2fca939bd75582202244941278544 | f29e0e343bba167f459be6f33f08fcd0d96504ff |
refs/heads/main | <file_sep>import React, {useState} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Image,
ImageBackground,
Text,
} from 'react-native';
import { scale,ScaledSheet } from 'react-native-size-matters';
export default function bmiIndex({range,bmi}) {
function showBMI()
{
return(
<ImageBackground resizeMode= 'stretch'
style={styles.bmiValueContainer}
source={require('../../assets/images/bmiValue.png')}>
<Text style={styles.textBMIValues}>{bmi.toFixed(1)}</Text>
</ImageBackground>
);
}
return(
<ImageBackground resizeMode= 'stretch'
style={styles.bmiRange}
source={require('../../assets/images/bmiRange.png')}>
<View style={styles.bmiPartsContainer}>
<View style={styles.bmiParts}>
<Text style={styles.textValues}>چاق</Text>
{range==4?showBMI():<></>}
</View>
<View style={styles.bmiParts}>
<Text style={{...styles.textValues,fontSize: scale(9), marginTop: scale(2)}}>اضافه وزن</Text>
{range==3?showBMI():<></>}
</View>
<View style={styles.bmiParts}>
<Text style={styles.textValues}>طبیعی</Text>
{range==2?showBMI():<></>}
</View>
<View style={styles.bmiParts}>
<Text style={styles.textValues}>لاغر</Text>
{range==1?showBMI():<></>}
</View>
<View style={styles.bmiParts}>
<Text style={{...styles.textValues,fontSize: scale(9),marginTop: scale(5), marginRight: scale(5)}}>کمبود وزن</Text>
{range==0?showBMI():<></>}
</View>
</View>
<View style={{flexDirection: 'row',justifyContent: 'center'}}>
<Text style={styles.textTitle}>شاخص</Text>
<Text style={{...styles.textTitle,marginTop: scale(3)}}>BMI </Text>
</View>
</ImageBackground>
);
}
const styles = ScaledSheet.create({
bmiRange:{
height: '45@s',
width: '250@s'
},
bmiValueContainer:{
height: '40@s',
width: '45@s',
position: 'absolute',
top: '-35@s'
},
bmiPartsContainer:{
width: "100%",
height: '45@s',
flexDirection: 'row',
},
bmiParts:{
flex:1,
alignItems: 'center',
},
textValues: {
color: "white",
marginBottom: '8@s',
fontSize: '12@s',
fontFamily: "Yekan",
textAlign: "center",
textShadowColor: 'rgba(0, 0, 0, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
textBMIValues: {
color: "white",
marginBottom: '8@s',
fontSize: '15@s',
fontFamily: "Yekan",
textAlign: "center",
},
textTitle: {
color: "#0f3648",
marginBottom: '8@s',
fontSize: '12@s',
fontFamily: "Yekan",
textAlign: "center",
},
});
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
TextInput,
Image,
ImageBackground,
} from 'react-native';
// const { width, height } = Dimensions.get('window')
import * as Animatable from 'react-native-animatable';
import RadioButton from '../components/radioBtn.js';
import Button from '../components/button.js';
import PopUp from '../components/popup.js';
import { useDispatch } from 'react-redux';
import { userName,userGender } from '../actions/user/user_data';
import { ScaledSheet } from 'react-native-size-matters';
export default function StartScreen({ navigation }) {
const [name,setName]=useState('');
const [gender,setGender]=useState(0);
const dispatch = useDispatch();
return(
<View style={styles.container}>
<Animatable.View animation="fadeInDown" delay={500} useNativeDriver={true}>
<PopUp style={styles.image} headerText={"خوش آمدید !"}>
<View style={{flex: 1,alignItems: 'center'}}>
<Text style={styles.textTitle}>اسم خودت رو اینجا بنویس</Text>
<TextInput
style={styles.TextInputStyleClass}
placeholderTextColor = "#8ab6c5"
placeholder="نام دلخواه"
value={name}
onChangeText={(value)=>setName(value)}
maxLength={10}
/>
<View style={styles.dialogContainer}>
<Animatable.View animation="fadeInRight"
delay={1000}
style={{flex: 1}}
useNativeDriver={true}>
<View style={styles.genderIcon}>
<RadioButton checked={gender==1} onPress={()=>setGender(1)} style={styles.radioButton}/>
<Image style={styles.avatar} source={require('../../assets/images/boy.png')}/>
</View>
<Text style={styles.textGender}>پسر هستم</Text>
</Animatable.View>
<Animatable.View animation="fadeInLeft"
delay={1000}
style={{flex: 1}}
useNativeDriver={true}>
<View style={styles.genderIcon}>
<RadioButton checked={gender==0} onPress={()=>setGender(0)} style={styles.radioButton}/>
<Image style={styles.avatar} source={require('../../assets/images/girl.png')}/>
</View>
<Text style={styles.textGender}>دختر هستم</Text>
</Animatable.View>
</View>
<Animatable.View animation="bounceIn" delay={1500} useNativeDriver={true}>
<Button text={"بعدی"} onPress={()=>{
dispatch(userName(name));
dispatch(userGender(gender));
navigation.push('PageProperties')
}} style={styles.button}/>
</Animatable.View>
</View>
</PopUp>
</Animatable.View>
</View>
);
}
const styles = ScaledSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
dialogContainer:{
height:'110@s',
flexDirection: 'row',
marginLeft: '40@s',
marginRight: '30@s',
marginBottom: '10@s',
marginTop: '15@s'
},
image: {
aspectRatio: 1.1,
width: '310@s',
resizeMode: "stretch",
justifyContent: "center"
},
textTitle: {
color: "#e46d8d",
fontSize: '18@s',
fontFamily: "Yekan",
textAlign: "center",
},
textGender: {
color: "#2b728c",
fontSize: '13@s',
fontFamily: "Yekan",
textAlign: "center",
},
radioButton:{
height: '40@s',
width: '40@s',
marginRight: '-30@s',
marginBottom: '-20@s',
zIndex: 10
},
genderIcon:{
height:'80@s',
alignItems:'center',
flexDirection: 'row',
},
TextInputStyleClass:{
marginTop: 10,
width: '180@s',
paddingHorizontal: '15@s',
paddingVertical: '3@s',
fontFamily: "Yekan",
fontSize: '15@s',
fontWeight: '300',
textAlign:'center',
borderWidth: 1,
borderRadius: '20@s' ,
borderColor: "#cfedf3",
backgroundColor : "#e2f4f9",
},
avatar:{
width: "80%",
height: '100@s',
resizeMode: 'contain'
},
button:{
height: '50@s',
width: '160@s',
}
});
<file_sep>import React, {useState, useEffect} from 'react';
import { View } from 'react-native';
import { createStackNavigator } from '@react-navigation/stack';
import { enableScreens } from 'react-native-screens';
enableScreens();
import PushPole from 'pushpole-react-native';
import PageName from "./PageName.js"
import PageProperties from "./PageProperties.js"
import PageMain from "./PageMain.js"
import PageFood from "./PageFood.js"
import PageFoodNeg from "./PageFoodNeg.js"
import PageActivity from "./PageActivity.js"
import PageActivityHalf from "./PageActivityHalf.js"
import PageActivityNeg from "./PageActivityNeg.js"
import SoundController from '../components/soundController.js'
import {RightTransition,LeftTransition,UpTransition} from "./transitions.js"
import { useDispatch, useSelector } from 'react-redux';
import { userHonorToday, userHonors } from '../actions/user/user_data';
import { dataDate, dataReset } from '../actions/data/data_actions.js';
import {todayDays, checkRules} from '../data/checkRules.js';
import {store} from '../store/configureStore.js';
const Stack = createStackNavigator();
export default function Screens(props) {
const todayHonor = useSelector(({user}) => user.todayHonor);
const honors = useSelector(({user}) => user.honors);
const bmi = useSelector(({user}) => user.bmi);
const lastDay = useSelector(({data}) => data.lastDay);
const state = store.getState();
const [todayChecked,setTodayChecked] = useState(false);
const dispatch = useDispatch();
// console.log(state);
function saveData(levels)
{
db.transaction( tx => {
tx.executeSql(
'INSERT INTO daily_data (Honor, FoodLevel, ActivityLevel, Day, Food1, Food2, Activity1, Activity2, Activity3) VALUES (?,?,?,?,?,?,?,?,?)',
[state.user.todayHonor , levels.levelFood, levels.levelActivity , lastDay, state.data.food1.toString(), state.data.food2.toString(), state.data.active1.toString(),state.data.active2.toString(),state.data.active3.toString()],
(tx, results) => {
// console.log('Results', results.rowsAffected);
let Today = todayDays();
dispatch(dataDate(Today));
if(todayHonor)
dispatch(userHonors(honors+1));
dispatch(userHonorToday(false));
dispatch(dataReset());
setTodayChecked(true);
},
(error)=>console.log(error)
)
});
}
useEffect(()=>{
if(bmi==0)
setTodayChecked(true);
else {
let Today = todayDays();
if(Today!=lastDay)
{
setTodayChecked(false);
let levels = checkRules(state);
saveData(levels);
}
else {
setTodayChecked(true);
}
}
PushPole.initialize(false);
},[])
return(
<>
<SoundController/>
{todayChecked?
<Stack.Navigator headerMode="none" initialRouteName={bmi>0?'PageMain':'PageName'}>
<Stack.Screen name="PageMain"
component={PageMain} />
<Stack.Screen name="PageName" component={PageName} />
<Stack.Screen name="PageProperties" component={PageProperties} />
<Stack.Screen name="PageFood"
options={{
gestureEnabled: true,
cardOverlayEnabled: true,
...RightTransition ,
}}
component={PageFood} />
<Stack.Screen name="PageFoodNeg"
options={{
gestureEnabled: true,
cardOverlayEnabled: true,
...UpTransition ,
}}
component={PageFoodNeg} />
<Stack.Screen name="PageActivity"
options={{
gestureEnabled: true,
cardOverlayEnabled: true,
...LeftTransition ,
}}
component={PageActivity} />
<Stack.Screen name="PageActivityHalf"
options={{
gestureEnabled: true,
cardOverlayEnabled: true,
...UpTransition ,
}}
component={PageActivityHalf} />
<Stack.Screen name="PageActivityNeg"
options={{
gestureEnabled: true,
cardOverlayEnabled: true,
...UpTransition ,
}}
component={PageActivityNeg} />
</Stack.Navigator>:
<View style={{flex:1, backgroundColor: "#0f3648"}}/>}
</>
);
}
<file_sep>import React from 'react';
import {
View,
Text,
Image,
ImageBackground,
TouchableWithoutFeedback,
ScrollView
} from 'react-native';
import Modal from 'react-native-modal';
import { scale, ScaledSheet } from 'react-native-size-matters';
import { soundMuteState, musicMuteState, soundPlay } from '../actions/sound/sound';
import { useDispatch } from 'react-redux';
export default function Dialoge(props) {
const dispatch = useDispatch();
function toggleModal(){
if(props.toggleModal) props.toggleModal()
if(props.close) props.close()
}
function items()
{
return props.data.units.map((data,index) => {
return (
<View key={index} style={{...styles.itemTextContainerRow,backgroundColor: index%2==0?"#dffff6":"#fff"}}>
<Text style={styles.textItemName}>{data.name}</Text>
<Text style={styles.textItemValue}>{data.value}</Text>
</View>
)
})
}
console.log(props.data);
return(
<Modal isVisible={props.isVisible}
//onBackdropPress={() => toggleModal()}
onBackButtonPress={() => toggleModal()}
animationIn="slideInDown"
animationOut="slideOutDown"
animationInTiming={600}
animationOutTiming={400}
backdropTransitionInTiming={0}
backdropTransitionOutTiming={0}
onModalWillShow={()=>dispatch(soundPlay('popupopen'))}
onModalWillHide={()=>dispatch(soundPlay('popup'))}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/popup.png')}>
<View style={{position: 'absolute', top: scale(28), alignSelf: 'center'}}>
<Text style={{color: "white",
fontSize: scale(15),
fontFamily: "Yekan",}}>راهنمای واحد غذایی</Text>
</View>
<TouchableWithoutFeedback onPress={()=>toggleModal()}>
<View style={styles.closeButtonContainer}>
<Image source={require('../../assets/images/Close.png')}
style={styles.closeButton}/>
</View>
</TouchableWithoutFeedback>
<View style={styles.childrenContain}>
<View style={styles.item}>
<Image source={props.data.icon} style={styles.itemImageContainer}/>
<View style={styles.itemTextContainer}>
<Text style={styles.textItemMain}>{props.data.name}</Text>
</View>
</View>
<View style={{...styles.item, height: scale(20),marginTop:scale(10), marginBottom: 0}}>
<View style={styles.itemTextContainerRow}>
<Text style={styles.textItemDescribe}>ماده غذایی</Text>
<Text style={styles.textItemDescribe}>مقدار هر واحد</Text>
</View>
</View>
<Image style={styles.line} source={require('../../assets/images/Line.png')}/>
<ScrollView persistentScrollbar={true} style={{ width: "80%", marginTop: scale(7)}}>
{items()}
</ScrollView>
</View>
</ImageBackground>
</Modal>
);
};
const styles = ScaledSheet.create({
dialog: {
height: '380@s',
width: '300@s',
marginBottom: '80@s',
},
closeButtonContainer:{
position: 'absolute',
top: '5@s'
},
closeButton:{
resizeMode: 'stretch',
height:'40@s',
width:'40@s'
},
childrenContain:{
height: "265@s",
width: "100%",
marginTop: '70@s',
alignItems: 'center',
},
item:{
width: "75%",
height: "45@s",
flexDirection: "row",
alignItems: "center",
justifyContent:'flex-start' ,
marginBottom: '3@s'
},
itemImageContainer:{
height: "40@s",
width: "40@s",
borderRadius: "10@s",
marginRight: "5@s",
},
itemTextContainer:{
height: "35@s",
width: "130@s",
marginLeft: "8@s",
},
itemTextContainerRow:{
height: "35@s",
width: "100%",
flexDirection: "row"
},
textItemMain: {
color: "#fe82a4",
fontSize: '15@s',
height: '50@s',
fontWeight: "bold",
fontFamily: "Yekan",
textAlign: "left",
marginRight: "3@s",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
textItemDescribe: {
color: "#2b728c",
fontSize: '12@s',
height: '20@s',
flex:1,
// fontWeight: "bold",
marginLeft: "4@s",
fontFamily: "Yekan",
textAlign: "center",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
textItemName: {
color: "#2b728c",
fontSize: '12@s',
flex:1,
marginLeft: "5@s",
// fontWeight: "bold",
fontFamily: "Yekan",
textAlign: "left",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
textItemValue: {
color: "#fe82a4",
fontSize: '12@s',
flex:1,
marginLeft: "8@s",
// fontWeight: "bold",
fontFamily: "Yekan",
textAlign: "left",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
line:{
width: "70%",
height: '1@s',
},
});
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch } from 'react-redux';
import { scale, ScaledSheet } from 'react-native-size-matters';
import ButtonLeft from '../components/buttonLeft.js';
import ButtonRight from '../components/buttonRight.js';
const COLORS = ['#a7f1d4','#f5a9c7','#f8dc8f','#65dfea','#fe7ea3'];
export default function Item({index, count, type, title, name, sign, tick, icon}) {
return(
<Animatable.View animation="fadeInRight"
delay={300+100*index}
duration = {500}
useNativeDriver={true}
style={{...styles.item,backgroundColor: "#dff1f6"}}>
<Image transition={false}
resizeMode= 'stretch'
style={styles.tick}
source={tick==true? require('../../assets/images/greenTick.png'):require('../../assets/images/greyTick.png')}/>
<View style={styles.itemButtonContainer}>
<ImageBackground transition={false}
resizeMode= 'stretch'
style={styles.sign}
source={sign==0? require('../../assets/images/Increase_signhdpi.png'):require('../../assets/images/Decrease_signhdpi.png')}>
<View style={styles.countContainer}>
<Text style={styles.countText}>{count.toString()}</Text>
</View>
</ImageBackground>
{type==2?<Text style={styles.minText}>دقیقه</Text>:<></>}
</View>
<View style={styles.itemTextContainer}>
<Text style={styles.textItemMain}>{title}</Text>
<Text style={styles.textItemDescribe}>{name}</Text>
</View>
<Image source={icon} style={styles.itemImageContainer}/>
</Animatable.View>
);
}
const styles = ScaledSheet.create({
item:{
width: "260@s",
height: "40@s",
backgroundColor: "#dff1f6",
borderRadius: "10@s",
flexDirection: "row",
alignItems: "center",
justifyContent:'flex-end' ,
marginBottom: '3@s'
},
itemImageContainer:{
height: "30@s",
width: "30@s",
borderRadius: "10@s",
marginRight: "5@s",
backgroundColor: "#a7f1d4",
},
itemTextContainer:{
height: "40@s",
width: "115@s",
marginRight: "5@s",
},
textItemMain: {
color: "#fe82a4",
fontSize: '12@s',
height: '18@s',
fontWeight: "bold",
fontFamily: "Yekan",
textAlign: "right",
marginRight: "3@s",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
textItemDescribe: {
color: "#2b728c",
fontSize: '9@s',
height: '18@s',
// fontWeight: "bold",
fontFamily: "Yekan",
textAlign: "right",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
itemButtonContainer:{
height: "40@s",
width: "50@s",
marginLeft: "10@s",
alignItems: 'center',
justifyContent: 'center',
},
countContainer:{
height: '30@s',
width: '30@s',
justifyContent: 'center',
},
sign: {
marginTop:'5@s',
height: '30@s',
width: '30@s',
},
tick: {
marginTop:'0@s',
height: '25@s',
width: '25@s',
},
countText: {
fontFamily: "Yekan",
fontSize: '13@s',
textAlign:'center',
color: "#fff",
marginTop: '-2@s'
},
minText: {
alignSelf: 'center',
marginTop: '-5@s',
fontFamily: "Yekan",
fontSize: '9@s',
textAlign:'center',
color: "#2b728c",
},
});
<file_sep>import React, {useState, useEffect,useRef,forwardRef,useImperativeHandle } from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch } from 'react-redux';
import { userHonorToday } from '../actions/user/user_data';
import MailIcon from '../../assets/svg/mailIcon.svg';
import CircleTask from '../../assets/svg/circleTask.svg';
import { scale, ScaledSheet } from 'react-native-size-matters';
import Dialoge from './Dialoge.js';
import DialogWin from './DialogWin.js';
import {Foods1,Foods2} from '../data/foods.js';
import {Activity1,Activity2,Activity3} from '../data/activity.js';
import {TasksData} from '../data/tasks.js';
import ItemTask from '../components/itemsTask.js';
import {todayDays,checkTasksData} from '../data/checkRules.js';
import { soundMuteState, musicMuteState, soundPlay } from '../actions/sound/sound';
const TotalTask = Math.floor(TasksData.length/4);
const Today = todayDays();
const SliceStart = (Today%TotalTask)*4;
const SliceEnd = ((Today%TotalTask)+1)*4;
const Tasks = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
checkTasks(state, values)
{
let checkData= checkTasksData(state,values,SliceStart,SliceEnd);
let lastTotal=totalTask;
if(checkData.total==0 && values.levelFood==3 && values.levelActivity==3)
{
setMedal(true);
dispatch(userHonorToday(true));
if(!medal)toggleWinModal();
}
else {
setMedal(false);
dispatch(userHonorToday(false));
if(checkData.total==0 && lastTotal!=checkData.total)
dispatch(soundPlay('missionend'));
}
if(checkData.total>0 && lastTotal!=checkData.total)
{
if(numberRef.current)numberRef.current.animate("bounceIn");
// if(checkData.total==0)
dispatch(soundPlay('mission'));
}
setTotalTask(checkData.total);
setTicks(checkData.ticks);
// console.log(ticks);
}
}),
)
const [isModalVisible, setModalVisible] = useState(false);
const [isWinVisible, setWinVisible] = useState(false);
const [ticks,setTicks]=useState(new Array(5).fill(false));
const [medal,setMedal]=useState(false);
const [totalTask,setTotalTask]=useState(5);
const dispatch = useDispatch();
const numberRef = useRef();
function foodList() {
// type:1 food, 2:Activity
// sign 0: green, 1:red
return TasksData.slice(SliceStart, SliceEnd).map((data,index) => {
if(data.type==1)
{
if(data.subType==1)
return(
<ItemTask key={index}
index={index}
count={data.value}
sign={0}
title={Foods1.find(item=>item.id==data.id).name}
name={data.name}
type={1}
icon={Foods1.find(item=>item.id==data.id).icon}
tick={ticks[index]}/>
);
if(data.subType==3)
return(
<ItemTask key={index}
index={index}
count={data.value}
sign={1}
title={Foods2.find(item=>item.id==data.id).name}
name={data.name}
type={1}
icon={Foods2.find(item=>item.id==data.id).icon}
tick={ticks[index]}/>
);
}
if(data.type==2)
{
if(data.subType==1)
return(
<ItemTask key={index}
index={index}
count={data.value}
sign={0}
title={Activity1.find(item=>item.id==data.id).name}
name={data.name}
type={2}
icon={Activity1.find(item=>item.id==data.id).icon}
tick={ticks[index]}/>
);
if(data.subType==2)
return(
<ItemTask key={index}
index={index}
count={data.value}
sign={0}
title={Activity2.find(item=>item.id==data.id).name}
name={data.name}
type={2}
icon={Activity2.find(item=>item.id==data.id).icon}
tick={ticks[index]}/>
);
if(data.subType==3)
return(
<ItemTask key={index}
index={index}
count={data.value}
sign={1}
title={Activity3.find(item=>item.id==data.id).name}
name={data.name}
type={2}
icon={Activity3.find(item=>item.id==data.id).icon}
tick={ticks[index]}/>
);
}
})
}
function toggleModal(){
setModalVisible(!isModalVisible);
}
function toggleWinModal(){
setWinVisible(!isWinVisible);
}
return(
<>
<Dialoge isVisible={isModalVisible}
toggleModal={toggleModal}>
<ItemTask key={0}
index={0}
count={""}
sign={0}
title={"نیاز غذایی روزانه"}
name={"مصرف واحدهای غذایی امروز"}
type={1}
icon={require('../../assets/images/daily.png')}
tick={ticks[4]}/>
{foodList()}
</Dialoge>
<DialogWin isVisible={isWinVisible}
toggleModal={toggleWinModal}/>
<TouchableWithoutFeedback onPress={()=>{toggleModal()}}>
<Animatable.View animation="bounceIn" delay={props.delay}>
<MailIcon width={scale(70)} height={scale(70)} />
{totalTask!=0?
<Animatable.View animation="bounceIn" delay={props.delay+400} ref={numberRef} style={{position: 'absolute'}}>
<CircleTask width={scale(35)} height={scale(35)} style={{position: 'absolute'}}/>
<View style={styles.countContainer}>
<Text style={styles.countText}>{totalTask.toString()}</Text>
</View>
</Animatable.View>:
<Image resizeMode= 'stretch' style={{position: 'absolute', height: scale(40), width: scale(40)}} source={medal? require('../../assets/images/medal.png'):require('../../assets/images/Mission_complete.png')}/> }
</Animatable.View>
</TouchableWithoutFeedback>
</>
);
})
const styles = ScaledSheet.create({
countContainer:{
position: 'absolute',
height: '30@s',
width: '30@s',
marginTop: '2@s',
marginLeft: '2@s',
justifyContent: 'center',
},
countText: {
fontFamily: "Yekan",
fontSize: '20@s',
textAlign:'center',
color: "#fff",
marginTop: '-2@s'
},
});
export default Tasks;
<file_sep>import { USER_NAME,USER_GENDER,USER_YEAR,USER_MONTH,USER_BMI,USER_BMI_RANGE,USER_HEIGHT,USER_WEIGHT,USER_HONOR_TODAY,USER_HONORS } from '../../constants/action-types';
export const userName = (user) => (
{
type: USER_NAME,
payload: user,
}
);
export const userGender = (user) => (
{
type: USER_GENDER,
payload: user,
}
);
export const userYear = (user) => (
{
type: USER_YEAR,
payload: user,
}
);
export const userMonth = (user) => (
{
type: USER_MONTH,
payload: user,
}
);
export const userBMI = (user) => (
{
type: USER_BMI,
payload: user,
}
);
export const userBMIRange = (user) => (
{
type: USER_BMI_RANGE,
payload: user,
}
);
export const userHeight = (user) => (
{
type: USER_HEIGHT,
payload: user,
}
);
export const userWeight = (user) => (
{
type: USER_WEIGHT,
payload: user,
}
);
export const userHonorToday = (user) => (
{
type: USER_HONOR_TODAY,
payload: user,
}
);
export const userHonors = (user) => (
{
type: USER_HONORS,
payload: user,
}
);
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
} from 'react-native';
import {openDatabase} from 'react-native-sqlite-storage';
import { Picker, DatePicker } from 'react-native-wheel-pick';
// Connction to access the pre-populated user_db.db
const db = openDatabase(
{
name: 'database.db',
createFromLocation: 1
},
// ()=>console.log("Database Success"),
// ()=>console.log("Daatbase Fail")
);
async function dbTest()
{
await db.transaction(tx => {
tx.executeSql('SELECT * FROM bmi_boys WHERE Month=228', [], (tx, results) => {
let data = results.rows.length;
for (let i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i)); //looping through each row in the table and storing it as object in the 'users' array
}
});
});
}
export default function Screens(props) {
const [date, setDate] = useState(new Date())
useEffect(() => {
dbTest();
},[]);
return(
<View style={{backgroundColor: "#0ee",flex:1, flexDirection: 'row'}}>
<Picker
style={{ backgroundColor: "#0ee", width: 200, height: 215 }}
selectedValue='item4'
pickerData={['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']}
onValueChange={value => { }}
itemSpace={30} // this only support in android
/>
<Picker
style={{ backgroundColor: "#0ee", width: 200, height: 215 }}
selectedValue='item4'
pickerData={['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']}
onValueChange={value => { }}
itemSpace={30} // this only support in android
/>
</View>
);
}
<file_sep>export const TasksData=new Array(
{ type: 1, subType: 1, id:4, value: 2, name: "پیشنهاد مصرف گروه غذایی"},
{ type: 2, subType: 1, id:1, value: 10, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 2, id:1, value: 30, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 3, id:3, value: 60, name: "پیشنهاد کاهش فعالیت"},
{ type: 1, subType: 1, id:1, value: 2, name: "پیشنهاد مصرف گروه غذایی"},
{ type: 2, subType: 1, id:1, value: 20, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 2, id:1, value: 30, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 3, id:1, value: 60, name: "پیشنهاد کاهش فعالیت"},
{ type: 1, subType: 1, id:2, value: 2, name: "پیشنهاد مصرف گروه غذایی"},
{ type: 2, subType: 1, id:2, value: 10, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 2, id:2, value: 30, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 3, id:2, value: 60, name: "پیشنهاد کاهش فعالیت"},
{ type: 1, subType: 1, id:3, value: 2, name: "پیشنهاد مصرف گروه غذایی"},
{ type: 2, subType: 1, id:4, value: 10, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 2, id:0, value: 30, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 3, id:3, value: 60, name: "پیشنهاد کاهش فعالیت"},
{ type: 1, subType: 1, id:0, value: 2, name: "پیشنهاد مصرف گروه غذایی"},
{ type: 2, subType: 1, id:0, value: 10, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 2, id:0, value: 30, name: "پیشنهاد افزایش فعالیت"},
{ type: 2, subType: 3, id:0, value: 60, name: "پیشنهاد کاهش فعالیت"},
);
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Image,
ImageBackground,
Text,
} from 'react-native';
import { ScaledSheet } from 'react-native-size-matters';
export default function ButtonUp(props) {
const [isPressed, setPressButton] = useState(false);
return(
<TouchableWithoutFeedback
onPressIn={()=>setPressButton(true)}
onPressOut={()=>setPressButton(false)}
onPress={()=>{if(props.onPress)props.onPress();}}>
<View style={{...props.style,justifyContent: 'center',alignItems: 'center'}}>
<ImageBackground resizeMode= 'stretch' style={{height: isPressed?"95%":"100%", width: isPressed?"95%":"100%",resizeMode: "stretch",justifyContent:'center'}} source={require('../../assets/images/Min_Bluehdpi.png')}>
</ImageBackground>
</View>
</TouchableWithoutFeedback>
);
}
const styles = ScaledSheet.create({
textHeader: {
color: "white",
marginBottom: '8@s',
fontSize: '24@s',
fontFamily: "Yekan",
textAlign: "center",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
});
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
TextInput,
Image,
ImageBackground,
Dimensions
} from 'react-native';
const { width, height } = Dimensions.get('window')
import * as Animatable from 'react-native-animatable';
import RadioButton from '../components/radioBtn.js';
import Button from '../components/button.js';
import ButtonUp from '../components/buttonUp.js';
import ButtonDown from '../components/buttonDown.js';
import PopUp from '../components/popup.js';
import { Picker } from 'react-native-wheel-pick';
import {
WheelPicker,
} from "react-native-wheel-picker-android";
import { useDispatch, useSelector } from 'react-redux';
import { userYear,userMonth,userBMI,userBMIRange,userHeight,userWeight } from '../actions/user/user_data';
import { scale,ScaledSheet } from 'react-native-size-matters';
import moment from "moment-jalaali";
import { CommonActions } from '@react-navigation/native';
import {openDatabase} from 'react-native-sqlite-storage';
const db = openDatabase(
{
name: 'database.db',
createFromLocation: 1
},
// ()=>console.log("Database Success"),
// ()=>console.log("Daatbase Fail")
);
const Years=Array(14).fill().map((_,idx)=>(moment().jYear()-5-idx).toString());
export default function StartScreen({ navigation }) {
const gender = useSelector(state => state.user.gender);
const [height,setHeight]=useState("110");
const [weight,setWeight]=useState("20");
const [bYear,setbYear]=useState(moment().jYear()-5);
const [bMonth,setbMonth]=useState(0);
const [bmiRange,setBmiRange]=useState(-1);
const dispatch = useDispatch();
useEffect(()=>{
if(bmiRange>-1)
{
dispatch(userBMIRange(bmiRange));
navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'PageMain' },
],
})
);
// navigation.push('PageMain')
}
},[bmiRange])
async function checkBMIRange(BMI,Month,Gender)
{
await db.transaction(async tx => {
let dataset = Gender==0?'bmi_girls':'bmi_boys'
await tx.executeSql('SELECT * FROM '+ dataset +' WHERE Month='+Month.toString(), [], (tx, results) => {
let data = results.rows.length;
// for (let i = 0; i < results.rows.length; i++) {
// console.log(results.rows.item(i)); //looping through each row in the table and storing it as object in the 'users' array
// }
let bmiRange= 2;
if(data>0)
{
if(BMI<results.rows.item(0)["SD3neg"])
bmiRange=0;
else if(BMI<results.rows.item(0)["SD2neg"])
bmiRange=1;
else if(BMI<results.rows.item(0)["SD1"])
bmiRange=2;
else if(BMI<results.rows.item(0)["SD2"])
bmiRange=3;
else
bmiRange=4;
}
// console.log(bmiRange);
setBmiRange(bmiRange);
});
});
}
return(
<View style={styles.container}>
<Animatable.View animation="fadeInDown" delay={500} useNativeDriver={true}>
<PopUp style={styles.image} headerText={"مشخصات"}>
<View style={{flex: 1,alignItems: 'center',marginTop: -15}}>
<Animatable.View animation="fadeInRight"
delay={1000}
style={styles.dialogContainer}
useNativeDriver={true}>
<View style={{flex:.8, alignItems: 'center',justifyContent:'center'}}>
<ButtonUp style={styles.buttonUp} onPress={()=>{if(!isNaN(parseFloat(height)))
setHeight((parseFloat(height)+1).toFixed(0));
else setHeight("110");}}/>
<ButtonDown style={styles.buttonUp} onPress={()=>{if(!isNaN(parseFloat(height)))
{
if(parseFloat(height)>10)
setHeight((parseFloat(height)-1).toFixed(0));
}
else setHeight("20");}}/>
</View>
<View style={{flex:1, alignItems: 'center',justifyContent:'center'}}>
<Text style={styles.textGender}>قد</Text>
<TextInput
style={styles.TextInputStyleClass}
placeholderTextColor = "#8ab6c5"
placeholder=""
numeric
value={height}
keyboardType='number-pad'
onChangeText={(value)=>{setHeight(value)}}
onBlur={()=>{if(isNaN(parseFloat(height)))
setHeight("110");
if(parseFloat(height)<10)
setHeight("10");
}}
maxLength={10}
/>
</View>
<Image style={styles.avatar} source={require('../../assets/images/Height.png')}/>
</Animatable.View>
<Image style={styles.line} source={require('../../assets/images/Line.png')}/>
<Animatable.View animation="fadeInRight"
delay={1200}
style={styles.dialogContainer}
useNativeDriver={true}>
<View style={{flex:.8, alignItems: 'center',justifyContent:'center'}}>
<ButtonUp style={styles.buttonUp} onPress={()=>{if(!isNaN(parseFloat(weight)))
setWeight((parseFloat(weight)+0.1).toFixed(1));
else setWeight("20");}}/>
<ButtonDown style={styles.buttonUp} onPress={()=>{if(!isNaN(parseFloat(weight)))
{
if(parseFloat(weight)>1)
setWeight((parseFloat(weight)-0.1).toFixed(1));
}
else setWeight("20");}}/>
</View>
<View style={{flex:1, alignItems: 'center',justifyContent:'center'}}>
<Text style={styles.textGender}>وزن</Text>
<TextInput
style={styles.TextInputStyleClass}
placeholderTextColor = "#8ab6c5"
placeholder=""
numeric
value={weight}
keyboardType='number-pad'
onChangeText={(value)=>{setWeight(value);}}
onBlur={()=>{if(isNaN(parseFloat(weight)))
setWeight("20");
if(parseFloat(weight)<1)
setWeight("1");
}}
maxLength={10}
/>
</View>
<Image style={styles.avatar} source={require('../../assets/images/Weight.png')}/>
</Animatable.View>
<Image style={styles.line} source={require('../../assets/images/Line.png')}/>
<Animatable.View animation="fadeInRight"
delay={1400}
style={{}}>
<Text style={styles.textDate}>تاریخ تولد</Text>
<View style={{flexDirection: 'row'}}>
<WheelPicker
style={styles.picker}
selectedItem={bMonth}
data={['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر','آبان','آذر','دی','بهمن','اسفند']}
onItemSelected={value => { setbMonth(value);}}
selectedItemTextFontFamily={'Yekan'}
itemTextFontFamily={'Yekan'}
selectedItemTextColor={'#2b728c'}
isCyclic={true}
itemTextSize={scale(12)}
selectedItemTextSize={scale(12)}
/>
<WheelPicker
style={styles.picker}
selectedItem={0}
data={Years}
onItemSelected={value => {setbYear(parseInt(Years[value])); }}
selectedItemTextFontFamily={'Yekan'}
itemTextFontFamily={'Yekan'}
selectedItemTextColor={'#2b728c'}
itemTextSize={scale(12)}
selectedItemTextSize={scale(12)}
/>
</View>
</Animatable.View>
<Animatable.View animation="bounceIn" delay={1800} useNativeDriver={true}>
<Button text={"شروع"} onPress={async()=>{
let heightNum=110;
let weightNum=20;
if(!isNaN(parseFloat(height)))
{
dispatch(userHeight(parseFloat(height)));
heightNum=parseFloat(height);
}
if(!isNaN(parseFloat(weight)))
{
dispatch(userWeight(parseFloat(weight)));
weightNum=parseFloat(weight);
}
dispatch(userYear(bYear));
dispatch(userMonth(bMonth));
let bmi=weight/((height/100)**2);
dispatch(userBMI(bmi));
let month=(moment().jYear()-bYear)*12+(moment().jMonth()-bMonth)
await checkBMIRange(bmi,month,gender);
// console.log(month);
}} style={styles.button}/>
</Animatable.View>
</View>
</PopUp>
</Animatable.View>
</View>
);
}
const styles = ScaledSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
dialogContainer:{
height:'80@s',
flexDirection: 'row',
marginLeft: '30@s',
marginRight: '30@s',
marginBottom: '10@s',
marginTop: '15@s',
alignItems: 'center',
justifyContent: 'center'
},
image: {
aspectRatio: .8,
width: '320@s',
resizeMode: "stretch",
justifyContent: "center"
},
textTitle: {
color: "#e46d8d",
fontSize: '18@s',
fontFamily: "Yekan",
textAlign: "center",
},
textGender: {
marginTop:'-30@s',
color: "#2b728c",
fontSize: '20@s',
fontFamily: "Yekan",
textAlign: "center",
},
textDate: {
color: "#2b728c",
fontSize: '16@s',
fontFamily: "Yekan",
textAlign: "center",
},
TextInputStyleClass:{
height: '35@s',
marginTop: 5,
width: '90@s',
paddingHorizontal: '15@s',
paddingVertical: '3@s',
fontFamily: "Yekan",
fontSize: '17@s',
fontWeight: '300',
textAlign:'center',
borderWidth: 1,
borderRadius: '10@s' ,
borderColor: "#cfedf3",
backgroundColor : "#e2f4f9",
color: "#2b728c",
},
avatar:{
flex:.8 ,
height: '80@s',
resizeMode: 'contain',
},
button:{
height: '50@s',
width: '160@s',
},
buttonUp:{
height: '40@s',
width: '40@s',
margin: '4@s'
},
line:{
width: "70%",
height: '1@s',
},
picker:{
width: '100@s',
height: '100@s',
}
});
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch, useSelector } from 'react-redux';
import { scale, ScaledSheet } from 'react-native-size-matters';
import Item from '../components/itemsValue.js';
import DialogeUnit from '../components/DialogeUnit.js';
import {Foods1, FoodNeeds} from '../data/foods.js';
import { dataFood1 } from '../actions/data/data_actions.js';
import { copilot, walkthroughable, CopilotStep } from "react-native-copilot";
const CopilotView = walkthroughable(View);
function StartScreen({ navigation, start }) {
const bYear = useSelector(({user}) => user.bYear);
const bmiRange = useSelector(({user}) => user.bmiRange);
const food1 = useSelector(({data}) => data.food1);
const dispatch = useDispatch();
const [foodNumber, setFoodNumber] = useState(0);
const [isUnitVisible, setUnitVisible] = useState(false);
function toggleUnit(){
setUnitVisible(!isUnitVisible);
}
function openUnitDialoge(id)
{
setFoodNumber(id);
setUnitVisible(true);
}
const Needs = FoodNeeds(bYear, bmiRange);
function addFood(id){
let foodValue = food1[id]+1;
if(foodValue<100)
{
// food1[id] = foodValue;
dispatch(dataFood1(foodValue,id))
}
}
function decFood(id){
let foodValue = food1[id]-1;
if(foodValue>-1)
{
// food1[id] = foodValue;
dispatch(dataFood1(foodValue,id))
}
}
function foodList() {
return Foods1.map((data) => {
return (
<Item key={data.id} needs={Needs.find(item=>item.id==data.id)} values={data} count={food1[data.id]} addPress={addFood} decPress={decFood} onClick={openUnitDialoge}/>
)
})
}
return(
<>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.container}
source={require('../../assets/images/Sun_Backgroundhdpi.png')}>
<DialogeUnit isVisible={isUnitVisible}
toggleModal={toggleUnit}
data={Foods1[foodNumber]}/>
<TouchableWithoutFeedback
onPress={()=>navigation.pop()}>
<Animatable.Image animation="fadeInDown" delay={1500} useNativeDriver={true} resizeMode= 'stretch'
style={styles.backButton}
source={require('../../assets/images/Arrow.png')}/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={()=>{
start();
}}>
<Animatable.View animation="fadeInDown"
delay={1500}
style={styles.helpIcon}
useNativeDriver={true}>
<Image resizeMode= 'stretch' style={styles.helpIconImage} source={require('../../assets/images/help.png')}/>
</Animatable.View>
</TouchableWithoutFeedback>
<Animatable.View animation="fadeInDown" delay={500} useNativeDriver={true}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/Food_Good.png')}>
<View style={styles.childrenContain}>
<View style={styles.headerContain}>
<Text style={styles.textHeader}>تغذیه سالم</Text>
</View>
<View style={styles.itemContain}>
<CopilotStep
text="گروه های غذایی رو میتونی ثبت کنی"
order={1}
name="group"
>
<CopilotView style={styles.help1}/>
</CopilotStep>
<CopilotStep
text="مقدار مصرفی واحد غذایی رو کم و زیاد کن"
order={2}
name="buttons"
>
<CopilotView style={styles.help2}/>
</CopilotStep>
<CopilotStep
text="با کلیک روی اینجا، میتونی مقدار واحدهای غذایی رو ببینی"
order={3}
name="units"
>
<CopilotView style={styles.help3}/>
</CopilotStep>
{foodList()}
</View>
<Text style={styles.textTip}>نیاز روزانه</Text>
</View>
</ImageBackground>
</Animatable.View>
<TouchableWithoutFeedback
onPress={()=>navigation.navigate('PageFoodNeg')}
>
<Animatable.View animation={'fadeIn'}
delay={2000}
style={{position: 'absolute',
bottom: scale(0),
justifyContent: 'center',
alignItems: 'center',
height: scale(170),
width: scale(150)}}>
<View style={{position: 'absolute', bottom: scale(140)}}>
<Text style={{color: "#2b728c",
fontSize: scale(18),
fontFamily: "Yekan",}}>تغذیه ناسالم</Text>
</View>
<Animatable.Image
animation={'fadeOut'}
duration={2000}
delay={2500}
iterationDelay={100}
iterationCount={'infinite'}
source={require('../../assets/images/Scroll_Down_Flash.png')}
style={{position: 'absolute',
bottom: scale(65),
opacity: 0.5,
width: scale(80),
height: scale(70),
resizeMode: 'stretch'
}}/>
<Animatable.Image
animation={'fadeOut'}
duration={2000}
delay={3000}
iterationDelay={100}
iterationCount={'infinite'}
source={require('../../assets/images/Scroll_Down_Flash.png')}
style={{position: 'absolute',
bottom: scale(30),
opacity: 0.5,
width: scale(70),
height: scale(65),
resizeMode: 'stretch'
}}/>
<Animatable.Image
animation={'fadeOut'}
duration={2000}
delay={3500}
iterationDelay={100}
iterationCount={'infinite'}
source={require('../../assets/images/Scroll_Down_Flash.png')}
style={{position: 'absolute',
bottom: scale(0),
opacity: 0.5,
width: scale(60),
height: scale(60),
resizeMode: 'stretch'
}}/>
</Animatable.View>
</TouchableWithoutFeedback>
</ImageBackground>
</>
);
}
const styles = ScaledSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
dialog: {
height: '355@s',
width: '320@s',
marginBottom: '80@s',
},
childrenContain:{
height: "100%",
width: "100%",
marginTop: '5@s',
alignItems: 'center',
},
headerContain:{
marginTop: '55@s',
width: "100%",
height: "33@s",
justifyContent:'flex-start'
},
textHeader: {
color: "white",
fontSize: '18@s',
fontFamily: "Yekan",
textAlign: "left",
marginLeft: '60@s',
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
textTip: {
width: "100%",
color: "#2b728c",
fontSize: '10@s',
fontFamily: "Yekan",
textAlign: "left",
marginLeft: "40@s",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
itemContain:{
marginTop:'8@s'
},
textScroll: {
position: "absolute",
bottom: scale(130),
color: "#2b728c",
fontSize: '18@s',
fontFamily: "Yekan",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
backButton:{
position: 'absolute',
top: '20@s',
left: '10@s',
width: '90@s',
height: '60@s',
},
helpIcon:{
position: 'absolute',
right: '19@s',
top: '30@s'
},
helpIconImage:{
height: '39@s',
width: '39@s',
},
help1:{
position: 'absolute',
top: '15@vs',
right: '-2@s',
height: '50@s',
width: '285@s'
},
help2:{
position: 'absolute',
top: '15@vs',
right: '140@s',
height: '50@s',
width: '100@s',
},
help3:{
position: 'absolute',
top: '15@vs',
right: '240@s',
height: '50@s',
width: '50@s',
}
});
export default copilot({
animated: true, // Can be true or false
overlay: 'view', // Can be either view or svg
labels: {
previous: "قبلی",
next: "بعدی",
skip: "رد کردن",
finish: "بستن"
}
})(StartScreen);
<file_sep>// RootNavigation.js
import * as React from 'react';
import { StackActions, NavigationActions,CommonActions } from '@react-navigation/native';
export const isReadyRef = React.createRef();
export const navigationRef = React.createRef();
export function navigate(name, params) {
if (isReadyRef.current && navigationRef.current) {
// Perform navigation if the app has mounted
if(typeof navigationRef.current.getRootState() !== 'undefined')
navigationRef.current.navigate(name, params);
}
}
export function reset(name, params) {
if (isReadyRef.current && navigationRef.current) {
if(typeof navigationRef.current.getRootState() !== 'undefined')
navigationRef.current.dispatch(CommonActions.reset({
index: 1,
routes: [
{
name: name,
params: params,
},
],
}));
}
}
// add other navigation functions that you need and export them
<file_sep>// @flow
import {
DATA_FOOD1,DATA_FOOD2,DATA_ACTIVITY1,DATA_ACTIVITY2,DATA_ACTIVITY3,DATA_DATE,DATA_RESET
} from '../constants/action-types';
import moment from "moment-jalaali";
const MAX_DATA=15;
const initialState = {
food1: new Array(MAX_DATA).fill(0),
food2: new Array(MAX_DATA).fill(0),
active1: new Array(MAX_DATA).fill(0),
active2: new Array(MAX_DATA).fill(0),
active3: new Array(MAX_DATA).fill(0),
lastDay: Math.floor(moment().valueOf()/8.64e7)
};
const dataReducer = (state = initialState, action) => {
switch (action.type) {
case DATA_FOOD1: {
let food1 = [...state.food1];
food1[action.id] = action.payload;
return {
...state,
food1: food1,
// food1: state.food1[action.id] = action.payload,
};
}
case DATA_FOOD2: {
let food2 = [...state.food2];
food2[action.id] = action.payload;
// console.log({
// ...state,
// food1: state.food1[action.id] = action.payload,
// });
return {
...state,
food2: food2,
};
}
case DATA_ACTIVITY1: {
let active1 = [...state.active1];
active1[action.id] = action.payload;
return {
...state,
active1: active1,
};
}
case DATA_ACTIVITY2: {
let active2 = [...state.active2];
active2[action.id] = action.payload;
return {
...state,
active2: active2,
};
}
case DATA_ACTIVITY3: {
let active3 = [...state.active3];
active3[action.id] = action.payload;
return {
...state,
active3: active3,
};
}
case DATA_DATE: {
return {
...state,
lastDay: action.payload,
};
}
case DATA_RESET: {
return {
...state,
food1: new Array(MAX_DATA).fill(0),
food2: new Array(MAX_DATA).fill(0),
active1: new Array(MAX_DATA).fill(0),
active2: new Array(MAX_DATA).fill(0),
active3: new Array(MAX_DATA).fill(0),
};
}
default: {
return state;
}
}
};
export default dataReducer;
<file_sep>// @flow
import {
USER_NAME,USER_GENDER,USER_YEAR,USER_MONTH,USER_BMI,USER_BMI_RANGE,USER_HEIGHT,USER_WEIGHT,
USER_HONOR_TODAY, USER_HONORS
} from '../constants/action-types';
const initialState = {
name: '',
gender: 0,
bmi: 0,
bmiRange: 0,
bYear: 0,
bMonth: 0,
weight: 0,
height: 0,
todayHonor: false,
honors: 0,
};
const userReducer = (state = initialState, action) => {
switch (action.type) {
case USER_NAME: {
return {
...state,
name: action.payload,
};
}
case USER_GENDER: {
return {
...state,
gender: action.payload,
};
}
case USER_YEAR: {
return {
...state,
bYear: action.payload,
};
}
case USER_MONTH: {
return {
...state,
bMonth: action.payload,
};
}
case USER_BMI: {
return {
...state,
bmi: action.payload,
};
}
case USER_BMI_RANGE: {
return {
...state,
bmiRange: action.payload,
};
}
case USER_HEIGHT: {
return {
...state,
height: action.payload,
};
}
case USER_WEIGHT: {
return {
...state,
weight: action.payload,
};
}
case USER_HONOR_TODAY: {
return {
...state,
todayHonor: action.payload,
};
}
case USER_HONORS: {
return {
...state,
honors: action.payload,
};
}
default: {
return state;
}
}
};
export default userReducer;
<file_sep>import React, {useState, useEffect} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Image,
ImageBackground,
Text,
} from 'react-native';
import { scale,ScaledSheet } from 'react-native-size-matters';
import {todayDays, weekDay} from '../data/checkRules.js';
export default function plot() {
const [medal,setMedal]=useState(new Array(7).fill(false));
const [level,setLevel]=useState(new Array(7).fill(-1));
const [today,setToday]=useState(0);
const [weekDayState, setWeekDay]=useState(0);
useEffect(()=>{
let Today = todayDays();
let WeekDay = weekDay(WeekDay);
setToday(Today);
setWeekDay(WeekDay)
weeklyData(Today,WeekDay);
},[]);
function weeklyData(todayValue,weekDayValue)
{
db.transaction(async tx => {
tx.executeSql('SELECT * FROM daily_data WHERE Day BETWEEN '+(todayValue-weekDayValue).toString() +' AND ' +todayValue.toString(), [],
(tx, results) => {
let data = results.rows.length;
let levels = new Array(7).fill(-1);
let medals = new Array(7).fill(false);
var i;
for (i = 0; i < data; i++) {
let day = results.rows.item(i)["Day"];
let activityLevel = results.rows.item(i)["ActivityLevel"];
let foodLevel = results.rows.item(i)["FoodLevel"];
let medal = results.rows.item(i)["Honor"];
let weekLast = todayValue-day;
console.log(weekLast);
if(weekLast>0)
{
levels[weekDayValue-weekLast-1] = Math.min(activityLevel,foodLevel);
if(medal>0) medals[weekDayValue-weekLast-1]=true;
}
}
for (i = 0; i < weekDayValue-1; i++) {
if(levels[i]==-1)
levels[i]=0;
}
setMedal(medals);
setLevel(levels);
});
});
}
function showPlot(pos)
{
return(
<>
<View style={{flex:1, zIndex: 100}}>
{medal[pos]?<Image style={{height: scale(20), width: scale(20)}} source={require('../../assets/images/medal.png')}/>:<></>}
</View>
<View style={{flex:1}}>
{level[pos]==3?<Image style={{height: scale(20), width: scale(20)}} source={require('../../assets/images/Green.png')}/>:<></>}
</View>
<View style={{flex:1}}>
{level[pos]==2?<Image style={{height: scale(20), width: scale(20)}} source={require('../../assets/images/Yellow.png')}/>:<></>}
</View>
<View style={{flex:1}}>
{level[pos]==1?<Image style={{height: scale(20), width: scale(20)}} source={require('../../assets/images/Red.png')}/>:<></>}
</View>
<View style={{flex:1}}>
{level[pos]==0?<Image style={{height: scale(20), width: scale(20)}} source={require('../../assets/images/Grey.png')}/>:<></>}
</View>
</>
);
}
return(
<View style={styles.plotContainer}>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==1?"#d0e0ff":'#f0f0f0'}}>
{showPlot(0)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>شنبه</Text>
</View>
</View>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==2?"#d0e0ff":'#f0f0f0'}}>
{showPlot(1)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>یکشنبه</Text>
</View>
</View>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==3?"#d0e0ff":'#f0f0f0'}}>
{showPlot(2)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>دوشنبه</Text>
</View>
</View>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==4?"#d0e0ff":'#f0f0f0'}}>
{showPlot(3)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>سه شنبه</Text>
</View>
</View>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==5?"#d0e0ff":'#f0f0f0'}}>
{showPlot(4)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>چهارشنبه</Text>
</View>
</View>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==6?"#d0e0ff":'#f0f0f0'}}>
{showPlot(5)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>پنج شنبه</Text>
</View>
</View>
<View style={{...styles.bmiParts,backgroundColor: weekDayState==7?"#d0e0ff":'#f0f0f0'}}>
{showPlot(6)}
<View style={{flex:1.5}}>
<Text style={styles.textValues}>جمعه</Text>
</View>
</View>
<View style={styles.bmiParts}>
<View style={{flex:1}}>
<Text style={styles.textValuesLabel}></Text>
</View>
<View style={{flex:1}}>
<Text style={{...styles.textValuesLabel,color:"#0f0"}}>عالی</Text>
</View>
<View style={{flex:1}}>
<Text style={{...styles.textValuesLabel,color:"#fa0"}}>متوسط</Text>
</View>
<View style={{flex:1}}>
<Text style={{...styles.textValuesLabel,color:"#f00"}}>بد</Text>
</View>
<View style={{flex:1}}>
<Text style={styles.textValuesLabel}>ثبت نکردی</Text>
</View>
<View style={{flex:1.5}}>
</View>
</View>
</View>
);
}
const styles = ScaledSheet.create({
plotContainer:{
flex: 1,
flexDirection: 'row',
backgroundColor: '#f0f0f0',
borderRadius: '10@s',
paddingLeft: '10@s'
},
bmiValueContainer:{
height: '40@s',
width: '45@s',
position: 'absolute',
top: '-35@s'
},
bmiParts:{
flex:1,
alignItems: 'center',
justifyContent: 'flex-end'
},
textValues: {
color: "#a2a2a2",
marginTop: '4@s',
marginBottom: '8@s',
fontSize: '9@s',
fontFamily: "Yekan",
textAlign: "center",
transform: [{ rotate: '-45deg'}]
},
textValuesLabel: {
color: "#a2a2a2",
fontSize: '9@s',
marginTop: '-5@s',
fontFamily: "Yekan",
textAlign: "center",
},
textBMIValues: {
color: "white",
marginBottom: '8@s',
fontSize: '15@s',
fontFamily: "Yekan",
textAlign: "center",
},
textTitle: {
color: "#0f3648",
marginBottom: '8@s',
fontSize: '12@s',
fontFamily: "Yekan",
textAlign: "center",
},
});
<file_sep>import { SOUND_PLAY, SOUND_PLAY_MUSIC, SOUND_STOP_MUSIC, SOUND_STOP_ALL, SOUND_MUTE, MUSIC_MUTE } from '../../constants/action-types';
export const soundPlay = (sound) => (
(dispatch: Function)=>
{
return soundStopAllThis(dispatch).then(()=>dispatch(soundPlayThis(sound)));
}
);
export const soundStopAllThis = (dispatch) => {
return new Promise((resolve, reject) => {
dispatch(soundStopAll());
resolve();
});
}
export const soundPlayThis = (sound) => (
{
type: SOUND_PLAY,
payload: sound,
}
);
export const soundPlayMusic = (music) => (
{
type: SOUND_PLAY_MUSIC,
payload: music,
}
);
export const soundStopMusic = () => (
{
type: SOUND_STOP_MUSIC,
payload: '',
}
);
export const soundStopAll = () => (
{
type: SOUND_STOP_ALL,
}
);
export const soundMuteState = (mute) => (
{
type: SOUND_MUTE,
payload: mute,
}
);
export const musicMuteState = (mute) => (
{
type: MUSIC_MUTE,
payload: mute,
}
);
<file_sep>import React from 'react';
import {
View,
Text,
Image,
ImageBackground,
TouchableWithoutFeedback
} from 'react-native';
import Modal from 'react-native-modal';
import { scale, ScaledSheet } from 'react-native-size-matters';
import { soundMuteState, musicMuteState, soundPlay } from '../actions/sound/sound';
import { useDispatch } from 'react-redux';
export default function Dialoge(props) {
const dispatch = useDispatch();
function toggleModal(){
if(props.toggleModal) props.toggleModal()
if(props.close) props.close()
}
return(
<Modal isVisible={props.isVisible}
//onBackdropPress={() => toggleModal()}
onBackButtonPress={() => toggleModal()}
animationIn="slideInDown"
animationOut="slideOutDown"
animationInTiming={600}
animationOutTiming={400}
backdropTransitionInTiming={0}
backdropTransitionOutTiming={0}
onModalWillShow={()=>dispatch(soundPlay('popupopen'))}
onModalWillHide={()=>dispatch(soundPlay('popup'))}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/Task_Border.png')}>
<View style={{position: 'absolute', top: scale(48),left: scale(50)}}>
<Text style={{color: "white",
fontSize: scale(15),
fontFamily: "Yekan",}}>پیشنهاد روزانه</Text>
</View>
<TouchableWithoutFeedback onPress={()=>toggleModal()}>
<View style={styles.closeButtonContainer}>
<Image source={require('../../assets/images/Close.png')}
style={styles.closeButton}/>
</View>
</TouchableWithoutFeedback>
<View style={styles.childrenContain}>
{props.children}
</View>
</ImageBackground>
</Modal>
);
};
const styles = ScaledSheet.create({
dialog: {
height: '325@s',
width: '300@s',
marginBottom: '80@s',
},
closeButtonContainer:{
position: 'absolute',
top: '15@s'
},
closeButton:{
resizeMode: 'stretch',
height:'40@s',
width:'40@s'
},
childrenContain:{
height: "100%",
width: "100%",
marginTop: '90@s',
alignItems: 'center',
},
});
<file_sep>// @flow
export const USER_NAME = 'USER_NAME';
export const USER_GENDER = 'USER_GENDER';
export const USER_YEAR = 'USER_YEAR';
export const USER_MONTH = 'USER_MONTH';
export const USER_BMI = 'USER_BMI';
export const USER_BMI_RANGE = 'USER_BMI_RANGE';
export const USER_HEIGHT = 'USER_HEIGHT';
export const USER_WEIGHT = 'USER_WEIGHT';
export const USER_HONOR_TODAY = 'USER_HONOR_TODAY';
export const USER_HONORS = 'USER_HONORS';
export const DATA_FOOD1 = 'DATA_FOOD1';
export const DATA_FOOD2 = 'DATA_FOOD2';
export const DATA_ACTIVITY1 = 'DATA_ACTIVITY1';
export const DATA_ACTIVITY2 = 'DATA_ACTIVITY2';
export const DATA_ACTIVITY3 = 'DATA_ACTIVITY3';
export const DATA_DATE = 'DATA_DATE';
export const DATA_RESET = 'DATA_RESET';
export const SOUND_PLAY = 'SOUND_PLAY';
export const SOUND_PLAY_MUSIC = 'SOUND_PLAY_MUSIC';
export const SOUND_STOP_MUSIC = 'SOUND_STOP_MUSIC';
export const SOUND_STOP_ALL = 'SOUND_STOP_ALL';
export const SOUND_MUTE = 'SOUND_MUTE';
export const MUSIC_MUTE = 'MUSIC_MUTE';
<file_sep>import moment from "moment-jalaali";
import {TasksData} from '../data/tasks.js';
import {FoodNeeds} from '../data/foods.js';
export const todayDays = () =>
{
return Math.floor(moment().valueOf()/8.64e7);
}
export const weekDay = () =>
{
let day = moment().isoWeekday();
if(day==6)
day=1;
else if(day==7)
day=2;
else {
day=day+2;
}
return day;
}
export const checkRules = (state) =>
{
let bmiRange=state.user.bmiRange; //0: very Thin, 1: Thin, 2: Normal 3: Fat, 4: Very Fat
let bYear = state.user.bYear;
//(accumulator, currentValue)
let totalFood = state.data.food1.reduce((a,b)=>a+b)+state.data.food2.reduce((a,b)=>a+b);
let goodFood = state.data.food1.reduce((a,b)=>a+b);
let badFood = state.data.food2.reduce((a,b)=>a+b);
let highActivity = state.data.active1.reduce((a,b)=>a+b);
let lowActivity = state.data.active2.reduce((a,b)=>a+b);
let badActivity = state.data.active3.reduce((a,b)=>a+b);
let levelFood=0;
let levelActivity=0;
let tipFood="";
let tipActivity="";
const Needs = FoodNeeds(bYear, bmiRange);
if(totalFood==0)
{
levelFood=0;
tipFood="واحدهای غذایی امروز رو ثبت نکردی";
}
else
{
if(badFood==0)
{
let notEat=Needs.reduce((acc,value,index)=>{
if(state.data.food1[index]>=value.min && state.data.food1[index]<=value.max)
return acc;
else
return acc=acc+1;},
0);
let badEat=Needs.reduce((acc,value,index)=>{
if(state.data.food1[index]>value.max)
return acc=acc+1;
else
return acc;},
0);
if(badEat>0)
{
levelFood=1;
tipFood=`${badEat} نوع غذای سالم بیشتر از نیاز روزانه مصرف کردی`;
}
else if(notEat>0)
{
levelFood=2;
tipFood=`${notEat} نوع غذای سالم به اندازه نیاز روزانه مصرف نکردی`;
}
else {
levelFood=3;
tipFood="";
}
}
else {
if(bmiRange<3)
{
if(badFood==1)
{
levelFood=2;
tipFood=`${badFood} وعده غذایی ناسالم داری`;
}
else if(badFood==2){
levelFood=2;
tipFood=`${badFood} وعده غذایی ناسالم داری`
}
else {
levelFood=1;
tipFood=`${badFood} وعده غذایی ناسالم داری`
}
}
else {
if(badFood==1)
{
levelFood=2;
tipFood=`${badFood} وعده غذایی ناسالم داری`
}
else {
levelFood=1;
tipFood=`${badFood} وعده غذایی ناسالم داری`
}
}
if(state.data.food2[1]!=0)
{
levelFood=1;
tipFood=`بهتره فست فودها رو کمتر مصرف کنی`;
}
}
}
let totalActive=highActivity*2+lowActivity-badActivity;
if(bmiRange<3)
{
if(highActivity>=30 && lowActivity>=60)
{
if(badActivity<120)
{
levelActivity=3;
tipActivity=""
}
else {
levelActivity=2;
tipActivity="باید عادت رفتاری غیر فعال رو به کمتر از 2 ساعت برسونی"
}
}
else {
if(badActivity<120)
{
if(lowActivity<60)
{
levelActivity=2;
tipActivity="باید روزانه 60 دقیقه عادت رفتاری نیمه فعال داشته باشی"
}
else {
levelActivity=2;
tipActivity="روزانه 30 دقیقه عادت رفتاری فعال نیاز داری"
}
}
else {
levelActivity=1;
tipActivity="باید عادت رفتاری غیر فعال رو به کمتر از 2 ساعت برسونی"
}
}
}
else {
if(highActivity>=30 && lowActivity>=60)
{
if(badActivity<60)
{
if(badActivity<30)
{
levelActivity=3;
tipActivity=""
}
else {
levelActivity=2;
tipActivity="عادت رفتاری غیر فعال رو باید کم کنی";
}
}
else {
levelActivity=1;
tipActivity="باید عادت رفتاری غیر فعال رو به کمتر از 1 ساعت برسونی"
}
}
else {
if(badActivity<60)
{
if(lowActivity<60)
{
levelActivity=1;
tipActivity="روزانه باید 60 دقیقه عادت رفتاری نیمه فعال داشته باشی"
}
else {
levelActivity=1;
tipActivity="روزانه 30 دقیقه عادت رفتاری فعال نیاز داری"
}
}
else {
levelActivity=1;
tipActivity="باید عادت رفتاری غیر فعال رو به کمتر از 1 ساعت برسونی"
}
}
}
if(highActivity+lowActivity==0 && badActivity==0)
{
if(totalFood==0)
{
levelActivity=0;
tipActivity="فعالیت امروز رو ثبت نکردی";
}
else {
if(bmiRange<3)
{
levelActivity=2;
tipActivity= "روزانه 30 دقیقه عادت رفتاری فعال نیاز داری"
}
else {
levelActivity=1;
tipActivity="روزانه باید 30 دقیقه عادت رفتاری فعال داشته باشی"
}
}
}
return {levelFood:levelFood, tipFood:tipFood, levelActivity:levelActivity, tipActivity:tipActivity};
}
export const checkTasksData = (state, values, SliceStart, SliceEnd) =>
{
let bmiRange=state.user.bmiRange; //0: very Thin, 1: Thin, 2: Normal 3: Fat, 4: Very Fat
let bYear = state.user.bYear;
const Needs = FoodNeeds(bYear, bmiRange);
let notEat=Needs.reduce((acc,value,index)=>{
if(state.data.food1[index]>=value.min && state.data.food1[index]<=value.max)
return acc;
else
return acc=acc+1;},
0);
console.log("notEat"+notEat);
let temp=new Array(5).fill(false);
if(notEat==0) temp[4]=true;
TasksData.slice(SliceStart, SliceEnd).map((data,index) => {
if(data.type==1)
{
if(values.levelFood>0)
{
if(data.subType==1)
{
if(state.data.food1[data.id]>=data.value)
temp[index]=true;
else
temp[index]=false;
}
if(data.subType==3)
{
if(state.data.food2[data.id]<data.value)
temp[index]=true;
else
temp[index]=false;
}
}
else
temp[index]=false;
}
if(data.type==2)
{
if(values.levelActivity>0)
{
if(data.subType==1)
{
if(state.data.active1[data.id]>=data.value)
temp[index]=true;
else
temp[index]=false;
}
if(data.subType==2)
{
if(state.data.active2[data.id]>=data.value)
temp[index]=true;
else
temp[index]=false;
}
if(data.subType==3)
{
if(state.data.active3[data.id]<data.value)
temp[index]=true;
else
temp[index]=false;
}
}
else
temp[index]=false;
}
});
// temp[0]=true;
let total = 5-temp.reduce((a,b)=>{if(b)return a+1;else return a;},0);
return {ticks:temp, total:total};
}
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import Screens from "./src/screens";
import {
SafeAreaView,
StatusBar
} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef, isReadyRef } from './RootNavigation';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';
import { ThemeProvider } from 'styled-components';
import { ToastProvider } from 'react-native-styled-toast';
import { scale } from 'react-native-size-matters';
const theme= {
space: [0, 4, 8, 12, 16, 20, 24, 32, 40, 48],
fontFamily: "Yekan",
colors: {
text: '#0A0A0A',
background: '#FFF',
border: '#E2E8F0',
muted: '#F0F1F3',
success: '#7DBE31',
error: '#FC0021',
info: '#00FFFF'
}
}
import {store} from './src/store/configureStore';
const persistor = persistStore(store);
import {openDatabase} from 'react-native-sqlite-storage';
global.db = openDatabase(
{
name: 'database1.db',
createFromLocation: 1
},
()=>console.log("Database Success"),
()=>console.log("Daatbase Fail")
);
const App: () => React$Node = () => {
return (
<>
<ThemeProvider theme={{...theme}}>
<ToastProvider maxToasts={3} offset={scale(50)} position="BOTTOM">
<StatusBar barStyle="dark-content" />
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<NavigationContainer ref={navigationRef} onReady={() => {
isReadyRef.current = true;
}}>
<Screens/>
</NavigationContainer>
</PersistGate>
</Provider>
</ToastProvider>
</ThemeProvider>
</>
);
};
export default App;
<file_sep>import React,{useEffect} from 'react';
import {
View,
Text,
Image,
ImageBackground,
TouchableWithoutFeedback
} from 'react-native';
import Modal from 'react-native-modal';
import { scale, ScaledSheet } from 'react-native-size-matters';
import { useDispatch, useSelector } from 'react-redux';
import { soundMuteState, musicMuteState, soundPlay } from '../actions/sound/sound';
import Button from './button.js';
export default function Dialoge(props) {
// const sound = useSelector(state => state.sound);
const soundMute = useSelector(({sound}) => sound.soundMute);
const musicMute = useSelector(({sound}) => sound.musicMute);
const dispatch = useDispatch();
function toggleModal(){
if(props.toggleModal) props.toggleModal()
if(props.close) props.close()
// dispatch(soundPlay("popup"));
}
return(
<Modal isVisible={props.isVisible}
//onBackdropPress={() => toggleModal()}
onBackButtonPress={() => toggleModal()}
animationIn="slideInDown"
animationOut="slideOutDown"
animationInTiming={600}
animationOutTiming={400}
backdropTransitionInTiming={0}
backdropTransitionOutTiming={0}
onModalWillShow={()=>dispatch(soundPlay('popupopen'))}
onModalWillHide={()=>dispatch(soundPlay('popup'))}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/popup.png')}>
<View style={{position: 'absolute', top: scale(20), alignSelf: 'center'}}>
<Text style={{color: "white",
fontSize: scale(18),
fontFamily: "Yekan",}}>تنظیمات</Text>
</View>
<TouchableWithoutFeedback onPress={()=>toggleModal()}>
<View style={styles.closeButtonContainer}>
<Image source={require('../../assets/images/Close.png')}
style={styles.closeButton}/>
</View>
</TouchableWithoutFeedback>
<View style={styles.childrenContain}>
<View style = {{flex: 1, flexDirection: 'row',justifyContent:'center'}}>
<View style={{flex:1,alignItems:'center'}}>
<Text style={{color: "#2b728c",
fontSize: scale(14),
fontFamily: "Yekan",
textAlign: 'center'}}>صدا</Text>
<TouchableWithoutFeedback onPress={()=>dispatch(soundMuteState(!soundMute))}>
<View>
<ImageBackground resizeMode= 'stretch' style={styles.sliderBack} source={soundMute?require('../../assets/images/Green_Slider.png'):require('../../assets/images/Gray_Slider.png')}>
{!soundMute?<ImageBackground resizeMode= 'stretch' style={styles.slider} source={require('../../assets/images/Grey.png')}>
<Image style={styles.icon} source={require('../../assets/images/Sound_Icon.png')}/>
</ImageBackground>:<></>}
{soundMute?<ImageBackground resizeMode= 'stretch' style={styles.sliderLeft} source={require('../../assets/images/Green.png')}>
<Image style={styles.icon} source={require('../../assets/images/Sound_Icon.png')}/>
</ImageBackground>:<></>}
</ImageBackground>
</View>
</TouchableWithoutFeedback>
</View>
<View style={{flex:1, alignItems:'center'}}>
<Text style={{color: "#2b728c",
fontSize: scale(14),
fontFamily: "Yekan",
textAlign: 'center'}}>موسیقی</Text>
<TouchableWithoutFeedback onPress={()=>dispatch(musicMuteState(!musicMute))}>
<View>
<ImageBackground resizeMode= 'stretch' style={styles.sliderBack} source={musicMute?require('../../assets/images/Green_Slider.png'):require('../../assets/images/Gray_Slider.png')}>
{!musicMute?<ImageBackground resizeMode= 'stretch' style={styles.slider} source={require('../../assets/images/Grey.png')}>
<Image style={styles.icon} source={require('../../assets/images/Music_Icon.png')}/>
</ImageBackground>:<></>}
{musicMute?<ImageBackground resizeMode= 'stretch' style={styles.sliderLeft} source={require('../../assets/images/Green.png')}>
<Image style={styles.icon} source={require('../../assets/images/Music_Icon.png')}/>
</ImageBackground>:<></>}
</ImageBackground>
</View>
</TouchableWithoutFeedback>
</View>
</View>
<Image style={styles.line} source={require('../../assets/images/Line.png')}/>
<TouchableWithoutFeedback onPress={()=>{toggleModal();props.navigation.navigate('PageName');}}>
<View style = {{flex: 1.2, flexDirection: 'row',justifyContent:'center',alignItems: 'center'}}>
<Image style={styles.icon} source={require('../../assets/images/edit.png')}/>
<Text style={{color: "#2b728c",
fontSize: scale(14),
fontFamily: "Yekan",
textAlign: 'center'}}> ویرایش مشخصات</Text>
</View>
</TouchableWithoutFeedback>
<Button text={"بستن"} onPress={()=>{
toggleModal();
}} style={styles.button}/>
</View>
</ImageBackground>
</Modal>
);
};
const styles = ScaledSheet.create({
dialog: {
height: '350@s',
width: '280@s',
marginBottom: '50@s',
alignSelf: 'center'
},
closeButtonContainer:{
position: 'absolute',
top: '0@s',
left: '5@s'
},
closeButton:{
resizeMode: 'stretch',
height:'45@s',
width:'45@s'
},
childrenContain:{
alignSelf: 'center',
height: '70%',
width: '90%',
marginTop: '90@s',
alignItems: 'center',
},
sliderBack: {
height: '32@s',
width: '80@s',
marginTop: '5@s',
resizeMode: 'stretch',
},
slider:{
height: '45@s',
width: '45@s',
position: 'absolute',
top: '-8@s',
left: '-8@s',
justifyContent: 'center'
},
sliderLeft:{
height: '45@s',
width: '45@s',
position: 'absolute',
top: '-8@s',
right: '-8@s',
justifyContent: 'center'
},
icon:{
height: '20@s',
width: '20@s',
alignSelf: 'center',
resizeMode: 'stretch',
},
line:{
width: "70%",
height: '1@s',
},
button:{
height: '50@s',
width: '140@s',
marginBottom: '10@s'
}
});
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch, useSelector } from 'react-redux';
import { scale, ScaledSheet } from 'react-native-size-matters';
import Item from '../components/items.js';
import {Activity3} from '../data/activity.js';
import { dataActivity3 } from '../actions/data/data_actions.js';
export default function PageActivityNeg({ navigation }) {
const active3 = useSelector(({data}) => data.active3);
const dispatch = useDispatch();
function addActivity(id){
let activityValue=active3[id]+10;
if(activityValue<999)
{
// food1[id] = foodValue;
dispatch(dataActivity3(activityValue,id))
}
}
function decActivity(id){
let activityValue=active3[id]-10;
if(activityValue>-1)
{
// food1[id] = foodValue;
dispatch(dataActivity3(activityValue,id))
}
}
function activityList() {
return Activity3.map((data) => {
return (
<Item key={data.id} values={data} count={active3[data.id]} addPress={addActivity} decPress={decActivity}/>
)
})
}
return(
<>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.container}
source={require('../../assets/images/Rain_back.png')}>
<TouchableWithoutFeedback
onPress={()=>navigation.pop()}>
<Animatable.Image animation="fadeInDown" delay={1500} useNativeDriver={true} resizeMode= 'stretch'
style={styles.backButton}
source={require('../../assets/images/Arrow.png')}/>
</TouchableWithoutFeedback>
<Animatable.View animation="fadeInDown" delay={500} useNativeDriver={true}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/bad_activity.png')}>
<View style={styles.childrenContain}>
<View style={styles.headerContain}>
<Text style={styles.textHeader}>عادت های رفتاری غیر فعال</Text>
</View>
<View style={styles.itemContain}>
{activityList()}
</View>
</View>
</ImageBackground>
</Animatable.View>
</ImageBackground>
</>
);
}
const styles = ScaledSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
dialog: {
height: '325@s',
width: '300@s',
marginBottom: '80@s',
},
childrenContain:{
height: "100%",
width: "100%",
marginTop: '20@s',
alignItems: 'center',
},
headerContain:{
marginTop: '50@s',
width: "100%",
height: "33@s",
justifyContent:'flex-start'
},
textHeader: {
color: "white",
fontSize: '9@s',
fontFamily: "Yekan",
textAlign: "right",
marginRight: '48@s',
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
itemContain:{
marginTop:'8@s'
},
textScroll: {
position: "absolute",
bottom: scale(130),
color: "#2b728c",
fontSize: '18@s',
fontFamily: "Yekan",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
backButton:{
position: 'absolute',
top: 20,
left: 10,
width: '90@s',
height: '60@s',
}
});
<file_sep>import React, {useState,useEffect} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Image,
ImageBackground,
Text,
} from 'react-native';
import { scale,ScaledSheet } from 'react-native-size-matters';
import { useToast } from 'react-native-styled-toast';
const Bars=[
require('../../assets/images/bar_0.png'),
require('../../assets/images/bar_25.png'),
require('../../assets/images/bar_75.png'),
require('../../assets/images/bar_100.png')
];
const COLORS=[
["#EEF2FA","#2E5AAC","#89A7E0"],
["#FEEFEF","#DA1414","#f48989"],
["#FFF4EC","#B95000","#FF8F39"],
["#EDF9F0","#28FD3C","#5ACA75"]
]
export default function BarColor({level,info,tip,icon}) {
const { toast } = useToast();
function showTip()
{
// console.log("Toast");
toast({
message: tip,
messageFontSize: scale(15),
messageFontFamily: "Yekan",
toastStyles: {
bg: COLORS[level][0],
borderRadius: 10,
borderColor: COLORS[level][2],
borderWidth: 2,
},
color: COLORS[level][1],
iconColor: COLORS[level][1],
iconFamily: 'Ionicons',
//iconName: 'restaurant',
// iconName: 'ios-bicycle',
iconName: icon,
iconSize: scale(24),
closeIconFamily: 'Ionicons',
closeIconName: 'close',
closeButtonStyles: {
px: 4,
bg: COLORS[level][1],
borderRadius: 10
},
closeIconColor: 'white',
hideAccent: true,
});
}
useEffect(() => {
if(tip!="")setTimeout(()=>showTip(),info*1000);
}, [tip]);
return(
<View style={styles.barContain}>
<ImageBackground style={{height: "100%", width: "100%"}}
resizeMode={'cover'}
source={Bars[level]}>
</ImageBackground>
{tip!=""?<TouchableWithoutFeedback onPress={()=>{showTip();}}>
{info==0?<Image source={require('../../assets/images/info.png')} style={styles.infoIconRight}/>:<Image source={require('../../assets/images/info.png')} style={styles.infoIcon}/>}
</TouchableWithoutFeedback>:<></>}
</View>
)
}
const styles = ScaledSheet.create({
barContain:{
height: '16@s',
width: "90@s",
position: 'absolute',
bottom: '60@s',
alignSelf: 'center'
},
infoIcon:{
position: "absolute",
bottom: '-50@s',
left: '-7@s',
width: "35@s",
height: "35@s",
},
infoIconRight:{
position: "absolute",
bottom: '-50@s',
right: '-7@s',
width: "35@s",
height: "35@s",
}
});
<file_sep>
import {
SOUND_PLAY,
SOUND_MUTE,
SOUND_PLAY_MUSIC,
MUSIC_MUTE,
SOUND_STOP_MUSIC,
SOUND_STOP_ALL,
} from '../constants/action-types';
const initialState = {
sound: '',
soundMute: true,
music: '',
musicMute: true,
stop: false,
};
const soundReducer = (state = initialState, action) => {
switch (action.type) {
case SOUND_PLAY: {
return {
...state,
sound: action.payload,
};
}
case SOUND_PLAY_MUSIC: {
return {
...state,
music: action.payload,
stop: false,
};
}
case SOUND_STOP_MUSIC: {
return {
...state,
music: '',
stop: true,
};
}
case SOUND_STOP_ALL: {
return {
...state,
sound: '',
stop: true,
};
}
case SOUND_MUTE: {
return {
...state,
soundMute: action.payload,
};
}
case MUSIC_MUTE: {
return {
...state,
musicMute: action.payload,
};
}
default: {
return state;
}
}
};
export default soundReducer;
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch, useSelector } from 'react-redux';
import { scale, ScaledSheet } from 'react-native-size-matters';
import Item from '../components/items.js';
import {Activity1} from '../data/activity.js';
import { dataActivity1 } from '../actions/data/data_actions.js';
export default function PageActivity({ navigation }) {
const active1 = useSelector(({data}) => data.active1);
const dispatch = useDispatch();
function addActivity(id){
let activityValue=active1[id]+10;
if(activityValue<999)
{
// food1[id] = foodValue;
dispatch(dataActivity1(activityValue,id))
}
}
function decActivity(id){
let activityValue=active1[id]-10;
if(activityValue>-1)
{
// food1[id] = foodValue;
dispatch(dataActivity1(activityValue,id))
}
}
function activityList() {
return Activity1.map((data) => {
return (
<Item key={data.id} values={data} count={active1[data.id]} addPress={addActivity} decPress={decActivity}/>
)
})
}
return(
<>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.container}
source={require('../../assets/images/Sun_Backgroundhdpi.png')}>
<TouchableWithoutFeedback
onPress={()=>navigation.pop()}>
<Animatable.Image animation="fadeInDown" delay={1500} useNativeDriver={true} resizeMode= 'stretch'
style={styles.backButton}
source={require('../../assets/images/Arrow.png')}/>
</TouchableWithoutFeedback>
<Animatable.View animation="fadeInDown" delay={500} useNativeDriver={true}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/good_activity.png')}>
<View style={styles.childrenContain}>
<View style={styles.headerContain}>
<Text style={styles.textHeader}>عادت های رفتاری فعال</Text>
</View>
<View style={styles.itemContain}>
{activityList()}
</View>
</View>
</ImageBackground>
</Animatable.View>
<TouchableWithoutFeedback
onPress={()=>navigation.navigate('PageActivityHalf')}
>
<Animatable.View animation={'fadeIn'}
delay={2000}
style={{position: 'absolute',
bottom: scale(0),
justifyContent: 'center',
alignItems: 'center',
height: scale(170),
width: scale(200)}}>
<View style={{position: 'absolute', bottom: scale(140)}}>
<Text style={{color: "#2b728c",
fontSize: scale(14),
fontFamily: "Yekan",}}>عادت های رفتاری نیمه فعال</Text>
</View>
<Animatable.Image
animation={'fadeOut'}
duration={2000}
delay={2500}
iterationDelay={100}
iterationCount={'infinite'}
source={require('../../assets/images/Scroll_Down_Flash.png')}
style={{position: 'absolute',
bottom: scale(65),
opacity: 0.5,
width: scale(80),
height: scale(70),
resizeMode: 'stretch'
}}/>
<Animatable.Image
animation={'fadeOut'}
duration={2000}
delay={3000}
iterationDelay={100}
iterationCount={'infinite'}
source={require('../../assets/images/Scroll_Down_Flash.png')}
style={{position: 'absolute',
bottom: scale(30),
opacity: 0.5,
width: scale(70),
height: scale(65),
resizeMode: 'stretch'
}}/>
<Animatable.Image
animation={'fadeOut'}
duration={2000}
delay={3500}
iterationDelay={100}
iterationCount={'infinite'}
source={require('../../assets/images/Scroll_Down_Flash.png')}
style={{position: 'absolute',
bottom: scale(0),
opacity: 0.5,
width: scale(60),
height: scale(60),
resizeMode: 'stretch'
}}/>
</Animatable.View>
</TouchableWithoutFeedback>
</ImageBackground>
</>
);
}
const styles = ScaledSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
dialog: {
height: '380@s',
width: '300@s',
marginBottom: '100@s',
},
childrenContain:{
height: "100%",
width: "100%",
marginTop: '5@s',
alignItems: 'center',
},
headerContain:{
marginTop: '65@s',
width: "100%",
height: "33@s",
justifyContent:'flex-start'
},
textHeader: {
color: "white",
fontSize: '11@s',
fontFamily: "Yekan",
textAlign: "left",
marginLeft: '45@s',
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
itemContain:{
marginTop:'-1@s'
},
textScroll: {
position: "absolute",
bottom: scale(130),
color: "#2b728c",
fontSize: '18@s',
fontFamily: "Yekan",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
backButton:{
position: 'absolute',
top: 20,
left: 10,
width: '90@s',
height: '60@s',
},
});
<file_sep>// @flow
import { combineReducers } from 'redux';
import userReducer from './user-reducer';
import dataReducer from './data-reducer';
import soundReducer from './sound-reducer';
// Root Reducer
const rootReducer = combineReducers({
user: userReducer,
data: dataReducer,
sound: soundReducer,
});
export default rootReducer;
<file_sep>import {
DATA_FOOD1,DATA_FOOD2,DATA_ACTIVITY1,DATA_ACTIVITY2,DATA_ACTIVITY3,DATA_DATE,DATA_RESET
} from '../../constants/action-types';
export const dataFood1 = (data,id) => (
{
type: DATA_FOOD1,
payload: data,
id: id,
}
);
export const dataFood2 = (data,id) => (
{
type: DATA_FOOD2,
payload: data,
id: id,
}
);
export const dataActivity1 = (data,id) => (
{
type: DATA_ACTIVITY1,
payload: data,
id: id,
}
);
export const dataActivity2 = (data,id) => (
{
type: DATA_ACTIVITY2,
payload: data,
id: id,
}
);
export const dataActivity3 = (data,id) => (
{
type: DATA_ACTIVITY3,
payload: data,
id: id,
}
);
export const dataDate = (date) => (
{
type: DATA_DATE,
payload: date,
}
);
export const dataReset = () => (
{
type: DATA_RESET,
payload: '',
}
);
<file_sep><h2> A Children Fittness Game Created by React Native <h2>
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch, useSelector } from 'react-redux';
import { scale, ScaledSheet } from 'react-native-size-matters';
import Item from '../components/items.js';
import {Foods2} from '../data/foods.js';
import { dataFood2 } from '../actions/data/data_actions.js';
export default function PageFoodNeg({ navigation }) {
const food2 = useSelector(({data}) => data.food2);
const dispatch = useDispatch();
function addFood(id){
let foodValue=food2[id]+1;
if(foodValue<10)
{
// food1[id] = foodValue;
dispatch(dataFood2(foodValue,id))
}
}
function decFood(id){
let foodValue=food2[id]-1;
if(foodValue>-1)
{
// food1[id] = foodValue;
dispatch(dataFood2(foodValue,id))
}
}
function foodList() {
return Foods2 && Foods2.map((data) => {
return (
<Item key={data.id} values={data} count={food2[data.id]} addPress={addFood} decPress={decFood}/>
)
})
}
return(
<>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.container}
source={require('../../assets/images/Rain_back.png')}>
<TouchableWithoutFeedback
onPress={()=>navigation.pop()}>
<Animatable.Image animation="fadeInDown" delay={1500} useNativeDriver={true} resizeMode= 'stretch'
style={styles.backButton}
source={require('../../assets/images/Arrow.png')}/>
</TouchableWithoutFeedback>
<Animatable.View animation="fadeInDown" delay={500} useNativeDriver={true}>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.dialog}
source={require('../../assets/images/Food_Bad.png')}>
<View style={styles.childrenContain}>
<View style={styles.headerContain}>
<Text style={styles.textHeader}>تغذیه ناسالم</Text>
</View>
<View style={styles.itemContain}>
{foodList()}
</View>
</View>
</ImageBackground>
</Animatable.View>
</ImageBackground>
</>
);
}
const styles = ScaledSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
dialog: {
height: '325@s',
width: '300@s',
marginBottom: '80@s',
},
childrenContain:{
height: "100%",
width: "100%",
marginTop: '5@s',
alignItems: 'center',
},
headerContain:{
marginTop: '45@s',
width: "100%",
height: "33@s",
justifyContent:'flex-start'
},
textHeader: {
color: "white",
fontSize: '16@s',
fontFamily: "Yekan",
textAlign: "right",
marginRight: '55@s',
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
itemContain:{
marginTop:'8@s'
},
textScroll: {
position: "absolute",
bottom: scale(130),
color: "#2b728c",
fontSize: '18@s',
fontFamily: "Yekan",
textShadowColor: 'rgba(255, 255, 255, .75)',
textShadowOffset: {width: -1, height: 1},
textShadowRadius: 10
},
backButton:{
position: 'absolute',
top: 20,
left: 10,
width: '90@s',
height: '60@s',
}
});
<file_sep>/**
* @format
*/
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import AppMetrica from 'react-native-appmetrica';
AppMetrica.activate({
apiKey: '',
sessionTimeout: 120,
firstActivationAsUpdate: false,
});
AppRegistry.registerComponent(appName, () => App);
<file_sep>import React, {useState, useEffect, useRef} from 'react';
import { useDispatch,useSelector } from 'react-redux';
import Sound from 'react-native-sound';
import { AppState } from 'react-native'
function SoundController(props) {
const sound = useSelector(({sound}) => sound.sound);
const music = useSelector(({sound}) => sound.music);
const soundMute = useSelector(({sound}) => sound.soundMute);
const musicMute = useSelector(({sound}) => sound.musicMute);
const [loaded,setLoaded]=useState(false);
const dispatch = useDispatch();
const soundCallbacks = useRef([]);
const musicCallbacks = useRef([]);
const muteRef = React.useRef(musicMute);
const musiRef = React.useRef(music);
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);
const _handleAppStateChange = (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
if(musicCallbacks.current[musiRef.current])
if(muteRef.current)
musicCallbacks.current[musiRef.current].play();
// console.log("App has come to the foreground!");
}
if (
appState.current.match(/active/) &&
nextAppState.match(/inactive|background/)
) {
if(musicCallbacks.current[musiRef.current])
musicCallbacks.current[musiRef.current].pause();
// console.log("App has come to the background!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
// console.log("AppState", appState.current);
};
function handlePress()
{
soundCallbacks.current["decrease"].stop(() => {
soundCallbacks.current["decrease"].play();
});
}
useEffect(() => {
soundCallbacks.current["increase"]= new Sound('increase.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
soundCallbacks.current["mission"]= new Sound('mission.wav', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
soundCallbacks.current["decrease"]= new Sound('decrease.wav', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
soundCallbacks.current["missionend"]= new Sound('missionend.wav', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
soundCallbacks.current["popup"]= new Sound('popup.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
soundCallbacks.current["popupopen"]= new Sound('popupopen.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
soundCallbacks.current["win"]= new Sound('win.wav', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
musicCallbacks.current["music"]= new Sound('music.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed /to load the sound', error);
return;
}
setLoaded(true);
});
},[]);
useEffect(() => {
if(soundMute){
if(sound!='')
soundCallbacks.current[sound].stop(() => {
soundCallbacks.current[sound].play();
});
}
},[sound]);
useEffect(() => {
muteRef.current = musicMute;
if(!musicMute)
for (let key in musicCallbacks.current) {
musicCallbacks.current[key].stop();
}
else {
if(music!='')
musicCallbacks.current[music].stop(() => {
musicCallbacks.current[music].setNumberOfLoops(-1);
// if(appState.current.match(/inactive|background/))
// musicCallbacks.current[music].pause();
// else
musicCallbacks.current[music].play();
});
}
},[musicMute]);
useEffect(() => {
musiRef.current=music;
if(!musicMute)
{
for (let key in musicCallbacks.current) {
musicCallbacks.current[key].stop();
}
}
else {
if(music!='')
musicCallbacks.current[music].stop(() => {
musicCallbacks.current[music].setNumberOfLoops(-1);
// if(appState.current.match(/inactive|background/))
// musicCallbacks.current[music].pause();
// else
musicCallbacks.current[music].play();
});
else {
for (let key in musicCallbacks.current) {
musicCallbacks.current[key].stop();
}
}
}
return () => {
for (let key in musicCallbacks.current) {
musicCallbacks.current[key].stop();
}
}
},[music,loaded]);
return(
<></>
);
}
export default SoundController;
<file_sep>import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import loggingMiddleware from './middleware/logging';
import AsyncStorage from '@react-native-community/async-storage';
import { persistStore, persistReducer, createMigrate } from 'redux-persist';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import rootReducer from '../reducers';
const migrations = {
0: (state) => {
return {...
state,
user: {...
state.user,
honors: 0,
todayHonor: false,
}
}
}
}
// Middleware: Redux Persist Config
const persistConfig = {
// Root
key: 'root',
version: 0,
// Storage Method (React Native)
storage: AsyncStorage,
// Whitelist (Save Specific Reducers)
whitelist: [
'user','data','sound',
],
// Blacklist (Don't Save Specific Reducers)
blacklist: [
'Network',
],
stateReconciler: autoMergeLevel2,
migrate: createMigrate(migrations, { debug: false })
};
// Middleware: Redux Persist Persisted Reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);
const configureStore = (initialState: Object) => {
// const middleware = applyMiddleware(thunk, loggingMiddleware);
const middleware = applyMiddleware(thunk);
return createStore(persistedReducer, initialState, middleware);
};
export const store = configureStore({});
export default configureStore;
<file_sep>import React, {useState, useEffect,useRef} from 'react';
import {
StyleSheet,
TouchableWithoutFeedback,
View,
Text,
Image,
ImageBackground,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { useDispatch, useSelector } from 'react-redux';
import { useFocusEffect } from '@react-navigation/native';
import { scale, ScaledSheet } from 'react-native-size-matters';
import HelpButton from '../../assets/svg/HelpButton.svg';
import SettingsButton from '../../assets/svg/SettingsButton.svg';
import BarColor from '../components/barColor.js';
import Tasks from '../components/tasks.js';
import BmiIndex from '../components/bmiIndex.js';
import Plot from '../components/plot.js';
import DialogeSetting from '../components/DialogeSetting.js';
import {store} from '../store/configureStore.js';
import { soundPlay,soundPlayMusic, soundStopMusic } from '../actions/sound/sound.js';
import {checkRules} from '../data/checkRules.js';
import { copilot, walkthroughable, CopilotStep } from "react-native-copilot";
const CopilotView = walkthroughable(View);
function StartScreen({ navigation, start}) {
const [levelFood,setLevelFood]=useState(0);
const [tipFood,setTipFood]=useState("");
const [levelActivity,setLevelActivity]=useState(0);
const [tipActivity,setTipActivity]=useState("");
const [isSettingVisible, setSettingVisible] = useState(false);
const dispatch = useDispatch();
function toggleSetting(){
setSettingVisible(!isSettingVisible);
}
// const state = useSelector(state => state);
const honors = useSelector(({user}) => user.honors);
const gender = useSelector(({user}) => user.gender);
const bmi = useSelector(({user}) => user.bmi);
const bmiRange = useSelector(({user}) => user.bmiRange);
const taskRef = useRef();
const levelUpdate=React.useCallback(() => {
setTimeout(function() {
let state = store.getState();
let values = checkRules(state);
setLevelFood(values.levelFood);
setTipFood(values.tipFood);
setLevelActivity(values.levelActivity);
setTipActivity(values.tipActivity);
if(taskRef.current)taskRef.current.checkTasks(state,values);
},500);
}, []);
useFocusEffect(
levelUpdate
);
useEffect(() => {
// setTimeout(() => {start();}, 1500)
// console.log("Tab");
setTimeout(() => {dispatch(soundPlayMusic("music"))}, 1000)
return () => {
// console.log("UnmountTab");
dispatch(soundPlayMusic(""));
}
},[]);
// <TouchableWithoutFeedback onPress={()=> console.log("Test")}>
// <Animatable.View animation="bounceIn"
// delay={500}
// style={styles.helpIcon}
// useNativeDriver={true}>
// <HelpButton width={scale(50)} height={scale(50)}/>
// </Animatable.View>
// </TouchableWithoutFeedback>
return(
<>
<DialogeSetting isVisible={isSettingVisible}
toggleModal={toggleSetting}
navigation= {navigation}/>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.container}
source={require('../../assets/images/mainBack.png')}>
<Animatable.View animation="bounceIn"
delay={500}
style={styles.honorContainer}
useNativeDriver={true}>
<CopilotStep
text="جمع مدال هایی که روزانه بدست اوردی اینجاست"
order={4}
name="medal"
>
<CopilotView style={styles.help4}/>
</CopilotStep>
<ImageBackground resizeMode= 'stretch' style={styles.countContainer} source={require('../../assets/images/Honor_Box.png')}>
<Text style={styles.countText}>{honors}</Text>
</ImageBackground>
<Image resizeMode= 'stretch' style={styles.honorIcon} source={require('../../assets/images/Honor.png')}/>
</Animatable.View>
<TouchableWithoutFeedback onPress={()=>{
toggleSetting();
}}>
<Animatable.View animation="bounceIn"
delay={500}
style={styles.settingIcon}
useNativeDriver={true}>
<SettingsButton width={scale(50)} height={scale(50)}/>
</Animatable.View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={()=>{
start();
}}>
<Animatable.View animation="bounceIn"
delay={500}
style={styles.helpIcon}
useNativeDriver={true}>
<Image resizeMode= 'stretch' style={styles.helpIconImage} source={require('../../assets/images/help.png')}/>
</Animatable.View>
</TouchableWithoutFeedback>
<Animatable.View animation="bounceIn"
delay={800}
style={styles.avatarContainer}
useNativeDriver={true}>
<TouchableWithoutFeedback onPress={()=>console.log("Press")}>
{gender==0?
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.avatar}
source={require('../../assets/images/avatarGirl.png')}/>:
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={styles.avatar}
source={require('../../assets/images/avatarBoy.png')}/>}
</TouchableWithoutFeedback>
<View style={styles.taskMail}>
<CopilotStep
text="پیشنهادهای روزانه اینجاست. اگه کامل کنی مدال میگیری"
order={3}
name="tasks"
>
<CopilotView style={styles.help3}/>
</CopilotStep>
<Tasks ref={taskRef} delay={1300}/>
</View>
</Animatable.View>
<Animatable.View animation="fadeInUp"
delay={1500}
style={styles.bmiContainer}
useNativeDriver={true}>
<BmiIndex range={bmiRange} bmi={bmi}/>
</Animatable.View>
<TouchableWithoutFeedback onPress={()=>navigation.navigate('PageActivity')}>
<Animatable.View animation="fadeInLeft"
delay={1900}
style={styles.activityIcon}
useNativeDriver={true}>
<CopilotStep
text="فعالیت امروزت رو اینجا ثبت کن"
order={2}
name="activity"
>
<CopilotView style={styles.help1}/>
</CopilotStep>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={{height: scale(140),width: scale(130)}}
source={require('../../assets/images/Activity_iconhdpi.png')}>
</ImageBackground>
<BarColor icon={'ios-bicycle'} info={0} level={levelActivity} tip={tipActivity}/>
</Animatable.View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={()=>navigation.navigate('PageFood')}>
<Animatable.View animation="fadeInRight"
delay={1900}
style={styles.foodIcon}
useNativeDriver={true}>
<CopilotStep
text="مصرف غذایی امروزت رو اینجا ثبت کن"
order={1}
name="food"
>
<CopilotView style={styles.help1}/>
</CopilotStep>
<ImageBackground
transition={false}
resizeMode= 'stretch'
style={{height: scale(140),width: scale(130)}}
source={require('../../assets/images/Food_icon_hdpi.png')}>
</ImageBackground>
<BarColor icon={'restaurant'} info={1} level={levelFood} tip={tipFood}/>
</Animatable.View>
</TouchableWithoutFeedback>
<Animatable.View animation="fadeInUp"
delay={2000}
style={styles.plotContainer}
useNativeDriver={true}>
<Plot/>
</Animatable.View>
</ImageBackground>
</>
);
}
const styles1 = StyleSheet.create({
test:{
position: 'absolute',
alignSelf: 'flex-start'
},
});
const styles = ScaledSheet.create({
container: {
flex: 1,
alignItems: 'center',
flexDirection: "column",
backgroundColor: "#0f3648"
},
avatarContainer:{
alignItems: 'center',
justifyContent: 'center',
height: '150@s',
width: '150@s',
top: '50@s',
},
avatar:{
position: 'absolute',
alignSelf: 'center',
height: '140@s',
width: '140@s',
},
taskMail:{
position: 'absolute',
left: '0@s',
bottom: '-10@s',
},
bmiContainer:{
alignItems: 'center',
justifyContent: 'center',
height: '50@s',
width: '150@s',
top: '80@s',
},
helpIcon:{
position: 'absolute',
right: '15@s',
top: '20@s'
},
settingIcon:{
position: 'absolute',
left: '15@s',
top: '20@s'
},
helpIcon:{
position: 'absolute',
left: '19@s',
top: '73@s'
},
helpIconImage:{
height: '39@s',
width: '39@s',
},
activityIcon:{
position: 'absolute',
height: '180@s',
width: '130@s',
right: '30@s',
top: '300@s'
},
foodIcon:{
position: 'absolute',
height: '180@s',
width: '130@s',
left: '30@s',
top: '300@s',
},
honorContainer:{
width:'90@s',
height: '40@s',
position: 'absolute',
right: '15@s',
top: '25@s',
alignItems: 'center',
justifyContent: 'center'
},
honorIcon:{
position: 'absolute',
height: '45@s',
width: '42@s',
right:0,
},
countContainer:{
height: '30@s',
width: '50@s',
justifyContent: 'center',
marginRight: '15@s',
marginBottom: '7@s'
},
countText: {
fontFamily: "Yekan",
fontSize: '15@s',
textAlign:'center',
color: "#2b728c",
},
plotContainer:{
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
height: '115@s',
left: '20@s',
right: '20@s',
bottom: '5@s',
},
help1:{
position: 'absolute',
top: '20@vs',
right: '-2@s',
height: '150@s',
width: '130@s',
},
help3: {
position: 'absolute',
top: '20@vs',
right: '-2@s',
height: '50@s',
width: '80@s',
},
help4:{
position: 'absolute',
top: '15@vs',
right: '-2@s',
height: '50@s',
width: '80@s'
}
});
export default copilot({
animated: true, // Can be true or false
overlay: 'view', // Can be either view or svg
labels: {
previous: "قبلی",
next: "بعدی",
skip: "رد کردن",
finish: "بستن"
}
})(StartScreen);
| 4525da8b58a984fbd5227242e41c644f04a658bd | [
"JavaScript",
"Markdown"
] | 34 | JavaScript | aftabaminzoobiapps/fitness-game | 361225d108b22945ac747dfa648941e721f512e3 | 1b9fbba5d8ecaf79ebe01571c97708b1fb89d5d0 |
refs/heads/master | <file_sep>export const validationError = (meta, validateOnMount) => {
if (validateOnMount) {
return meta.error || meta.submitError;
}
return meta.touched && (meta.error || meta.submitError);
};
export const validationWarning = (meta, validateOnMount) => {
if (validateOnMount) {
return meta.warning;
}
return meta.touched && meta.warning;
};
export default {
validationError, validationWarning
};
<file_sep>import { baseExamples } from '../examples-definitions';
const mappersSchema = [
{
subHeader: true,
noRoute: true,
title: 'Component mapper'
},
{
linkText: 'Custom mapper',
link: 'custom-mapper'
},
{
linkText: 'Global component props',
link: 'global-component-props'
},
{
linkText: 'File input',
link: 'file-input'
},
{
linkText: 'Common components API',
link: 'component-api'
},
{
subHeader: true,
noRoute: true,
title: 'Provided mappers'
},
{
link: 'ant-component-mapper',
linkText: 'Ant Design Mapper'
},
{
link: 'blueprint-component-mapper',
linkText: 'Blueprint mapper'
},
{
link: 'carbon-component-mapper',
linkText: 'Carbon mapper'
},
{
link: 'mui-component-mapper',
linkText: 'Material UI mapper'
},
{
link: 'pf4-component-mapper',
linkText: 'PF4 mapper'
},
{
link: 'suir-component-mapper',
linkText: 'Semantic UI mapper'
},
{
subHeader: true,
noRoute: true,
title: 'Mapper components'
},
...baseExamples.sort((a, b) => a.linkText.localeCompare(b.linkText)),
{
subHeader: true,
noRoute: true,
title: 'Schema mappers'
},
{
link: 'action-mapper',
linkText: 'Action mapper'
},
{
link: 'schema-validator-mapper ',
linkText: 'Schema validator mapper'
},
{
link: 'validator-mapper',
linkText: 'Validator mapper',
divider: true
}
];
export default mappersSchema;
| f08f821cc1acfa13dff978ca99211fa13afd0f28 | [
"JavaScript"
] | 2 | JavaScript | ReactDev313/react-forms | 2f01b1e554927db13928b18b6e1e01c8f7bbff71 | bfa3a46a302f6e33cb73dd87db6f7a5d802e90fd |
refs/heads/master | <file_sep>namespace ItAcademy.Homework1
{
class Program
{
static void Main(string[] args)
{
// Task 1:
// Declare and initialize variables of all primitive value types
byte byteVariable = 250; // byte variable
sbyte sbyteVariable = -128; // sbyte variable
char charVariable = 'c'; // char variable
short shortVariable = -32760; // short variable
ushort ushortVariable = 65530; // ushort variable
int intVariable = 214700501; // int variable
uint uintVariable = 4294000080; // uint variable
long longVariable = -9223000000000000018; // long variable
ulong ulongVariable = 18440000000000000022; // ulong variable
float floatVariable = 3.0120F; // float variable
double doubleVariable = -14.701; // double variable
decimal decimalVariable = 591.546M; // decimal variable
bool boolVariable = true; // bool variable
// Task 2:
// Boxing and unboxing
// Declare and initialize value type variable
double valType = 3.14;
// Case of boxing
object refType = valType;
// Case of unboxing
int unboxedValue = (int)refType;
}
}
}
| 35a1be36301015d54183578b8ab402c5f2955f4b | [
"C#"
] | 1 | C# | iliaorlenko/ItAcademy | 215db64ee69a340bc83d869471993d6f798fd45f | 745802465cde2deefb8638df2f2bdb5a4028c6ff |
refs/heads/master | <file_sep>package lsandwichmaker.sathya.adp.com.sandwichmaker9.fillings;
import lsandwichmaker.sathya.adp.com.sandwichmaker9.R;
public class Camembert extends Cheese implements Filling {
@Override
public String getName() {
return "Camembert";
}
@Override
public int getImage() {
return R.drawable.camembert;
}
@Override
public int getKcal() {
return 193;
}
@Override
public boolean getVeg() {
return true;
}
@Override
public int getPrice() {
return 70;
}
}
| 800f71235d539a331afca852894c1c04be332776 | [
"Java"
] | 1 | Java | sathyaBabu/SandwichMaker9 | ca7193eaf3436deb3225d28949754cc9ae573462 | c5fa40481f891359a1b0d68d0a7be24d040afb31 |
refs/heads/master | <repo_name>LydiaYoon/mobx-practice<file_sep>/src/index.js
import { observable, computed, autorun, action, transaction } from "mobx";
class GS25 {
@observable
basket = [];
@computed
get total() {
console.log("계산중 ...");
// Reduce 함수로 배열 내부 객체의 price 총합 계산
return this.basket.reduce((prev, curr) => prev + curr.price, 0);
}
@action
select(name, price) {
this.basket.push({ name, price });
}
}
const gs25 = new GS25();
autorun(() => gs25.total);
// *** 새 데이터가 추가될 때 알림
autorun(() => {
if (gs25.basket.length > 0) {
console.log(gs25.basket[gs25.basket.length - 1]);
}
});
transaction(() => {
gs25.select("물", 800);
gs25.select("물", 800);
gs25.select("포카칩", 1500);
});
console.log(gs25.total);
<file_sep>/README.md
# mobx-practice
https://velog.io/@velopert/redux-or-mobx
| 925cbc412fd5ebe515562230d6c605f3e1b4d6ae | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | LydiaYoon/mobx-practice | 01d436c82902e7748f37c883b7c33517a0cb611a | c55b7706404b58cdc6ed82d31dbe638ba7dddb04 |
refs/heads/master | <repo_name>tuanha2000vn/GPlayer<file_sep>/android/src/main/java/com/github/tcking/gplayer/GPlayerPlugin.java
package com.github.tcking.gplayer;
import android.content.Context;
import android.media.AudioManager;
import android.view.Window;
import android.view.WindowManager;
import java.util.HashMap;
import java.util.Map;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import io.flutter.view.FlutterNativeView;
/**
* GPlayerPlugin
*/
public class GPlayerPlugin implements MethodCallHandler {
private final Registrar registrar;
private GPlayerPlugin(Registrar registrar) {
this.registrar = registrar;
PlayerManager.getInstance().onPluginInit(registrar);
}
// -----------------
// -----------------
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "com.github.tcking/gplayer");
final GPlayerPlugin plugin = new GPlayerPlugin(registrar);
channel.setMethodCallHandler(plugin);
registrar.addViewDestroyListener(new PluginRegistry.ViewDestroyListener() {
@Override
public boolean onViewDestroy(FlutterNativeView view) {
plugin.onDestroy();
return false; // We are not interested in assuming ownership of the NativeView.
}
});
}
private void onDestroy() {
PlayerManager.getInstance().onPluginDestroy();
}
@Override
public void onMethodCall(MethodCall call, Result result) {
String fingerprint = call.argument("fingerprint");
if (fingerprint == null) {
result.error("fingerprint is null", null, null);
return;
}
if (call.method.equals("init")) {
PlayerManager.getInstance().createPlayer(VideoInfo.from((Map) call.arguments));
result.success(null);
return;
}
GiraffePlayer player = PlayerManager.getInstance().getPlayerByFingerprint(fingerprint);
if (player == null) {
result.error("can't find player for fingerprint:" + fingerprint, null, null);
return;
}
if (call.method.equals("start")) {
player.start();
result.success(null);
} else if (call.method.equals("pause")) {
player.pause();
result.success(null);
}else if (call.method.equals("release")) {
player.release();
result.success(null);
} else if (call.method.equals("getCurrentPosition")) {
result.success(player.getCurrentPosition());
} else if (call.method.equals("seekTo")) {
System.out.println("seekTo:" + ((Map) call.arguments).get("position"));
player.seekTo((Integer) ((Map) call.arguments).get("position"));
result.success(null);
} else if (call.method.equals("getAllInfo")) {
AudioManager am = (AudioManager) registrar.context().getSystemService(Context.AUDIO_SERVICE);
Map rsp = new HashMap<>();
rsp.put("maxVolume", am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
rsp.put("volume", am.getStreamVolume(AudioManager.STREAM_MUSIC));
rsp.put("currentPosition", player.getCurrentPosition());
Window window = registrar.activity().getWindow();
rsp.put("screenBrightness", window.getAttributes().screenBrightness);
result.success(rsp);
} else if (call.method.equals("setStreamVolume")) {
AudioManager am = (AudioManager) registrar.context().getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_MUSIC, (Integer) ((Map) call.arguments).get("volume"), 0);
result.success(null);
} else if (call.method.equals("setScreenBrightness")) {
Window window = registrar.activity().getWindow();
WindowManager.LayoutParams lpa = window.getAttributes();
double brightness = (Double) ((Map) call.arguments).get("brightness");
lpa.screenBrightness = (float) brightness;
if (lpa.screenBrightness > 1.0f) {
lpa.screenBrightness = 1.0f;
} else if (lpa.screenBrightness < 0.01f) {
lpa.screenBrightness = 0.01f;
}
window.setAttributes(lpa);
result.success(null);
} else {
result.notImplemented();
}
}
}
<file_sep>/android/build.gradle
group 'com.github.tcking.gplayer'
version '1.0-SNAPSHOT'
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
}
}
rootProject.allprojects {
repositories {
google()
jcenter()
}
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 21
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
lintOptions {
disable 'InvalidPackage'
}
}
dependencies{
compile 'com.github.tcking:ijkplayer-java:0.8.8'
//not want to using lazy load,uncomment the line which aib you want to support
// api 'com.github.tcking:ijkplayer-armv7a:0.8.8-full' //support armv7
// api 'com.github.tcking:ijkplayer-arm64:0.8.8-full' //support arm64
// api 'com.github.tcking:ijkplayer-armv5:0.8.8-full' //support armv5
// api 'com.github.tcking:ijkplayer-x86:0.8.8-full' //support x86
// api 'com.github.tcking:ijkplayer-x86_64:0.8.8-full' //support x86_64
}<file_sep>/README.md
# GPlayer
[](https://pub.dartlang.org/packages/gplayer)
Video Player plugin for Flutter,On Android, the backing player is base on [ijkplayer 0.8.8](https://github.com/Bilibili/ijkplayer) (not implement on iOS)

## features
1. base on ijkplayer(ffmpeg),support RTMP , HLS (http & https) , MP4,M4A etc.
2. gestures for volume control
3. gestures for brightness control
4. gestures for forward or backward
5. support fullscreen
6. try to replay when error(only for live video)
7. specify video scale type
8. support lazy load (download player on demand)
9. customize media controller (without change this project source code)
*note:* this using lazy load for default,it will take a few seconds to download decoders before first play,
if you want to include the decoder in your apk just find the `android/build.gradle` and add the dependencies
which you want to support.
## Getting Started
### 1.add dependency
First, add `gplayer` as a [dependency in your pubspec.yaml file](https://flutter.io/using-packages/).
``` yaml
dependencies:
flutter:
sdk: flutter
# add gplayer dependency
gplayer: ^0.0.2
```
### 2.create player
``` dart
import 'package:flutter/material.dart';
import 'package:gplayer/gplayer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GPlayer player;
@override
void initState() {
super.initState();
//1.create & init player
player = GPlayer(uri: 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4')
..init()
..addListener((_) {
//update control button out of player
setState(() {});
});
}
@override
void dispose() {
player?.dispose(); //2.release player
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Demo',
home: Scaffold(
appBar: AppBar(
title: Text('GPlayer'),
),
body: player.display,//3.put the player display in Widget tree
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
player.isPlaying ? player.pause() : player.start();
});
},
child: Icon(
player.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
),
);
}
}
```
## Customize media contoller
1.define a class extend from `buildMediaController`
2.implement method `Widget buildMediaController(BuildContext context)`
3.pass the instance to player constructor `GPlayer(uri:'',mediaController:MyMeidaController())`<file_sep>/CHANGELOG.md
## 0.0.1
* init release.
## 0.0.2
* support float window
* fixed some bugs
<file_sep>/android/settings.gradle
rootProject.name = 'gplayer'
<file_sep>/android/src/main/java/com/github/tcking/gplayer/VideoInfo.java
package com.github.tcking.gplayer;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* Created by tcking on 2017
*/
public class VideoInfo implements Parcelable {
public static final String PLAYER_IMPL_IJK = "ijk";
public static final String PLAYER_IMPL_SYSTEM = "system";
private HashSet<Option> options = new HashSet<>();
private Uri uri;
private String fingerprint = Integer.toHexString(hashCode());
private String lastFingerprint;
private Uri lastUri;
private int retryInterval = 0;
private String playerImpl = PLAYER_IMPL_IJK;
private boolean looping = false;
// public VideoInfo(VideoInfo defaultVideoInfo) {
// title = defaultVideoInfo.title;
// for (Option op : defaultVideoInfo.options) {
// try {
// options.add(op.clone());
// } catch (CloneNotSupportedException e) {
// e.printStackTrace();
// }
// }
// showTopBar = defaultVideoInfo.showTopBar;
// retryInterval = defaultVideoInfo.retryInterval;
// bgColor = defaultVideoInfo.bgColor;
// playerImpl = defaultVideoInfo.playerImpl;
// fullScreenAnimation = defaultVideoInfo.fullScreenAnimation;
// looping = defaultVideoInfo.looping;
// currentVideoAsCover = defaultVideoInfo.currentVideoAsCover;
// fullScreenOnly = defaultVideoInfo.fullScreenOnly;
//
// }
public static VideoInfo from(Map arguments) {
String fingerprint = (String) arguments.get("fingerprint");
VideoInfo videoInfo = new VideoInfo();
videoInfo.fingerprint = fingerprint;
videoInfo.setUri(Uri.parse((String) arguments.get("uri")));
videoInfo.looping = (boolean) arguments.get("looping");
videoInfo.playerImpl = (String) arguments.get("playerImpl");
videoInfo.options.addAll(Option.from((List<Map>) arguments.get("options")));
return videoInfo;
}
public String getPlayerImpl() {
return playerImpl;
}
public VideoInfo setPlayerImpl(String playerImpl) {
this.playerImpl = playerImpl;
return this;
}
public int getRetryInterval() {
return retryInterval;
}
/**
* retry to play again interval (in second)
*
* @param retryInterval interval in second <=0 will disable retry
* @return VideoInfo
*/
public VideoInfo setRetryInterval(int retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public HashSet<Option> getOptions() {
return options;
}
/**
* add player init option
*
* @param option option
* @return VideoInfo
*/
public VideoInfo addOption(Option option) {
this.options.add(option);
return this;
}
/**
* add player init option
*
* @return VideoInfo
*/
public VideoInfo addOptions(Collection<Option> options) {
this.options.addAll(options);
return this;
}
public VideoInfo() {
}
public VideoInfo(Uri uri) {
this.uri = uri;
}
public VideoInfo(String uri) {
this.uri = Uri.parse(uri);
}
protected VideoInfo(Parcel in) {
fingerprint = in.readString();
uri = in.readParcelable(Uri.class.getClassLoader());
lastFingerprint = in.readString();
lastUri = in.readParcelable(Uri.class.getClassLoader());
options = (HashSet<Option>) in.readSerializable();
retryInterval = in.readInt();
playerImpl = in.readString();
looping = in.readByte() != 0;
}
public static final Creator<VideoInfo> CREATOR = new Creator<VideoInfo>() {
@Override
public VideoInfo createFromParcel(Parcel in) {
return new VideoInfo(in);
}
@Override
public VideoInfo[] newArray(int size) {
return new VideoInfo[size];
}
};
public VideoInfo setFingerprint(Object fingerprint) {
String fp = "" + fingerprint;//to string first
if (lastFingerprint != null && !lastFingerprint.equals(fp)) {
//different from last setFingerprint, release last
// PlayerManager.getInstance().releaseByFingerprint(lastFingerprint);
}
this.fingerprint = fp;
lastFingerprint = this.fingerprint;
return this;
}
/**
* A Fingerprint represent a player
*
* @return setFingerprint
*/
public String getFingerprint() {
return fingerprint;
}
public Uri getUri() {
return uri;
}
/**
* set video uri
*
* @param uri uri
* @return VideoInfo
*/
public VideoInfo setUri(Uri uri) {
if (lastUri != null && !lastUri.equals(uri)) {
//different from last uri, release last
// PlayerManager.getInstance().releaseByFingerprint(fingerprint);
}
this.uri = uri;
this.lastUri = this.uri;
return this;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fingerprint);
dest.writeParcelable(uri, flags);
dest.writeString(lastFingerprint);
dest.writeParcelable(lastUri, flags);
dest.writeSerializable(options);
dest.writeInt(retryInterval);
dest.writeString(playerImpl);
dest.writeByte((byte) (looping ? 1 : 0));
}
public static VideoInfo createFromDefault() {
return new VideoInfo();
}
public boolean isLooping() {
return looping;
}
public void setLooping(boolean looping) {
this.looping = looping;
}
}
| b2343b2f11425331f4ff9959493ccfca515577fd | [
"Markdown",
"Java",
"Gradle"
] | 6 | Java | tuanha2000vn/GPlayer | 725d791c89f5cad6ab705675bd4175ec3286b02a | 0b48069ae2bb188aabe063dcd309765941e277c8 |
refs/heads/master | <repo_name>CodeLab20/R_Programming<file_sep>/8.Apply_Function.R
#Apply function ins R
# Apply functions are set of loop functions in R and more efficient, faster than for loop
stockData = read.table(file="E:/Courses/R/StockExample.csv", header=TRUE, row.names=1, sep=",")
#get help on apply function
?apply
#MARGIN
# a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates rows, 2 indicates
# columns, c(1, 2) indicates rows and columns. Where X has named dimnames, it can be a character vector selecting dimension
# names.
#gives mean column wise. if na.rm is not set, for NA/missing values, mean will be NA
apply(stockData, MARGIN = 2, mean, na.rm = TRUE)
#gives mean column wise
colMeans(stockData, na.rm=TRUE)
#gives mean row wise
apply(stockData, MARGIN = 1, mean, na.rm = TRUE)
#gives mean row wise
rowMeans(stockData, na.rm = TRUE)
#gives max column wise
apply(stockData, MARGIN = 2, max, na.rm = TRUE)
#find 20th, 80th percentile, foreach stock
apply(stockData, MARGIN = 2, quantile, probs=c(0.2,0.8), na.rm=TRUE)
#create a plot for each stock
apply(stockData, MARGIN=2, plot, type='l')
apply(stockData, MARGIN=2, plot, type='l', main="Stock", ylab="Price", xlab="Day")
#calculate row wise sum
apply(stockData, MARGIN=1, sum, na.rm=TRUE)
rowSums(stockData, na.rm=TRUE)
#plot of sum of all stocks
plot(rowSums(stockData, na.rm=TRUE), type="l", main="Market Trend", ylab="Total Market Value", xlab="Day" )
#highlight plot with coloured points
points(rowSums(stockData, na.rm=TRUE), pch=16, col="blue")<file_sep>/9.Tapply_Function.R
#tapply function.
#tapply function can be used to apply a function on subset of variable or vector
LungCapData = read.csv("E:/Courses/R/LungCapData.csv", header=TRUE)
attach(LungCapData)
#summary of data
summary(LungCapData)
#help for tapply
?tapply
#calculate mean age of smokers and non-smokers
tapply(X=Age, INDEX=Smoke, FUN=mean, na.rm=TRUE)
tapply(Age, Smoke, mean, na.rm=TRUE)
#simplify = TRUE is default. if we set it to false, it will return a vector
#if FALSE, tapply always returns an array of mode "list"; in other words, a list with a dim attribute.
tapply(Age, Smoke, mean, simplify = FALSE)
#without using tapply function, alternate less-efficient way
mean(Age[Smoke=="yes"])
mean(Age[Smoke=="no"])
#summary command with tapply
tapply(Age, Smoke, summary)
#quantile function with tapply
tapply(Age, Smoke, quantile, probs=c(0.2,0.8))
#subset based on multiple variables/vectors
#calculate mean age for smoker/non-smoker and male/female
tapply(Age, list(Smoke, Gender), mean, na.rm=TRUE)
#altername less efficient way
mean(Age[Smoke == 'no' & Gender=='male'])
mean(Age[Smoke == 'no' & Gender=='female'])
mean(Age[Smoke == 'yes' & Gender=='male'])
mean(Age[Smoke == 'yes' & Gender=='female'])
#by function is similar to tapply except it returns results in vector format
v = by(Age, list(Smoke, Gender), mean, na.rm=TRUE)
v
type(v)
<file_sep>/10.Bar_Pie_Charts.R
#Bar Chart and Pie Chart in R
#Bar Chart
LungCapData = read.csv("E:/Courses/R/LungCapData.csv", header=TRUE)
attach(LungCapData)
#summary of data
summary(LungCapData)
#help for barplot
?barplot
#frequencies for variables can be produced using table
#dividing number of males and females by total count will give percentage of each gender
gCount = table(Gender)
gCount
gPercent = gCount/725 *100
gPercent
#barplot of count
barplot(gCount)
#barplot of percentage
barplot(gPercent)
barplot(gPercent, main="Gender %", ylab = "%", xlab = "Gender")
#las param will change orientation of y-axis labels
barplot(gPercent, main="Gender %", ylab = "%", xlab = "Gender", las = 1)
#names.arg will set names on X-Axis
barplot(gPercent, main="Gender %", ylab = "%", xlab = "Gender", las = 1, names.arg = c("Female", "Male"))
#Horizontal bar chart
barplot(gPercent, main="Gender %", xlab = "%", ylab = "Gender", las = 1, names.arg = c("Female", "Male"), horiz = 1)
#PieCharts
pie(gPercent, main = "Gender %")
#add box around pie chart
box()
<file_sep>/5. Working_Wtih_Data.R
#Working With Data in R - 1
LungCapData = read.csv("E:/Courses/R/LungCapData.csv", header=TRUE)
#Dimensions of an object. Will give info about size, columns etc
dim(LungCapData)
nrow(LungCapData) #gives number of rows
ncol(LungCapData) #gives number of columns
str(LungCapData) #gives structure of R object like data type, column names, sample data
summary(LungCapData) #gives more insights of R objects . mlike mean, min, max, 1st, 3rd quantile
#first few rows
head(LungCapData)
head(LungCapData, n=10) #gives first 10 rows
#last few rows
tail(LungCapData)
tail(LungCapData, n=10) #gives last 10 rows
#creating subset of data
LungCapData[c(5,6,7,8,9), ] #creates subset of LungCapData with 5-9 rows
LungCapData[5:9, ]
LungCapData[-(4:722),] #creates subset of LungCapData with 1-3, 723-725 rows
is.data.frame(LungCapData[5:9, ]) #gives a rows subset of dataframe is a dataframe or not
#>true
is.data.frame(LungCapData[,1 ]) #gives a column subset of dataframe is a dataframe or not
#>false
is.data.frame(LungCapData[,1, drop=F ]) #gives a column subset of dataframe is a dataframe or not
#>true
#Adding a column to dataframe
LungCapData$MyCol = LungCapData$Age * LungCapData$Height
#Removing a column from dataframe
LungCapData$MyCol = NULL
#column names present in Data
names(LungCapData)
#gives mean value for column : Age
mean(LungCapData$Age)
#attaches set of R objects to Path. After attaching dataset, we can use column names directly
attach(LungCapData)
mean(Age)
Age
#detaches set of R objects from Path
#detach(LungCapData)
#gives data type
class(Age) #integer
class(Height) #numeric
class(Smoke) #factor i.e. category
#gives categories present in column
levels(Smoke) #yes, no
levels(Gender) #male, female
#gives summary of data
summary(LungCapData)
x = c(0,1,0,1,1,1,0,0,0,1,1,0,1)
> class(x)
[1] "numeric"
> typeof(x)
[1] "double"
> y = as.factor(x) #if 0,1 values indicate some category, mark them as factor
> class(y)
[1] "factor"
<file_sep>/4. Export_Data.R
#Export Data from R
#General Export
#This command will export LungCapData to csv file. This will also export row names/numbers.
> write.table(LungCapData, file="E:/Courses/R/expData.csv", sep=",")
#Remove row names/numbers using row.names = F
> write.table(LungCapData, file="E:/Courses/R/expData2.csv", row.names=F, sep=",")
#CSV export (no need to specify seperator)
> write.csv(LungCapData, file="E:/Courses/R/expData3.csv", row.names=F)
#txt export using tab delimited
write.table(LungCapData, file="E:/Courses/R/expData2.txt", row.names=F, sep="\t")<file_sep>/1.R_Basics.R
#R Basics
#integer
i = 2L
#double
d = 2.5
#complex
cm = 1 + 2i
#use typeof command to check datatype of a variable
#character
a = "Hello"
b = "World"
#paste function concatenates vectors with default seperator as " ".
c = paste(a, b)
#negation operator !
res = !(4 < 5)
# OR operator |
b1 = TRUE
b2 = FALSE
b3 = b1 | b2
# AND operator
b4 = b1 & b2
# isTRUE operator
isTRUE(b4)
#while loop
count = 1
while(count < 5)
{
print(count)
count = count + 1
}
#for loop
for(i in 1:5)
{
print("Hello R")
print(i)
}
#mean Normal distribution of random numbers fall in -1 to 1
N = 10000
count = 0
for(i in rnorm(N))
{
if(i > -1 & i < 1)
{
count= count + 1
}
}
print(count / N)<file_sep>/7.Working_Dir.R
#get current working directory
>getwd()
#set current working directory
>setwd("E:\\Courses\\R\\work_dir")
#Saves current work
save.image("FirstProject.Rdata")
#load the previous work
load("FirstProject.Rdata")
#File select dialog to load older work.
load(file.choose())
#Install Packages. Also can use menu option in R-Studio. Tools-> Install Package
install.packages("epiR") #install epiR Package
#install.packages() will list all packages in dialog box.
help(package = epiR)
#remove packages
remove.packages("epiR")<file_sep>/6.Working_With_Data.R
LungCapData = read.csv("E:/Courses/R/LungCapData.csv", header=TRUE)
attach(LungCapData)
#subset of data with 11-14 rows and all columns
LungCapData[11:14,]
#mean Age of women
mean(Age[Gender == 'female'])
#mean Age of men
mean(Age[Gender == "male"])
#subset of all data for women
femData = LungCapData[Gender == "female",]
#subset of all data for male
maleData = LungCapData[Gender == "male",]
#subset of all data for male with age > 15
maleOver15 = LungCapData[Gender == 'male' & Age > 15, ]
#Subset of Age in LungCapData with Age > 15
temp = Age > 15
temp[1:5]
temp2 = as.numeric(Age > 15)
temp2[1:5]
#Data for smoking women
femSmoke = Gender == "female" & Smoke == "yes"
#Adding column: femSmoke to LungCapData
newData = cbind(LungCapData, femSmoke )
names(newData)
#Removing all objects in workspace
rm(list=ls())<file_sep>/12.GGPlot-2.R
movieRatings = read.csv("E:/Courses/Datasets/P2-Movie-Ratings.csv", header=TRUE)
colnames(movieRatings) = c("Film", "Genre", "CriticRating", "AudienceRating", "Budget", "Year")
str(movieRatings)
#here Film, Genre are identified as Factors by R. but year is not.
#to make year as factor
movieRatings$Year = factor(movieRatings$Year)
# This can work too
#movieRatings$Year = as.factor(movieRatings$Year)
str(movieRatings)
library(ggplot2)
#Chart for Audiesnce Rating vs Critic Rating for movies. should include budget too
#this will print empty chart
ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating))
#this will draw points on chart
ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating)) + geom_point()
#this will draw coloured points on chart
ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre)) +
geom_point()
#this will draw coloured points with size depends on budget on chart
ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre,
size=Budget)) + geom_point()
#-------------------------------------------------------------------------------
#Plotting with layers
#This function return is assigned to a variable. Note that complete dataframe gets
#duplicated by this operation.
p = ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre,
size=Budget))
#Plotting point layer
p + geom_point()
#plotting Lines Layer
p + geom_line()
#plotting point and lines layers
#for plotting multiple layers, order of plotting is important. This plotes points before
#Lines. so points are not visible in some extent
p + geom_point() + geom_line()
p + geom_line() + geom_point()
#-------------------------------------------------------------------------------
#Overriding aesthetics
q = ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre,
size=Budget))
#Overriding size
q + geom_point(aes(size=CriticRating))
#Overriding colours
q + geom_point(aes(size=Budget))
#overriding X-Axis
q + geom_point(aes(x=Budget))
#Above line changes x-axis data. But label remains same.
#Overriding x label
q + geom_point(aes(x=Budget)) + xlab("Budget In Millions")
#Changing line size. Changing size is called as setting size while if aes function
#is used, it is called as mapping size.
#i.e. for Mapping use aes function.i.e. color is mapped to genres.
#for setting, use varible assignment.
p + geom_line(size = 1) + geom_point()
#-------------------------------------------------------------------------------
#Mapping vs Setting
r = ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre))
#Mapping
r + geom_point(aes(size=Budget))
#setting
r + geom_point(colour="DarkGreen")
#Error
r + geom_point(aes(size=10))
#-------------------------------------------------------------------------------
#Histograms and Density Charts
s = ggplot(data=movieRatings, aes(x=Budget))
s + geom_histogram(binwidth = 10)
#Map colour to genres
s + geom_histogram(binwidth = 10, aes(fill=Genre))
#as some colours look similar, set a border
s + geom_histogram(binwidth = 10, aes(fill=Genre), colour = "Black")
#Density Charts
s + geom_density(aes(fill=Genre))
#this will mix up all charts. so stack them on one another
s + geom_density(aes(fill=Genre), position = "stack" )
#-------------------------------------------------------------------------------
#Starting Layer Tips
t = ggplot(data=movieRatings, aes(x=AudienceRating) )
t + geom_histogram(binwidth = 10, fill="white", color = "blue")
#Another way
t = ggplot(data=movieRatings)
t + geom_histogram(aes(x=AudienceRating), binwidth = 10,
fill="white", color = "blue")
#Setting x-axis as critic rating
t + geom_histogram(aes(x=CriticRating), binwidth = 10,
fill="white", color = "blue")
#-------------------------------------------------------------------------------
#Statistical Transformations
u = ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre))
u + geom_point() + geom_smooth(fill=NA)
#Analysis: For Romantic movies, for less critic ratings, audience gave more rating.
#Action movies have more ratings than other movies
#-------------------------------------------------------------------------------
#Boxplots
v = ggplot(data=movieRatings, aes(x=Genre, y=AudienceRating, colour=Genre))
v + geom_boxplot()
v + geom_boxplot(size=1.2)
v + geom_boxplot(size=1.2)+ geom_point()
#instead of points, use jitters
#jitter places points randomly on plot
v + geom_boxplot(size=1.2)+ geom_jitter()
v + geom_jitter() + geom_boxplot(size=1.2, alpha=0.5)
#analysis: Thriller movies got highest ratings, as their box is smaller
#Horror movies got lowest ratings
#Boxplot using critic rating
w = ggplot(data=movieRatings, aes(x=Genre, y=CriticRating, colour=Genre))
w + geom_jitter() + geom_boxplot(size=1.2, alpha=0.5)
#-------------------------------------------------------------------------------
#Facets
a = ggplot(data=movieRatings, aes(x=Budget))
a + geom_histogram(aes(fill=Genre), binwidth = 10, colour="black")
#this will plot multiple plots per genre sharing a common X-axis and seperate y-axis
a + geom_histogram(aes(fill=Genre), binwidth = 10, colour="black") +
facet_grid(Genre~.,scale="free")
#Scatter plot with facets
b = ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating, colour=Genre))
b + geom_point(size=3)
b + geom_point(size=3) + facet_grid(Genre~., scale="free")
#Year-wise Facet
#year horizontal
b + geom_point(size=3) + facet_grid(Year~., scale="free")
#Year vertical
b + geom_point(size=3) + facet_grid(.~Year, scale="free")
#Genre Horizontal, Year vertical
b + geom_point(size=3) + facet_grid(Genre~Year, scale="free")
b + geom_point(size=3) + geom_smooth() +facet_grid(Genre~Year, scale="free")
b + geom_point(size=3) + geom_smooth(fill=NA) +facet_grid(Genre~Year, scale="free")
b + geom_point(aes(size=Budget)) + geom_smooth(fill=NA) +facet_grid(Genre~Year, scale="free")
#-------------------------------------------------------------------------------
#co ordinates
#Limits
c = ggplot(data=movieRatings, aes(x=CriticRating, y=AudienceRating,
colour=Genre, size=Budget))
c + geom_point()
#this will zoom into data but removes other rows
c + geom_point() + xlim(50,100) + ylim(50,100)
#setting x and y limits wont work always.
d = ggplot(data=movieRatings, aes(x=Budget))
d + geom_histogram(binwidth = 10, aes(fill = Genre), colour = "black")
d + geom_histogram(binwidth = 10, aes(fill = Genre), colour = "black") + ylim(0, 50)
#Zoom : this wont remove rows
d + geom_histogram(binwidth = 10, aes(fill = Genre), colour = "black") +
coord_cartesian(ylim=c(0,50))
b + geom_point(aes(size=Budget)) + geom_smooth(fill=NA) +
facet_grid(Genre~Year, scale="free") + coord_cartesian(ylim=c(0,100))
#-------------------------------------------------------------------------------
#Themes
e = ggplot(data=movieRatings, aes(x=Budget))
f = e + geom_histogram(binwidth = 10, aes(fill = Genre), colour = "black")
#Axis Labels
f + xlab("Budget in Millions") + ylab("No.Of Movies")
#Label Formatting
f + xlab("Budget in Millions") + ylab("No.Of Movies") +
theme(axis.title.x = element_text(colour = "DarkGreen", size = 25),
axis.title.y = element_text(color = "Red", size=25))
#Tick mark formatting(x, y axis points text)
f + xlab("Budget in Millions") + ylab("No.Of Movies") +
theme(axis.title.x = element_text(colour = "DarkGreen", size = 25),
axis.title.y = element_text(color = "Red", size=25),
axis.text.x = element_text(size=12),
axis.text.y = element_text(size = 12))
#Legend Formatting
f + xlab("Budget in Millions") + ylab("No.Of Movies") +
theme(axis.title.x = element_text(colour = "DarkGreen", size = 25),
axis.title.y = element_text(color = "Red", size=25),
axis.text.x = element_text(size=12),
axis.text.y = element_text(size = 12),
legend.title = element_text(size = 15),
legend.text = element_text(size=10),
legend.position = c(1,1),
legend.justification = c(1,1))
#Chart title formatting
f + xlab("Budget in Millions") + ylab("No.Of Movies") +
ggtitle("Movie Budget Distribution") +
theme(axis.title.x = element_text(colour = "DarkGreen", size = 25),
axis.title.y = element_text(color = "Red", size=25),
axis.text.x = element_text(size=12),
axis.text.y = element_text(size = 12),
legend.title = element_text(size = 15),
legend.text = element_text(size=10),
legend.position = c(1,1),
legend.justification = c(1,1),
plot.title = element_text(colour = "Blue",
size = 30,
family = "Courier"))<file_sep>/11.GGPlot-1.R
countryStats = read.csv("E:/Courses/R/R-Programming/Datasets/P2-Demographic-Data.csv")
library(ggplot2)
#just x supplied = histogram
qplot(countryStats$Internet.users, data=countryStats)
# just y supplied = scatterplot, with x = seq_along(y)
qplot(y = countryStats$Birth.rate, data=countryStats)
# Income group wise birth rate
qplot(y = countryStats$Birth.rate, x=countryStats$Income.Group, data=countryStats)
#Adds legend for graph as size = 10
qplot(y = countryStats$Birth.rate, x=countryStats$Income.Group, data=countryStats, size=10)
#does not add legend for graph
qplot(y = countryStats$Birth.rate, x=countryStats$Income.Group, data=countryStats, size=I(3))
qplot(y = countryStats$Birth.rate, x=countryStats$Income.Group, data=countryStats, size=I(3), color=I("blue"))
#Boxplot is a chart which tells min value, 1st quartile, 2nd quartile(median), 3rd quartile, max value
#Box is made up of 1st,2nd,3rd quartile. while min and max values are called as whiskers
#Data is sorted to print boxplot.
qplot(y = countryStats$Birth.rate, x=countryStats$Income.Group, data=countryStats,
size=I(3), color=I("blue"), geom = "boxplot")
#Internet users wise birth rate
qplot(data=countryStats, x=countryStats$Internet.users, y=countryStats$Birth.rate,
color=I("red"), size=I(4))
#Internet users wise birth rate with colours set as per income group
qplot(data=countryStats, x=Internet.users, y=Birth.rate,
color=Income.Group, size=I(4))
########################################################################
#Use additional data in script: E:\Courses\R\R-Programming\5. Data Frames\CountryRegionVectors.R
#This data tells countrywise regions
#This functions creates a dataframe with columns renamed
regionsDF = data.frame(Country=Countries_2012_Dataset, Code=Codes_2012_Dataset, Region=Regions_2012_Dataset)
summary(regionsDF)
head(regionsDF)
#Merging countryStats and regionsDF dataframes
RegionCountryStats = merge(countryStats, regionsDF, by.x ="Country.Code", by.y="Code" )
str(RegionCountryStats)
#RegionCountryStats dataframe contains duplicate columns: Country and Country.Name
#So we remove Country column
RegionCountryStats$Country = NULL
#Internet users wise birth rate with colours set as per Country Region
qplot(data=RegionCountryStats, x=Internet.users, y=Birth.rate,
color=Region, size=I(4))
#Different shapes. Refer Image: E:\Courses\R\GGPlot_Shapes.png
qplot(data=RegionCountryStats, x=Internet.users, y=Birth.rate,
color=Region, size=I(4), shape=I(17))
#Transparency. So we can view overlapped points. 0= transparent 1 = opaque
qplot(data=RegionCountryStats, x=Internet.users, y=Birth.rate,
color=Region, size=I(4), shape=I(20), alpha=I(0.5))
#Title for chart
qplot(data=RegionCountryStats, x=Internet.users, y=Birth.rate,
color=Region, size=I(4), shape=I(20), alpha=I(0.5),
main="Birth Rate vs Internet Users")
<file_sep>/2. Vectors, Matrix.R
> x = 11
> x1 = c(1,3,5,7,9) #vector definition. c means combine
> x1
[1] 1 3 5 7 9
#Named Vector
names(x1) = c("a", "b", "c", "d","e")
x1
#Accessing elements using names
x1["c"]
#clearing names
names(x1) = NULL
> gender = c("male", "female")
> gender
[1] "male" "female"
> y = 2:7
> y
[1] 2 3 4 5 6 7
> z = seq(from=3, to=10, by=1) #sequence with increment
> z
[1] 3 4 5 6 7 8 9 10
> z1 = seq(from=3, to=10, by=0.5)
> z1
[1] 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0 9.5 10.0
> rep(1, times=10) #repeat 1 10 times
[1] 1 1 1 1 1 1 1 1 1 1
> rep("AU", times=5)
[1] "AU" "AU" "AU" "AU" "AU"
> rep(1:4, times=4)
[1] 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
> rep(1:4, each=4)
[1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
> rep(seq(from=2, to=6, by=0.5), times=3) #repeat sequence 3 times
[1] 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 2.0 2.5
[21] 3.0 3.5 4.0 4.5 5.0 5.5 6.0
> z = 3:8
> z + 10 #add 10 to each element in vector
[1] 13 14 15 16 17 18
> z-5
[1] -2 -1 0 1 2 3
> z-8
[1] -5 -4 -3 -2 -1 0
> z*8
[1] 24 32 40 48 56 64
> z/05
[1] 0.6 0.8 1.0 1.2 1.4 1.6
> #if 2 vectors have same length, we can add/sub/mul/div corresponding elements
> a = 5:10
> a + z #addition of 2 vectors
[1] 8 10 12 14 16 18
> a - z
[1] 2 2 2 2 2 2
> a * z
[1] 15 24 35 48 63 80
> a/z
[1] 1.666667 1.500000 1.400000 1.333333 1.285714 1.250000
> a
[1] 5 6 7 8 9 10
> a[3] #3rd element in vector. (indexing begins with 1)
[1] 7
> a[-3] # exclude 3rd element in vector
[1] 5 6 8 9 10
> a[6] #Index > size of vector
[1] NA
> a[-7] # exclude index > size of vector
[1] 5 6 7 8 9 10
> a[1:3] #1 to 3 elements in vector
[1] 5 6 7
> a[c(1,5)] # 1st, 5th element in vector
[1] 5 9
> a[-c(1,5)] # exclude 1st, 5th elements in vector
[1] 6 7 8 10
> a[a < 7] # all elements <7 in vector
[1] 5 6
> matrix(c(1:9), nrow=3, byrow=TRUE) #defining matrix
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
> matrix(c(1:9), nrow=3, byrow=FALSE)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> mat = matrix(c(1:9), nrow=3, byrow=TRUE)
> mat
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
> mat[1,2] #element in 1st row, 2nd column
[1] 2
> mat[c(1,3), 2] #1st, 3rd elements in 2nd column
[1] 2 8
> mat[2,] #All elements in 2nd row
[1] 4 5 6
> mat[,3] #All elements in 3rd column
[1] 3 6 9
#can assign names to rows and columns in matrix and access using them
rownames(mat) = c("a", "b", "c")
colnames(mat) = c("x", "y","z")
mat["a","z"]
mat["b",] #2nd row
mat[,'z'] #3rd column
> mat * 10 # *10 for each element in matrix
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
#Transpose of matrix. i.e. converts rows into columns and vice-versa
t(mat)
<file_sep>/3. Load_CSV_into_R.R
>data = read.csv("E:/Courses/R/LungCapData.csv", header=TRUE)
>data
LungCap Age Height Smoke Gender Caesarean
1 6.475 6 62.1 no male no
2 10.125 18 74.7 yes female no
3 9.550 16 69.7 no female yes
4 11.125 14 71.0 no male no
5 4.800 5 56.9 no male no
6 6.225 11 58.7 no female no
7 4.950 8 63.3 no male yes
8 7.325 11 70.4 no male no
9 8.875 15 70.5 no male no
10 6.800 11 59.2 no male no
11 11.500 19 76.4 no male yes
>data = read.csv(file.choose(), header=TRUE) #this will popup file selection dialog
>data = read.delim(file.choose(), header=TRUE) #read tab-seperated file
>data = read.table(file.choose(), header=TRUE, sep="\t") #read tab-seperated file. generic function | 4fa931340a74722f87d71fa4721d991b3c53be93 | [
"R"
] | 12 | R | CodeLab20/R_Programming | 6673c949330ae1ead4c92f515d10fd012d49d656 | 15c8b88c1946482d04a2b9405a5d97ed31b227b7 |
refs/heads/master | <repo_name>flight846/node_express_blog<file_sep>/app.js
// dependencies
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const morgan = require('morgan')
const bodyParser =require('body-parser')
const router = require('./config/routes')
// Set view templates
app.set('views', './views')
app.set('view engine', 'ejs')
// Use morgan
app.use(morgan('dev'));
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
// In this file, routes should be with root api/ prefix
app.use('/api', router)
// Tell express to use a function eg. middleware
// app.use((req, res, next) => {
// console.log(`${req.method} request to ${req.path} from ${req.ip}`)
// next() // Tells Express what middleware to use next
// })
// Specify routes in express like routes.rb
// Render index, only one needed in app.js as placeholder
app.get('/', (req, res) => {
res.render('index', {title: 'Welcome!'})
// res.status(200).json({message: 'Hello World'})
})
// Render JSON
// app.get('/posts', (req, res) => {
// res.status(200).json({message: 'Hello World'})
// })
// starting server
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
| 7a1fe200b6f423e83a787abece84f3a684a48faa | [
"JavaScript"
] | 1 | JavaScript | flight846/node_express_blog | 99bfa1ef641aab295bb9aad8d64e1d9b69570bb4 | 82e1aae4642e53cefa4d0f7659a4f9d9bfecb86b |
refs/heads/master | <file_sep>taxrate = 0.175
print "Enter price (ex tax):"
s = gets
subtotal = s.to_f
if(subtotal<0.0) then
subtotal = 0.0
end
tax = subtotal*taxrate
puts"Tax on $/{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}<file_sep>require 'sinatra'
get '/' do
#{}"Hola!"
erb :index
end
get '/read_more' do
erb :read_more
end
<file_sep>#Install sinatra using code:
require 'sinatra'
get '/' do
'Hello World!'
end
You can run the site by compiling site.rb using the Ruby compiler.
i.e. ruby site.rb
It can then be viewed at your localhost.
<file_sep>class X
A = 10
class Y
end
end<file_sep>require 'test/unit'
class TetClass
def initialise( aVal)
@val = aval*10
end
def getVal
return @val
end
end
class MyTest < Test::Unit::Testcase
def test1
t = TestClass.new(10)
assert_equal(100,t.getVal)
asser_equal(101,t.getVal)
assert(100 != t.getVal)
end
def test2
assert_equal(1000, TestClass,new(100).getVal)
end
end<file_sep>begin
x = x.superclass
puts(x)
end until x == nil | 57701b1d34dd1b783a186c273455d22fb7564ddc | [
"Markdown",
"Ruby"
] | 6 | Ruby | saulwiggin/Website | ffd5df50e06de73f499a1f7072f4fc98dd7d38cc | 17844aff8158b3c26689e89219dd6a72fae204f0 |
refs/heads/haritaM | <file_sep>package dbse.fopj.blinktopus.resources;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.codahale.metrics.annotation.Timed;
import dbse.fopj.blinktopus.api.datamodel.User;
import dbse.fopj.blinktopus.api.managers.LogManager;
import dbse.fopj.blinktopus.api.managers.SVManager;
import dbse.fopj.blinktopus.api.resultmodel.LogResult;
import dbse.fopj.blinktopus.api.resultmodel.Result;
import dbse.fopj.blinktopus.api.resultmodel.SVManagerResult;
/**
* Resource class that parses user's query and redirects it either to LogManager or SVManager.
* @author <NAME> (urmikl18),<NAME> and Ms.c <NAME>
*
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class QueryProcessor {
/**
* Map that transforms attribute names into numbers. Used to simplify query processing.
*/
public final static HashMap<String, Integer> attrIndex=new HashMap<String,Integer>(){
private static final long serialVersionUID=1L;
{put("totalprice",0);put("orderdate",1);
put("linenumber",0);put("quantity",1);put("extendedprice",2);put("discount",3);put("tax",4);put("shipdate",5);put("commitdate",6);put("receiptdate",7);}};
/**
* Default constructor.
*/
public QueryProcessor() {
}
/**
*
* @return List of existing Storage Views , stored in SVManager.
*/
@Path("/sv/all")
@GET
@Timed
public SVManagerResult getAllSVs() {
return SVManager.getSVManager().getAllSV();
}
/**
* Deletes all stored Storage Views.
*/
@Path("/sv/clear")
@GET
@Timed
public void removeAllSVs() {
SVManager.getSVManager().clear();
}
/**
*
* @return Returns all the data currently stored in the primary log.
*/
@Path("/log")
@GET
@Timed
public LogResult getAllLog() {
return LogManager.getLogManager().getAllLog();
}
/**
* The method that returns relevant tuples and relevant information about the query to the user.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem)
* @param attr The attribute to be queried on (e.g. totalprice/extendedprice)
* @param lower The lower boundary of a range query.
* @param higher The higher boundary of a range query.
* @param createSV True, if new SV of given type should be created, false, otherwise.
* @param distinct True, if a number of unique values in given range should be returned, false otherwise.
* @return An instance of a class Result that contains information about the query (table, attr, lower, higher),
* information about SV (Id, Type (Col,Row,AQP)), information about result (tuples, size), and
* analytical information (time it took to retrieve the result, and error if necessary).
*/
@Path("/query")
@GET
@Timed
public Result query(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table, @QueryParam("attr") String attr, @QueryParam("lower") String lower,
@QueryParam("higher") String higher, @QueryParam("create") String createSV, @QueryParam("distinct") String distinct) {
if (type.toLowerCase().equals("log"))
return LogManager.getLogManager().scan(table, attr, Double.parseDouble(lower), Double.parseDouble(higher),"OK");
else
{
if (type.toLowerCase().equals("aqp"))
return SVManager.getSVManager().maintain(SVId, type, table, attr, Double.parseDouble(lower),
Double.parseDouble(higher), false, Boolean.parseBoolean(distinct));
else
return SVManager.getSVManager().maintain(SVId, type, table, attr, Double.parseDouble(lower),
Double.parseDouble(higher), Boolean.parseBoolean(createSV), Boolean.parseBoolean(distinct));
}
}
/**
* The method that returns relevant tuples and relevant information about the query to the user.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem)
* @param key The key to be queried
* @param fields The fields to be queried
* @return An instance of a class Result that contains information about the query (table, attr, lower, higher),
* information about SV (Id, Type (Col,Row,AQP)), information about result (tuples, size), and
* analytical information (time it took to retrieve the result, and error if necessary).
*/
@Path("/readLog")
@GET
@Timed
//@ApiOperation(response=dbse.fopj.blinktopus.api.resultmodel.User.class)
public Response readLog(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table, @QueryParam("key") String key, @QueryParam("fields") List<String> fields) {
return LogManager.getLogManager().read(table, key, fields, null, null);
}
/**
* The method that returns relevant tuples and relevant information about the query to the user.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem)
* @param key The key to be queried
* @param fields The fields to be queried
* @param recordCount The number of records to be scanned
* @return An instance of a class Result that contains information about the query (table, attr, lower, higher),
* information about SV (Id, Type (Col,Row,AQP)), information about result (tuples, size), and
* analytical information (time it took to retrieve the result, and error if necessary).
*/
@Path("/scanLog")
@GET
@Timed
//@ApiOperation(response=dbse.fopj.blinktopus.api.resultmodel.User.class)
public Response scanLog(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table, @QueryParam("key") String key, @QueryParam("fields") List<String> fields, @QueryParam("recordCount") Integer recordCount) {
if (recordCount.equals(null) || recordCount<0 || key.equals(null)){
return Response.status(Status.BAD_REQUEST).build();
}
return LogManager.getLogManager().scan(table, key, fields, recordCount);
}
/**
* The method that returns relevant tuples and relevant information about the query to the user.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem)
* @return An instance of a class Result that contains information about the query (table, attr, lower, higher),
* information about SV (Id, Type (Col,Row,AQP)), information about result (tuples, size), and
* analytical information (time it took to retrieve the result, and error if necessary).
*/
@Path("/getAll")
@GET
@Timed
//@ApiOperation(response=dbse.fopj.blinktopus.api.resultmodel.User.class)
public Response getAll(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table) {
return LogManager.getLogManager().getAll(table);
}
/**
* The method that loads data into the rowstore.
* @return An instance of a class Result.
*/
@Path("/loadIntoRows")
@GET
@Timed
//@ApiOperation(response=dbse.fopj.blinktopus.api.resultmodel.User.class)
public Response loadIntoRows() {
return LogManager.getLogManager().load();
}
/**
* The method starts the background thread.
* @return An instance of a class Result.
*/
@Path("/startBT")
@GET
@Timed
//@ApiOperation(response=dbse.fopj.blinktopus.api.resultmodel.User.class)
public Response startBackgroundThread() {
return LogManager.getLogManager().startBT();
}
/**
* The method starts the background thread.
* @return An instance of a class Result.
*/
@Path("/resetBT")
@GET
@Timed
//@ApiOperation(response=dbse.fopj.blinktopus.api.resultmodel.User.class)
public Response resetBackgroundThread() {
return LogManager.getLogManager().resetBT();
}
/**
* This method inserts a tuple of type User in the log.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem/user)
* @param key
* @param field0
* @param field1
* @param field2
* @param field3
* @param field4
* @param field5
* @param field6
* @param field7
* @param field8
* @param field9
* @return status OK
*/
@Path("/insertLog")
@GET
@Timed
public Response insertLog(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table, @QueryParam("key") String key, @QueryParam("field0") String field0, @QueryParam("field1") String field1, @QueryParam("field2") String field2, @QueryParam("field3") String field3, @QueryParam("field4") String field4, @QueryParam("field5") String field5, @QueryParam("field6") String field6, @QueryParam("field7") String field7, @QueryParam("field8") String field8, @QueryParam("field9") String field9) {
if (type.toLowerCase().equals("log")){
if (table.equals("User")){
return LogManager.getLogManager().insert(table, key, field0, field1, field2, field3, field4, field5, field6, field7, field8, field9);
}
}
return Response.status(Status.BAD_REQUEST).build();
}
/**
* This method updates a tuple of type User in the log.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem/user)
* @param key
* @param field0
* @param field1
* @param field2
* @param field3
* @param field4
* @param field5
* @param field6
* @param field7
* @param field8
* @param field9
* @return status OK
*/
@Path("/updateLog")
@GET
@Timed
public Response updateLog(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table, @QueryParam("key") String key, @QueryParam("field0") String field0, @QueryParam("field1") String field1, @QueryParam("field2") String field2, @QueryParam("field3") String field3, @QueryParam("field4") String field4, @QueryParam("field5") String field5, @QueryParam("field6") String field6, @QueryParam("field7") String field7, @QueryParam("field8") String field8, @QueryParam("field9") String field9) {
if (type.toLowerCase().equals("log")){
if (table.equals("User")){
return LogManager.getLogManager().update(table, key, field0, field1, field2, field3, field4, field5, field6, field7, field8, field9);
}
}
return Response.status(Status.BAD_REQUEST).build();
}
/**
* This method deletes a tuple of type User in the log.
* @param SVId The ID of a Storage View to be used to answer user's query.
* @param type The type of a Storage View to be used to answer user's query (Col,Row,AQP).
* @param table The table to be queried (Order/LineItem/user)
* @param key
* @return status OK
*/
@Path("/deleteLog")
@GET
@Timed
public Response deleteLog(@QueryParam("SVid") String SVId, @QueryParam("type") String type,
@QueryParam("table") String table, @QueryParam("key") String key) {
if (type.toLowerCase().equals("log")){
if (table.equals("User")){
return LogManager.getLogManager().delete(table, key);
}
}
return Response.status(Status.BAD_REQUEST).build();
}
}
<file_sep>package dbse.fopj.blinktopus.benchmark;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.ws.rs.core.Response.Status;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* YCSB binding for <a href="http://redis.io/">Redis</a>.
*
* See {@code redis/README.md} for details.
*/
public class YCSBBenchmark {
public Status read(String table, String key, Set<String> fields,
Map<String, Map<String, String>> result) throws IOException {
String url = "http://localhost:8080/readLog?SvId=primary&type=log&table=User&key="+key+"&";
if (fields!=null){
for (String field: fields){
url+="fields="+field+"&";
}
}
url = url.substring(0, url.length()-1);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
ObjectMapper mapper=new ObjectMapper();
while ((inputLine = in.readLine()) != null) {
Map<String,String> object=new HashMap<String,String>();
object=mapper.readValue(inputLine,new TypeReference<Map<String,String>>(){});
result.put((String)object.get("key"),object);
}
in.close();
return result.isEmpty() ? Status.INTERNAL_SERVER_ERROR : Status.OK;
}
public Status insert(String table, String key,
Map<String, Map<String, String>> values) {
String url = "http://localhost:8080/insertLog?SvId=primary&type=log&table=User&key="+key+"&";
for (Map.Entry<String, Map<String, String>> object : values.entrySet()){
for (Map.Entry<String, String> field : object.getValue().entrySet()){
url+=field.getKey()+"="+field.getValue()+"&";
}
}
url = url.substring(0, url.length()-1);
URL obj;
HttpURLConnection con = null;
int respStatus = Status.INTERNAL_SERVER_ERROR.getStatusCode();
try {
obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
}
in.close();
respStatus = con.getResponseCode();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return respStatus==Status.INTERNAL_SERVER_ERROR.getStatusCode()?Status.INTERNAL_SERVER_ERROR:respStatus==201?Status.CREATED:Status.BAD_REQUEST;
}
public Status delete(String table, String key) throws IOException {
String url = "http://localhost:8080/deleteLog?SvId=primary&type=log&table=User&key="+key;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
}
in.close();
return con.getResponseCode()==201?Status.OK:Status.BAD_REQUEST;
}
public Status update(String table, String key,
Map<String, Map<String, String>> values) throws IOException {
String url = "http://localhost:8080/updateLog?SvId=primary&type=log&table=User&key="+key+"&";
for (Map.Entry<String, Map<String, String>> object : values.entrySet()){
for (Map.Entry<String, String> field : object.getValue().entrySet()){
url+=field.getKey()+"="+field.getValue()+"&";
}
}
url = url.substring(0, url.length()-1);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
}
in.close();
return con.getResponseCode()==201?Status.OK:Status.BAD_REQUEST;
}
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, Map<String, String>>> result) throws JsonParseException, JsonMappingException, IOException {
String url = "http://localhost:8080/scanLog?SvId=primary&type=log&table=User&key="+startkey+"&recordCount="+recordcount+"&";
if (fields!=null){
for (String field: fields){
url+="fields="+field+"&";
}
}
url = url.substring(0, url.length()-1);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
ObjectMapper mapper=new ObjectMapper();
while ((inputLine = in.readLine()) != null) {
List<Map<String,String>> object=new ArrayList<>();
object=mapper.readValue(inputLine,new TypeReference<List<Map<String,String>>>(){});
System.out.println("Object size: "+object.size());
for (Map<String,String> entry: object){
HashMap<String,Map<String,String>> base=new HashMap<String,Map<String,String>>();
base.put((String)entry.get("key"),entry);
result.addElement(base);
}
}
in.close();
return result.isEmpty() ? Status.INTERNAL_SERVER_ERROR : Status.OK;
}
public static void main (String args[]) throws IOException{
YCSBBenchmark test = new YCSBBenchmark();
Map<String, Map<String, String>> values = new HashMap<>();
Map<String, String> object = new HashMap<>();
object.put("key", "10");
object.put("field0", "5");
object.put("field1", "5");
object.put("field2", "5");
object.put("field3", "5");
object.put("field4", "5");
object.put("field5", "5");
object.put("field6", "5");
object.put("field7", "5");
object.put("field8", "5");
object.put("field9", "5");
values.put("10", object);
test.insert("User", "10", values);
}
}
| f8399432eefa1eeaf47f97558642371d0a6cdca8 | [
"Java"
] | 2 | Java | HaritaM/blinktopus | e4803ee6d17ad8e60a686697dcfaefe83360c129 | cc6de8123b980c0c11d8e282b9fa8d9c08aeebc2 |
refs/heads/master | <file_sep>#Εργασία 1
########################################################3
#Κάτω από κάθε ερώτηση να τοποθετήσετε το κώδικα-απάντηση της αντίστοιχης ερώτησης
#Μπορείτε για κάθε απάντηση να χρησιμοποιήσετε οποιοδήποτε μοτίβο κώδικα έχετε διδαχθεί
#An den emfanizontai sosta ta ellinika epilegetai apo to menu tools->global options->code->saving->default code encoding->utf-8
#epeita epilegetai apply kleinete to arxeio kai to ksanaanoigete
#Να υπολογίσετε και να εμφανίσετε τις απαντήσεις για κάθε ένα από τα παρακάτω ερωτήματα
#Ερώτηση 1:να βρείτε (αν υπάρχουν) και να εμφανίσετε το πλήθος των κενών γραμμών σε κάθε στήλη του dataset
colSums(is.na(DelayedFlights))
#Ερώτηση 2:να υπολογίσετε και να εμφανίσετε ποια ημέρα σε ποιον μήνα σημειώθηκαν οι περισσότερες καθυστερήσεις πτήσεων
f<-DelayedFlights
f<-filter(f,f$ArrTime>f$CRSArrTime)
f<-filter(f,f$ArrTime>f$CRSArrTime)
f<-group_by(f,f$Month,f$DayofMonth)
f<-tally(f)
which.max(f$n)
#Ερώτηση 3: να υπολογίσετε και να εμφανίσετε τον ημερήσιο μέσο όρο καθυστερήσεων για καθέναν από τους θερινούς μήνες του 2008
f%>%
filter(Month>=6 & Month<=8, ArrDelay>=0)%>%
group_by(Month)%>%
tally()%>%
mutate(AvgDailyDelays=c(185394/30,167105/31,145598/31))
#Ερώτηση 4: να υπολογίσετε και να εμφανίσετε το όνομα της αεροπορικής εταιρίας που είχε το μεγαλύτερο πλήθος κωδικών ακύρωσης τύπου Β
f<-DelayedFlights
f%>%
filter(CancellationCode=="B")%>%
group_by(UniqueCarrier)%>%
tally()%>%
arrange(desc(n))%>%
slice(1)
#Ερώτηση 5: να βρείτε τους κωδικούς των πτήσεων με τον μεγαλύτερο αριθμό καθυστερήσεων
f%>%
filter(ArrDelay>0)%>%
group_by(FlightNum)%>%
tally()%>%
arrange(desc(n))
rm(f)
#Ερώτηση 6: να βρείτε και να υπολογίσετε το όνομα του μεγαλύτερου σε απόσταση προορισμού με τις περισσότερες καθυστερήσεις
DelayedFlights%>%
filter(ArrDelay>0, Distance==max(Distance))%>%
select(Dest,Distance,ArrDelay)%>%
group_by(Dest)%>%
tally()%>%
arrange(desc(n))
#Ερώτηση 7: να βρείτε και να εμφανίσετε τους προορισμούς που είχαν την μεγαλύτερη καθυστέρηση (πτήσεις πουεκτελέστηκαν)
DelayedFlights%>%
filter(ArrDelay>0 & Cancelled==0)%>%
select(Dest,ArrDelay,Cancelled)%>%
group_by(Dest)%>%
arrange(desc(ArrDelay))%>%
tally()%>%
arrange(desc(n))
#Ερώτηση 8: να βρείτε και να εμφανίσετε το όνομα της αεροπορικής εταιρείας που είχε τις μεγαλύτερες καθυστερήσεις που οφείλονται σε καθυστερημένη άφιξη αεροσκαφών
DelayedFlights%>%
filter(ArrDelay>0 & LateAircraftDelay>0)%>%
select(UniqueCarrier,ArrDelay,LateAircraftDelay)%>%
group_by(UniqueCarrier)%>%
tally()%>%
arrange(desc(n))%>%
slice(1)
#Ερώτηση 9: να υποlογίσετε πόσες ακυρώσεις πτήσεων τύπου Α σημειώθηκαν την 13η ημέρα κάθε μήνα
DelayedFlights%>%
filter(DayofMonth==13 & CancellationCode=="A")%>%
select(Month,DayofMonth,CancellationCode)%>%
group_by(Month)%>%
tally()
#Ερώτηση 10: υπολογίσετε και να εμφανίσετε την μέση καθυστέρηση πτήσεων που εκτελέστηκαν από την 10η μέχρι την 23 Απριλίου 2008
DelayedFlights%>%
filter(DayofMonth >=10 & DayofMonth<=23 & Month==4 & ArrDelay>0)%>%
select(ArrDelay,DayofMonth,Month)%>%
summarise(ArrDelay=sum(ArrDelay)/13)
#Ερώτηση 11: να υπολογίσετε και να εμφανίσετε τον μήνα που σημειώθηκε η μεγαλύτερη καθυστέρηση που οφειλόταν σε έλεγχους ασφαλείας κατά τις ώρες 06.00-14.00
DelayedFlights%>%
filter(SecurityDelay==0, DepTime>=600, DepTime<=1400, DepDelay>0)%>%
select(SecurityDelay,DepTime,Month,DepDelay)%>%
arrange(desc(DepDelay))%>%
slice(1)
#Ερώτηση 12: να υπολογίσετε και να εμφανίσετε ποιος κωδικός πτήσης(αριθμός πτήσης) είχε το πρώτο δεκαήμερο του Νοεμβρίου του 2008 την μεγαλύτερη προ του αναμενόμενου χρόνου άφιξη στον προορισμό της
DelayedFlights%>%
filter(DayofMonth>=1 & DayofMonth<=10 & Month==11 & ArrDelay<0)%>%
select(FlightNum,DayofMonth,Month,ArrDelay)%>%
arrange(ArrDelay)%>%
slice(1)
#Ερώτηση 13: να υπολογίσετε και να εμφανίσετε ποιο αεροδρόμιο (τοποθεσία αναχώρησης) είχε το δεύτερο δεκαήμερο του Αυγούστου 2018 τις περισσότερες πτήσεις με καθυστέρηση(αναχωρίσεων) μεγαλύτερη από μισή ώρα που οφείλονται στους αερομεταφορείς
DelayedFlights%>%
filter(Month==8,DayofMonth>=11,DayofMonth<=21,DepDelay>=30,CarrierDelay>0)%>%
select(Origin,Month,DayofMonth,DepDelay,CarrierDelay)%>%
group_by(Origin)%>%
tally()%>%
arrange(desc(n))
#Ερώτηση 14: να βρείτε και να εμφανίσετε τις πτήσεις που εκτράπηκαν από την πορεία τους αλλά ολοκληρώθηκαν καθώς και τον συνολικό χρόνο που απαιτήθηκε
DelayedFlights%>%
filter(Diverted==1,Cancelled==0,ArrDelay!=0)%>%
select(Diverted,Cancelled,CRSArrTime,DepTime)
#Ερώτηση 15: ποιος μήνας είχε την μεγαλύτερη τυπική απόκλιση σε καθυστερήσεις ("πιο απρόβλεπτος μήνας"). Ως απόκλιση να θεωρηθεί η διαφορά ανάμεσα στον προγραμματισμένο και τον πραγματικό χρόνο εκτέλεσης της πτήσης
DelayedFlights%>%
select(CRSDepTime,DepTime,Month)%>%
group_by(Month)%>%
mutate(DepTime - CRSDepTime)%>%
arrange(DepTime - CRSDepTime)
#rename("DepTime - CRSDepTime" = "Apoklisi")
#sd(DepTime - CRSDepTime, na.rm = TRUE)
#tally()%>%
#n%>%
| 1ec4782704c705076a06d7bdcc017f6f784422b2 | [
"R"
] | 1 | R | nikoloulis7/Flights | cdbddb1ff5709db6b1374e654e5379e52f50d2c2 | 4fc2d928842b23cc7ae74a68e755e9f6e5dd9558 |
refs/heads/master | <file_sep>require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
puts "Exercise 4"
puts "----------"
# Your code goes here ...
Store.create(:name => "Surrey", :annual_revenue => 224000, :mens_apparel =>false, :womens_apparel => true )
Store.create(:name => "Whistler", :annual_revenue => 1900000, :mens_apparel =>true, :womens_apparel => false )
Store.create(:name => "Yaletown", :annual_revenue => 430000, :mens_apparel =>true, :womens_apparel => true )
@men_stores = Store.where(mens_apparel:true)
puts @men_stores.count
@men_stores.each {|n| p n.name, n.annual_revenue }
@woman_stores = Store.where(womens_apparel:true)
@woman_stores.each {|store|p store.annual_revenue < 1000000, store.name}<file_sep>require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
require_relative './exercise_5'
require_relative './exercise_6'
puts "Exercise 7"
puts "----------"
# Your code goes here ...
class Employee < ActiveRecord::Base
belongs_to :store
validates :first_name, presence:true
validates :last_name, presence:true
# validates :store_id
validates :hourly_rate, :inclusion => {:in => [40,200], :only_integer => true}
validates :annual_revenue, :inclusion => {in: [0], :only_integer => true}
end
@store2.employees.create(first_name:"Peter" , last_name: "Syn", hourly_rate:45 )
| 0e389d1cbb3e7406e356b3e7d8e932b8aefa01c8 | [
"Ruby"
] | 2 | Ruby | Danny-Tran/ar-exercises | 1543dc25987c16de92c80280ef531640ecf8e200 | d779c808c43272102c771b9ac001d4e5bda2414d |
refs/heads/main | <repo_name>chrisharrisUU/2020_BA_RP1<file_sep>/Analyses/exp1.R
# Setup -------------------------------------------------------------------
if (!require(needs)) {install.packages("needs"); library(needs)}
if (!require(goallabr)) {
if (!require(devtools)) {install.packages("devtools"); library(devtools)}
install_github("chrisharrisUU/goallabr")
}
needs(BayesFactor, dplyr, ggplot2, ggsci, goallabr,
gridExtra, haven, Hmisc, here, lme4, lmerTest,
magrittr, tidyr, papaja, purrr, svglite)
prioritize(dplyr)
# Color palette for graphs
pal <- ggsci::pal_uchicago()(5)[c(3, 5, 1)]
source(here("Auxiliary/functions.R"))
# Data import -------------------------------------------------------------
source(here("Auxiliary/exp1_import.r"))
rm(as.data.frame.avector, `[.avector`)
data1 <- filter(data1, LASTPAGE == 17)
### Rename variables
column.rename <- function(.data) {
# Prolific id
id <- .data$IV01_RV1
# Condition
# condition (rich vs impoverished)
# winning option (tools vs weapons)
# primacy (left vs right)
# direction of question (tool vs weapon)
# i-weapons-left-tool
# i-weapons-right-tool
# i-weapons-left-weapon
# i-weapons-right-weapon
# Condition
condition <- transmute(.data, condition = "impoverished")
# Primacy
primacy <- .data %>%
transmute(primacy = ifelse(UR01 %in% c(1, 3), -1, 1)) %>%
mutate(primacy = factor(primacy, levels = c(-1,1), labels = c("left frequent", "right frequent")))
# Winning option
winning <- transmute(.data, winning = "knife")
# Direction of question
questdir <- .data %>%
transmute(questdir = ifelse(UR01 %in% c(3, 4), -1, 1)) %>%
mutate(questdir = factor(questdir, levels = c(-1,1), labels = c("weapon", "tool")))
# All conditions
levelnames <- c("i-weapons-left-tool", "i-weapons-right-tool", "i-weapons-left-weapon", "i-weapons-right-weapon")
counterbalancing <- factor(.data$UR01, levels = 1:4, labels = levelnames[1:4])
# Sampling
freeselection <- .data %>%
select(contains("TR02")) %>%
select(everything(), -contains("a")) %>%
mutate(across(everything(), ~ifelse(.x == "group1.png", -1, ifelse(.x == "group2.png", 1, NA))))
# Assign useful column names
colnames(freeselection) <- paste("trial", 17:100, sep = "")
# Create selection index
freeselection <- freeselection %>%
mutate(choiceindex_raw = rowSums(., na.rm = TRUE))
# Preference
pref <- .data %>%
transmute(prepref_raw = DV01_01 - 1,
postpref_raw = DV02_01 - 1)
# Conditionals
cond <- .data %>%
transmute(precond_l_raw = DV03_01 - 1,
precond_r_raw = DV03_02 - 1,
postcond_l_raw = DV04_01 - 1,
postcond_r_raw = DV04_02 - 1)
# Confidence
conf <- .data %>%
transmute(preconf_l_raw = DV05_01 - 1,
preconf_r_raw = DV05_02 - 1,
postconf_l_raw = DV06_01 - 1,
postconf_r_raw = DV06_02 - 1)
# Demographics
age <- .data$DM04 %>% as.character() %>% as.numeric()
gender <- .data$DM05
psych <- .data$DM06
edu <- .data$DM07
# Account
account <- as.integer(as.character(.data$IV02_02))
# Output as dataframe
data.frame(id,
counterbalancing, condition, primacy, winning, questdir,
freeselection, pref, cond, conf,
age, gender, psych, edu,
account)
}
df1_raw <- column.rename(data1)
# Counterbalancing --------------------------------------------------------
df1 <- df1_raw %>%
# Everything as if asked from weapon's perspective
mutate(prepref_1 = ifelse(questdir == "weapon", prepref_raw, 100 - prepref_raw),
postpref_1 = ifelse(questdir == "weapon", postpref_raw, 100 - postpref_raw),
precond_l_1 = ifelse(questdir == "weapon", precond_l_raw, 100 - precond_l_raw),
precond_r_1 = ifelse(questdir == "weapon", precond_r_raw, 100 - precond_r_raw),
postcond_l_1 = ifelse(questdir == "weapon", postcond_l_raw, 100 - postcond_l_raw),
postcond_r_1 = ifelse(questdir == "weapon", postcond_r_raw, 100 - postcond_r_raw),
preconf_l_1 = ifelse(questdir == "weapon", preconf_l_raw, 100 - preconf_l_raw),
preconf_r_1 = ifelse(questdir == "weapon", preconf_r_raw, 100 - preconf_r_raw),
postconf_l_1 = ifelse(questdir == "weapon", postconf_l_raw, 100 - postconf_l_raw),
postconf_r_1 = ifelse(questdir == "weapon", postconf_r_raw, 100 - postconf_r_raw)) %>%
# Collapse primacy
mutate(prepref_2 = ifelse(primacy == "right frequent", prepref_1, 100 - prepref_1),
postpref_2 = ifelse(primacy == "right frequent", postpref_1, 100 - postpref_1),
precond_2 = ifelse(primacy == "left frequent", precond_l_1 - precond_r_1, precond_r_1 - precond_l_1),
postcond_2 = ifelse(primacy == "left frequent", postcond_l_1 - postcond_r_1, postcond_r_1 - postcond_l_1),
preconf_2 = ifelse(primacy == "left frequent", preconf_l_1 - preconf_r_1, preconf_r_1 - preconf_l_1),
postconf_2 = ifelse(primacy == "left frequent", postconf_l_1 - postconf_r_1, postconf_r_1 - postconf_l_1),
choiceindex_freq = ifelse(primacy == "left frequent", choiceindex_raw * (-1), choiceindex_raw)) %>%
# Shift from 0 - 100 to -50 to 50 and deltaps to -1, 1
mutate(prepref_freq = prepref_2 - 50,
postpref_freq = postpref_2 - 50,
precond_dp = precond_2 / 100,
postcond_dp = postcond_2 / 100,
preconf_dp = preconf_2 / 100,
postconf_dp = postconf_2 / 100,
# Sampling as percentage
choiceindex_per = (choiceindex_freq + 84) / (84 * 2))
# summary(lm(prepref_raw ~ questdir * primacy * 1, data = df1_raw))
# summary(lm(prepref_freq ~ 1, data = df1))
#
# summary(lm(postpref_raw ~ questdir * primacy * 1, data = df1_raw))
# summary(lm(postpref_freq ~ 1, data = df1))
#
# summary(lm((precond_l_raw - precond_r_raw) ~ winning * questdir * primacy * 1, data = df1_raw))
# summary(lm(precond_dp ~ 1, data = df1))
#
# summary(lm((postcond_l_raw - postcond_r_raw) ~ questdir * primacy * 1, data = df1_raw))
# summary(lm(postcond_dp ~ 1, data = df1))
#
# summary(lm(choiceindex_raw ~ questdir * primacy * 1, data = df1_raw))
# summary(lm(choiceindex_freq ~ 1, data = df1))
# Dummy variable
df1 %<>%
mutate(bias = ifelse(prepref_freq > 0 & precond_dp > 0, 1, 0)) %>%
mutate(bias = factor(bias, levels = c(0, 1), labels = c("no bias", "bias")))
# Prolific ----------------------------------------------------------------
# # Create CSV of all accepted IDs
# df1 %>%
# select(id) %>%
# distinct(id) %>%
# write.csv(file = "Output/Prolific/2020_BA_RP1_Prolific_accepted.csv", row.names = FALSE)
#
#
# # Parameters
# minearn <- .85
# meanearn <- 1
# maxearn <- 1.15
#
# # Helper function for adjusting payments
# adjuster <- function(x) {
# if (dplyr::is_grouped_df(x)) {
# return(dplyr::do(x, adjuster(., ...)))
# }
#
# while (mean(x) < (meanearn - .02)) {
# maximum <- max(x[x < maxearn])
# x[which(x == maximum)] <- maxearn
# }
# while (mean(x) > (meanearn + 2)) {
# maximum <- which(x > meanearn)
# x[maximum] <- x[maximum] - 0.01
# }
# x
# }
#
# # Create CSV file of extra payments
# df1 %>%
# group_by(condition) %>%
# mutate(transformed_account = ((account - min(account)) / (max(account) - min(account))) * (maxearn - minearn) + minearn) %>%
# mutate(transformed_account = adjuster(transformed_account)) %>%
# mutate(extra_earnings = round(transformed_account, 2) - minearn) %>%
# ungroup() %>%
# # summarize(min = min(extra_earnings) + .85,
# # mean = mean(extra_earnings) + .85,
# # max = max(extra_earnings) + .85,
# # total = sum(extra_earnings))
# select(id, extra_earnings) %>%
# filter(extra_earnings > 0) %>%
# write.csv(file = "Output/Prolific/2020_BA_RP1_Prolific_earnings.csv", row.names = FALSE)
# Data export for students ------------------------------------------------
# df1 %>%
# select(id, counterbalancing, condition, primacy, winning, questdir,
# contains("trial"), choiceindex_per,
# prepref_freq, postpref_freq, precond_dp, postcond_dp, preconf_dp, postconf_dp,
# age, gender, psych, edu) %>%
# # Counterbalance
# mutate_at(vars(contains("trial")),
# ~ifelse(primacy == "left frequent", .x * (-1), .x)) %>%
# write_sav(., path = "Output/data.sav")
# Demographic data --------------------------------------------------------
# Summary of most relevant demographic data
df1 %>%
summarise(N = n(),
female = length(which(gender == "female")),
age_mean = mean(age, na.rm = TRUE),
age_sd = sd(age, na.rm = TRUE),
Psychstudents_percent = length(which(psych == "Yes")) / n() * 100)
# Level of education
df1 %>%
group_by(edu) %>%
summarise(count = length(edu))
# Percentage degree
length(which(as.integer(df1$edu) > 2)) / nrow(df1)
# Preference premeasure ----------------------------------------------------------------
# From which of the two groups were you more likely to draw knife/ruler?
# Graph
df1 %>%
ggplot(aes(x = condition,
y = prepref_freq,
fill = condition)) +
geom_violin() +
stat_summary(fun.data = "mean_sdl", geom = "crossbar", width = 0.2, fun.args = list(mult = 1)) +
geom_jitter(size = 0.5, width = 0.2) +
geom_hline(yintercept = 0, linetype = 2) +
scale_fill_manual(values = pal) +
theme_apa() +
labs(x = "Condition",
y = "Relative contingency estimates - pre-measure") +
theme(legend.position = "none")
# Means and sds
df1 %>%
summarise(pre_avg = printnum(mean(prepref_freq)),
pre_SD = printnum(sd(prepref_freq)))
### Analyses
df1 %$%
ttestBF(prepref_freq,
mu = 0,
nullInterval = c(0, Inf)) %>%
printBFt()
df1 %>%
ttest(data = .,
y = prepref_freq,
x = condition,
mu = 0,
dir = "greater")
# Conditionals pre measure -------------------------------------------------
# How likely was it (in %) that you drew knife/ruler if...
# Graph
df1 %>%
ggplot(aes(x = condition,
y = precond_dp,
fill = condition)) +
geom_violin() +
stat_summary(fun.data = "mean_sdl", geom = "crossbar", width = 0.2, fun.args = list(mult = 1)) +
geom_jitter(size = 0.5, width = 0.2) +
geom_hline(yintercept = 0, linetype = 2) +
scale_fill_manual(values = pal) +
theme_apa() +
labs(x = "Conditional probability estimates",
y = expression(Delta*"p")) +
theme(legend.position = "none")
# Summary statistics and tests
df1 %>%
mutate(frequent = ifelse(primacy == "left frequent", preconf_l_raw, preconf_r_raw),
infrequent = ifelse(primacy == "left frequent", preconf_r_raw, preconf_l_raw)) %>%
summarize(pre_winning_rich = printnum(mean(frequent)),
pre_losing_rich = printnum(mean(infrequent)),
winning_bag_sd = printnum(sd(frequent)),
losing_bag_sd = printnum(sd(infrequent)))
df1 %>%
summarize(pre_avg = printnum(mean(precond_dp)),
pre_SD = printnum(sd(precond_dp)))
### Analyses
# Normative
ttestBF(df1$precond_dp, mu = 0, nullInterval = c(0, Inf)) %>% printBFt()
ttest(data = df1,
y = precond_dp,
x = condition,
mu = 0,
dir = "greater")
# Confidence pre measure -------------------------------------------------
# Means and sds
df1 %>%
summarise(pre_avg = printnum(mean(preconf_dp)),
pre_SD = printnum(sd(preconf_dp)))
preconf <- df1 %>%
mutate(conf_pre_fr = ifelse(primacy == "left frequent", preconf_l_raw, preconf_r_raw),
conf_pre_in = ifelse(primacy == "left frequent", preconf_r_raw, preconf_l_raw)) %>%
select(id, bias, conf_pre_fr, conf_pre_in) %>%
pivot_longer(cols = c(conf_pre_fr, conf_pre_in),
names_to = "type",
values_to = "confidence")
preconf %>%
group_by(bias, type) %>%
summarize(avg = printnum(mean(confidence)),
sd = printnum(sd(confidence)))
# Inference tests
df1 %>%
as.data.frame() %$%
ttestBF(preconf_dp,
mu = 0,
nullInterval = c(-Inf, Inf),
data = .) %>%
printBFt()
ttest(data = df1, y = preconf_dp, x = condition, mu = 0)
# Sampling -------------------------------------------------
# Graph over trials
time_series(df1, condition)
time_series(df1, bias)
ggsave(filename = "Output/Graphs/sampling1.svg", device = "svg", dpi = 320, width = 9.08, height = 5.72)
# ggsave("Output/sampling.png", device = "png" , dpi = 320, width = 9.08, height = 5.72)
# First trial
df1 %>%
# Counterbalance
mutate_at(vars(contains("trial")),
~ifelse(primacy == "left frequent", .x * (-1), .x)) %>%
select(id, bias, contains("trial")) %>%
# Trial 18
mutate(trial17 = ifelse(trial17 == 1, 1, 0)) %>%
group_by(bias) %>%
summarize(test = mean(trial17, na.rm = T))
# Means and sds
df1 %>%
group_by(bias) %>%
summarise(M = printnum(100 * mean(choiceindex_per)),
SD = printnum(100 * sd(choiceindex_per)))
### Analyses
# asd
# Mixed-effects model
df1 %>%
# Counterbalance
mutate_at(vars(contains("trial")),
~ifelse(primacy == "left frequent", .x * (-1), .x)) %>%
select(id, bias, contains("trial")) %>%
# Long format
pivot_longer(cols = -c(id, bias),
names_to = "trial",
values_to = "choice") %>%
# Correct variables
mutate(trial = substr(trial, 6, nchar(trial)),
choice = ifelse(choice == 1, 1, 0)) %>%
mutate(trial = as.double(trial),
trials = as.double(trial - 16) / 100) %>%
# Mixed-effects models
glmer(choice ~ (I(trials^2) + trials) * bias + (1|id), family = binomial, data = .) %>%
summary()
# Preference post measure ----------------------------------------------------------------
# Graph
df1 %>%
ggplot(aes(x = condition,
y = postpref_freq,
fill = condition)) +
geom_violin() +
stat_summary(fun.data = "mean_sdl", geom = "crossbar", width = 0.2, fun.args = list(mult = 1)) +
geom_jitter(size = 0.5, width = 0.2) +
geom_hline(yintercept = 0, linetype = 2) +
scale_fill_manual(values = pal) +
theme_apa() +
labs(x = "Condition",
y = "Relative contingency estimates - post-measure") +
theme(legend.position = "none")
# Means and sds
df1 %>%
group_by(bias) %>%
summarise(post_avg = printnum(mean(postpref_freq)),
post_SD = printnum(sd(postpref_freq)))
### Analyses
# asd
# Graph
df1 %>%
gather(key = time,
value = polarity,
c(prepref_freq, postpref_freq)) %>%
mutate(time = factor(time,
levels = c("prepref_freq", "postpref_freq"),
labels = c("pre", "post"))) %>%
within_ci(data = .,
subject = id,
value = polarity,
ws_factors = time,
bs_factors = bias) %>%
ggplot(aes(color = bias)) +
geom_point(aes(x = time,
y = sample_mean)) +
geom_line(aes(x = time,
y = sample_mean,
group = bias),
size = .9) +
geom_errorbar(width = .1,
aes(x = time,
ymin = sample_mean - CI,
ymax = sample_mean + CI)) +
scale_color_manual(values = pal) +
theme_apa() +
labs(x = "Measurement point",
y = "Relative contingency estimates")
# Conditionals post measure -------------------------------------------------
# Graph
df1 %>%
ggplot(aes(x = condition,
y = postcond_dp,
fill = condition)) +
geom_violin() +
stat_summary(fun.data = "mean_sdl", geom = "crossbar", width = 0.2, fun.args = list(mult = 1)) +
geom_jitter(size = 0.5, width = 0.2) +
geom_hline(yintercept = 0, linetype = 2) +
scale_fill_manual(values = pal) +
theme_apa() +
labs(x = "Conditional probability estimates",
y = expression(Delta*"p")) +
theme(legend.position = "none")
# Summary statistics and tests
df1 %>%
mutate(frequent = ifelse(primacy == "left frequent", postcond_l_1, postcond_r_1),
infrequent = ifelse(primacy == "left frequent", postcond_r_1, postcond_l_1)) %>%
group_by(bias) %>%
summarise(winning_bag = printnum(mean(frequent)),
losing_bag = printnum(mean(infrequent)),
winning_bag_sd = printnum(sd(frequent)),
losing_bag_sd = printnum(sd(infrequent)))
df1 %>%
group_by(bias) %>%
summarise(post_avg = printnum(mean(postcond_dp)),
post_SD = printnum(sd(postcond_dp)))
### Analyses
# asd
# Graph
df1 %>%
gather(key = time,
value = conditionals,
c(precond_dp, postcond_dp)) %>%
mutate(time = factor(time,
levels = c("precond_dp", "postcond_dp"),
labels = c("Pre", "Post"))) %>%
within_ci(data = .,
subject = id,
value = conditionals,
ws_factors = time,
bs_factors = bias) %>%
ggplot(aes(color = bias)) +
geom_point(aes(x = time,
y = sample_mean)) +
geom_line(aes(x = time,
y = sample_mean,
group = bias),
size = .9) +
geom_errorbar(width = .1,
aes(x = time,
ymin = sample_mean - CI,
ymax = sample_mean + CI)) +
scale_color_manual(values = pal) +
theme_apa() +
labs(x = "Measurement point",
y = expression(Delta*"p"))
# Confidence post measure -------------------------------------------------
# Means and sds
df1 %>%
group_by(bias) %>%
summarise(post_avg = printnum(mean(postconf_dp)),
post_SD = printnum(sd(postconf_dp)))
postconf <- df1 %>%
group_by(condition) %>%
mutate(conf_post_fr = ifelse(primacy == "left frequent", postconf_l_raw, postconf_r_raw),
conf_post_in = ifelse(primacy == "left frequent", postconf_r_raw, postconf_l_raw)) %>%
ungroup %>%
select(condition, bias, conf_post_fr, conf_post_in) %>%
pivot_longer(cols = c(conf_post_fr, conf_post_in),
names_to = "type",
values_to = "confidence")
postconf %>%
group_by(bias, type) %>%
summarize(avg = printnum(mean(confidence)),
sd = printnum(sd(confidence)))
# Inference tests
# Bias
df1 %>%
filter(bias == "bias") %>%
as.data.frame() %$%
ttestBF(postconf_dp,
mu = 0,
nullInterval = c(-Inf, Inf)) %>%
printBFt()
ttest(data = df1, y = postconf_dp, x = bias, sub = "bias", mu = 0)
# No bias
df1 %>%
filter(bias == "no bias") %>%
as.data.frame() %$%
ttestBF(postconf_dp,
mu = 0,
nullInterval = c(-Inf, Inf)) %>%
printBFt()
ttest(data = df1, y = postconf_dp, x = bias, sub = "no bias", mu = 0)
<file_sep>/README.md
R code for
*Citation*
[OSF Repository](https://osf.io/) (*not included yet*)
### Structure of the repository
The data files are organized as follows: The main scripts can be found in the folder `Analyses`. These scripts load the raw data (from the `Data` folder), as well as helper functions that have been outsourced to the `Auxiliary` folder. The respective analyses are grouped and in the same order also found in the manuscript, though within groups the order of individual statistical tests might vary slightly. Output (especially the graphs) is saved to the `Output` folder. Finally, the `Survey` folder includes stimulus material as well as the xml-files that make up the experiment as it was run on SosciSurvey.
The `Analyses` folder furthermore contains a script which allowed us to copy/paste Bayesian t-tests for robustness analyses. It requires copying the respective test and some manual adjustments! The `Auxiliary` folder contains two scripts for each experiment. One to import the raw data as it was downloaded from SosciSurvey into an R environment and one script that trims the dataset to completed cases, renames the variables of interest from SosciSurvey, and provides a function that recodes the counterbalancing measures we had taken during the survey.
We also provide a second readme file in the `Data` folder that provides a codebook for the variables we use in these datasets. **Not done yet**<file_sep>/Auxiliary/exp1_import.r
# This script reads a CSV file in GNU R.
# While reading this file, comments will be created for all variables.
# The comments for values will be stored as attributes (attr) as well.
# data1_file = file.choose()
# setwd("./")
data1_file = here("Data/exp1_data.csv")
data1 = read.table(
file=data1_file, encoding="UTF-8",
header = FALSE, sep = "\t", quote = "\"",
dec = ".", row.names = "CASE",
col.names = c(
"CASE","SERIAL","REF","QUESTNNR","MODE","STARTED","UR01_CP","UR01","UR02_CP",
"UR02x01","UR02x02","UR02x03","UR02x04","UR02x05","UR02x06","UR02x07","UR02x08",
"UR02x09","UR02x10","UR02x11","UR02x12","UR02x13","UR02x14","UR02x15","UR02x16",
"UR02x17","UR02x18","UR02x19","UR02x20","UR02x21","UR02x22","UR02x23","UR02x24",
"UR02x25","UR02x26","UR02x27","UR02x28","UR02x29","UR02x30","UR02x31","UR02x32",
"UR02x33","UR02x34","UR02x35","UR02x36","UR02x37","UR02x38","UR02x39","UR02x40",
"UR02x41","UR02x42","UR02x43","UR02x44","UR02x45","UR02x46","UR02x47","UR02x48",
"UR02x49","UR02x50","UR02x51","UR02x52","UR02x53","UR02x54","UR02x55","UR02x56",
"UR02x57","UR02x58","UR02x59","UR02x60","UR02x61","UR02x62","UR02x63","UR02x64",
"UR02x65","UR02x66","UR02x67","UR02x68","UR02x69","UR02x70","UR02x71","UR02x72",
"UR02x73","UR02x74","UR02x75","UR02x76","UR02x77","UR02x78","UR02x79","UR02x80",
"UR02x81","UR02x82","UR02x83","UR02x84","TR01_01","TR01_01a","TR01_02",
"TR01_02a","TR01_03","TR01_03a","TR01_04","TR01_04a","TR01_05","TR01_05a",
"TR01_06","TR01_06a","TR01_07","TR01_07a","TR01_08","TR01_08a","TR01_09",
"TR01_09a","TR01_10","TR01_10a","TR01_11","TR01_11a","TR01_12","TR01_12a",
"TR01_13","TR01_13a","TR01_14","TR01_14a","TR01_15","TR01_15a","TR01_16",
"TR01_16a","TR02_01","TR02_01a","TR02_02","TR02_02a","TR02_03","TR02_03a",
"TR02_04","TR02_04a","TR02_05","TR02_05a","TR02_06","TR02_06a","TR02_07",
"TR02_07a","TR02_08","TR02_08a","TR02_09","TR02_09a","TR02_10","TR02_10a",
"TR02_11","TR02_11a","TR02_12","TR02_12a","TR02_13","TR02_13a","TR02_14",
"TR02_14a","TR02_15","TR02_15a","TR02_16","TR02_16a","TR02_17","TR02_17a",
"TR02_18","TR02_18a","TR02_19","TR02_19a","TR02_20","TR02_20a","TR02_21",
"TR02_21a","TR02_22","TR02_22a","TR02_23","TR02_23a","TR02_24","TR02_24a",
"TR02_25","TR02_25a","TR02_26","TR02_26a","TR02_27","TR02_27a","TR02_28",
"TR02_28a","TR02_29","TR02_29a","TR02_30","TR02_30a","TR02_31","TR02_31a",
"TR02_32","TR02_32a","TR02_33","TR02_33a","TR02_34","TR02_34a","TR02_35",
"TR02_35a","TR02_36","TR02_36a","TR02_37","TR02_37a","TR02_38","TR02_38a",
"TR02_39","TR02_39a","TR02_40","TR02_40a","TR02_41","TR02_41a","TR02_42",
"TR02_42a","TR02_43","TR02_43a","TR02_44","TR02_44a","TR02_45","TR02_45a",
"TR02_46","TR02_46a","TR02_47","TR02_47a","TR02_48","TR02_48a","TR02_49",
"TR02_49a","TR02_50","TR02_50a","TR02_51","TR02_51a","TR02_52","TR02_52a",
"TR02_53","TR02_53a","TR02_54","TR02_54a","TR02_55","TR02_55a","TR02_56",
"TR02_56a","TR02_57","TR02_57a","TR02_58","TR02_58a","TR02_59","TR02_59a",
"TR02_60","TR02_60a","TR02_61","TR02_61a","TR02_62","TR02_62a","TR02_63",
"TR02_63a","TR02_64","TR02_64a","TR02_65","TR02_65a","TR02_66","TR02_66a",
"TR02_67","TR02_67a","TR02_68","TR02_68a","TR02_69","TR02_69a","TR02_70",
"TR02_70a","TR02_71","TR02_71a","TR02_72","TR02_72a","TR02_73","TR02_73a",
"TR02_74","TR02_74a","TR02_75","TR02_75a","TR02_76","TR02_76a","TR02_77",
"TR02_77a","TR02_78","TR02_78a","TR02_79","TR02_79a","TR02_80","TR02_80a",
"TR02_81","TR02_81a","TR02_82","TR02_82a","TR02_83","TR02_83a","TR02_84",
"TR02_84a","IV01_RV1","IV01_REF","IV02_01","IV02_02","DM03","DM04","DM05",
"DM06","DM07","DM10_01","DM11","DM11_01","DV01_01","DV02_01","DV03_01",
"DV03_02","DV04_01","DV04_02","DV05_01","DV05_02","DV06_01","DV06_02","TIME001",
"TIME002","TIME003","TIME004","TIME005","TIME006","TIME007","TIME008","TIME009",
"TIME010","TIME011","TIME012","TIME013","TIME014","TIME015","TIME016","TIME017",
"TIME_SUM","MAILSENT","LASTDATA","FINISHED","Q_VIEWER","LASTPAGE","MAXPAGE",
"MISSING","MISSREL","TIME_RSI","DEG_TIME"
),
as.is = TRUE,
colClasses = c(
CASE="numeric", SERIAL="character", REF="character", QUESTNNR="character",
MODE="character", STARTED="POSIXct", UR01_CP="numeric", UR01="numeric",
UR02_CP="numeric", UR02x01="numeric", UR02x02="numeric", UR02x03="numeric",
UR02x04="numeric", UR02x05="numeric", UR02x06="numeric", UR02x07="numeric",
UR02x08="numeric", UR02x09="numeric", UR02x10="numeric", UR02x11="numeric",
UR02x12="numeric", UR02x13="numeric", UR02x14="numeric", UR02x15="numeric",
UR02x16="numeric", UR02x17="numeric", UR02x18="numeric", UR02x19="numeric",
UR02x20="numeric", UR02x21="numeric", UR02x22="numeric", UR02x23="numeric",
UR02x24="numeric", UR02x25="numeric", UR02x26="numeric", UR02x27="numeric",
UR02x28="numeric", UR02x29="numeric", UR02x30="numeric", UR02x31="numeric",
UR02x32="numeric", UR02x33="numeric", UR02x34="numeric", UR02x35="numeric",
UR02x36="numeric", UR02x37="numeric", UR02x38="numeric", UR02x39="numeric",
UR02x40="numeric", UR02x41="numeric", UR02x42="numeric", UR02x43="numeric",
UR02x44="numeric", UR02x45="numeric", UR02x46="numeric", UR02x47="numeric",
UR02x48="numeric", UR02x49="numeric", UR02x50="numeric", UR02x51="numeric",
UR02x52="numeric", UR02x53="numeric", UR02x54="numeric", UR02x55="numeric",
UR02x56="numeric", UR02x57="numeric", UR02x58="numeric", UR02x59="numeric",
UR02x60="numeric", UR02x61="numeric", UR02x62="numeric", UR02x63="numeric",
UR02x64="numeric", UR02x65="numeric", UR02x66="numeric", UR02x67="numeric",
UR02x68="numeric", UR02x69="numeric", UR02x70="numeric", UR02x71="numeric",
UR02x72="numeric", UR02x73="numeric", UR02x74="numeric", UR02x75="numeric",
UR02x76="numeric", UR02x77="numeric", UR02x78="numeric", UR02x79="numeric",
UR02x80="numeric", UR02x81="numeric", UR02x82="numeric", UR02x83="numeric",
UR02x84="numeric", TR01_01="numeric", TR01_01a="numeric", TR01_02="numeric",
TR01_02a="numeric", TR01_03="numeric", TR01_03a="numeric",
TR01_04="numeric", TR01_04a="numeric", TR01_05="numeric",
TR01_05a="numeric", TR01_06="numeric", TR01_06a="numeric",
TR01_07="numeric", TR01_07a="numeric", TR01_08="numeric",
TR01_08a="numeric", TR01_09="numeric", TR01_09a="numeric",
TR01_10="numeric", TR01_10a="numeric", TR01_11="numeric",
TR01_11a="numeric", TR01_12="numeric", TR01_12a="numeric",
TR01_13="numeric", TR01_13a="numeric", TR01_14="numeric",
TR01_14a="numeric", TR01_15="numeric", TR01_15a="numeric",
TR01_16="numeric", TR01_16a="numeric", TR02_01="numeric",
TR02_01a="numeric", TR02_02="numeric", TR02_02a="numeric",
TR02_03="numeric", TR02_03a="numeric", TR02_04="numeric",
TR02_04a="numeric", TR02_05="numeric", TR02_05a="numeric",
TR02_06="numeric", TR02_06a="numeric", TR02_07="numeric",
TR02_07a="numeric", TR02_08="numeric", TR02_08a="numeric",
TR02_09="numeric", TR02_09a="numeric", TR02_10="numeric",
TR02_10a="numeric", TR02_11="numeric", TR02_11a="numeric",
TR02_12="numeric", TR02_12a="numeric", TR02_13="numeric",
TR02_13a="numeric", TR02_14="numeric", TR02_14a="numeric",
TR02_15="numeric", TR02_15a="numeric", TR02_16="numeric",
TR02_16a="numeric", TR02_17="numeric", TR02_17a="numeric",
TR02_18="numeric", TR02_18a="numeric", TR02_19="numeric",
TR02_19a="numeric", TR02_20="numeric", TR02_20a="numeric",
TR02_21="numeric", TR02_21a="numeric", TR02_22="numeric",
TR02_22a="numeric", TR02_23="numeric", TR02_23a="numeric",
TR02_24="numeric", TR02_24a="numeric", TR02_25="numeric",
TR02_25a="numeric", TR02_26="numeric", TR02_26a="numeric",
TR02_27="numeric", TR02_27a="numeric", TR02_28="numeric",
TR02_28a="numeric", TR02_29="numeric", TR02_29a="numeric",
TR02_30="numeric", TR02_30a="numeric", TR02_31="numeric",
TR02_31a="numeric", TR02_32="numeric", TR02_32a="numeric",
TR02_33="numeric", TR02_33a="numeric", TR02_34="numeric",
TR02_34a="numeric", TR02_35="numeric", TR02_35a="numeric",
TR02_36="numeric", TR02_36a="numeric", TR02_37="numeric",
TR02_37a="numeric", TR02_38="numeric", TR02_38a="numeric",
TR02_39="numeric", TR02_39a="numeric", TR02_40="numeric",
TR02_40a="numeric", TR02_41="numeric", TR02_41a="numeric",
TR02_42="numeric", TR02_42a="numeric", TR02_43="numeric",
TR02_43a="numeric", TR02_44="numeric", TR02_44a="numeric",
TR02_45="numeric", TR02_45a="numeric", TR02_46="numeric",
TR02_46a="numeric", TR02_47="numeric", TR02_47a="numeric",
TR02_48="numeric", TR02_48a="numeric", TR02_49="numeric",
TR02_49a="numeric", TR02_50="numeric", TR02_50a="numeric",
TR02_51="numeric", TR02_51a="numeric", TR02_52="numeric",
TR02_52a="numeric", TR02_53="numeric", TR02_53a="numeric",
TR02_54="numeric", TR02_54a="numeric", TR02_55="numeric",
TR02_55a="numeric", TR02_56="numeric", TR02_56a="numeric",
TR02_57="numeric", TR02_57a="numeric", TR02_58="numeric",
TR02_58a="numeric", TR02_59="numeric", TR02_59a="numeric",
TR02_60="numeric", TR02_60a="numeric", TR02_61="numeric",
TR02_61a="numeric", TR02_62="numeric", TR02_62a="numeric",
TR02_63="numeric", TR02_63a="numeric", TR02_64="numeric",
TR02_64a="numeric", TR02_65="numeric", TR02_65a="numeric",
TR02_66="numeric", TR02_66a="numeric", TR02_67="numeric",
TR02_67a="numeric", TR02_68="numeric", TR02_68a="numeric",
TR02_69="numeric", TR02_69a="numeric", TR02_70="numeric",
TR02_70a="numeric", TR02_71="numeric", TR02_71a="numeric",
TR02_72="numeric", TR02_72a="numeric", TR02_73="numeric",
TR02_73a="numeric", TR02_74="numeric", TR02_74a="numeric",
TR02_75="numeric", TR02_75a="numeric", TR02_76="numeric",
TR02_76a="numeric", TR02_77="numeric", TR02_77a="numeric",
TR02_78="numeric", TR02_78a="numeric", TR02_79="numeric",
TR02_79a="numeric", TR02_80="numeric", TR02_80a="numeric",
TR02_81="numeric", TR02_81a="numeric", TR02_82="numeric",
TR02_82a="numeric", TR02_83="numeric", TR02_83a="numeric",
TR02_84="numeric", TR02_84a="numeric", IV01_RV1="character",
IV01_REF="character", IV02_01="character", IV02_02="character",
DM03="numeric", DM04="numeric", DM05="numeric", DM06="numeric",
DM07="numeric", DM10_01="character", DM11="numeric", DM11_01="logical",
DV01_01="numeric", DV02_01="numeric", DV03_01="numeric", DV03_02="numeric",
DV04_01="numeric", DV04_02="numeric", DV05_01="numeric", DV05_02="numeric",
DV06_01="numeric", DV06_02="numeric", TIME001="integer", TIME002="integer",
TIME003="integer", TIME004="integer", TIME005="integer", TIME006="integer",
TIME007="integer", TIME008="integer", TIME009="integer", TIME010="integer",
TIME011="integer", TIME012="integer", TIME013="integer", TIME014="integer",
TIME015="integer", TIME016="integer", TIME017="integer", TIME_SUM="integer",
MAILSENT="POSIXct", LASTDATA="POSIXct", FINISHED="logical",
Q_VIEWER="logical", LASTPAGE="numeric", MAXPAGE="numeric",
MISSING="numeric", MISSREL="numeric", TIME_RSI="numeric", DEG_TIME="numeric"
),
skip = 1,
check.names = TRUE, fill = TRUE,
strip.white = FALSE, blank.lines.skip = TRUE,
comment.char = "",
na.strings = ""
)
rm(data1_file)
attr(data1, "project") = "ba21rp"
attr(data1, "description") = "BA21-rp"
attr(data1, "date") = "2021-04-23 14:48:50"
attr(data1, "server") = "https://www.soscisurvey.de"
# Variable und Value Labels
data1$TR01_01 = factor(data1$TR01_01, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_02 = factor(data1$TR01_02, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_03 = factor(data1$TR01_03, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_04 = factor(data1$TR01_04, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_05 = factor(data1$TR01_05, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_06 = factor(data1$TR01_06, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_07 = factor(data1$TR01_07, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_08 = factor(data1$TR01_08, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_09 = factor(data1$TR01_09, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_10 = factor(data1$TR01_10, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_11 = factor(data1$TR01_11, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_12 = factor(data1$TR01_12, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_13 = factor(data1$TR01_13, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_14 = factor(data1$TR01_14, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_15 = factor(data1$TR01_15, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR01_16 = factor(data1$TR01_16, levels=c("1"), labels=c("%forced%"), ordered=FALSE)
data1$TR02_01 = factor(data1$TR02_01, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_02 = factor(data1$TR02_02, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_03 = factor(data1$TR02_03, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_04 = factor(data1$TR02_04, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_05 = factor(data1$TR02_05, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_06 = factor(data1$TR02_06, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_07 = factor(data1$TR02_07, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_08 = factor(data1$TR02_08, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_09 = factor(data1$TR02_09, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_10 = factor(data1$TR02_10, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_11 = factor(data1$TR02_11, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_12 = factor(data1$TR02_12, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_13 = factor(data1$TR02_13, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_14 = factor(data1$TR02_14, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_15 = factor(data1$TR02_15, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_16 = factor(data1$TR02_16, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_17 = factor(data1$TR02_17, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_18 = factor(data1$TR02_18, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_19 = factor(data1$TR02_19, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_20 = factor(data1$TR02_20, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_21 = factor(data1$TR02_21, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_22 = factor(data1$TR02_22, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_23 = factor(data1$TR02_23, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_24 = factor(data1$TR02_24, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_25 = factor(data1$TR02_25, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_26 = factor(data1$TR02_26, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_27 = factor(data1$TR02_27, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_28 = factor(data1$TR02_28, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_29 = factor(data1$TR02_29, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_30 = factor(data1$TR02_30, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_31 = factor(data1$TR02_31, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_32 = factor(data1$TR02_32, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_33 = factor(data1$TR02_33, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_34 = factor(data1$TR02_34, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_35 = factor(data1$TR02_35, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_36 = factor(data1$TR02_36, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_37 = factor(data1$TR02_37, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_38 = factor(data1$TR02_38, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_39 = factor(data1$TR02_39, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_40 = factor(data1$TR02_40, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_41 = factor(data1$TR02_41, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_42 = factor(data1$TR02_42, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_43 = factor(data1$TR02_43, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_44 = factor(data1$TR02_44, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_45 = factor(data1$TR02_45, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_46 = factor(data1$TR02_46, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_47 = factor(data1$TR02_47, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_48 = factor(data1$TR02_48, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_49 = factor(data1$TR02_49, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_50 = factor(data1$TR02_50, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_51 = factor(data1$TR02_51, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_52 = factor(data1$TR02_52, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_53 = factor(data1$TR02_53, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_54 = factor(data1$TR02_54, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_55 = factor(data1$TR02_55, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_56 = factor(data1$TR02_56, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_57 = factor(data1$TR02_57, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_58 = factor(data1$TR02_58, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_59 = factor(data1$TR02_59, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_60 = factor(data1$TR02_60, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_61 = factor(data1$TR02_61, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_62 = factor(data1$TR02_62, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_63 = factor(data1$TR02_63, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_64 = factor(data1$TR02_64, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_65 = factor(data1$TR02_65, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_66 = factor(data1$TR02_66, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_67 = factor(data1$TR02_67, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_68 = factor(data1$TR02_68, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_69 = factor(data1$TR02_69, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_70 = factor(data1$TR02_70, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_71 = factor(data1$TR02_71, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_72 = factor(data1$TR02_72, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_73 = factor(data1$TR02_73, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_74 = factor(data1$TR02_74, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_75 = factor(data1$TR02_75, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_76 = factor(data1$TR02_76, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_77 = factor(data1$TR02_77, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_78 = factor(data1$TR02_78, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_79 = factor(data1$TR02_79, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_80 = factor(data1$TR02_80, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_81 = factor(data1$TR02_81, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_82 = factor(data1$TR02_82, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_83 = factor(data1$TR02_83, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$TR02_84 = factor(data1$TR02_84, levels=c("1","2"), labels=c("group1.png","group2.png"), ordered=FALSE)
data1$DM03 = factor(data1$DM03, levels=c("1","2","-9"), labels=c("I agree","I disagree","[NA] Not answered"), ordered=FALSE)
data1$DM04 = factor(data1$DM04, levels=c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78","79","80","81","82","83","-9"), labels=c("18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78","79","80","81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97","98","99","100","[NA] Not answered"), ordered=FALSE)
data1$DM05 = factor(data1$DM05, levels=c("1","2","3","-9"), labels=c("male","female","other","[NA] Not answered"), ordered=FALSE)
data1$DM06 = factor(data1$DM06, levels=c("1","2","-9"), labels=c("Yes","No","[NA] Not answered"), ordered=FALSE)
data1$DM07 = factor(data1$DM07, levels=c("1","2","3","4","5","6","-9"), labels=c("No formal education","Secondary school/GCSE","College/A levels","Undergraduate degree (BA, BSc or comparable)","Graduate degree (MA, MSc or comparable)","Doctorate degree (PhD, MD, or comparable)","[NA] Not answered"), ordered=FALSE)
attr(data1$UR01,"1") = "i-weapons-left-tool"
attr(data1$UR01,"2") = "i-weapons-right-tool"
attr(data1$UR01,"3") = "i-weapons-left-weapon"
attr(data1$UR01,"4") = "i-weapons-right-weapon"
attr(data1$UR02x01,"1") = "1"
attr(data1$UR02x01,"2") = "2"
attr(data1$UR02x01,"3") = "3"
attr(data1$UR02x01,"4") = "4"
attr(data1$UR02x02,"1") = "1"
attr(data1$UR02x02,"2") = "2"
attr(data1$UR02x02,"3") = "3"
attr(data1$UR02x02,"4") = "4"
attr(data1$UR02x03,"1") = "1"
attr(data1$UR02x03,"2") = "2"
attr(data1$UR02x03,"3") = "3"
attr(data1$UR02x03,"4") = "4"
attr(data1$UR02x04,"1") = "1"
attr(data1$UR02x04,"2") = "2"
attr(data1$UR02x04,"3") = "3"
attr(data1$UR02x04,"4") = "4"
attr(data1$UR02x05,"1") = "1"
attr(data1$UR02x05,"2") = "2"
attr(data1$UR02x05,"3") = "3"
attr(data1$UR02x05,"4") = "4"
attr(data1$UR02x06,"1") = "1"
attr(data1$UR02x06,"2") = "2"
attr(data1$UR02x06,"3") = "3"
attr(data1$UR02x06,"4") = "4"
attr(data1$UR02x07,"1") = "1"
attr(data1$UR02x07,"2") = "2"
attr(data1$UR02x07,"3") = "3"
attr(data1$UR02x07,"4") = "4"
attr(data1$UR02x08,"1") = "1"
attr(data1$UR02x08,"2") = "2"
attr(data1$UR02x08,"3") = "3"
attr(data1$UR02x08,"4") = "4"
attr(data1$UR02x09,"1") = "1"
attr(data1$UR02x09,"2") = "2"
attr(data1$UR02x09,"3") = "3"
attr(data1$UR02x09,"4") = "4"
attr(data1$UR02x10,"1") = "1"
attr(data1$UR02x10,"2") = "2"
attr(data1$UR02x10,"3") = "3"
attr(data1$UR02x10,"4") = "4"
attr(data1$UR02x11,"1") = "1"
attr(data1$UR02x11,"2") = "2"
attr(data1$UR02x11,"3") = "3"
attr(data1$UR02x11,"4") = "4"
attr(data1$UR02x12,"1") = "1"
attr(data1$UR02x12,"2") = "2"
attr(data1$UR02x12,"3") = "3"
attr(data1$UR02x12,"4") = "4"
attr(data1$UR02x13,"1") = "1"
attr(data1$UR02x13,"2") = "2"
attr(data1$UR02x13,"3") = "3"
attr(data1$UR02x13,"4") = "4"
attr(data1$UR02x14,"1") = "1"
attr(data1$UR02x14,"2") = "2"
attr(data1$UR02x14,"3") = "3"
attr(data1$UR02x14,"4") = "4"
attr(data1$UR02x15,"1") = "1"
attr(data1$UR02x15,"2") = "2"
attr(data1$UR02x15,"3") = "3"
attr(data1$UR02x15,"4") = "4"
attr(data1$UR02x16,"1") = "1"
attr(data1$UR02x16,"2") = "2"
attr(data1$UR02x16,"3") = "3"
attr(data1$UR02x16,"4") = "4"
attr(data1$UR02x17,"1") = "1"
attr(data1$UR02x17,"2") = "2"
attr(data1$UR02x17,"3") = "3"
attr(data1$UR02x17,"4") = "4"
attr(data1$UR02x18,"1") = "1"
attr(data1$UR02x18,"2") = "2"
attr(data1$UR02x18,"3") = "3"
attr(data1$UR02x18,"4") = "4"
attr(data1$UR02x19,"1") = "1"
attr(data1$UR02x19,"2") = "2"
attr(data1$UR02x19,"3") = "3"
attr(data1$UR02x19,"4") = "4"
attr(data1$UR02x20,"1") = "1"
attr(data1$UR02x20,"2") = "2"
attr(data1$UR02x20,"3") = "3"
attr(data1$UR02x20,"4") = "4"
attr(data1$UR02x21,"1") = "1"
attr(data1$UR02x21,"2") = "2"
attr(data1$UR02x21,"3") = "3"
attr(data1$UR02x21,"4") = "4"
attr(data1$UR02x22,"1") = "1"
attr(data1$UR02x22,"2") = "2"
attr(data1$UR02x22,"3") = "3"
attr(data1$UR02x22,"4") = "4"
attr(data1$UR02x23,"1") = "1"
attr(data1$UR02x23,"2") = "2"
attr(data1$UR02x23,"3") = "3"
attr(data1$UR02x23,"4") = "4"
attr(data1$UR02x24,"1") = "1"
attr(data1$UR02x24,"2") = "2"
attr(data1$UR02x24,"3") = "3"
attr(data1$UR02x24,"4") = "4"
attr(data1$UR02x25,"1") = "1"
attr(data1$UR02x25,"2") = "2"
attr(data1$UR02x25,"3") = "3"
attr(data1$UR02x25,"4") = "4"
attr(data1$UR02x26,"1") = "1"
attr(data1$UR02x26,"2") = "2"
attr(data1$UR02x26,"3") = "3"
attr(data1$UR02x26,"4") = "4"
attr(data1$UR02x27,"1") = "1"
attr(data1$UR02x27,"2") = "2"
attr(data1$UR02x27,"3") = "3"
attr(data1$UR02x27,"4") = "4"
attr(data1$UR02x28,"1") = "1"
attr(data1$UR02x28,"2") = "2"
attr(data1$UR02x28,"3") = "3"
attr(data1$UR02x28,"4") = "4"
attr(data1$UR02x29,"1") = "1"
attr(data1$UR02x29,"2") = "2"
attr(data1$UR02x29,"3") = "3"
attr(data1$UR02x29,"4") = "4"
attr(data1$UR02x30,"1") = "1"
attr(data1$UR02x30,"2") = "2"
attr(data1$UR02x30,"3") = "3"
attr(data1$UR02x30,"4") = "4"
attr(data1$UR02x31,"1") = "1"
attr(data1$UR02x31,"2") = "2"
attr(data1$UR02x31,"3") = "3"
attr(data1$UR02x31,"4") = "4"
attr(data1$UR02x32,"1") = "1"
attr(data1$UR02x32,"2") = "2"
attr(data1$UR02x32,"3") = "3"
attr(data1$UR02x32,"4") = "4"
attr(data1$UR02x33,"1") = "1"
attr(data1$UR02x33,"2") = "2"
attr(data1$UR02x33,"3") = "3"
attr(data1$UR02x33,"4") = "4"
attr(data1$UR02x34,"1") = "1"
attr(data1$UR02x34,"2") = "2"
attr(data1$UR02x34,"3") = "3"
attr(data1$UR02x34,"4") = "4"
attr(data1$UR02x35,"1") = "1"
attr(data1$UR02x35,"2") = "2"
attr(data1$UR02x35,"3") = "3"
attr(data1$UR02x35,"4") = "4"
attr(data1$UR02x36,"1") = "1"
attr(data1$UR02x36,"2") = "2"
attr(data1$UR02x36,"3") = "3"
attr(data1$UR02x36,"4") = "4"
attr(data1$UR02x37,"1") = "1"
attr(data1$UR02x37,"2") = "2"
attr(data1$UR02x37,"3") = "3"
attr(data1$UR02x37,"4") = "4"
attr(data1$UR02x38,"1") = "1"
attr(data1$UR02x38,"2") = "2"
attr(data1$UR02x38,"3") = "3"
attr(data1$UR02x38,"4") = "4"
attr(data1$UR02x39,"1") = "1"
attr(data1$UR02x39,"2") = "2"
attr(data1$UR02x39,"3") = "3"
attr(data1$UR02x39,"4") = "4"
attr(data1$UR02x40,"1") = "1"
attr(data1$UR02x40,"2") = "2"
attr(data1$UR02x40,"3") = "3"
attr(data1$UR02x40,"4") = "4"
attr(data1$UR02x41,"1") = "1"
attr(data1$UR02x41,"2") = "2"
attr(data1$UR02x41,"3") = "3"
attr(data1$UR02x41,"4") = "4"
attr(data1$UR02x42,"1") = "1"
attr(data1$UR02x42,"2") = "2"
attr(data1$UR02x42,"3") = "3"
attr(data1$UR02x42,"4") = "4"
attr(data1$UR02x43,"1") = "1"
attr(data1$UR02x43,"2") = "2"
attr(data1$UR02x43,"3") = "3"
attr(data1$UR02x43,"4") = "4"
attr(data1$UR02x44,"1") = "1"
attr(data1$UR02x44,"2") = "2"
attr(data1$UR02x44,"3") = "3"
attr(data1$UR02x44,"4") = "4"
attr(data1$UR02x45,"1") = "1"
attr(data1$UR02x45,"2") = "2"
attr(data1$UR02x45,"3") = "3"
attr(data1$UR02x45,"4") = "4"
attr(data1$UR02x46,"1") = "1"
attr(data1$UR02x46,"2") = "2"
attr(data1$UR02x46,"3") = "3"
attr(data1$UR02x46,"4") = "4"
attr(data1$UR02x47,"1") = "1"
attr(data1$UR02x47,"2") = "2"
attr(data1$UR02x47,"3") = "3"
attr(data1$UR02x47,"4") = "4"
attr(data1$UR02x48,"1") = "1"
attr(data1$UR02x48,"2") = "2"
attr(data1$UR02x48,"3") = "3"
attr(data1$UR02x48,"4") = "4"
attr(data1$UR02x49,"1") = "1"
attr(data1$UR02x49,"2") = "2"
attr(data1$UR02x49,"3") = "3"
attr(data1$UR02x49,"4") = "4"
attr(data1$UR02x50,"1") = "1"
attr(data1$UR02x50,"2") = "2"
attr(data1$UR02x50,"3") = "3"
attr(data1$UR02x50,"4") = "4"
attr(data1$UR02x51,"1") = "1"
attr(data1$UR02x51,"2") = "2"
attr(data1$UR02x51,"3") = "3"
attr(data1$UR02x51,"4") = "4"
attr(data1$UR02x52,"1") = "1"
attr(data1$UR02x52,"2") = "2"
attr(data1$UR02x52,"3") = "3"
attr(data1$UR02x52,"4") = "4"
attr(data1$UR02x53,"1") = "1"
attr(data1$UR02x53,"2") = "2"
attr(data1$UR02x53,"3") = "3"
attr(data1$UR02x53,"4") = "4"
attr(data1$UR02x54,"1") = "1"
attr(data1$UR02x54,"2") = "2"
attr(data1$UR02x54,"3") = "3"
attr(data1$UR02x54,"4") = "4"
attr(data1$UR02x55,"1") = "1"
attr(data1$UR02x55,"2") = "2"
attr(data1$UR02x55,"3") = "3"
attr(data1$UR02x55,"4") = "4"
attr(data1$UR02x56,"1") = "1"
attr(data1$UR02x56,"2") = "2"
attr(data1$UR02x56,"3") = "3"
attr(data1$UR02x56,"4") = "4"
attr(data1$UR02x57,"1") = "1"
attr(data1$UR02x57,"2") = "2"
attr(data1$UR02x57,"3") = "3"
attr(data1$UR02x57,"4") = "4"
attr(data1$UR02x58,"1") = "1"
attr(data1$UR02x58,"2") = "2"
attr(data1$UR02x58,"3") = "3"
attr(data1$UR02x58,"4") = "4"
attr(data1$UR02x59,"1") = "1"
attr(data1$UR02x59,"2") = "2"
attr(data1$UR02x59,"3") = "3"
attr(data1$UR02x59,"4") = "4"
attr(data1$UR02x60,"1") = "1"
attr(data1$UR02x60,"2") = "2"
attr(data1$UR02x60,"3") = "3"
attr(data1$UR02x60,"4") = "4"
attr(data1$UR02x61,"1") = "1"
attr(data1$UR02x61,"2") = "2"
attr(data1$UR02x61,"3") = "3"
attr(data1$UR02x61,"4") = "4"
attr(data1$UR02x62,"1") = "1"
attr(data1$UR02x62,"2") = "2"
attr(data1$UR02x62,"3") = "3"
attr(data1$UR02x62,"4") = "4"
attr(data1$UR02x63,"1") = "1"
attr(data1$UR02x63,"2") = "2"
attr(data1$UR02x63,"3") = "3"
attr(data1$UR02x63,"4") = "4"
attr(data1$UR02x64,"1") = "1"
attr(data1$UR02x64,"2") = "2"
attr(data1$UR02x64,"3") = "3"
attr(data1$UR02x64,"4") = "4"
attr(data1$UR02x65,"1") = "1"
attr(data1$UR02x65,"2") = "2"
attr(data1$UR02x65,"3") = "3"
attr(data1$UR02x65,"4") = "4"
attr(data1$UR02x66,"1") = "1"
attr(data1$UR02x66,"2") = "2"
attr(data1$UR02x66,"3") = "3"
attr(data1$UR02x66,"4") = "4"
attr(data1$UR02x67,"1") = "1"
attr(data1$UR02x67,"2") = "2"
attr(data1$UR02x67,"3") = "3"
attr(data1$UR02x67,"4") = "4"
attr(data1$UR02x68,"1") = "1"
attr(data1$UR02x68,"2") = "2"
attr(data1$UR02x68,"3") = "3"
attr(data1$UR02x68,"4") = "4"
attr(data1$UR02x69,"1") = "1"
attr(data1$UR02x69,"2") = "2"
attr(data1$UR02x69,"3") = "3"
attr(data1$UR02x69,"4") = "4"
attr(data1$UR02x70,"1") = "1"
attr(data1$UR02x70,"2") = "2"
attr(data1$UR02x70,"3") = "3"
attr(data1$UR02x70,"4") = "4"
attr(data1$UR02x71,"1") = "1"
attr(data1$UR02x71,"2") = "2"
attr(data1$UR02x71,"3") = "3"
attr(data1$UR02x71,"4") = "4"
attr(data1$UR02x72,"1") = "1"
attr(data1$UR02x72,"2") = "2"
attr(data1$UR02x72,"3") = "3"
attr(data1$UR02x72,"4") = "4"
attr(data1$UR02x73,"1") = "1"
attr(data1$UR02x73,"2") = "2"
attr(data1$UR02x73,"3") = "3"
attr(data1$UR02x73,"4") = "4"
attr(data1$UR02x74,"1") = "1"
attr(data1$UR02x74,"2") = "2"
attr(data1$UR02x74,"3") = "3"
attr(data1$UR02x74,"4") = "4"
attr(data1$UR02x75,"1") = "1"
attr(data1$UR02x75,"2") = "2"
attr(data1$UR02x75,"3") = "3"
attr(data1$UR02x75,"4") = "4"
attr(data1$UR02x76,"1") = "1"
attr(data1$UR02x76,"2") = "2"
attr(data1$UR02x76,"3") = "3"
attr(data1$UR02x76,"4") = "4"
attr(data1$UR02x77,"1") = "1"
attr(data1$UR02x77,"2") = "2"
attr(data1$UR02x77,"3") = "3"
attr(data1$UR02x77,"4") = "4"
attr(data1$UR02x78,"1") = "1"
attr(data1$UR02x78,"2") = "2"
attr(data1$UR02x78,"3") = "3"
attr(data1$UR02x78,"4") = "4"
attr(data1$UR02x79,"1") = "1"
attr(data1$UR02x79,"2") = "2"
attr(data1$UR02x79,"3") = "3"
attr(data1$UR02x79,"4") = "4"
attr(data1$UR02x80,"1") = "1"
attr(data1$UR02x80,"2") = "2"
attr(data1$UR02x80,"3") = "3"
attr(data1$UR02x80,"4") = "4"
attr(data1$UR02x81,"1") = "1"
attr(data1$UR02x81,"2") = "2"
attr(data1$UR02x81,"3") = "3"
attr(data1$UR02x81,"4") = "4"
attr(data1$UR02x82,"1") = "1"
attr(data1$UR02x82,"2") = "2"
attr(data1$UR02x82,"3") = "3"
attr(data1$UR02x82,"4") = "4"
attr(data1$UR02x83,"1") = "1"
attr(data1$UR02x83,"2") = "2"
attr(data1$UR02x83,"3") = "3"
attr(data1$UR02x83,"4") = "4"
attr(data1$UR02x84,"1") = "1"
attr(data1$UR02x84,"2") = "2"
attr(data1$UR02x84,"3") = "3"
attr(data1$UR02x84,"4") = "4"
attr(data1$TR01_01a,"-1") = "Mensuration impossible"
attr(data1$TR01_02a,"-1") = "Mensuration impossible"
attr(data1$TR01_03a,"-1") = "Mensuration impossible"
attr(data1$TR01_04a,"-1") = "Mensuration impossible"
attr(data1$TR01_05a,"-1") = "Mensuration impossible"
attr(data1$TR01_06a,"-1") = "Mensuration impossible"
attr(data1$TR01_07a,"-1") = "Mensuration impossible"
attr(data1$TR01_08a,"-1") = "Mensuration impossible"
attr(data1$TR01_09a,"-1") = "Mensuration impossible"
attr(data1$TR01_10a,"-1") = "Mensuration impossible"
attr(data1$TR01_11a,"-1") = "Mensuration impossible"
attr(data1$TR01_12a,"-1") = "Mensuration impossible"
attr(data1$TR01_13a,"-1") = "Mensuration impossible"
attr(data1$TR01_14a,"-1") = "Mensuration impossible"
attr(data1$TR01_15a,"-1") = "Mensuration impossible"
attr(data1$TR01_16a,"-1") = "Mensuration impossible"
attr(data1$TR02_01a,"-1") = "Mensuration impossible"
attr(data1$TR02_02a,"-1") = "Mensuration impossible"
attr(data1$TR02_03a,"-1") = "Mensuration impossible"
attr(data1$TR02_04a,"-1") = "Mensuration impossible"
attr(data1$TR02_05a,"-1") = "Mensuration impossible"
attr(data1$TR02_06a,"-1") = "Mensuration impossible"
attr(data1$TR02_07a,"-1") = "Mensuration impossible"
attr(data1$TR02_08a,"-1") = "Mensuration impossible"
attr(data1$TR02_09a,"-1") = "Mensuration impossible"
attr(data1$TR02_10a,"-1") = "Mensuration impossible"
attr(data1$TR02_11a,"-1") = "Mensuration impossible"
attr(data1$TR02_12a,"-1") = "Mensuration impossible"
attr(data1$TR02_13a,"-1") = "Mensuration impossible"
attr(data1$TR02_14a,"-1") = "Mensuration impossible"
attr(data1$TR02_15a,"-1") = "Mensuration impossible"
attr(data1$TR02_16a,"-1") = "Mensuration impossible"
attr(data1$TR02_17a,"-1") = "Mensuration impossible"
attr(data1$TR02_18a,"-1") = "Mensuration impossible"
attr(data1$TR02_19a,"-1") = "Mensuration impossible"
attr(data1$TR02_20a,"-1") = "Mensuration impossible"
attr(data1$TR02_21a,"-1") = "Mensuration impossible"
attr(data1$TR02_22a,"-1") = "Mensuration impossible"
attr(data1$TR02_23a,"-1") = "Mensuration impossible"
attr(data1$TR02_24a,"-1") = "Mensuration impossible"
attr(data1$TR02_25a,"-1") = "Mensuration impossible"
attr(data1$TR02_26a,"-1") = "Mensuration impossible"
attr(data1$TR02_27a,"-1") = "Mensuration impossible"
attr(data1$TR02_28a,"-1") = "Mensuration impossible"
attr(data1$TR02_29a,"-1") = "Mensuration impossible"
attr(data1$TR02_30a,"-1") = "Mensuration impossible"
attr(data1$TR02_31a,"-1") = "Mensuration impossible"
attr(data1$TR02_32a,"-1") = "Mensuration impossible"
attr(data1$TR02_33a,"-1") = "Mensuration impossible"
attr(data1$TR02_34a,"-1") = "Mensuration impossible"
attr(data1$TR02_35a,"-1") = "Mensuration impossible"
attr(data1$TR02_36a,"-1") = "Mensuration impossible"
attr(data1$TR02_37a,"-1") = "Mensuration impossible"
attr(data1$TR02_38a,"-1") = "Mensuration impossible"
attr(data1$TR02_39a,"-1") = "Mensuration impossible"
attr(data1$TR02_40a,"-1") = "Mensuration impossible"
attr(data1$TR02_41a,"-1") = "Mensuration impossible"
attr(data1$TR02_42a,"-1") = "Mensuration impossible"
attr(data1$TR02_43a,"-1") = "Mensuration impossible"
attr(data1$TR02_44a,"-1") = "Mensuration impossible"
attr(data1$TR02_45a,"-1") = "Mensuration impossible"
attr(data1$TR02_46a,"-1") = "Mensuration impossible"
attr(data1$TR02_47a,"-1") = "Mensuration impossible"
attr(data1$TR02_48a,"-1") = "Mensuration impossible"
attr(data1$TR02_49a,"-1") = "Mensuration impossible"
attr(data1$TR02_50a,"-1") = "Mensuration impossible"
attr(data1$TR02_51a,"-1") = "Mensuration impossible"
attr(data1$TR02_52a,"-1") = "Mensuration impossible"
attr(data1$TR02_53a,"-1") = "Mensuration impossible"
attr(data1$TR02_54a,"-1") = "Mensuration impossible"
attr(data1$TR02_55a,"-1") = "Mensuration impossible"
attr(data1$TR02_56a,"-1") = "Mensuration impossible"
attr(data1$TR02_57a,"-1") = "Mensuration impossible"
attr(data1$TR02_58a,"-1") = "Mensuration impossible"
attr(data1$TR02_59a,"-1") = "Mensuration impossible"
attr(data1$TR02_60a,"-1") = "Mensuration impossible"
attr(data1$TR02_61a,"-1") = "Mensuration impossible"
attr(data1$TR02_62a,"-1") = "Mensuration impossible"
attr(data1$TR02_63a,"-1") = "Mensuration impossible"
attr(data1$TR02_64a,"-1") = "Mensuration impossible"
attr(data1$TR02_65a,"-1") = "Mensuration impossible"
attr(data1$TR02_66a,"-1") = "Mensuration impossible"
attr(data1$TR02_67a,"-1") = "Mensuration impossible"
attr(data1$TR02_68a,"-1") = "Mensuration impossible"
attr(data1$TR02_69a,"-1") = "Mensuration impossible"
attr(data1$TR02_70a,"-1") = "Mensuration impossible"
attr(data1$TR02_71a,"-1") = "Mensuration impossible"
attr(data1$TR02_72a,"-1") = "Mensuration impossible"
attr(data1$TR02_73a,"-1") = "Mensuration impossible"
attr(data1$TR02_74a,"-1") = "Mensuration impossible"
attr(data1$TR02_75a,"-1") = "Mensuration impossible"
attr(data1$TR02_76a,"-1") = "Mensuration impossible"
attr(data1$TR02_77a,"-1") = "Mensuration impossible"
attr(data1$TR02_78a,"-1") = "Mensuration impossible"
attr(data1$TR02_79a,"-1") = "Mensuration impossible"
attr(data1$TR02_80a,"-1") = "Mensuration impossible"
attr(data1$TR02_81a,"-1") = "Mensuration impossible"
attr(data1$TR02_82a,"-1") = "Mensuration impossible"
attr(data1$TR02_83a,"-1") = "Mensuration impossible"
attr(data1$TR02_84a,"-1") = "Mensuration impossible"
attr(data1$DM11_01,"F") = "Not checked"
attr(data1$DM11_01,"T") = "Checked"
attr(data1$DV01_01,"1") = "group1.png"
attr(data1$DV01_01,"101") = "group2.png"
attr(data1$DV02_01,"1") = "group1.png"
attr(data1$DV02_01,"101") = "group2.png"
attr(data1$DV03_01,"1") = "0 %"
attr(data1$DV03_01,"101") = "100 %"
attr(data1$DV03_02,"1") = "0 %"
attr(data1$DV03_02,"101") = "100 %"
attr(data1$DV04_01,"1") = "0 %"
attr(data1$DV04_01,"101") = "100 %"
attr(data1$DV04_02,"1") = "0 %"
attr(data1$DV04_02,"101") = "100 %"
attr(data1$DV05_01,"1") = "not confident at all"
attr(data1$DV05_01,"101") = "very confident"
attr(data1$DV05_02,"1") = "not confident at all"
attr(data1$DV05_02,"101") = "very confident"
attr(data1$DV06_01,"1") = "not confident at all"
attr(data1$DV06_01,"101") = "very confident"
attr(data1$DV06_02,"1") = "not confident at all"
attr(data1$DV06_02,"101") = "very confident"
attr(data1$FINISHED,"F") = "Canceled"
attr(data1$FINISHED,"T") = "Finished"
attr(data1$Q_VIEWER,"F") = "Respondent"
attr(data1$Q_VIEWER,"T") = "Spectator"
comment(data1$SERIAL) = "Serial number (if provided)"
comment(data1$REF) = "Reference (if provided in link)"
comment(data1$QUESTNNR) = "Questionnaire that has been used in the interview"
comment(data1$MODE) = "Interview mode"
comment(data1$STARTED) = "Time the interview has started (Europe/Berlin)"
comment(data1$UR01_CP) = "Condition: Complete clearances of the ballot, yet"
comment(data1$UR01) = "Condition: Code drawn"
comment(data1$UR02_CP) = "Trials: Complete clearances of the ballot, yet"
comment(data1$UR02x01) = "Trials: Code drawn (1)"
comment(data1$UR02x02) = "Trials: Code drawn (2)"
comment(data1$UR02x03) = "Trials: Code drawn (3)"
comment(data1$UR02x04) = "Trials: Code drawn (4)"
comment(data1$UR02x05) = "Trials: Code drawn (5)"
comment(data1$UR02x06) = "Trials: Code drawn (6)"
comment(data1$UR02x07) = "Trials: Code drawn (7)"
comment(data1$UR02x08) = "Trials: Code drawn (8)"
comment(data1$UR02x09) = "Trials: Code drawn (9)"
comment(data1$UR02x10) = "Trials: Code drawn (10)"
comment(data1$UR02x11) = "Trials: Code drawn (11)"
comment(data1$UR02x12) = "Trials: Code drawn (12)"
comment(data1$UR02x13) = "Trials: Code drawn (13)"
comment(data1$UR02x14) = "Trials: Code drawn (14)"
comment(data1$UR02x15) = "Trials: Code drawn (15)"
comment(data1$UR02x16) = "Trials: Code drawn (16)"
comment(data1$UR02x17) = "Trials: Code drawn (17)"
comment(data1$UR02x18) = "Trials: Code drawn (18)"
comment(data1$UR02x19) = "Trials: Code drawn (19)"
comment(data1$UR02x20) = "Trials: Code drawn (20)"
comment(data1$UR02x21) = "Trials: Code drawn (21)"
comment(data1$UR02x22) = "Trials: Code drawn (22)"
comment(data1$UR02x23) = "Trials: Code drawn (23)"
comment(data1$UR02x24) = "Trials: Code drawn (24)"
comment(data1$UR02x25) = "Trials: Code drawn (25)"
comment(data1$UR02x26) = "Trials: Code drawn (26)"
comment(data1$UR02x27) = "Trials: Code drawn (27)"
comment(data1$UR02x28) = "Trials: Code drawn (28)"
comment(data1$UR02x29) = "Trials: Code drawn (29)"
comment(data1$UR02x30) = "Trials: Code drawn (30)"
comment(data1$UR02x31) = "Trials: Code drawn (31)"
comment(data1$UR02x32) = "Trials: Code drawn (32)"
comment(data1$UR02x33) = "Trials: Code drawn (33)"
comment(data1$UR02x34) = "Trials: Code drawn (34)"
comment(data1$UR02x35) = "Trials: Code drawn (35)"
comment(data1$UR02x36) = "Trials: Code drawn (36)"
comment(data1$UR02x37) = "Trials: Code drawn (37)"
comment(data1$UR02x38) = "Trials: Code drawn (38)"
comment(data1$UR02x39) = "Trials: Code drawn (39)"
comment(data1$UR02x40) = "Trials: Code drawn (40)"
comment(data1$UR02x41) = "Trials: Code drawn (41)"
comment(data1$UR02x42) = "Trials: Code drawn (42)"
comment(data1$UR02x43) = "Trials: Code drawn (43)"
comment(data1$UR02x44) = "Trials: Code drawn (44)"
comment(data1$UR02x45) = "Trials: Code drawn (45)"
comment(data1$UR02x46) = "Trials: Code drawn (46)"
comment(data1$UR02x47) = "Trials: Code drawn (47)"
comment(data1$UR02x48) = "Trials: Code drawn (48)"
comment(data1$UR02x49) = "Trials: Code drawn (49)"
comment(data1$UR02x50) = "Trials: Code drawn (50)"
comment(data1$UR02x51) = "Trials: Code drawn (51)"
comment(data1$UR02x52) = "Trials: Code drawn (52)"
comment(data1$UR02x53) = "Trials: Code drawn (53)"
comment(data1$UR02x54) = "Trials: Code drawn (54)"
comment(data1$UR02x55) = "Trials: Code drawn (55)"
comment(data1$UR02x56) = "Trials: Code drawn (56)"
comment(data1$UR02x57) = "Trials: Code drawn (57)"
comment(data1$UR02x58) = "Trials: Code drawn (58)"
comment(data1$UR02x59) = "Trials: Code drawn (59)"
comment(data1$UR02x60) = "Trials: Code drawn (60)"
comment(data1$UR02x61) = "Trials: Code drawn (61)"
comment(data1$UR02x62) = "Trials: Code drawn (62)"
comment(data1$UR02x63) = "Trials: Code drawn (63)"
comment(data1$UR02x64) = "Trials: Code drawn (64)"
comment(data1$UR02x65) = "Trials: Code drawn (65)"
comment(data1$UR02x66) = "Trials: Code drawn (66)"
comment(data1$UR02x67) = "Trials: Code drawn (67)"
comment(data1$UR02x68) = "Trials: Code drawn (68)"
comment(data1$UR02x69) = "Trials: Code drawn (69)"
comment(data1$UR02x70) = "Trials: Code drawn (70)"
comment(data1$UR02x71) = "Trials: Code drawn (71)"
comment(data1$UR02x72) = "Trials: Code drawn (72)"
comment(data1$UR02x73) = "Trials: Code drawn (73)"
comment(data1$UR02x74) = "Trials: Code drawn (74)"
comment(data1$UR02x75) = "Trials: Code drawn (75)"
comment(data1$UR02x76) = "Trials: Code drawn (76)"
comment(data1$UR02x77) = "Trials: Code drawn (77)"
comment(data1$UR02x78) = "Trials: Code drawn (78)"
comment(data1$UR02x79) = "Trials: Code drawn (79)"
comment(data1$UR02x80) = "Trials: Code drawn (80)"
comment(data1$UR02x81) = "Trials: Code drawn (81)"
comment(data1$UR02x82) = "Trials: Code drawn (82)"
comment(data1$UR02x83) = "Trials: Code drawn (83)"
comment(data1$UR02x84) = "Trials: Code drawn (84)"
comment(data1$TR01_01) = "Forced: %forced%"
comment(data1$TR01_01a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_02) = "Forced: %forced%"
comment(data1$TR01_02a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_03) = "Forced: %forced%"
comment(data1$TR01_03a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_04) = "Forced: %forced%"
comment(data1$TR01_04a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_05) = "Forced: %forced%"
comment(data1$TR01_05a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_06) = "Forced: %forced%"
comment(data1$TR01_06a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_07) = "Forced: %forced%"
comment(data1$TR01_07a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_08) = "Forced: %forced%"
comment(data1$TR01_08a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_09) = "Forced: %forced%"
comment(data1$TR01_09a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_10) = "Forced: %forced%"
comment(data1$TR01_10a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_11) = "Forced: %forced%"
comment(data1$TR01_11a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_12) = "Forced: %forced%"
comment(data1$TR01_12a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_13) = "Forced: %forced%"
comment(data1$TR01_13a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_14) = "Forced: %forced%"
comment(data1$TR01_14a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_15) = "Forced: %forced%"
comment(data1$TR01_15a) = "Forced: %forced% response time [ms]"
comment(data1$TR01_16) = "Forced: %forced%"
comment(data1$TR01_16a) = "Forced: %forced% response time [ms]"
comment(data1$TR02_01) = "Free: "
comment(data1$TR02_01a) = "Free: response time [ms]"
comment(data1$TR02_02) = "Free: "
comment(data1$TR02_02a) = "Free: response time [ms]"
comment(data1$TR02_03) = "Free: "
comment(data1$TR02_03a) = "Free: response time [ms]"
comment(data1$TR02_04) = "Free: "
comment(data1$TR02_04a) = "Free: response time [ms]"
comment(data1$TR02_05) = "Free: "
comment(data1$TR02_05a) = "Free: response time [ms]"
comment(data1$TR02_06) = "Free: "
comment(data1$TR02_06a) = "Free: response time [ms]"
comment(data1$TR02_07) = "Free: "
comment(data1$TR02_07a) = "Free: response time [ms]"
comment(data1$TR02_08) = "Free: "
comment(data1$TR02_08a) = "Free: response time [ms]"
comment(data1$TR02_09) = "Free: "
comment(data1$TR02_09a) = "Free: response time [ms]"
comment(data1$TR02_10) = "Free: "
comment(data1$TR02_10a) = "Free: response time [ms]"
comment(data1$TR02_11) = "Free: "
comment(data1$TR02_11a) = "Free: response time [ms]"
comment(data1$TR02_12) = "Free: "
comment(data1$TR02_12a) = "Free: response time [ms]"
comment(data1$TR02_13) = "Free: "
comment(data1$TR02_13a) = "Free: response time [ms]"
comment(data1$TR02_14) = "Free: "
comment(data1$TR02_14a) = "Free: response time [ms]"
comment(data1$TR02_15) = "Free: "
comment(data1$TR02_15a) = "Free: response time [ms]"
comment(data1$TR02_16) = "Free: "
comment(data1$TR02_16a) = "Free: response time [ms]"
comment(data1$TR02_17) = "Free: "
comment(data1$TR02_17a) = "Free: response time [ms]"
comment(data1$TR02_18) = "Free: "
comment(data1$TR02_18a) = "Free: response time [ms]"
comment(data1$TR02_19) = "Free: "
comment(data1$TR02_19a) = "Free: response time [ms]"
comment(data1$TR02_20) = "Free: "
comment(data1$TR02_20a) = "Free: response time [ms]"
comment(data1$TR02_21) = "Free: "
comment(data1$TR02_21a) = "Free: response time [ms]"
comment(data1$TR02_22) = "Free: "
comment(data1$TR02_22a) = "Free: response time [ms]"
comment(data1$TR02_23) = "Free: "
comment(data1$TR02_23a) = "Free: response time [ms]"
comment(data1$TR02_24) = "Free: "
comment(data1$TR02_24a) = "Free: response time [ms]"
comment(data1$TR02_25) = "Free: "
comment(data1$TR02_25a) = "Free: response time [ms]"
comment(data1$TR02_26) = "Free: "
comment(data1$TR02_26a) = "Free: response time [ms]"
comment(data1$TR02_27) = "Free: "
comment(data1$TR02_27a) = "Free: response time [ms]"
comment(data1$TR02_28) = "Free: "
comment(data1$TR02_28a) = "Free: response time [ms]"
comment(data1$TR02_29) = "Free: "
comment(data1$TR02_29a) = "Free: response time [ms]"
comment(data1$TR02_30) = "Free: "
comment(data1$TR02_30a) = "Free: response time [ms]"
comment(data1$TR02_31) = "Free: "
comment(data1$TR02_31a) = "Free: response time [ms]"
comment(data1$TR02_32) = "Free: "
comment(data1$TR02_32a) = "Free: response time [ms]"
comment(data1$TR02_33) = "Free: "
comment(data1$TR02_33a) = "Free: response time [ms]"
comment(data1$TR02_34) = "Free: "
comment(data1$TR02_34a) = "Free: response time [ms]"
comment(data1$TR02_35) = "Free: "
comment(data1$TR02_35a) = "Free: response time [ms]"
comment(data1$TR02_36) = "Free: "
comment(data1$TR02_36a) = "Free: response time [ms]"
comment(data1$TR02_37) = "Free: "
comment(data1$TR02_37a) = "Free: response time [ms]"
comment(data1$TR02_38) = "Free: "
comment(data1$TR02_38a) = "Free: response time [ms]"
comment(data1$TR02_39) = "Free: "
comment(data1$TR02_39a) = "Free: response time [ms]"
comment(data1$TR02_40) = "Free: "
comment(data1$TR02_40a) = "Free: response time [ms]"
comment(data1$TR02_41) = "Free: "
comment(data1$TR02_41a) = "Free: response time [ms]"
comment(data1$TR02_42) = "Free: "
comment(data1$TR02_42a) = "Free: response time [ms]"
comment(data1$TR02_43) = "Free: "
comment(data1$TR02_43a) = "Free: response time [ms]"
comment(data1$TR02_44) = "Free: "
comment(data1$TR02_44a) = "Free: response time [ms]"
comment(data1$TR02_45) = "Free: "
comment(data1$TR02_45a) = "Free: response time [ms]"
comment(data1$TR02_46) = "Free: "
comment(data1$TR02_46a) = "Free: response time [ms]"
comment(data1$TR02_47) = "Free: "
comment(data1$TR02_47a) = "Free: response time [ms]"
comment(data1$TR02_48) = "Free: "
comment(data1$TR02_48a) = "Free: response time [ms]"
comment(data1$TR02_49) = "Free: "
comment(data1$TR02_49a) = "Free: response time [ms]"
comment(data1$TR02_50) = "Free: "
comment(data1$TR02_50a) = "Free: response time [ms]"
comment(data1$TR02_51) = "Free: "
comment(data1$TR02_51a) = "Free: response time [ms]"
comment(data1$TR02_52) = "Free: "
comment(data1$TR02_52a) = "Free: response time [ms]"
comment(data1$TR02_53) = "Free: "
comment(data1$TR02_53a) = "Free: response time [ms]"
comment(data1$TR02_54) = "Free: "
comment(data1$TR02_54a) = "Free: response time [ms]"
comment(data1$TR02_55) = "Free: "
comment(data1$TR02_55a) = "Free: response time [ms]"
comment(data1$TR02_56) = "Free: "
comment(data1$TR02_56a) = "Free: response time [ms]"
comment(data1$TR02_57) = "Free: "
comment(data1$TR02_57a) = "Free: response time [ms]"
comment(data1$TR02_58) = "Free: "
comment(data1$TR02_58a) = "Free: response time [ms]"
comment(data1$TR02_59) = "Free: "
comment(data1$TR02_59a) = "Free: response time [ms]"
comment(data1$TR02_60) = "Free: "
comment(data1$TR02_60a) = "Free: response time [ms]"
comment(data1$TR02_61) = "Free: "
comment(data1$TR02_61a) = "Free: response time [ms]"
comment(data1$TR02_62) = "Free: "
comment(data1$TR02_62a) = "Free: response time [ms]"
comment(data1$TR02_63) = "Free: "
comment(data1$TR02_63a) = "Free: response time [ms]"
comment(data1$TR02_64) = "Free: "
comment(data1$TR02_64a) = "Free: response time [ms]"
comment(data1$TR02_65) = "Free: "
comment(data1$TR02_65a) = "Free: response time [ms]"
comment(data1$TR02_66) = "Free: "
comment(data1$TR02_66a) = "Free: response time [ms]"
comment(data1$TR02_67) = "Free: "
comment(data1$TR02_67a) = "Free: response time [ms]"
comment(data1$TR02_68) = "Free: "
comment(data1$TR02_68a) = "Free: response time [ms]"
comment(data1$TR02_69) = "Free: "
comment(data1$TR02_69a) = "Free: response time [ms]"
comment(data1$TR02_70) = "Free: "
comment(data1$TR02_70a) = "Free: response time [ms]"
comment(data1$TR02_71) = "Free: "
comment(data1$TR02_71a) = "Free: response time [ms]"
comment(data1$TR02_72) = "Free: "
comment(data1$TR02_72a) = "Free: response time [ms]"
comment(data1$TR02_73) = "Free: "
comment(data1$TR02_73a) = "Free: response time [ms]"
comment(data1$TR02_74) = "Free: "
comment(data1$TR02_74a) = "Free: response time [ms]"
comment(data1$TR02_75) = "Free: "
comment(data1$TR02_75a) = "Free: response time [ms]"
comment(data1$TR02_76) = "Free: "
comment(data1$TR02_76a) = "Free: response time [ms]"
comment(data1$TR02_77) = "Free: "
comment(data1$TR02_77a) = "Free: response time [ms]"
comment(data1$TR02_78) = "Free: "
comment(data1$TR02_78a) = "Free: response time [ms]"
comment(data1$TR02_79) = "Free: "
comment(data1$TR02_79a) = "Free: response time [ms]"
comment(data1$TR02_80) = "Free: "
comment(data1$TR02_80a) = "Free: response time [ms]"
comment(data1$TR02_81) = "Free: "
comment(data1$TR02_81a) = "Free: response time [ms]"
comment(data1$TR02_82) = "Free: "
comment(data1$TR02_82a) = "Free: response time [ms]"
comment(data1$TR02_83) = "Free: "
comment(data1$TR02_83a) = "Free: response time [ms]"
comment(data1$TR02_84) = "Free: "
comment(data1$TR02_84a) = "Free: response time [ms]"
comment(data1$IV01_RV1) = "POST/GET Variable: PROLIFIC_PID"
comment(data1$IV01_REF) = "Referer (HTTP_REFERER)"
comment(data1$IV02_01) = "Internal: Pageorder"
comment(data1$IV02_02) = "Internal: account"
comment(data1$DM03) = "AttCheck"
comment(data1$DM04) = "Age"
comment(data1$DM05) = "Gender"
comment(data1$DM06) = "Psychstudent"
comment(data1$DM07) = "Education"
comment(data1$DM10_01) = "Comments: [01]"
comment(data1$DM11) = "consent: Residual option (negative) or number of selected options"
comment(data1$DM11_01) = "consent: I agree and understand all the points listed above and would like to participate in this study."
comment(data1$DV01_01) = "Preference_pre: group1.png/group2.png"
comment(data1$DV02_01) = "Preference_post: group1.png/group2.png"
comment(data1$DV03_01) = "Conditionals_pre: ...you stopped someone from group 1?"
comment(data1$DV03_02) = "Conditionals_pre: ...you stopped someone from group 2?"
comment(data1$DV04_01) = "Conditionals_post: ...you stopped someone from group 1?"
comment(data1$DV04_02) = "Conditionals_post: ...you stopped someone from group 2?"
comment(data1$DV05_01) = "Confidence_pre: How confident are you that you can make a reasonable estimate regarding group 1?"
comment(data1$DV05_02) = "Confidence_pre: How confident are you that you can make a reasonable estimate regarding group 2?"
comment(data1$DV06_01) = "Confidence_post: How confident are you that you can make a reasonable estimate regarding group 1?"
comment(data1$DV06_02) = "Confidence_post: How confident are you that you can make a reasonable estimate regarding group 2?"
comment(data1$TIME001) = "Time spent on page 1"
comment(data1$TIME002) = "Time spent on page 2"
comment(data1$TIME003) = "Time spent on page 3"
comment(data1$TIME004) = "Time spent on page 4"
comment(data1$TIME005) = "Time spent on page 5"
comment(data1$TIME006) = "Time spent on page 6"
comment(data1$TIME007) = "Time spent on page 7"
comment(data1$TIME008) = "Time spent on page 8"
comment(data1$TIME009) = "Time spent on page 9"
comment(data1$TIME010) = "Time spent on page 10"
comment(data1$TIME011) = "Time spent on page 11"
comment(data1$TIME012) = "Time spent on page 12"
comment(data1$TIME013) = "Time spent on page 13"
comment(data1$TIME014) = "Time spent on page 14"
comment(data1$TIME015) = "Time spent on page 15"
comment(data1$TIME016) = "Time spent on page 16"
comment(data1$TIME017) = "Time spent on page 17"
comment(data1$TIME_SUM) = "Time spent overall (except outliers)"
comment(data1$MAILSENT) = "Time when the invitation mailing was sent (personally identifiable recipients, only)"
comment(data1$LASTDATA) = "Time when the data was most recently updated"
comment(data1$FINISHED) = "Has the interview been finished (reached last page)?"
comment(data1$Q_VIEWER) = "Did the respondent only view the questionnaire, omitting mandatory questions?"
comment(data1$LASTPAGE) = "Last page that the participant has handled in the questionnaire"
comment(data1$MAXPAGE) = "Hindmost page handled by the participant"
comment(data1$MISSING) = "Missing answers in percent"
comment(data1$MISSREL) = "Missing answers (weighted by relevance)"
comment(data1$TIME_RSI) = "Degradation points for being very fast"
comment(data1$DEG_TIME) = "Degradation points for being very fast"
# Assure that the comments are retained in subsets
as.data.frame.avector = as.data.frame.vector
`[.avector` <- function(x,i,...) {
r <- NextMethod("[")
mostattributes(r) <- attributes(x)
r
}
data1_tmp = data.frame(
lapply(data1, function(x) {
structure( x, class = c("avector", class(x) ) )
} )
)
mostattributes(data1_tmp) = attributes(data1)
data1 = data1_tmp
rm(data1_tmp)
<file_sep>/Auxiliary/functions.R
# My functions for outputting inference tests in APAish style -------------
source("https://raw.githubusercontent.com/chrisharrisUU/testoutputs/master/functions.R")
# Time series functions ---------------------------------------------------
time_series <- function(.data, grouping_var) {
# Enquote
grouping_var <- enquo(grouping_var)
# Range
trials <- colnames(.data) %>%
.[grep("trial", .)] %>%
substr(., 6, nchar(.)) %>%
as.integer(.)
from <- min(trials)
to <- max(trials)
# Data prep
.data %<>%
select(id, !!grouping_var, primacy, contains("trial")) %>%
# Counterbalancing
mutate_at(.vars = vars(contains("trial")),
.funs = ~ifelse(primacy == "left frequent", . * (-1), .)) %>%
# # Dominant
# mutate_at(.vars = vars(contains("week")),
# .funs = funs(ifelse(condition == "rich", ., . * (-1)))) %>%
# 0 - 1 for percentages
mutate_at(.vars = vars(contains("trial")),
.funs = ~ifelse(. < 0, 0, 1)) %>%
group_by(!!grouping_var) %>%
# Summarize percentage positive hits
summarize_at(.vars = vars(contains("trial")),
.funs = ~mean(., na.rm = TRUE)) %>%
# Long format
gather(key = time,
value = sampling,
paste0("trial", from:to)) %>%
# As integer for time series graph
mutate(time = as.integer(substr(time, 6, nchar(time))))
# Create graph
ggplot(.data,
aes(x = time,
y = sampling,
color = !!grouping_var,
group = !!grouping_var)) +
# geom_hline(yintercept = .5,
# alpha = .3) +
geom_segment(aes(x = 5,
xend = 100,
y = .5,
yend = .5),
color = "#999999",
size = .1) +
geom_point(size = .9) +
geom_line(size = .2,
alpha = .3) +
geom_smooth(method = "loess",
span = 1,
size = 1,
formula = "y ~ x") +
scale_color_manual(values = pal, name = "Group") +
theme_apa() +
labs(y = "Percentage sampling frequent option",
x = "Trial") + guides(color = guide_legend(reverse = TRUE))
}
| 8a0e02e232ecca918727077a2937ea23e74841a1 | [
"Markdown",
"R"
] | 4 | R | chrisharrisUU/2020_BA_RP1 | 69e43832e4e2459b4d46aeb802f57646950875e4 | c4b09351102d681979daaeed1fb8fcd833107079 |
refs/heads/master | <repo_name>SarahMarieFerguson/se-challenge<file_sep>/expenses/import_file/models.py
from django.db import models
from django.db.models import Sum
class Employee(models.Model):
name = models.CharField(max_length=200)
address = models.CharField(max_length=200)
def __str__(self):
return self.name
@staticmethod
def get_employee(name, address):
if Employee.objects.filter(name=name).exists():
return Employee.objects.get(name=name)
else:
employee_object = Employee(name=name, address=address)
employee_object.save()
return employee_object
class File(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Expenses(models.Model):
upload_file = models.ForeignKey(File)
date = models.DateField()
category = models.CharField(max_length=200)
employee = models.ForeignKey(Employee)
expense_description = models.CharField(max_length=200)
pre_tax_amount = models.DecimalField(max_digits=19, decimal_places=2)
tax_name = models.CharField(max_length=200)
tax_amount = models.DecimalField(max_digits=19, decimal_places=2)
def __str__(self):
return self.expense_description
@staticmethod
def get_monthly_expenses(file_id):
file_object = File.objects.filter(id=file_id)
dates = Expenses.objects.filter(upload_file=file_object).dates('date', 'month')
monthly_expenses_dict = {}
for date in dates:
amount_dict = Expenses.objects.filter(upload_file=file_object, date__month=date.month, date__year=date.year).aggregate(Sum('tax_amount'), Sum('pre_tax_amount'))
tax_amount = amount_dict['tax_amount__sum']
pre_tax_amount = amount_dict['pre_tax_amount__sum']
monthly_expenses_dict.update({date: pre_tax_amount + tax_amount})
return monthly_expenses_dict
<file_sep>/expenses/import_file/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^upload_results$', views.upload_results, name='upload_results'),
]<file_sep>/expenses/import_file/file_handler.py
import csv
from datetime import datetime
from .models import Employee, Expenses, File
class FileHandler(object):
def __init__(self, f):
self.uploaded_file = f
self.file_object = File(name=f.name)
self.file_object.save()
def parse_uploaded_file(self):
reader = csv.DictReader(self.uploaded_file)
for row in reader:
date = datetime.strptime(row['date'], "%m/%d/%Y")
category = row['category']
employee = Employee.get_employee(row['employee name'], row['employee address'])
expense_description = row['expense description']
pre_tax_amount = row['pre-tax amount'].replace(',', '')
tax_name = row['tax name']
tax_amount = row['tax amount'].replace(',', '')
expense_object = Expenses(date=date, category=category,employee=employee, expense_description=expense_description, pre_tax_amount=pre_tax_amount, tax_amount=tax_amount, tax_name=tax_name, upload_file=self.file_object)
expense_object.save()
<file_sep>/expenses/README.markdown
# Sarah's Wave Challenge Solution
#Setup
1. Make sure you have python installed
1. Make sure you have django installed (pip install django), preferably in a virtual environment
1. From the directory expenses/ run the command python manage.py migrate - this will set up your local database.
#Using the app
1. Navigate to expenses/ and run the command python manage.py runserver
1. On your browser, navigate to http://127.0.0.1:8000/
2. Upload your file and click submit
3. You'll see your results on the page.. :)
#What I'm proud of
1. I think the models work well together, they make sense, and you can search by file in case you'd like to do queries on previous files uploaded.
<file_sep>/expenses/import_file/views.py
from django.core.context_processors import csrf
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.template import RequestContext, loader
from .file_handler import FileHandler
from .forms import UploadFileForm
from .models import Expenses
def index(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = FileHandler(request.FILES['form_file'])
uploaded_file.parse_uploaded_file()
request.session['filename'] = request.FILES['form_file'].name
request.session['file_id'] = uploaded_file.file_object.id
return HttpResponseRedirect('upload_results')
else:
form = UploadFileForm()
context = {'form': form}
context.update(csrf(request))
return render_to_response('import_file/index.html', context)
def upload_results(request):
monthly = Expenses.get_monthly_expenses(request.session['file_id'])
context = {'monthly': monthly}
context.update({'filename': request.session['filename']})
return render_to_response('import_file/upload_results.html', context)
| 1a935809e6a9842db0f7e147b7c5caeb0deeba4e | [
"Markdown",
"Python"
] | 5 | Python | SarahMarieFerguson/se-challenge | 2ed6b7684d4533e2cf97b55dd7735e8120568ccc | ab7ddf25c50a35c957405c53a300414e3ae5aad8 |
refs/heads/master | <file_sep>package edu.cnm.deepdive.blackjackdemo.service;
import edu.cnm.deepdive.blackjackdemo.model.Deck;
import edu.cnm.deepdive.blackjackdemo.model.Draw;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface DeckOfCardsService {
@GET("deck/new/shuffle")
Call<Deck> newDeck(@Query("deck_count") int count);
@GET("deck/{deckId}/draw")
Call<Draw> draw(@Path("deckId") String deckId, @Query("count") int count);
@GET("deck/{deckId}/shuffle")
Call<Deck> shuffle(@Path("deckId") String deckId);
}
<file_sep>package edu.cnm.deepdive.blackjackdemo;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import edu.cnm.deepdive.blackjackdemo.model.Card;
import edu.cnm.deepdive.blackjackdemo.model.Deck;
import edu.cnm.deepdive.blackjackdemo.model.Draw;
import edu.cnm.deepdive.blackjackdemo.model.Hand;
import edu.cnm.deepdive.blackjackdemo.service.DeckOfCardsService;
import java.io.IOException;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final int DECKS_IN_SHOE = 6;
private Deck deck;
private Hand hand;
private DeckOfCardsService service;
private RecyclerView handView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener((view) -> {
// TODO Handle click by drawing a card.
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean handled = true;
switch (item.getItemId()) {
case R.id.shuffle_deck:
// TODO Shuffle deck.
break;
case R.id.deal_hand:
// TODO Deal a new hand.
break;
default:
handled = super.onOptionsItemSelected(item);
}
return handled;
}
private void setupService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.base_url))
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(DeckOfCardsService.class);
}
private class CreateDeckTask extends AsyncTask<Integer, Void, Deck> {
@Override
protected void onPostExecute(Deck deck) {
if (deck != null) {
MainActivity.this.deck = deck;
hand = new Hand();
new DrawCardsTask(deck).execute(2);
}
}
@Override
protected Deck doInBackground(Integer... integers) {
int decksInShoe = values[0];
Deck deck = null;
try {
Response<Deck> response = service.newDeck(decksInShoe).execute();
if (response.isSuccessful()) {
deck = response.body();
}
} catch (IOException e) {
// Deck is already null, which is fine.
cancel(true);
}
return deck;
}
}
private class DrawCardsTask extends AsyncTask<Integer, Void, Draw> {
private Deck deck;
public DrawCardsTask(Deck deck) {
this.deck = deck;
}
@Override
protected void onPostExecute(Draw draw) {
for (Card card : draw.getCards()) {
hand.addCard(card);
}
// TODO Make this smarter.
HandAdapter adapter = new HandAdapter(MainActivity.this, hand.getCards());
handView.setAdapter(adapter);
}
@Override
protected Draw doInBackground(Integer... values) {
int cardsToDraw = values[0];
Draw draw = null;
try {
Response<Draw> response = service.draw(deck.getId(), cardsToDraw).execute();
if (response.isSuccessful()) {
draw = response.body();
}
} catch (IOException e) {
cancel(true);
}
return draw;
}
}
}
| 8490edfb99493dc5e83901d34922a8e99ca440f9 | [
"Java"
] | 2 | Java | achigbrow/blackjack-demo | e717c736d1315284b0d3f66fd3fb8197f6cf864d | bf43d73271a86417156ded1f6544feb3aaee0e28 |
refs/heads/master | <file_sep>L.Control.AddBikelot = L.Control.extend({
options: {
position: 'topright'
},
onAdd: function (map) {
var container = L.DomUtil.create('div',
'leaflet-control-addbikelot leaflet-bar leaflet-control active')
, self = this
;
this._active = true;
var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
link.innerHTML = '+';
link.href = '#';
link.title = 'Add bike parking';
self.locating = false;
var cancel = function() {
self._map.removeLayer(self.marker);
L.DomUtil.removeClass(link, "locating");
}
L.DomEvent
.on(link, 'click', L.DomEvent.stopPropagation)
.on(link, 'click', L.DomEvent.preventDefault)
.on(link, 'click', function() {
if(self.locating) {
cancel();
self.locating = false;
} else {
self.locating = true;
if(typeof self.marker === 'undefined')
self.marker = L.marker(
[0,0]
, {
'icon' : app.map.getBikeParkIcon('new')
, 'draggable' : true
}
)
.on('dblclick', L.DomEvent.stopPropagation)
.on('dblclick', function() {
self._map.spin(true);
var latlng = self.marker.getLatLng();
$.ajax({
'url' : app.httpBase + 'locations'
, 'type' : 'post'
, 'data' : {
'location[latitude]' : latlng.lat
, 'location[longitude]' : latlng.lng
}
,'success' : function() {
alert(
'Se agrego el estacionamiento, gracias'
+ ' por tu contribución.'
);
cancel();
app.map.reloadBikeparkings();
self.locating = false;
self._map.spin(false);
}
, 'fail' : function() {
alert(
'Ha habido un error, intenta otra vez.'
);
self._map.spin(false);
self.locating = false;
}
, 'always' : function() {
self.locating = false;
self._map.spin(false);
}
});
}).bindLabel('Doble '+(L.Browser.touch ? 'tap' : 'click')+' para agregar.')
L.DomUtil.addClass(link, "locating");
self.marker.setLatLng(self._map.getCenter()).addTo(self._map);
}
})
;
return container;
}
})<file_sep>class LocationsController < ApplicationController
skip_before_filter :verify_authenticity_token, only: :create
def index
@locations = Location.all
@locations = Location.active.within_lat_range(params[:min_lat], params[:max_lat]).within_long_range(params[:min_long], params[:max_long]) if [:min_lat, :max_lat, :min_long, :max_long].all? {|s| params.key? s}
render json: @locations, only: [:latitude, :longitude, :spots]
end
# POST
# params: latitude REQ, longitude REQ, spots DEF 1
def create
if Location.find_or_create_by_coords(location_params)
render json: {success: true}
else
render json: {success: false}
end
end
private
def location_params
params.require(:location).permit(:latitude, :longitude, :spots)
end
end
<file_sep>source 'https://rubygems.org'
ruby '1.9.3'
gem 'rails', '4.0.0'
gem 'pg'
gem 'unicorn'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'haml-rails'
#gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
#gem 'gmaps4rails'
gem 'leaflet-rails'
gem 'geocoder'
group :doc do
gem 'sdoc', require: false
end
gem 'rails_12factor', group: :production
group :development, :test do
gem 'pry'
gem 'pry-rails'
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'capybara'
end
<file_sep>class AddDetailsToLocation < ActiveRecord::Migration
def change
add_column :locations, :spots, :integer
add_column :locations, :score, :integer
end
end
<file_sep>class StaticController < ApplicationController
def index
@json = Location.all
end
end
<file_sep>class Location < ActiveRecord::Base
scope :active, -> { where('score > 0') }
scope :within_lat_range, ->(min_lat, max_lat) { where(latitude: (min_lat..max_lat)) }
scope :within_long_range, ->(min_long, max_long) { where(longitude: (min_long..max_long)) }
validates :latitude, :longitude, presence: true, numericality: {
greater_than: -180,
less_than: 180
}
validates :spots, presence: true, numericality: {
greater_than: -1,
less_than: 4
}
validates :score, presence: true
reverse_geocoded_by :latitude, :longitude
def coords
[latitude, longitude]
end
def inc_score
self.score += 1
end
def dec_score
self.score -= 1
end
class << self
def find_by_coords(coords)
coords = [coords[:latitude], coords[:longitude]]
unless (locs = Location.near(coords, 0.05, {units: :km})).nil?
locs.first
end
end
def find_or_create_by_coords(location_params)
if location = Location.find_by_coords(location_params)
if location_params[:spots].to_i == -1
location.dec_score
else
location.spots = location_params[:spots] || 1
location.inc_score
end
else
unless location_params[:spots].to_i == -1
location = Location.new({spots: 1}.merge(location_params.merge({score: 1})))
end
end
location.save if location
end
end
end
<file_sep> <EMAIL>:rojo/bikelot.git - Geekli.st repo
<EMAIL>:elfenars/bikelot.git - Github repo
<EMAIL>:bikelot.git - Heroku repo<file_sep>require 'spec_helper'
describe LocationsController do
describe 'POST create' do
it 'should create location for valid params' do
expect {
post :create, location: {latitude: 40, longitude: 10, spots: 1}, format: :json
}.to change {
Location.count
}.by(1)
end
it 'should respond with success true json' do
post :create, location: {latitude: 40, longitude: 10, spots: 1}, format: :json
expect(response.body).to have_content ({success: true}.to_json)
end
it 'should respond with success false with invalid params' do
post :create, location: {latitude: 181, longitude: 10, spots: 1}
expect(response.body).to have_content ({success: false}.to_json)
end
it 'should create a new location with score 1' do
post :create, location: {latitude: 32, longitude: -13, spots: 1}, format: :json
expect(Location.last.score).to eq(1)
end
it 'should only increment the score rather than create a duplicate entry for close coordinates' do
expect {
post :create, location: {latitude: 32, longitude: -13, spots: 1}, format: :json
post :create, location: {latitude: 32, longitude: -13.0001, spots: 1}, format: :json
}.to change {
Location.count
}.by(1)
expect(Location.last.score).to eq(2)
end
it 'should not create anything for new coordinates with -1 spots' do
expect {
post :create, location: {latitude: 32, longitude: -13, spots: -1}, format: :json
}.to_not change {
Location.count
}
end
it 'should decrement the score when similar coordinates are passed with -1 spots' do
expect {
post :create, location: {latitude: 32, longitude: -13, spots: 1}, format: :json
post :create, location: {latitude: 32, longitude: -13.0001, spots: -1}, format: :json
}.to change {
Location.count
}.by(1)
expect(Location.last.score).to eq(0)
end
end
end
<file_sep># Be sure to restart your server when you modify this file.
Bikelot::Application.config.session_store :cookie_store, key: '_bikelot_session'
<file_sep>var app = {
'httpBase' : ''
, 'locks' :{
'bikeparkingsLayer' : false
}
, 'xhr' : {}
, 'map' : {
'layers' : {}
, 'features' : {}
, 'controls' : {}
, 'markers' : []
, 'icons' : {
'bikeParkingMarker' : {
// 'shadowUrl' : ''
'iconSize' : [25, 30]
// , 'shadowSize' : [37, 34]
, 'iconAnchor' : [12.5, 30]
, 'shadowAnchor' : [12.5, 30]
, 'popupAnchor' : [0, 0]
}
}
}
};
app.map.getBikeParkIcon = function(suff) {
return L.icon($.extend({}, app.map.icons.bikeParkingMarker, {
'iconUrl' : app.httpBase + 'assets/bikepark-marker'+(suff ? '-'+suff : '')+'.png'
}));
}
$(function() {
app.map.L = L.map('map').setView([-33.437778, -70.650278], 16);
app.map.layers.osm = new L.TileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
, {
minZoom: 4
, maxZoom: 19
, attribution: 'Map data © OpenStreetMap contributors'
, opacity : 0.8
}
).addTo(app.map.L);
/*
// OpenCycleMap
app.map.layers.ocm = new L.TileLayer(
'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png'
, {
minZoom : 12
, maxZoom : 18
, attribution : '© OpenCycleMap, Map Data © '
+ '<a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
+ ', <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
}
).addTo(app.map.L);
*/
app.map.reloadBikeparkings = function() {
var bounds = app.map.L.getBounds();
if(typeof app.xhr.bikeparkingsLayer !== 'undefined') {
app.xhr.bikeparkingsLayer.abort();
app.locks.bikeparkingsLayer = true;
}
app.xhr.bikeparkingsLayer = $.getJSON(
app.httpBase
+ 'locations'
+ '?max_lat=' + bounds._northEast.lat
+ '&max_long=' + bounds._northEast.lng
+ '&min_lat=' + bounds._southWest.lat
+ '&min_long=' + bounds._southWest.lng
, function(points) {
var i,k = 0;
if(typeof app.map.layers.markers !== 'undefined')
app.map.layers.markers.clearLayers();
app.map.markers = [];
for(i in points) {
app.map.markers.push(
L.marker(
[points[i].latitude, points[i].longitude]
, {'icon' : app.map.getBikeParkIcon()}
).addTo(app.map.L)
)
}
app.map.layers.markers = L.layerGroup(app.map.markers)
app.locks.bikeparkingsLayer = false;
delete app.xhr.bikeparkingsLayer;
}
);
};
app.map.L
.on('zoomend', app.map.reloadBikeparkings)
.on('dragend', app.map.reloadBikeparkings)
;
app.map.controls.locate = L.control.locate({
'position' : 'topright'
, 'follow' : true
}).addTo(app.map.L);
app.map.controls.addBikelot = new L.Control.AddBikelot().addTo(app.map.L);
app.map.controls.locate.locate();
});<file_sep>Bikelot::Application.routes.draw do
root to: "static#index"
resources :locations, only: [:index, :create]
end
| e4a82e765c2e46bf19db09949af97b90434477ec | [
"JavaScript",
"Ruby",
"Markdown"
] | 11 | JavaScript | elfenars/bikelot | 5c48c7f1a34e5f1f6c369bd7828e5d45fba7eb4e | b1107ef64bbbf1d2158847c8dba8a5f18be0b905 |
refs/heads/master | <file_sep># RandomWalk-MK1
This is so bad...
<file_sep>package com.example.randomwalk;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class DrawSurfaceView extends SurfaceView implements OnTouchListener {
Paint paint = new Paint();
float start_X;
float start_Y;
Path path = new Path();
int ok = 0;
double random;
int counter = 0;
SurfaceHolder surfaceHolder;
Canvas canvas;
public DrawSurfaceView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
surfaceHolder = getHolder();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(ok<1)
{ ok++;
start_X = event.getX();
start_Y = event.getY();
Log.d("SURFACEEE","Is "+surfaceHolder.getSurface().isValid());
canvas = surfaceHolder.lockCanvas();
while (ok == 1 && counter < 100) {//&& start_X <=500 && start_Y<=500
Log.d("COUNTER","COUNTER + "+counter);
counter++;
random = Math.random();
char r = 'i';
if (random <= 0.25)
r = 'u';
else if (random <= 0.5)
r = 'd';
else if (random <= 0.75)
r = 'l';
else if (random <= 1)
r = 'r';
switch (r) {
case 'u': {
surfaceHolder.lockCanvas();
canvas.drawLine(start_X, start_Y, start_X, start_Y - 25,
paint);
start_Y = start_Y - 25;
surfaceHolder.unlockCanvasAndPost(canvas);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("UP", "point: " + start_X + " " + start_Y + " " + ok);
break;
}
case 'd': {
surfaceHolder.lockCanvas();
canvas.drawLine(start_X, start_Y, start_X, start_Y + 25,
paint);
start_Y = start_Y + 25;
surfaceHolder.unlockCanvasAndPost(canvas);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("DOWN", "point: " + start_X + " " + start_Y + " "
+ ok);
break;
}
case 'l': {
surfaceHolder.lockCanvas();
canvas.drawLine(start_X, start_Y, start_X - 25, start_Y,
paint);
start_X = start_X - 25;
surfaceHolder.unlockCanvasAndPost(canvas);
//invalidate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//path.moveTo(start_X, start_Y);
Log.d("LEFT", "point: " + start_X + " " + start_Y + " "
+ ok);
break;
}
case 'r': {
surfaceHolder.lockCanvas();
canvas.drawLine(start_X, start_Y, start_X + 25, start_Y,
paint);
start_X = start_X + 25;
surfaceHolder.unlockCanvasAndPost(canvas);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("RIGHT", "point: " + start_X + " " + start_Y + " "
+ ok);
break;
}
default:
Log.d("BLA", "Invalid!");
}
}
}
Log.d("DRAWVIEW!!!!", "point: " + start_X +" "+start_Y+" "+ok);
//surfaceHolder.unlockCanvasAndPost(canvas);
return true;
}
}
//for (float i = 0; i < 500; i++) {
// canvas = holder.lockCanvas();
// canvas.drawLine(0, i, 600, i, paint);
// holder.unlockCanvasAndPost(canvas);
//}
<file_sep>package com.example.randomwalk;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Working extends View implements OnTouchListener {
Paint paint = new Paint();
float start_X;
float start_Y;
Path path = new Path();
int ok = 0;
double random;
int counter = 0;
Canvas canvas;
Bitmap bitmap;
public Working(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
//bitmap = new Bitmap();
this.setOnTouchListener(this);
//canvas = new Canvas(bitmap);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(5);
}
@Override
public void onDraw(final Canvas canvas) {
//canvas.drawLine(50,50, 10, 1000, paint);
//canvas.drawLine(20, 0, 0, 20, paint);
paint.setStyle(Paint.Style.STROKE);
this.canvas = canvas;
if (ok == 1 ) {//&& start_X <=500 && start_Y<=500
drawTick();
Log.d("COUNTER","COUNTER + "+counter);
counter++;
}
//drawTick();
//canvas.drawBitmap(bitmap, 0, 0, paint);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(ok<1)
{ ok++;
start_X = event.getX();
start_Y = event.getY();invalidate();}
Log.d("DRAWVIEW!!!!", "point: " + start_X +" "+start_Y+" "+ok);
return true;
}
public void drawTick(){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
random = Math.random();
char r = 'i';
if (random <= 0.25)
r = 'u';
else if (random <= 0.5)
r = 'd';
else if (random <= 0.75)
r = 'l';
else if (random <= 1)
r = 'r';
switch (r) {
case 'u': {
canvas.drawLine(start_X, start_Y, start_X, start_Y - 25,
paint);
start_Y = start_Y - 25;
Log.d("UP", "point: " + start_X + " " + start_Y + " " + ok);
break;
}
case 'd': {
canvas.drawLine(start_X, start_Y, start_X, start_Y + 25,
paint);
start_Y = start_Y + 25;
Log.d("DOWN", "point: " + start_X + " " + start_Y + " "
+ ok);
break;
}
case 'l': {
canvas.drawLine(start_X, start_Y, start_X - 25, start_Y,
paint);
start_X = start_X - 25;
Log.d("LEFT", "point: " + start_X + " " + start_Y + " "
+ ok);
break;
}
case 'r': {
canvas.drawLine(start_X, start_Y, start_X + 25, start_Y,
paint);
start_X = start_X + 25;
Log.d("RIGHT", "point: " + start_X + " " + start_Y + " "
+ ok);
break;
}
default:
Log.d("BLA", "Invalid!");
}
invalidate();
}
}
<file_sep>package com.example.randomwalk;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class MainActivity extends Activity {
//DrawView drawView;
DrawSurfaceView drawSurfaceView;
SurfaceViewTest surfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawView = new DrawView(this);
drawSurfaceView = new DrawSurfaceView(this);
surfaceView = new SurfaceViewTest(this);
//drawView.setBackgroundColor(Color.BLACK);
drawSurfaceView.setBackgroundColor(Color.BLACK);
surfaceView.setBackgroundColor(Color.BLACK);
setContentView(surfaceView);
}
}
<file_sep>package com.example.randomwalk;
import java.util.Random;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
public class SurfaceViewTest extends View implements OnTouchListener {
Paint paint = new Paint();
float start_X;
float start_Y;
Path path = new Path();
int ok = 0;
int random;
int counter = 0;
Canvas canvas;
Bitmap bitmap;
Random rand;
Paint paintBoundries = new Paint();
DisplayMetrics metrics;
boolean canvasCheck = false;
public SurfaceViewTest(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
//bitmap = new Bitmap();
this.setOnTouchListener(this);
rand = new Random();
//canvas = new Canvas(bitmap);
paint.setColor(Color.WHITE);
paintBoundries.setColor(Color.YELLOW);
paintBoundries.setStrokeWidth(3);
paint.setStrokeWidth(5);
//if(Bitmap.Config.ARGB_8888 == null || canvas.getHeight() == 0 || canvas.getWidth() == 0)
// Log.d("BITMAP","Is null");
//else
metrics = getResources().getDisplayMetrics();
Log.d("HEIGHT","Height"+metrics.heightPixels);
Log.d("WIDTH","Height"+metrics.widthPixels);
bitmap = Bitmap.createBitmap(metrics.widthPixels, metrics.heightPixels, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
}
@Override
public void onDraw(final Canvas canvas) {
//canvas.drawLine(50,50, 10, 1000, paint);
//canvas.drawLine(20, 0, 0, 20, paint);
paint.setStyle(Paint.Style.STROKE);
this.canvas.drawLine(metrics.widthPixels/6,0,metrics.widthPixels/6,metrics.heightPixels,paintBoundries);
this.canvas.drawLine(metrics.widthPixels, metrics.heightPixels/2-100,
metrics.widthPixels-20, metrics.heightPixels/2-100, paint);
this.canvas.drawLine(metrics.widthPixels, metrics.heightPixels/2+100,
metrics.widthPixels-20, metrics.heightPixels/2+100, paint);
this.canvas.drawLine(metrics.widthPixels-20, metrics.heightPixels/2-100,
metrics.widthPixels-20, metrics.heightPixels/2+100, paint);
if (ok == 1 ) {//&& start_X <=500 && start_Y<=500
if(start_X + 25 == metrics.widthPixels)
if(start_Y >= metrics.heightPixels/2-100+25 && start_Y <= metrics.heightPixels/2+100+25)
Toast.makeText(getContext(), "YOU ARE HOME!", 10000);
else
Toast.makeText(getContext(), "Almost There"+ Math.abs(start_Y - metrics.heightPixels/2), 10000);
drawTick();
//Log.d("COUNTER","COUNTER + "+counter);
counter++;
}
//drawTick();
canvas.drawBitmap(bitmap, 0, 0, paint);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(ok<1 && event.getX()<=metrics.widthPixels/6)
{ ok++;
start_X = event.getX();
start_Y = event.getY();invalidate();}
return true;
}
public void drawTick(){
int distance = 25;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
random = rand.nextInt(7);
switch (random) {
case 0: {
canvas.drawLine(start_X, start_Y, start_X, start_Y - distance,
paint);
start_Y = start_Y - distance;
break;
}
case 1: {
canvas.drawLine(start_X, start_Y, start_X, start_Y + distance,
paint);
start_Y = start_Y + distance;
break;
}
// case 2: {
//
//
// canvas.drawLine(start_X, start_Y, start_X - distance, start_Y,
// paint);
// start_X = start_X - distance;
// }
case 3: {
canvas.drawLine(start_X, start_Y, start_X + distance, start_Y,
paint);
start_X = start_X + distance;
break;
}
// case 4: {
// canvas.drawLine(start_X, start_Y, start_X - distance, start_Y - distance,
// paint);
//
// start_Y = start_Y - distance;
// start_X = start_X - distance;
// break;
// }
case 5: {
canvas.drawLine(start_X, start_Y, start_X + distance, start_Y + distance,
paint);
start_Y = start_Y + distance;
start_X = start_X + distance;
break;
}
// case 6: {
//
//
// canvas.drawLine(start_X, start_Y, start_X - distance, start_Y + distance,
// paint);
// start_X = start_X - distance;
// start_Y = start_Y + distance;
// }
case 7: {
canvas.drawLine(start_X, start_Y, start_X + distance, start_Y - distance,
paint);
start_X = start_X + distance;
start_Y = start_Y - distance;
break;
}
}
invalidate();
}
}
| 820e8c6c6c85b96a3376f920a7a5b6e2b72ff05c | [
"Markdown",
"Java"
] | 5 | Markdown | SariNusier/RandomWalk-MK1 | 4a908979e60b64de736cf2bcec570826608c2f93 | f0fe3bd7ce529f59d7bca0c7ab9dd701606815a5 |
refs/heads/master | <repo_name>enspdf/parcel-vuejs-example<file_sep>/app.js
import Vue from 'vue/dist/vue.js';
const app = new Vue({
el: '#app',
template: `<h1>{{ name }}</h1>`,
data () {
return {
name: 'Name'
}
}
}); | 3d5b6cfdf3042c438d2684700d2635047574d596 | [
"JavaScript"
] | 1 | JavaScript | enspdf/parcel-vuejs-example | 6537a2e2573a1383276480f6ae4a7150fcefaa49 | dd47150aef67f014f1f38a471c8eb7228d1834c2 |
refs/heads/main | <repo_name>mairaouf6100/Invoices<file_sep>/app/Http/Controllers/InvoicesAttachmentsController.php
<?php
namespace App\Http\Controllers;
use App\invoices_attachments;
use Illuminate\Http\Request;
class InvoicesAttachmentsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\invoices_attachments $invoices_attachments
* @return \Illuminate\Http\Response
*/
public function show(invoices_attachments $invoices_attachments)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\invoices_attachments $invoices_attachments
* @return \Illuminate\Http\Response
*/
public function edit(invoices_attachments $invoices_attachments)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\invoices_attachments $invoices_attachments
* @return \Illuminate\Http\Response
*/
public function update(Request $request, invoices_attachments $invoices_attachments)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\invoices_attachments $invoices_attachments
* @return \Illuminate\Http\Response
*/
public function destroy(invoices_attachments $invoices_attachments)
{
//
}
}
<file_sep>/app/Http/Controllers/ProductsController.php
<?php
namespace App\Http\Controllers;
use App\Products;
use App\Sections;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$sections=Sections::all();
$products=Products::all();
return view('products.products',compact('sections','products'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $validatedData=$request->validate([
// 'products_name'=>'required|unique:products|max:255',
// 'description'=>'required',
// 'section_id' =>'required',
// ],[
// 'products_name.required' =>'يرجي ادخال اسم المنتج',
// 'products_name.unique' =>'اسم المنتج مسجل مسبقا',
// 'section_id.required'=>'يرجي اختيار القسم',
// ]);
Products::create([
'products_name' => $request->products_name,
'section_id' => $request->section_id,
'description' => $request->description,
]);
return redirect('/products')->with('success','تم اضافه المنتج');
}
/**
* Display the specified resource.
*
* @param \App\Products $products
* @return \Illuminate\Http\Response
*/
public function show(Products $products)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Products $products
* @return \Illuminate\Http\Response
*/
public function edit(Products $products)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Products $products
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$id=Sections::where('section_name',$request->section_name)->first()->id;
$products=Products::findOrFail($request->pro_id);
$products->update([
'products_name'=>$request->products_name,
'description'=>$request->description,
'section_id' => $id,
]);
return redirect('/products')->with('success','تم التعديل');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Products $products
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$products=Products::findOrFail($request->pro_id);
$products->delete();
return redirect('/products')->with('success','تم الحذف');
}
}
<file_sep>/app/Http/Controllers/InvoicesController.php
<?php
namespace App\Http\Controllers;
use App\Invoices;
use App\Sections;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class InvoicesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('invoices.invoices');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$sections=Sections::all();
return view('invoices.add_invoices',compact('sections'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return $request;
//return request
}
/**
* Display the specified resource.
*
* @param \App\Invoices $invoices
* @return \Illuminate\Http\Response
*/
public function show(Invoices $invoices)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Invoices $invoices
* @return \Illuminate\Http\Response
*/
public function edit(Invoices $invoices)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Invoices $invoices
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Invoices $invoices)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Invoices $invoices
* @return \Illuminate\Http\Response
*/
public function destroy(Invoices $invoices)
{
//
}
public function getProducts($id){
$prducts=DB::table("products")->where("section_id", $id)->pluck("products_name","id");
return json_encode($prducts);
}
}
| f91fc47dbdf6fb270fee29c3b648ba9176b5034a | [
"PHP"
] | 3 | PHP | mairaouf6100/Invoices | 06adff07a2fa77fb46b20ee9a6b2cae1ef4903b2 | fb006b6cb6222bc277643ca61bfcc1850a001b30 |
refs/heads/master | <repo_name>wk1cast/wk1cast.github.io<file_sep>/site/templates/js/dom.js
(function ($) {
'use strict';
$(document).ready(function () {
/* MEJS Audio player */
$('audio').mediaelementplayer({
audioWidth: '100%',
features: ['playpause','progress', 'volume']
}).on('play', function () {
this.player.container.addClass('playing');
}).on('pause', function () {
this.player.container.removeClass('playing');
});
/* Sticky navigation */
$('.nav-page').waypoint('sticky');
/* Swap out link to home page */
$('.nav-page-internal').append('<a class="nav-page-home-swap" href="/"></a>');
});
}(jQuery)); | b86bcc5c0ac10e1ce3066a516bb3a898cd920248 | [
"JavaScript"
] | 1 | JavaScript | wk1cast/wk1cast.github.io | 98bbf9d7a9d3f87d6222fa6b60d067952fce6ae6 | 8d6853e917c8be98a29117f35812da9c00caac9f |
refs/heads/main | <repo_name>daaniell/console-todolist<file_sep>/ToDoList/ToDoList/AppContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace ToDoList
{
class AppContext : DbContext
{
public DbSet<TaskList> Tasks { get; set; }
public AppContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=tasklistdb;trusted_Connection=True;");
}
}
}
| cc307a7bb319ee06a89f99e104d511486c0f14f4 | [
"C#"
] | 1 | C# | daaniell/console-todolist | 8c92cf28cb7827649f77ad6d49c1a49f11937349 | 47f008694b7b366744e3a213b4956ededfbef9e4 |
refs/heads/master | <repo_name>carrieguan17/paymentconfirmation<file_sep>/server.js
// import dependencies
const express = require('express');
const app = express();
const path = require('path');
const filePath = path.join(__dirname, './public');
const ENDPOINT = "/checkout";
const ENDPOINT2 = "/confirmation";
const PORT = '3000';
const model = require('./db/model.js')
// middleware
app.use((req, res, next) => {
console.log(`${req.method} received for ${req.path}`);
next()
})
app.use(express.static(filePath))
app.use(express.json())
// routes
app.post(ENDPOINT, (req, res) => {
if (req.body['form'] === 'f1') {
model.createProfile(req.body)
res.status(201)
res.send(req.body)
} else if (req.body['form'] === 'f2') {
model.addContact(req.body)
res.status(201)
res.send(req.body)
} else if (req.body['form'] === 'f3') {
model.addPayment(req.body)
res.status(201)
res.send(req.body)
}
})
app.get(ENDPOINT, (req, res) => {
model.getCurrentUserId((err, result) => {
if (err) {
res.status(404)
console.log(err)
} else {
res.status(201)
res.send(result)
}
})
})
app.get(ENDPOINT2, (req, res) => {
model.getConfirmation((err, result) => {
if (err) {
res.status(404)
console.log(err)
} else {
res.status(201)
res.send(result)
}
})
})
// start server
app.listen(PORT, () => {
console.log(`Server is listening on PORT: ${PORT}`)
})
<file_sep>/db/model.js
const db = require('./index.js')
module.exports = {
createProfile: (profile, callback) => {
db.query(`insert into f1 (name, email, password) values ("${profile.name}", "${profile.email}", "${profile.password}")`, (err, profile) => {
if (err) {
console.log(err)
} else {
console.log('Profile created in DB')
}
})
},
addContact: (contact, callback) => {
db.query(`insert into f2 (f1_id, shippingAddL1, shippingAddL2, city, state, zipCode, phoneNum) values ("${contact.currentUserId}", "${contact.shippingAddL1}", "${contact.shippingAddL2}", "${contact.city}", "${contact.state}", "${contact.zipCode}", "${contact.phoneNum}")`, (err, contact) => {
if (err) {
console.log(err)
} else {
console.log(`Contact info added to DB`)
}
})
},
addPayment: (payment, callback) => {
db.query(`insert into f3 (f1_id, creditCard, expirationDate, cvv, billingZip) values ("${payment.currentUserId}", "${payment.creditCard}", "${payment.expirationDate}", "${payment.cvv}", "${payment.billingZip}")`, (err, contact) => {
if (err) {
console.log(err)
} else {
console.log(`Payment info added to DB`)
}
})
},
getCurrentUserId: (callback) => {
db.query(`select last_insert_id()`, (err, result) => {
if (err) {
callback(err)
} else {
callback(null, result)
}
})
},
getConfirmation: (callback) => {
db.query(`select f1.*, f2.*, f3.* from f1, f2, f3 where f1.id = f2.f1_id and f1.id = f3.f1_id and f3.id = (select last_insert_id())`, (err, result) => {
if (err) {
callback(err)
} else {
callback(null, result)
}
})
}
} | 5e77d8d6250cc9b4c8644406ab50f9f0c5edd68e | [
"JavaScript"
] | 2 | JavaScript | carrieguan17/paymentconfirmation | 4383b080f43e1a72cf1136f371254b1896bc24fe | dd33540c349901a14699d9cdb773756fe1f4566d |
refs/heads/master | <repo_name>geyujia/map-viz<file_sep>/mock/information_map_general_mock_data.js
/*
InformationMap组件的mock数据
主要结构:
{
"initPoint": 地图初始点坐标
"zoom": 地图初始缩放比例
"markerArray": 地图标记点的内容
},
...
其中,markerArray中每一项的内容为:
export interface GeoData {
type: "hospital"|"hotel"|"other";
name: string;
url?: string;
coord: [number, number];
metadata: Metadata[];
}
export interface Metadata {
key: string;
label?: string;
value: string|number|InquiryMeta[],
}
使用:
<InformationMap
initPoint={initPoint}
zoom={zoom}
markers={makerArray} />
*/
export default {
initPoint: [110.350658, 32.938285],
zoom: 6,
makerArray: [
{
name: '华中科技大学同济医学院附属协和医院',
type: "hospital",
coord: [114.281196, 30.590103],
url: 'https://mp.weixin.qq.com/s/geO3CCd0_8B3L-r_xlBbZQ',
metadata: [
{
key: "request",
label: "物资需求",
value: [
['普通医用口罩', 10000],
['医用外科口罩', true],
['医用防护口罩 | N95口罩', 10000],
['防冲击眼罩/护目镜/防护眼镜', true],
['防护面罩', 25050],
['防护帽/医用帽/圆帽', 10420],
['隔离衣', true],
['防护服', 5000],
['手术衣', true],
['乳胶手套', true],
['长筒胶鞋/防污染靴', true],
['防污染鞋套', true],
['防污染靴套', true],
['84消毒液', true],
['过氧乙酸', true],
['75%酒精', true],
['手部皮肤消毒液', true],
['活力碘', true],
['床罩', true],
['医用面罩式雾化器', true],
['测体温设备', true],
['空气消毒设备', true],
['医用紫外线消毒车', true]
]
}, {
key: "address",
value: '湖北省武汉市江汉区解放大道1277号华中科技大学同济医学院附属协和医院总务处',
label: "邮寄地址",
}, {
key: "note",
value: null,
label: "备注信息",
}
]
},
{
name: '红安县人民医院',
coord: [114.625222, 31.286868],
url: 'https://mp.weixin.qq.com/s/geO3CCd0_8B3L-r_xlBbZQ',
address: '红安县人民医院红安县城关镇陵园大道附50号',
metadata: [
{
key: "request",
label: "物资需求",
value: [
['普通医用口罩', 1000],
['医用外科口罩', 1000],
['医用防护口罩 | N95口罩', 10000],
['防冲击眼罩/护目镜/防护眼镜', 1000],
['防护面罩', true],
['防护帽/医用帽/圆帽', 1000],
['隔离衣', true],
['防护服', 100],
['手术衣', true],
['乳胶手套', 1000],
['长筒胶鞋/防污染靴', 100],
['防污染鞋套', 100],
['防污染靴套', 10000],
['84消毒液', true],
['过氧乙酸', true],
['75%酒精', true],
['手部皮肤消毒液', true],
['活力碘', true],
['床罩', true],
['医用面罩式雾化器', true],
['测体温设备', true],
['空气消毒设备', true],
['医用紫外线消毒车', true]
]
}, {
key: "address",
value: '湖北省武汉市江汉区解放大道1277号华中科技大学同济医学院附属协和医院总务处',
label: "邮寄地址",
}, {
key: "note",
value: null,
label: "备注信息",
}, {
key: "contact",
label: "联系方式",
value: [
['0713-5242320'],
['设备科周主任, 13636105950']
]
}
]
},
{
type: 'hotel',
name: '住宿数据1',
coord: [114.881337, 30.205063],
metadata: [
{
key: "capability",
value: 100,
label: "容量",
}, {
key: "note",
value: '发布日期, 2020年1月25日',
label: "备注信息",
}, {
key: "contact",
label: "联系方式",
value: [
['XXX:123456789'],
]
}
]
},
{
type: 'others',
name: '其他数据',
coord: [114.681337, 30.295063],
metadata: [
{
key: "内容",
value: '我是内容'
}
]
}
]
};
| 1d5e6c7d172afafb00f941ebe8f5a04dc1fc598a | [
"JavaScript"
] | 1 | JavaScript | geyujia/map-viz | 52bcd397963dc677ac687c63f1afc3a49da772c9 | a790f7c656301e8967294c9b1da5b8b061b846ee |
refs/heads/master | <file_sep>import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import Api from '../../helpers/Api';
import './Home.css'
export default function Home() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
Api.getProducts()
.then(products => {
setProducts(products);
setLoading(false);
})
return (
<div>
<h1>Home</h1>
<hr />
{loading && <div><p>Carregando...</p></div> }
{products.length > 0 && <ul>{products.map(product => <li key={product.id}>{product.title}</li>)}</ul> }
<hr />
<Link to="/sobre">Ir para pagina sobre</Link>
</div>
)
}
<file_sep>const initialState = {
name: '<NAME>',
email: '<EMAIL>',
logged: true
}
const userReducer = (state = initialState, action) => {
if(action.type === 'changeName') {
return { ...state, name: action.payload.name }
}
return state
}
export default userReducer;
<file_sep>import React, { useState } from 'react';
import { Link } from 'react-router-dom'
import './Header.css'
import Menu from '../../../assets/Hamburger_icon.png'
export default function Header(props) {
const [menu, setMenu] = useState(false);
const { user } = props;
function menuToggle() {
setMenu(!menu)
}
return (
<header>
<div className="container">
<div className="menu-opener" onClick={menuToggle}>
<img src={Menu} alt="Menu" />
</div>
<div className="logo">
<Link to="/">
<span className="logo-o">O</span>
<span className="logo-l">L</span>
<span className="logo-x">X</span>
</Link>
</div>
<nav className={menu ? 'opened' : ''}>
<ul>
{user.logged &&
<li><Link to="/account">Minha Conta</Link></li>
}
{user.logged === false &&
<>
<li><Link to="/login">Login</Link></li>
<li><Link to="/register">Registrar</Link></li>
</>
}
<li><Link to="/post" className="link-button">Poste um Anúncio</Link></li>
</ul>
</nav>
</div>
</header>
);
}
<file_sep>const Api = {
getProducts: (limit = 10) => {
return new Promise((resolve, reject) => {
setTimeout(function() {
const array = [
{id: 1, title: 'Produto 1'},
{id: 2, title: 'Produto 2'},
{id: 3, title: 'Produto 3'}
];
resolve(array);
}, 1500)
})
}
};
export default Api | f45f1dee304edb5c98d25d11035f4711894c9df7 | [
"JavaScript"
] | 4 | JavaScript | GiovaniHMilani/olx-clone-react | e93758149b41ad11486646fe5353765c9213824b | c416aa17abfbf5485115a3608c1e83b1a3212885 |
refs/heads/master | <repo_name>shaheenkdr/capstone_yaafl<file_sep>/app/src/main/java/com/udacity/yaafl/neuron/HomeAway.java
package com.udacity.yaafl.neuron;
import com.udacity.yaafl.utility.TeamInfo;
import java.util.List;
/**
*Neuron which generates chances of success for home and
*Away team based on team id and home or away value
*/
public class HomeAway
{
private int team_id;
private boolean home_away_id;
private int home_wins;
private int away_wins;
private List<com.udacity.yaafl.cohesion.Situational>s_data;
public HomeAway(int team, boolean home_away, List<com.udacity.yaafl.cohesion.Situational> s_data)
{
this.team_id = team;
this.home_away_id = home_away;
this.s_data = s_data;
}
public int computeHomeAwayScore()
{
if(home_away_id)
{
for(com.udacity.yaafl.cohesion.Situational situation_data: s_data)
{
if(situation_data.getHome() && situation_data.getTeam().equals(TeamInfo.getTeamName(team_id)))
{
home_wins = (int)((double)(situation_data.getWon())/(double)(situation_data.getMatchPlayed())*100);
home_wins -= situation_data.getLose()*10;
}
}
return home_wins*2;
}
else
{
for(com.udacity.yaafl.cohesion.Situational situation_data: s_data)
{
if(situation_data.getAway() && situation_data.getTeam().equals(TeamInfo.getTeamName(team_id)))
{
away_wins = (int)((double)(situation_data.getWon())/(double)(situation_data.getMatchPlayed())*100);
away_wins -= situation_data.getLose()*5;
}
}
return away_wins*2;
}
}
}<file_sep>/app/src/main/java/com/udacity/yaafl/neuron/TeamHeadToHead.java
package com.udacity.yaafl.neuron;
import com.udacity.yaafl.utility.TeamInfo;
import java.util.List;
/**
* Neuron to measure the head to head match results of
* two teams to be played and generate score .
*/
public class TeamHeadToHead
{
private int team1_id;
private int team2_id;
private int[] score;
private List<com.udacity.yaafl.cohesion.Head2Head> head;
public TeamHeadToHead(List<com.udacity.yaafl.cohesion.Head2Head>head,int team1, int team2)
{
this.head = head;
this.team1_id = team1;
this.team2_id = team2;
score = new int[2];
}
public int[] computeScore()
{
final String MID = TeamInfo.getMatchId(TeamInfo.getTeamName(team1_id)+" VS "+TeamInfo.getTeamName(team2_id));
if(!MID.equals(""))
{
for(com.udacity.yaafl.cohesion.Head2Head versus:head)
{
if(versus.getMatchID().equals(MID))
{
score[0] = versus.getTeam1()*4;
score[1] = versus.getTeam2()*4;
break;
}
}
return score;
}
else
return score;
}
}<file_sep>/app/src/main/java/com/udacity/yaafl/activities/HomeTeamSelector.java
package com.udacity.yaafl.activities;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.transition.Fade;
import android.view.View;
import com.elmargomez.typer.Font;
import com.elmargomez.typer.Typer;
import com.udacity.yaafl.R;
import com.udacity.yaafl.adapter.HomeAdapter;
import com.udacity.yaafl.utility.SpeedyLinearLayoutManager;
import com.udacity.yaafl.utility.TeamInfo;
import java.util.ArrayList;
public class HomeTeamSelector extends AppCompatActivity
{
private static ArrayList<String> team_list;
private CollapsingToolbarLayout collapsingToolbarLayout = null;
static
{
team_list = new ArrayList<>();
for(int i=0;i<20;i++)
team_list.add(TeamInfo.getTeamNameForView(i));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_team_selector);
setupWindowAnimations();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final AppBarLayout abl = (AppBarLayout)findViewById(R.id.appbarhome);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
Typeface font = Typer.set(this).getFont(Font.ROBOTO_BOLD);
collapsingToolbarLayout.setExpandedTitleTypeface(font);
collapsingToolbarLayout.setTitle(getResources().getString(R.string.home_team));
dynamicToolbarColor();
toolbarTextAppernce();
final RecyclerView rView = (RecyclerView)findViewById(R.id.homeTeamRView);
rView.setHasFixedSize(true);
SpeedyLinearLayoutManager llm = new SpeedyLinearLayoutManager(HomeTeamSelector.this);
rView.setLayoutManager(llm);
HomeAdapter homeAdapter = new HomeAdapter(team_list);
rView.setAdapter(homeAdapter);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
abl.setExpanded(false);
rView.smoothScrollToPosition(7);
}
});
}
private void setupWindowAnimations() {
Fade fade = new Fade();
fade.setDuration(1000);
getWindow().setExitTransition(fade);
getWindow().setEnterTransition(fade);
}
private void dynamicToolbarColor() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.e5);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(ContextCompat.getColor(HomeTeamSelector.this,R.color.colorPrimary)));
collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(ContextCompat.getColor(HomeTeamSelector.this,R.color.colorPrimary)));
}
});
}
private void toolbarTextAppernce() {
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
}
}
| d459512d94cb8ad168e35cdc7c3db28e06a32af8 | [
"Java"
] | 3 | Java | shaheenkdr/capstone_yaafl | c836c81706b76d211d0695e192e5112b6e5e0b1a | 35deaa1561d66701d64874596b4cdf7aa428d744 |
refs/heads/main | <file_sep>require('dotenv').config();
var moment = require('moment');
const { Client } = require('discord.js');
const { channel_id, channel } = require('../config/config.js');
const client = new Client();
client.db = require("quick.db");
client.request = new (require("rss-parser"));
client.config = require("../config/config.js");
const PREFIX = ";"
client.login(client.config.DISCORD_BOT_TOKEN);
const isValidCommand = (message, cmdName) => message.content.toLowerCase().startsWith(PREFIX + cmdName);
client.on('ready', () => {
console.log(`${client.user.username} has logged in`);
lolTime();
handleUploads();
});
client.on('message', (message) =>{
if(message.author.bot === true)
return;
if(message.content.toLowerCase() === "que horas são?"){
message.reply(`Hora do Lolzinho!`)
}
else if(isValidCommand(message, "say")){
sendAdmMessage(message.content.substring(5))
}
});
function lolTime(){
setInterval(() => {
var hour = moment().hour()
var minute = moment().minute()
if(hour === 19 && minute === 00){
// const channel = await client.channels.cache.get('762689749818408973');
const channel = client.channels.cache.find(channel => channel.name === 'general')
channel.send("𝓗𝓸𝓻𝓪 𝓭𝓸 𝓛𝓸𝓵𝔃𝓲𝓷𝓱𝓸!")
}
}, 20000)
}
function handleUploads() {
if (client.db.fetch(`postedVideos`) === null) client.db.set(`postedVideos`, []);
setInterval(() => {
client.request.parseURL(`https://www.youtube.com/feeds/videos.xml?channel_id=${client.config.channel_id}`)
.then(data => {
if (client.db.fetch(`postedVideos`).includes(data.items[0].link)) return;
else {
client.db.set(`videoData`, data.items[0]);
client.db.push("postedVideos", data.items[0].link);
let parsed = client.db.fetch(`videoData`);
let channel = client.channels.cache.get(client.config.general_channel);
if (!channel) return;
let message = client.config.messageTemplate
.replace(/{author}/g, parsed.author)
.replace(/{title}/g, Discord.Util.escapeMarkdown(parsed.title))
.replace(/{url}/g, parsed.link);
channel.send(message);
}
});
}, client.config.watchInterval);
}
async function sendAdmMessage(message){
let channel = client.channels.cache.get(client.config.general_channel)
channel.send(message)
}<file_sep># lolzinho-discord-bot<file_sep>module.exports = {
DISCORD_BOT_TOKEN:"",
general_channel: "732768478406246514",
messageTemplate: "Oi @everyone, **{author}** acabou de publicar um vídeo **{title}**!\n{url}",
channel_id: "UC2t5bjwHdUX4vM2g8TRDq5g", // League Of legends Channel
watchInterval: 30000
} | 33a9337c73d842a00e5c40228e758814fc221ed8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jsantos93/lolzinho-discord-bot | f91b7722e94b8c569f9c810948998aa1470280c1 | 0ad23304118756df647a4be3191b71e5f7abed6e |
refs/heads/master | <repo_name>th3nule/Codeigniter<file_sep>/README.md
# Codeigniter
Meu codeigniter
<file_sep>/Replace Action URL.php
<?php
// Função simples para substituir parte de uma url por outra palavra.
// A função detecta a url atual do usuário, busca a palavra desejada e a substitui.
// Necessita do helper 'url' no controller ou loader.
// Cria a função, recebe "search (para buscar a palavra)" e "replace (para substituir a palavra)".
function replace_action_url($search, $replace){
// Retorna o resultado da substituição.
return str_replace($search, $replace, base_url(uri_string()));
}
| 79b9245047a65e6efbe98a37356c8fd988bac87f | [
"Markdown",
"PHP"
] | 2 | Markdown | th3nule/Codeigniter | dd0098af2f00a07a1f7eef64c87fdc8b978d30a4 | 57f29e15488e9da87bda2f4f6fd40e3d77d42973 |
refs/heads/master | <repo_name>mostafaMahfouz25/youtube-react-app-task-manager-list<file_sep>/src/components/AddTask.js
import React,{useState,useContext} from 'react'
import {TaskContext} from '../context/TaskContext'
import TaskList from './TaskList';
export default function AddTask()
{
const {addTask} = useContext(TaskContext);
const [title,setTitle] = useState('')
const handleSubmit = (e)=>
{
e.preventDefault()
addTask({title:title,id:Math.floor(Math.random() * 100000)})
setTitle('')
}
const handleChange = (e)=>{
setTitle(e.target.value)
}
return (
<>
<form className="border p-3 my-3 " onSubmit={handleSubmit}>
<h1 className="text-center display-4">Add New Task</h1>
<div className="form-group">
<input type="text" className="form-control" onChange={handleChange} value={title} placeholder="Type Title of Task" />
</div>
<button type="submit" className="btn btn-success btn-block">Submit</button>
</form>
<TaskList />
</>
)
}
<file_sep>/src/components/EditTask.js
import React,{useState,useContext,useEffect} from 'react'
import {TaskContext} from '../context/TaskContext'
import TaskList from './TaskList';
export default function EditTask()
{
const {editTask,item} = useContext(TaskContext);
const [title,setTitle] = useState('')
useEffect(()=>{
if(item !== null)
{
setTitle(item.title)
}
},[item])
const handleSubmit = (e)=>
{
e.preventDefault()
editTask({title:title,id:item.id})
setTitle('')
}
const handleChange = (e)=>{
setTitle(e.target.value)
}
return (
<>
<form className="border p-3 my-3 " onSubmit={handleSubmit}>
<h1 className="text-center display-4">Edit Task</h1>
<div className="form-group">
<input type="text" className="form-control" onChange={handleChange} value={title} placeholder="Type Title of Task" />
</div>
<button type="submit" className="btn btn-success btn-block">Submit</button>
</form>
</>
)
}
<file_sep>/src/components/TaskList.js
import React,{useContext} from 'react'
import {TaskContext} from '../context/TaskContext'
import Task from './Task'
import NotFound from './NotFound'
import EditTask from './EditTask'
export default function TaskList() {
const {tasks,item} = useContext(TaskContext);
return (
<>
{item ?<EditTask /> : ''}
<h1 className="text-center display-4 my-3">All Tasks</h1>
<ul className="list-unstyled p-3 m-3 rounded border">
{tasks.length ? tasks.map((item,index)=>{
return (<Task item={item} key={index} />)
}) : <NotFound />}
</ul>
</>
)
}
| 68ffe2db38d610363a62cddeb2eeac673e05a21d | [
"JavaScript"
] | 3 | JavaScript | mostafaMahfouz25/youtube-react-app-task-manager-list | e669b236f088938a2a306c1e86dc827e2c2deef0 | 507bdecc52cd5f60f4c962fb675121da022ad9fd |
refs/heads/master | <file_sep>## Guessing Game##
## Time for to check the number of files in the directory
cho=-1
cor=7
typeset -i num=0
# Guessing Game Begins
echo "How many files are in the working directory?"
(( answer = 7))
while (( cho !=answer )); do
num=num+1
read -p "Take a guess $num: " cho
if (( cho < cor )); then
echo "Too Low"
echo "Try again"
elif (( cho > cor )); then
echo "Too High"
echo "Try again"
fi
done
#End of Game
echo "You got it right!!"
| da2ab1de4722372e1e10f857804eec3c4fc88114 | [
"Shell"
] | 1 | Shell | angelabraham27/Unix-Workbench | 65c4f8aef9b0030d0bf9bcb9d507858934e9a8aa | d9b4e473ea7c6c4b1ec15bbf88bf76624e5d3d42 |
refs/heads/master | <repo_name>BarbaraPruz/js-advanced-scope-closures-lab-v-000<file_sep>/index.js
function produceDrivingRange(range) {
return function (start, end) {
let dist = Math.abs(parseInt(start)-parseInt(end));
if (dist <= range) {
return `within range by ${range-dist}`;
}
else {
return `${dist-range} blocks out of range`;
}
}
}
function produceTipCalculator(tipPercent) {
return function (total) {
return total*tipPercent;
}
}
function createDriver() {
let driverId=0;
return class {
constructor(name) {
this.name = name;
this.id = ++driverId;
}
}
}
| aeb3c942fb55cb074816e7a8c89a8321ba91e0b8 | [
"JavaScript"
] | 1 | JavaScript | BarbaraPruz/js-advanced-scope-closures-lab-v-000 | 8489ed7544f392977a9d2cfc01161bdd724e79b3 | a4d99e52b6782cf75ee9b15904e393c3ecb5a70d |
refs/heads/master | <file_sep>function execCopy(string) {
const tmp = document.createElement("div");
const pre = document.createElement('pre');
pre.style.webkitUserSelect = 'auto';
pre.style.userSelect = 'auto';
tmp.appendChild(pre).textContent = string;
const s = tmp.style;
s.position = 'fixed';
s.right = '200%';
document.body.appendChild(tmp);
document.getSelection().selectAllChildren(tmp);
const result = document.execCommand("copy");
document.body.removeChild(tmp);
return result;
}
const url = document.location.href;
if (url.match(/^https?:\/\/qiita\.com.*/)) {
/* Qiitaのページにマッチした */
/* 記事のタイトルを取得 */
const h1 = document.getElementsByClassName("it-Header_title")[0];
const title = h1.innerHTML;
const copyData = `[Qiita - ${title}](${url})`;
execCopy(copyData);
} else if (url.match(/^https?:\/\/github\.com.*/)) {
/* GitHubのページにマッチした */
/* リポジトリ名を取得 */
const h1 = document.getElementsByClassName("public")[0];
const title = h1.innerText;
const copyData = `[GitHub - ${title}](${url})`;
execCopy(copyData);
} else {
/* ページのタイトルを使う */
const title = document.title;
const copyData = `[${title}](${url})`;
execCopy(copyData);
}<file_sep># gen-scrapbox-url
ScrapboxのURLとしてコピーするChrome拡張。
作るだけ作ったけれど、Bookmarkletでよかった。
そして、すでに作ってる人がいたのでこれ以上開発しない。
https://scrapbox.io/shokai/Scrapbox%E7%94%A8%E3%81%AE%E5%A4%96%E9%83%A8%E3%83%AA%E3%83%B3%E3%82%AF%E8%A8%98%E6%B3%95%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8Bbookmarklet
## 使い方
* 何かしらのページを開いた状態で、開いているページを右クリック
* コンテキストメニューに「ページタイトルからScrapbox記法のリンクをコピー」という項目が存在するので、それをクリック
* クリップボードに以下のようなテキストがコピーされる
* ※ ページタイトルが Chrome拡張の作り方 というタイトルだった場合
* `[Chrome拡張の作り方 https://hogefuga.com/20190101]`
* URLは表示しているときのURL欄のURL
### Qiitaを開いている場合
Qiitaを開いている場合は以下のなリンクがコピーされる。
`[Qiita - ページタイトル https://qiita.com/xxxxxxx]`
### GitHubのリポジトリを開いている場合
`[GitHub - ユーザ名/リポジトリ名 https://github.com/xxxxxxx]`
そのままタイトルが欲しい場合はどうしたらいいだろう・・・
リポジトリのトップを表示しているときだけ特殊記法にするか
2種類メニューを用意してしまうか<file_sep>chrome.contextMenus.create({
"title": "ページタイトルからScrapbox記法のリンクをコピー",
"type": "normal",
"contexts": ["page"],
"onclick": function (info) {
chrome.tabs.executeScript({
file: 'src/main.js'
});
}
});
// chrome.contextMenus.create({
// "title": "リンクのテキストからScrapbox記法のリンクをコピー",
// "type": "normal",
// "contexts": ["link"],
// "onclick": function (info) {
// console.log(info); //デバッグ表示用
// console.log(info.linkUrl); //デバッグ表示用
// }
// }); | 7246669af0644030306220e405fd964e4daa226a | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jiro4989/gen-scrapbox-url | f19e041a7a212063d390fcfd655d2385bb072466 | 353b44581e4e42fdaa3e6b42bbe5df6cbd495f75 |
refs/heads/main | <file_sep>from os import name
import discord
import datetime as dt
import time
from discord import message
from discord.enums import Status
from discord.ext import commands
import asyncio
import db
import re
database = db.DataBase()
disc_client = discord.Client()
client = commands.Bot(command_prefix = '#')
client_id = 810231896524193833
client.remove_command("help")
token = input("Enter Token: ")
status = discord.Game("#commands for help")
def setupDB():
database.createTables()
database.saveToDB()
@client.event
async def on_ready():
msg = client.get_channel(client_id)
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
await client.change_presence(status=discord.Status.idle, activity=status)
setupDB()
@client.event
async def on_reaction_add(reaction,user):
# print(user)
# print(type(user))
channel = reaction.message.channel
if user.name == "J.A.R.V.I.S.":
return
print(user.name)
if reaction.emoji != '🥰':
return
ID = "<@!" + str(user.id) + ">"
if(database.isNotConfirmed(ID, reaction.message.embeds[0].fields[1].value)):
await channel.send('{} has confirmed attendance!'.format(user.name))#,reaction.emoji, reaction.message.content))
embed = discord.Embed(title="Meeting Confirmation", color=0x00FF00)
embed.add_field(name=reaction.message.embeds[0].fields[0].name, value=reaction.message.embeds[0].fields[0].value)
embed.add_field(name=reaction.message.embeds[0].fields[1].name, value=reaction.message.embeds[0].fields[1].value)
embed.add_field(name=reaction.message.embeds[0].fields[2].name, value=reaction.message.embeds[0].fields[2].value)
await user.send("",embed=embed)
print(user)
database.changeStatus(ID, reaction.message.embeds[0].fields[1].value, "yes")
@client.event
async def on_reaction_remove(reaction,user):
channel = reaction.message.channel
await channel.send('{} has removed {} to the message: {}'.format(user.name,reaction.emoji, reaction.message.content))
async def reminder(ctx, l):
set_time = dt.datetime.strptime(l[0],"%Y-%m-%d %H:%M")
initial_time = dt.datetime.now()
wait = (set_time - initial_time).total_seconds()
wait -= 600
await asyncio.sleep(wait)
embed = discord.Embed(title="NOTICE: You Have a Meeting Scheduled in 10 Minutes.")
# await ctx.message.channel.send(embed=embed)
result = re.sub('[^0-9]','',l[2])
user = await client.fetch_user(result)
await user.send("", embed=embed)
def split(names):
all = ''
for i in names:
all = all + i
return all
@client.command()
async def setup(ctx, *args):
args = list(args)
# print(args)
copy = args[:]
if len(args) <= 1:
embed = discord.Embed(title="Meeting Instructions", color=0xFF22FF)
embed.add_field(name="First Argument: Date Time", value="Please enter date-time value (year-month-day hour:minute")
embed.add_field(name="Second Argument: Location", value="Please enter location as second argument as one word or containted within " "")
embed.add_field(name="Additional Arguments: Names", value="You can enter as many names as you want as command line arguments after the first two.")
embed.add_field(name="When Ready", value="Create a meeting by using #setup time location names....")
await ctx.message.channel.send(embed=embed)
elif len(args) >= 3:
database.createMeeting(args[1], args[0])
for p in args[2:]:
database.createPerson(p)
database.createAttendance(p, args[1])
database.saveToDB()
embed = discord.Embed(title="Meeting Information", color=0xFF00FF)
embed.add_field(name="Date-Time", value=args[0], inline=True)
embed.add_field(name="Location", value=args[1], inline=True)
args.pop(0)
args.pop(0)
embed.add_field(name='Names',value= split(args) ,inline=True)
embed.set_footer(text="Please react " + '🥰' + "if you are able to attend!")
msg = await ctx.message.channel.send(embed = embed)
await msg.add_reaction('🥰')
await reminder(ctx, copy)
@client.command()
async def allSchedule(ctx):
embed = discord.Embed(title="Displaying current meetings", color=0xFF00FF)
meetingsList = database.displayAllMeetings().split("\n")
topic = ""
date = ""
for i in meetingsList:
tempList = i.split(" ")
topic = topic + tempList[0] + "\n"
date = date + tempList[1] + tempList[2] + "\n"
embed.add_field(name="Meeting Topic", value=topic, inline=True)
embed.add_field(name="Date-Time", value=date, inline=True)
await ctx.message.channel.send(embed=embed)
@client.command()
async def mySchedule(ctx):
embed = discord.Embed(title="Displaying Personal Meetings", color=0xFF00FF)
ID = "<@!" + str(ctx.message.author.id) + ">"
# print(ID)
meetingsList = database.personalMeetings(ID).split("\n")
topic = ""
date = ""
for i in meetingsList:
tempList = i.split(" ")
# print(tempList)
topic = topic + tempList[0] + "\n"
date = date + tempList[1] + tempList[2] + "\n"
embed.add_field(name="Meeting Topic", value=topic, inline=True)
embed.add_field(name="Date-Time", value=date, inline=True)
await ctx.message.channel.send(embed=embed)
# My Help Button
@client.command("commands")
async def commands(context):
msg = client.get_channel(client_id)
helplist = discord.Embed(title="Commands", description="Prefix for all commands is #", color=0xFF00FF)
helplist.add_field(name="commands", value="Shows commands.", inline=True)
helplist.add_field(name="setup", value = "Commands for setting up group meetings", inline=False)
helplist.add_field(name="allSchedule", value="Command to view all upcoming meetings in order (soonest to furthest)", inline=False)
helplist.add_field(name="mySchedule", value="Command to view personal upcoming confirmed meetings (soonest to furthest).", inline=False)
await context.message.channel.send(embed = helplist)
#Run the client on the server
client.run(token)
<file_sep># SecretaryBot
CONTRIBUTORS: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>.
VERSION: 1.0 Alpha
DESCRIPTION:
This is J.A.R.V.I.S, a discord bot made to organize meetings and set up polling services within servers for student during online schooling COVID conditions. This bot can easily be implemented into any discord server and its uses are not limited to a school environment. The main features include creating a schedule, communicating availability with other students, online data-basing using mySQL and personal reminders for each meeting. It is extremely intuitive and simple to use with various help and command functions in order to get started. Many students have trouble managing their non-official meetings with peers and J.A.R.V.I.S makes it easy for students to communicate in the online enviroment.
HOW TO RUN:
1. Download the GitHub repository: https://github.com/ryanitt/JustARatherVeryIntelligentScheduler
2. Navigate to the SecretaryBot directory.
3. Start the bot using bot.py.
4. Provide the unique token in the terminal (available from developers).
PROJECT DETAILS:
Language: Python 3.9
Engine: Discord Python Library - Discord.py
Software: Visual Studio Code. Discord.
Documentation: https://discordpy.readthedocs.io/en/latest/index.html#
PROJECT LOCATION:
University of Calgary
2500 University Drive NW
Calgary AB
T2N 1N4
<file_sep>import mysql.connector
import datetime
class DataBase:
def __init__(self):
self.mydb = mysql.connector.connect(
host="localhost",
user="root",
password="<PASSWORD>",
database="jarvisfc"
)
self.mycursor = self.mydb.cursor(buffered=True)
def saveToDB(self):
self.mycursor.execute("COMMIT;")
def createMeetingsTable(self):
created = False
self.mycursor.execute("SHOW TABLES")
for x in self.mycursor:
if(x[0] == 'meetings'):
created = True
if not created:
self.mycursor.execute("CREATE TABLE meetings (\
id INTEGER NOT NULL AUTO_INCREMENT,\
name VARCHAR(255) UNIQUE,\
time DATETIME,\
PRIMARY KEY (id)\
);")
print('created meetings')
def createPersonsTable(self):
created = False
self.mycursor.execute("SHOW TABLES")
for x in self.mycursor:
if(x[0] == 'persons'):
created = True
if not created:
self.mycursor.execute("CREATE TABLE persons (\
clientID VARCHAR(255),\
PRIMARY KEY (clientID)\
);")
print('created persons')
def createAttendanceTable(self):
created = False
self.mycursor.execute("SHOW TABLES")
for x in self.mycursor:
if(x[0] == 'attendance'):
created = True
if not created:
self.mycursor.execute("CREATE TABLE attendance (\
pNo VARCHAR(255),\
mNo INTEGER,\
status VARCHAR(255),\
PRIMARY KEY (pNo, mNo),\
FOREIGN KEY(mNo) REFERENCES meetings(id)\
);")
print('created attendance')
def createTables(self):
self.createMeetingsTable()
self.createPersonsTable()
self.createAttendanceTable()
def createMeeting(self, name, time):
sql = "SELECT * FROM meetings WHERE name = %s"
val = (name,)
self.mycursor.execute(sql, val)
if(self.mycursor.rowcount > 0):
print("meeting already exists: ", name)
return
sql = "INSERT INTO meetings (name, time) VALUES (%s, %s);"
val = (name, time)
self.mycursor.execute(sql, val)
def createPerson(self, disc):
if disc[0:3] != "<@!":
print("not a valid client ID: ", disc)
return
sql = "SELECT * FROM persons WHERE clientID = %s"
val = (disc,)
self.mycursor.execute(sql, val)
if(self.mycursor.rowcount > 0):
print("person already exists: ", disc)
return
sql = "INSERT INTO persons (clientID) VALUES (%s)"
val = (disc,)
print(sql, val)
self.mycursor.execute(sql, val)
def createAttendance(self, disc, meetingName):
sql = "SELECT * FROM meetings WHERE name = %s"
tpc = (meetingName,)
self.mycursor.execute(sql, tpc)
meeting = self.mycursor.fetchone()
# print(meeting)
sql = "INSERT INTO attendance (pNo, mNo, status) VALUES (%s, %s, %s)"
val = (disc, meeting[0], "maybe")
print(sql, val)
self.mycursor.execute(sql, val)
def changeStatus(self, disc, meetingName, newStatus):
sql = "SELECT * FROM meetings WHERE name = %s"
tpc = (meetingName,)
self.mycursor.execute(sql, tpc)
meeting = self.mycursor.fetchone()
print(meeting)
sql = "UPDATE attendance SET status = %s WHERE pNo = %s AND mNo = %s"
val = (newStatus, disc, meeting[0])
print(sql, val)
self.mycursor.execute(sql, val)
self.mydb.commit()
print(self.mycursor.rowcount, " record(s) changed")
def isNotConfirmed(self, disc, meetingName):
sql = "SELECT * FROM meetings WHERE name = %s"
tpc = (meetingName,)
self.mycursor.execute(sql, tpc)
meeting = self.mycursor.fetchone()
print(meeting)
sql = "SELECT * FROM attendance WHERE pNo = %s AND mNo = %s"
val = (disc, meeting[0])
print(sql, val)
self.mycursor.execute(sql, val)
if(self.mycursor.rowcount > 0):
confirm = self.mycursor.fetchone()
if(confirm[-1] == "maybe"):
return True
return False
def showInfo(self):
self.mycursor.execute("SELECT * FROM meetings")
for x in self.mycursor:
print(x)
self.mycursor.execute("SELECT * FROM persons")
for x in self.mycursor:
print(x)
def displayAllMeetings(self):
self.mycursor.execute("SELECT * FROM meetings ORDER BY time")
returnStr = ""
for x in self.mycursor:
x = list(x)
returnStr = returnStr + x[1] + " " + x[2].strftime("%m/%d/%Y, %H:%M") + "\n"
return returnStr.rstrip()
def personalMeetings(self, client_id):
sql = "SELECT name, time FROM meetings INNER JOIN attendance ON mNo = id WHERE status = 'yes' AND pNo = %s ORDER BY time"
val = (client_id, )
self.mycursor.execute(sql, val)
returnStr = ""
for x in self.mycursor:
x = list(x)
returnStr += x[0] + " " + x[1].strftime("%m/%d/%Y, %H:%M") + "\n"
return returnStr.rstrip()
if __name__ == "__main__":
db = DataBase()
| 09ef3caf4cb8a84e7e4be6372d775151221fe54c | [
"Markdown",
"Python"
] | 3 | Python | ryanitt/JustARatherVeryIntelligentScheduler | 8e643ed7f47742516eb2bdb297daa94e3bb9e21b | f1e60843289015bedffc9eb805fd477e2d96d7a4 |
refs/heads/master | <file_sep>require 'cases/helper'
require 'support/schema_dumping_helper'
class PrimaryKeyBigIntTest < ActiveRecord::TestCase
include SchemaDumpingHelper
class Widget < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table(:widgets, id: :bigint, force: true)
end
teardown do
@connection.execute("DROP TABLE IF EXISTS widgets")
end
test "primary key column type with bigint" do
column = Widget.columns_hash[Widget.primary_key]
assert_equal :integer, column.type
assert_equal 8, column.limit
end
test "primary key with bigint are automatically numbered" do
widget = Widget.create!
assert_not_nil widget.id
end
test "schema dump primary key with bigint" do
schema = dump_table_schema "widgets"
assert_match %r{create_table "widgets", id: :bigint}, schema
end
end
<file_sep>require 'activerecord/mysql/awesome'
<file_sep>require 'cases/helper'
require 'support/connection_helper'
class StrictModeTest < ActiveRecord::TestCase
include ConnectionHelper
def setup
super
@connection = ActiveRecord::Base.connection
end
def test_mysql_strict_mode_enabled
result = @connection.exec_query "SELECT @@SESSION.sql_mode"
assert_equal [["STRICT_ALL_TABLES"]], result.rows
end
def test_mysql_strict_mode_specified_default
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge({strict: :default}))
global_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.sql_mode"
session_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode"
assert_equal global_sql_mode.rows, session_sql_mode.rows
end
end
def test_mysql_strict_mode_disabled
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge({strict: false}))
result = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode"
assert_equal [[""]], result.rows
end
end
end
<file_sep>require 'active_record/schema_dumper'
module ActiveRecord
module Mysql
module Awesome
module SchemaDumper
private
def table(table, stream)
@types = @types.merge(@connection.options_for_column_spec(table))
pk = @connection.primary_key(table)
pkcol = @connection.columns(table).detect { |c| c.name == pk }
pkcolspec = @connection.column_spec_for_primary_key(pkcol, @types) if pkcol
table_options = @connection.table_options(table)
buf = StringIO.new
super(table, buf)
buf = buf.string
buf.sub!(/(?=, force: (?:true|:cascade))/, pkcolspec.map {|key, value| ", #{key}: #{value}"}.join) if pkcolspec
buf.sub!(/(?= do \|t\|)/, ", options: #{table_options.inspect}") if table_options
stream.print buf
stream
ensure
@types = @connection.native_database_types
end
end
end
end
class SchemaDumper #:nodoc:
prepend Mysql::Awesome::SchemaDumper
end
end
<file_sep>require 'active_record/connection_adapters/mysql2_adapter'
module ActiveRecord
module ConnectionAdapters
class Mysql2Adapter < AbstractMysqlAdapter
class Version
include Comparable
def initialize(version_string)
@version = version_string.split('.').map(&:to_i)
end
def <=>(version_string)
@version <=> version_string.split('.').map(&:to_i)
end
def [](index)
@version[index]
end
end
def version
@version ||= Version.new(@connection.server_info[:version].match(/^\d+\.\d+\.\d+/)[0])
end
end
end
end
<file_sep># ActiveRecord::Mysql::Awesome
[](https://travis-ci.org/kamipo/activerecord-mysql-awesome)
Awesome patches backported for ActiveRecord MySQL adapters.
Contains numerous patches backported from Rails 5 for use in Rails 4.x applications.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'activerecord-mysql-awesome'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install activerecord-mysql-awesome
## Usage
Just install it.
Patches from the following Rails pull requests are included:
* [Add SchemaDumper support table_options for MySQL. #17569](https://github.com/rails/rails/pull/17569)
* [Add charset and collation options support for MySQL string and text columns. #17574](https://github.com/rails/rails/pull/17574)
* [Add bigint pk support for MySQL #17631](https://github.com/rails/rails/pull/17631)
* [If do not specify strict_mode explicitly, do not set sql_mode. #17654](https://github.com/rails/rails/pull/17654)
* [Add unsigned option support for MySQL numeric data types #17696](https://github.com/rails/rails/pull/17696)
* [Support for any type primary key #17851](https://github.com/rails/rails/pull/17851)
## Contributing
1. Fork it ( https://github.com/kamipo/activerecord-mysql-awesome/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
<file_sep>source 'https://rubygems.org'
gem "activerecord", "~> #{ENV['AR_VERSION']}" if ENV['AR_VERSION']
gem "mysql2", "~> 0.3.18"
# Specify your gem's dependencies in activerecord-mysql-awesome.gemspec
gemspec
<file_sep>require 'active_record/connection_adapters/abstract/schema_dumper'
module ActiveRecord
module ConnectionAdapters # :nodoc:
module ColumnDumper
def options_for_column_spec(table_name)
{ table_name: table_name }
end
def column_spec_for_primary_key(column, options)
return if column.type == :integer
spec = { id: column.type.inspect }
spec.merge!(prepare_column_options(column, options).delete_if { |key, _| [:name, :type].include?(key) })
end
def table_options(table_name)
nil
end
end
end
end
<file_sep>require 'active_record/connection_adapters/abstract_mysql_adapter'
module ActiveRecord
module Mysql
module Awesome
class ChangeColumnDefinition < Struct.new(:column, :name)
end
module ColumnMethods
def primary_key(name, type = :primary_key, **options)
options[:auto_increment] = true if type == :bigint
super
end
def unsigned_integer(*args, **options)
args.each { |name| column(name, :unsigned_integer, options) }
end
end
class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
attr_accessor :auto_increment, :unsigned, :charset, :collation
end
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
include ColumnMethods
def initialize(types, name, temporary, options, as = nil)
super(types, name, temporary, options)
@as = as
end
def new_column_definition(name, type, options)
column = super
case column.type
when :primary_key
column.type = :integer
column.auto_increment = true
when :unsigned_integer
column.type = :integer
column.unsigned = true
end
column.auto_increment ||= options[:auto_increment]
column.unsigned ||= options[:unsigned]
column.charset = options[:charset]
column.collation = options[:collation]
column
end
private
def create_column_definition(name, type)
ColumnDefinition.new(name, type)
end
end
class Table < ActiveRecord::ConnectionAdapters::Table
include ColumnMethods
end
module SchemaCreation
def visit_AddColumn(o)
add_column_position!("ADD #{accept(o)}", column_options(o))
end
private
def visit_ColumnDefinition(o)
o.sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale, o.unsigned)
column_sql = "#{quote_column_name(o.name)} #{o.sql_type}"
add_column_options!(column_sql, column_options(o)) unless o.type == :primary_key
column_sql
end
def visit_ChangeColumnDefinition(o)
change_column_sql = "CHANGE #{quote_column_name(o.name)} #{accept(o.column)}"
add_column_position!(change_column_sql, column_options(o.column))
end
def column_options(o)
column_options = super
column_options[:first] = o.first
column_options[:after] = o.after
column_options[:auto_increment] = o.auto_increment
column_options[:primary_key] = o.primary_key
column_options[:charset] = o.charset
column_options[:collation] = o.collation
column_options
end
def add_column_options!(sql, options)
if options[:charset]
sql << " CHARACTER SET #{options[:charset]}"
end
if options[:collation]
sql << " COLLATE #{options[:collation]}"
end
if options[:primary_key] == true
sql << " PRIMARY KEY"
end
super
end
def add_column_position!(sql, options)
if options[:first]
sql << " FIRST"
elsif options[:after]
sql << " AFTER #{quote_column_name(options[:after])}"
end
sql
end
def type_to_sql(type, limit, precision, scale, unsigned)
@conn.type_to_sql(type.to_sym, limit, precision, scale, unsigned)
end
end
def update_table_definition(table_name, base)
Table.new(table_name, base)
end
module Column
def unsigned?
sql_type =~ /unsigned/i
end
def bigint?
sql_type =~ /bigint/i
end
def auto_increment?
extra == 'auto_increment'
end
end
def quote(value, column = nil)
return super if value.nil? || !value.acts_like?(:time)
return super unless column && /time/ === column.sql_type
if value.acts_like?(:time)
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
if value.respond_to?(zone_conversion_method)
value = value.send(zone_conversion_method)
end
end
if (precision = column.precision) && value.respond_to?(:usec)
number_of_insignificant_digits = 6 - precision
round_power = 10 ** number_of_insignificant_digits
value = value.change(usec: value.usec / round_power * round_power)
end
result = value.to_s(:db)
if value.respond_to?(:usec) && value.usec > 0
"'#{result}.#{sprintf("%06d", value.usec)}'"
else
"'#{result}'"
end
end
if ActiveRecord::VERSION::STRING < "4.2.0"
module Column
def extract_limit(sql_type)
case sql_type
when /time/i; nil
else
super
end
end
def extract_precision(sql_type)
case sql_type
when /time/i
if sql_type =~ /\((\d+)(,\d+)?\)/
$1.to_i
else
0
end
else
super
end
end
end
else
protected
def initialize_type_map(m) # :nodoc:
super
register_class_with_precision m, %r(time)i, Type::Time
register_class_with_precision m, %r(datetime)i, Type::DateTime
end
def register_class_with_precision(mapping, key, klass) # :nodoc:
mapping.register_type(key) do |*args|
precision = extract_precision(args.last)
klass.new(precision: precision)
end
end
def extract_precision(sql_type)
if /time/ === sql_type
super || 0
else
super
end
end
end
public
def supports_datetime_with_precision?
version >= '5.6.4'
end
def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = false)
sql = case type
when :integer
case limit
when nil, 4, 11; 'int' # compatibility with MySQL default
else
super(type, limit, precision, scale)
end
when :datetime, :time
case precision
when nil; super(type, limit, precision, scale)
when 0..6; "#{type}(#{precision})"
else raise(ActiveRecordError, "No #{type} type has precision of #{precision}. The allowed range of precision is from 0 to 6")
end
else
super(type, limit, precision, scale)
end
sql << ' unsigned' if unsigned && type != :primary_key
sql
end
def options_for_column_spec(table_name)
if collation = select_one("SHOW TABLE STATUS LIKE '#{table_name}'")["Collation"]
super.merge(collation: collation)
else
super
end
end
def column_spec_for_primary_key(column, options)
spec = {}
if column.auto_increment?
spec[:id] = ':bigint' if column.bigint?
spec[:unsigned] = 'true' if column.unsigned?
return if spec.empty?
else
spec[:id] = column.type.inspect
spec.merge!(prepare_column_options(column, options).delete_if { |key, _| [:name, :type, :null].include?(key) })
end
spec
end
def prepare_column_options(column, options) # :nodoc:
spec = super
spec.delete(:precision) if /time/ === column.sql_type && column.precision == 0
spec.delete(:limit) if :boolean === column.type
spec[:unsigned] = 'true' if column.unsigned?
if column.collation && column.collation != options[:collation]
spec[:collation] = column.collation.inspect
end
spec
end
def migration_keys
super | [:unsigned, :collation]
end
def table_options(table_name)
create_table_info = select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"]
return unless create_table_info
# strip create_definitions and partition_options
raw_table_options = create_table_info.sub(/\A.*\n\) /m, '').sub(/\n\/\*!.*\*\/\n\z/m, '').strip
# strip AUTO_INCREMENT
raw_table_options.sub(/(ENGINE=\w+)(?: AUTO_INCREMENT=\d+)/, '\1')
end
def drop_table(table_name, options = {})
execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
end
protected
def add_column_sql(table_name, column_name, type, options = {})
td = create_table_definition(table_name)
cd = td.new_column_definition(column_name, type, options)
schema_creation.visit_AddColumn cd
end
def change_column_sql(table_name, column_name, type, options = {})
column = column_for(table_name, column_name)
unless options_include_default?(options)
options[:default] = column.default
end
unless options.has_key?(:null)
options[:null] = column.null
end
td = create_table_definition(table_name)
cd = td.new_column_definition(column.name, type, options)
schema_creation.accept(ChangeColumnDefinition.new(cd, column.name))
end
def rename_column_sql(table_name, column_name, new_column_name)
column = column_for(table_name, column_name)
options = {
default: column.default,
null: column.null,
auto_increment: column.auto_increment?
}
current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", 'SCHEMA')["Type"]
td = create_table_definition(table_name)
cd = td.new_column_definition(new_column_name, current_type, options)
schema_creation.accept(ChangeColumnDefinition.new(cd, column.name))
end
private
def configure_connection
_config = @config
if [':default', :default].include?(@config[:strict])
@config = @config.deep_merge(variables: { sql_mode: :default })
end
super
ensure
@config = _config
end
def create_table_definition(name, temporary = false, options = nil, as = nil) # :nodoc:
TableDefinition.new(native_database_types, name, temporary, options, as)
end
end
end
module ConnectionAdapters
class AbstractMysqlAdapter < AbstractAdapter
prepend Mysql::Awesome
class Column < ConnectionAdapters::Column # :nodoc:
prepend Mysql::Awesome::Column
end
class SchemaCreation < AbstractAdapter::SchemaCreation
prepend Mysql::Awesome::SchemaCreation
end
end
end
end
<file_sep>if ActiveRecord::VERSION::MAJOR >= 4
require 'activerecord-mysql-awesome/active_record/schema_dumper'
require 'activerecord-mysql-awesome/active_record/connection_adapters/abstract/schema_dumper'
require 'activerecord-mysql-awesome/active_record/connection_adapters/abstract_mysql_adapter'
require 'activerecord-mysql-awesome/active_record/connection_adapters/mysql2_adapter'
else
raise "activerecord-mysql-awesome supports activerecord >= 4.x"
end
<file_sep>require 'cases/helper'
require 'support/schema_dumping_helper'
class CharsetCollationTest < ActiveRecord::TestCase
include SchemaDumpingHelper
class CharsetCollation < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table("charset_collations", force: true) do |t|
t.string "string_ascii_bin", charset: 'ascii', collation: 'ascii_bin'
t.text "text_ucs2_unicode_ci", charset: 'ucs2', collation: 'ucs2_unicode_ci'
end
end
teardown do
@connection.drop_table "charset_collations"
end
def test_column
string_column = CharsetCollation.columns_hash['string_ascii_bin']
assert_equal 'ascii_bin', string_column.collation
text_column = CharsetCollation.columns_hash['text_ucs2_unicode_ci']
assert_equal 'ucs2_unicode_ci', text_column.collation
end
def test_add_column
@connection.add_column 'charset_collations', 'title', :string, charset: 'utf8', collation: 'utf8_bin'
column = CharsetCollation.columns_hash['title']
assert_equal 'utf8_bin', column.collation
end
def test_change_column
@connection.add_column 'charset_collations', 'description', :string, charset: 'utf8', collation: 'utf8_unicode_ci'
@connection.change_column 'charset_collations', 'description', :text, charset: 'utf8', collation: 'utf8_general_ci'
CharsetCollation.reset_column_information
column = CharsetCollation.columns_hash['description']
assert_equal :text, column.type
assert_equal 'utf8_general_ci', column.collation
end
def test_schema_dump_column_collation
schema = dump_table_schema "charset_collations"
assert_match %r{t.string\s+"string_ascii_bin",(?:\s+limit: 255,)?\s+collation: "ascii_bin"$}, schema
assert_match %r{t.text\s+"text_ucs2_unicode_ci",(?:\s+limit: 65535,)?\s+collation: "ucs2_unicode_ci"$}, schema
end
end
<file_sep>require 'cases/helper'
require 'support/schema_dumping_helper'
class TableOptionsTest < ActiveRecord::TestCase
include SchemaDumpingHelper
teardown do
ActiveRecord::Base.connection.drop_table "table_options"
end
def test_dump_table_options
ActiveRecord::Base.connection.create_table(:table_options, force: true, options: "COMMENT 'london bridge is falling down'")
output = dump_table_schema("table_options")
assert_match %r{COMMENT='london bridge is falling down'}, output
end
end
<file_sep>require 'cases/helper'
require 'support/schema_dumping_helper'
class PrimaryKeyAnyTypeTest < ActiveRecord::TestCase
include SchemaDumpingHelper
class Barcode < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table(:barcodes, primary_key: "code", id: :string, limit: 42, force: true)
end
teardown do
@connection.drop_table 'barcodes', if_exists: true
end
test "primary key with any type and options" do
assert_equal "code", Barcode.primary_key
column = Barcode.columns_hash[Barcode.primary_key]
assert_equal :string, column.type
assert_equal 42, column.limit
end
test "schema dump primary key includes type and options" do
schema = dump_table_schema "barcodes"
assert_match %r{create_table "barcodes", primary_key: "code", id: :string, limit: 42}, schema
end
end
class PrimaryKeyBigSerialTest < ActiveRecord::TestCase
include SchemaDumpingHelper
class Widget < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table(:widgets, id: :bigint, unsigned: true, force: true)
end
teardown do
@connection.drop_table 'widgets', if_exists: true
end
test "primary key column type with bigint" do
column = @connection.columns(:widgets).find { |c| c.name == 'id' }
assert column.auto_increment?
assert_equal :integer, column.type
assert_equal 8, column.limit
assert column.unsigned?
end
test "primary key with bigserial are automatically numbered" do
widget = Widget.create!
assert_not_nil widget.id
end
test "schema dump primary key with bigint" do
schema = dump_table_schema "widgets"
assert_match %r{create_table "widgets", id: :bigint, unsigned: true}, schema
end
end
| 37ef0fe3e753f15689b10e3e7290e7170ccc70f7 | [
"Markdown",
"Ruby"
] | 13 | Ruby | ktsujichan/activerecord-mysql-awesome | 9efbb658e089245a11ab60dba118a47757d83ef0 | fa11bcae15b0b191358ee37003b949d63a843330 |
refs/heads/master | <file_sep>#include "function.h"
/*!
* Verifica se um ponto está dentro de um retângulo.
*/
location_t pt_in_rect( const Ponto &IE, const Ponto &SD, const Ponto &P )
{
// Conditionals created by analyzing a drawing of a rectangle.
if(P.x > IE.x && P.x < SD.x && P.y > IE.y && P.y < SD.y)
{
// Case where the point does not touch the edge and is inside the rectangle
return location_t::INSIDE;
} else if(P.x >= IE.x && P.x <= SD.x && P.y == IE.y || P.x == SD.x && P.y >= IE.y && P.y <= SD.y ||
P.x >= IE.x && P.x <= SD.x && P.y == SD.y || P.x == IE.x && P.y >= IE.y && P.y <= SD.y)
{ // Case where the stitch is touching the edge
// Bottom - Right - Top - Left
return location_t::BORDER;
} else {
// Case where the point is outside the rectangle
return location_t::OUTSIDE;
}
// TODO: Substitua o retorno conforme desejar. Isso é apenas um STUB, usado apenas para compilar.
return location_t::OUTSIDE;
}
<file_sep>/*!
* Remove negative and zero values from an array, preserving the
* relative order of the original values that will remain in the
* resulting array.
* We do not alter the origimal memory associated withe the input
* array. Rather, we just rearrange the values inside the array
* and return a pointer to the new 'logical' end of the array,
* after the processes of eliminating the required elements is
* finished.
*
* @param first Pointer to the beginning of the range we want to filter.
* @param last Pointer just past the last valid value of the range we want to filter.
* @return a pointer to the new 'logical' end of the array.
*/
int * filter( int * first, int * last )
{
int auxiliary; // Auxiliary variable that will receive individual values from the array.
// Loop that will traverse the entire array
while (first != last) {
//If we find a value less than or equal to zero, we shift all other values to the right one place
// to the left, while the value that is less than or equal to zero is shifted to the last position.
// And we only walk the array if the value that stays in the position is not less than or equal to 0.
if(* first <= 0) {
for (int * i = first; i != last; i += 1) {
if (i == (last - 1)) {
break;
}
auxiliary = * i;
* i = * (i + 1);
* (i + 1) = auxiliary;
}
last -= 1;
} else {
first += 1;
}
}
return last;
}
<file_sep>#include "function.h"
#include <iostream>
/*!
* Reverse de order of elements inside the array.
* @param arr Reference to the array with the values.
*/
template <size_t SIZE>
void reverse( std::array< std::string, SIZE > & arr )
{
std::string auxiliary; // Auxiliary variable that will temporarily contain a string
int counter = 1; // Variable that will help count the array backwards
// This loop will iterate through the array from start to end and end to start
for(int i = 0; i < arr.size(); i++)
{
// When we get halfway through the array, we have the entire array sorted, so we can exit the loop.
if(i == (int) arr.size() / 2) {
break;
}
// arr[arr.size() - counter] takes elements from end to beginning.
auxiliary = arr[i];
arr[i] = arr[arr.size() - counter];
arr[arr.size() - counter] = auxiliary;
counter += 1;
}
}
<file_sep>#include "function.h"
#include <utility>
/*!
* Finds and returns a pair with the first instance of the smallest element
* and the last instance of the largest element in an array.
*
* @param V This is the array-to-pointer decay representing an array.
* @param n The array's size.
*
* @return A pair of indexes to the first smallest and last largest values.
*/
std::pair<int,int> min_max( int V[], std::size_t n )
{
pair<int, int> VALUES; // Compound variable that will contain the values of the positions
std::size_t smaller; // Variable that will contain the smallest value
std::size_t larger; // Variable that will contain the largest value
// If empty
if (n == 0)
{
VALUES.first = -1;
VALUES.second = -1;
return VALUES;
}
// This loop cycles through all elements of the array
for(int i = 0; i < n; i++) {
if (i == 0)
{
larger = i;
smaller = i;
} else {
if (V[i] > V[larger] || V[i] == V[larger])
{
larger = i;
}
if (V[i] < V[smaller])
{
smaller = i;
}
}
}
VALUES.first = smaller;
VALUES.second = larger;
return VALUES;
}
<file_sep>/*!
* @brief Implementação do Ponto em Retângulo V2.
* @author selan
* @data June, 6th 2021
*/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <algorithm>
using std::min;
using std::max;
#include "function.h"
//=== Funções
// Coloque aqui qualquer função auxiliar que desejar.
int main(void)
{
int auxiliary; // Auxiliary variable
int res; // Analysis result
Ponto IE, SD, P;
// The loop continues as long as the points are entered
while (cin >> std::ws >> IE.x >> IE.y >> SD.x >> SD.y >> P.x >> P.y) {
// Check if the rectangle is valid
if (IE.x == SD.x && IE.y == SD.y) {
cout << "invalid" << std::endl;
continue;
}
// Analyze which is the low point
if(IE.x > SD.x && IE.y > SD.y) {
auxiliary = IE.x;
IE.x = SD.x;
SD.x = auxiliary;
auxiliary = IE.y;
IE.y = SD.y;
SD.y = auxiliary;
}
res = pt_in_rect( IE, SD, P );
if (res == 0) {
cout << "inside" << "\n";
} else if(res == 1) {
cout << "border" << "\n";
} else {
cout << "outside" << "\n";
}
}
return 0;
}
<file_sep>#include <iostream>
using std::cin;
using std::cout;
#include <algorithm>
using std::min;
const int SIZE = 5; // input size.
int main(void)
{
int value; // Variable that stores each value entered
int negatives = 0; // Variable that stores the amount of negative values entered
// Loop to read user values
for(int i = 0; i < SIZE; i++)
{
cin >> value;
if (value < 0)
{
negatives += 1;
}
}
cout << negatives << "\n";
return 0;
}
<file_sep>/*!
* @brief This code implements the Intervalos programming problem
* @author selan
* @data June, 6th 2021
*/
#include <iostream>
#include <map>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setprecision;
// Se desejar, crie funções aqui, antes do main().
int main(void)
{
std::map<std::string, double>values; // Creating the container that represents the scatter table, named values.
values["first"] = 0; // First numerical range: closed at 0 and open at 25
values["second"] = 0; // Second numerical range: closed at 25 and open at 50
values["third"] = 0; // Third numerical range: closed at 50 and open at 75
values["fourth"] = 0; // Fourth numerical range: closed at 75 and open at 100
values["fifth"] = 0; // Values that are outside the ranges, that is, less than zero or greater than or equal to 100
int x; // Variable that will store the values read by standard input
int counter = 0; // Variable that will store the total amount of values
while(cin >> std::ws >> x) // Looping continues while values are entered
{
if(x < 0 || x >= 100)
{
values["fifth"] += 1;
} else if (x >= 0 && x < 25)
{
values["first"] += 1;
} else if(x >= 25 && x < 50)
{
values["second"] += 1;
} else if (x >= 50 && x < 75)
{
values["third"] += 1;
} else if (x >= 75 && x < 100) {
values["fourth"] += 1;
}
}
counter += values["first"] + values["second"] + values["third"] + values["fourth"] + values["fifth"];
// Below is the division of the amount of each interval by the total,
// to find out the percentage that there is of each interval.
values["first"] = values["first"] / counter;
values["second"] = values["second"] / counter;
values["third"] = values["third"] / counter;
values["fourth"] = values["fourth"] / counter;
values["fifth"] = values["fifth"] / counter;
// We multiply by 100 to get the percentage value. We use setprecision to get a 4-digit numeric precision
cout << std::setprecision(4) << values["first"] * 100 << "\n";
cout << std::setprecision(4) << values["second"] * 100 << "\n";
cout << std::setprecision(4) << values["third"] * 100 << "\n";
cout << std::setprecision(4) << values["fourth"] * 100 << "\n";
cout << std::setprecision(4) << values["fifth"] * 100 << "\n";
return 0;
}
<file_sep>/*!
* @brief This code implements the "Soma Vizinhos" programming problem
* @author selan
* @data June, 6th 2021
*/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main( void )
{
int n, m; // Variables indicated in the question
int value; // Variable that assumes consecutive or antecedent numbers
int sum; // Variable that will store the value of the sum of the numbers
// This loop continues to run as long as two values are entered on standard input.
while(cin >> m >> n) {
sum = 0;
if(n > 0)
{
value = m;
// This loop runs through the amount of elements needed for the sum.
for (int i = 0; i < n; i++)
{
sum += value;
value += 1;
}
cout << sum << "\n";
}
else if (n < 0)
{
value = m;
// This loop runs through the amount of elements needed for the sum.
// And we change the value of the control variable because it is, in this case, a negative number.
for (int i = 0; i < (n * -1); i++)
{
sum += value;
value -= 1;
}
cout << sum <<"\n";
}
else { // Here is the case where n is equal to 0, only remaining case
cout << m << "\n";
}
}
return 0;
}
<file_sep>#include "function.h"
#include <vector>
std::vector<unsigned int> fib_below_n( unsigned int n )
{
std::vector<unsigned int> numbers; // Variable that will contain the fibonacci sequence values
int firstValue = 1; // First element of the sequence
int secondValue = 1; // Second element of the sequence
int sum; // Sum of the first and second elements
while (firstValue < n) // As long as the first value is less than the flag, the loop continues
{
numbers.push_back(firstValue); // Add the first element to the end vector
sum = firstValue + secondValue; // Add the two elements
firstValue = secondValue; // Updates the first element, receiving the value of its successor in the sequence
secondValue = sum; // Updates the second element, getting the sum of its current value plus the value of the first element
}
return numbers;
}
<file_sep># Identificação Pessoal
Preencha os dados abaixo para identificar a autoria do trabalho.
- Nome: *<NAME>*
- Email: *<EMAIL>*
- Turma: *<insira sua turma aqui>*
# Questões Finalizadas
- [ X ] Negativos 5
- [ X ] Soma Vizinhos
- [ X ] Intervalos
- [ X ] Fibonacci
- [ X ] Minmax
- [ X ] Inverter
- [ X ] Filtragem
- [ X ] Ponto em Retângulo 1
- [ X ] Ponto em Retângulo 2
- [ ] Interseção de Retângulos
--------
© DIMAp/UFRN 2021.
| 278a53be488b56471551a175e98f58bbe7f4621a | [
"Markdown",
"C++"
] | 10 | C++ | ThiagoOliveiraCordeiro/cpp-trabalho-01-lista-de-programacao | d2a0cc94252202fe4ee9191506c4bb6cfca48107 | be77fde06098c09cbd231ebac5e283d3047ca841 |
refs/heads/master | <repo_name>slazarska/calculator<file_sep>/src/main/java/service/impl/ConsoleWriter.java
package service.impl;
import service.Writer;
public class ConsoleWriter implements Writer {
@Override
public Object handleString(String output) {
System.out.println(output);
return null;
}
}
<file_sep>/src/main/java/service/Text.java
package service;
public enum Text {
ENTER_FIRST_ARG("Please, provide first argument, natural number only"),
ENTER_SECOND_ARG("Please, provide second argument, natural number only"),
ENTER_OPERATOR("Please, enter operator (+, *, -, /, %, ^):"),
RESULT_OUTPUT("Result:");
private final String text;
Text(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
<file_sep>/src/test/java/tests/OperationHandlerTests.java
package tests;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import service.OperationHandler;
import service.impl.*;
public class OperationHandlerTests {
private OperationHandler handler;
@Test
void sumTest() {
handler = new SumOperationHandler();
Assertions.assertEquals(8, handler.invoke(3, 5));
}
@Test
void subTest() {
handler = new SubOperationHandler();
Assertions.assertEquals(4, handler.invoke(10, 6));
}
@Test
void multTest() {
handler = new MultOperationHandler();
Assertions.assertEquals(5, handler.invoke(1, 5));
}
@Test
void divTest() {
handler = new DivisionOperationHandler();
Assertions.assertEquals(5, handler.invoke(10, 2));
}
@Test
void modularDivTest() {
handler = new ModularDivOperationHandler();
Assertions.assertEquals(1, handler.invoke(10, 3));
}
@Test
void powTest() {
handler = new PowOperationHandler();
Assertions.assertEquals(256, handler.invoke(4, 4));
}
}
<file_sep>/build.gradle
plugins {
id 'java'
id 'idea'
id 'io.franzbecker.gradle-lombok' version '4.0.0'
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
sourceCompatibility = 11
targetCompatibility = 11
}
repositories {
mavenCentral()
}
dependencies {
testImplementation(
'org.junit.jupiter:junit-jupiter:5.6.0',
'org.assertj:assertj-core:1.9.4',
'com.codeborne:selenide:5.20.1'
)
testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.6.0',
"org.slf4j:slf4j-simple:1.7.30")
}
test {
useJUnitPlatform()
}<file_sep>/src/test/java/mocks/MockMultReader.java
package mocks;
import service.Operation;
import service.Reader;
public class MockMultReader implements Reader {
@Override
public int readFirstArg() {
return 3;
}
@Override
public int readSecondArg() {
return 5;
}
@Override
public Operation readMathOperation() {
return Operation.MULT;
}
}
<file_sep>/src/test/java/tests/CalculatorTests.java
package tests;
import exception.DivideByZeroException;
import mocks.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import service.Calculator;
import service.Reader;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CalculatorTests {
private Calculator calculator;
private Reader mockReader;
private MockWriter mockWriter;
@Test
void calculatorSumTest() {
mockReader = new MockSumReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
String result = calculator.start();
Assertions.assertEquals("1 + 6 = 7", result);
}
@Test
void calculatorSubTest() {
mockReader = new MockSubReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
String result = calculator.start();
Assertions.assertEquals("12 - 8 = 4", result);
}
@Test
void calculatorMultTest() {
mockReader = new MockMultReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
String result = calculator.start();
Assertions.assertEquals("3 * 5 = 15", result);
}
@Test
void calculatorDivTest() {
mockReader = new MockDivReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
String result = calculator.start();
Assertions.assertEquals("10 / 5 = 2", result);
}
@Test
void calculatorZeroDivTest() {
mockReader = new MockDivByZeroReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
Exception exception = assertThrows(DivideByZeroException.class, () -> {
calculator.start();
});
Assertions.assertEquals("Error! Dividing by zero is not allowed.", exception.getMessage());
}
@Test
void calculatorModuleDivTest() {
mockReader = new MockModuleDivReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
String result = calculator.start();
Assertions.assertEquals("10 % 3 = 1", result);
}
@Test
void moduleDivByZeroTest() {
mockReader = new MockModuleDivByZeroReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
Exception exception = assertThrows(DivideByZeroException.class, () -> {
calculator.start();
});
Assertions.assertEquals("Error! Dividing by zero is not allowed.", exception.getMessage());
}
@Test
void calculatorPowTest() {
mockReader = new MockPowReader();
mockWriter = new MockWriter();
calculator = new Calculator(mockReader, mockWriter);
String result = calculator.start();
Assertions.assertEquals("2 ^ 7 = 128", result);
}
}
<file_sep>/src/main/java/service/Writer.java
package service;
public interface Writer<T> {
T handleString(String output);
}
<file_sep>/src/test/java/mocks/MockSumReader.java
package mocks;
import service.Operation;
import service.Reader;
public class MockSumReader implements Reader {
@Override
public int readFirstArg() {
return 1;
}
@Override
public int readSecondArg() {
return 6;
}
@Override
public Operation readMathOperation() {
return Operation.SUM;
}
}
<file_sep>/src/main/java/service/impl/DivisionOperationHandler.java
package service.impl;
import exception.DivideByZeroException;
import service.OperationHandler;
public class DivisionOperationHandler implements OperationHandler {
@Override
public int invoke(int first, int second) {
if (first == 0 || second == 0) {
throw new DivideByZeroException("Error! Dividing by zero is not allowed.");
} else {
return first / second;
}
}
}
| 2397f596e29e38f726109f69c5c2171758e0ca14 | [
"Java",
"Gradle"
] | 9 | Java | slazarska/calculator | 281998c62ea6224c3e144af7ad4f1c990d904493 | 8e2a3b24ea76131b63e89adcdd788ba04f8449d9 |
refs/heads/master | <file_sep>ojs Cookbook
=============
This cookbook will install [ojs](https://pkp.sfu.ca/ojs/). It does NOT configure dependencies! You'll need to install the dependencies yourself.
See [the documentation](https://pkp.sfu.ca/wiki/index.php?title=OJS_Documentation) for more details.
Requirements
------------
#### cookbook dependencies
Attributes
----------
#### ojs::default
Usage
-----
#### ojs::default
Just include `ojs` in your node's `run_list`:
```json
{
"name":"my_node",
"run_list": [
"recipe[ojs]"
]
}
```
License and Authors
-------------------
* <NAME> (<<EMAIL>>)
<file_sep>#
# Cookbook Name:: ojs
# Recipe:: default
#
# Copyright 2015, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
# Clone OJS repository into install directory
git node['ojs']['install_dir'] do
repository node['ojs']['git_repo']
revision node['ojs']['git_revision']
enable_submodules true
user node['nginx']['user']
group node['nginx']['group']
end
# Create config.inc.php from template
template "#{node['ojs']['install_dir']}/config.inc.php" do
source 'config.inc.php.erb'
group node['nginx']['user']
owner node['nginx']['user']
variables node['ojs']['config']
end
# Create file upload directory
directory "#{node['nginx']['default_root']}/files" do
owner node['nginx']['user']
group node['nginx']['group']
end
link '/var/lib/mysql/mysql.sock' do
to "/var/run/mysql-#{node['mysql']['service_name']}/mysqld.sock"
end
<file_sep>name 'ojs'
maintainer '<NAME>'
maintainer_email '<EMAIL>'
license 'All rights reserved'
description 'Installs/Configures Open Journal Systems'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
<file_sep>default['ojs']['git_repo'] = 'git://github.com/pkp/ojs.git'
default['ojs']['git_revision'] = 'ojs-stable-2_4_8'
# Don't change anything below unless you really know what you are doing!
default['ojs']['install_dir'] = "#{node['nginx']['default_root']}/ojs"
| ac07da187324b9fe0470204438dba7c7c75a1b21 | [
"Markdown",
"Ruby"
] | 4 | Markdown | followfung/ojs_cookbook | d9f9b9a7b94190d883f5a01280c412c5e486f14d | e5f2c59f7e1a16286afc65c95a5317cdf036ccf7 |
refs/heads/master | <file_sep>"use strict";
class ValidationResults {
constructor(status, msg) {
this.status = status;
this.msg = msg;
}
}
function getLen(str) {
return (str.length + encodeURI(str).split(/%..|./).length - 1) / 2;
}
function lenValid(value, name) {
if (value.length == 0)
return new ValidationResults(false, name + "不能为空");
if (getLen(value) < 4 || getLen(value) > 16)
return new ValidationResults(false, name + "长度不合法");
return new ValidationResults(true, name + "可用");
}
function submit() {
let ret = lenValid(document.getElementById('name').value, "名字");
document.getElementById('name').parentElement.className = ret.status ? "box verified" : "box error";
document.getElementById('name').nextSibling.setAttribute("data-validation", ret.msg);
} | ed8374fa2eb6afae8d636bb8241ec310c58c4255 | [
"JavaScript"
] | 1 | JavaScript | codehz/ife-j29 | 2facfdf7c9ade56db76c9e4d77e28e6e5594f060 | 014a1e4f7ab339ba83e54f16ba878bb2686417e0 |
refs/heads/master | <repo_name>soilhealthfeedback/SHEAF_DATA_CREATION<file_sep>/SHEAF_census_race_sex_diversity.R
library(pheatmap)
library(dplyr)
library(diverse)
library(PANDA)
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
census <- read.csv("https://nextcloud.sesync.org/index.php/s/iEpDeymRJG6oKFr/download")
colnames(census)[4] <- "State"
colnames(census)[8] <- "County"
census$County <- as.character(census$County)
census$State <- tolower(census$State)
census$State <- sapply(census$State, simpleCap)
census$County <- tolower(census$County)
census$County <- sapply(census$County, simpleCap)
countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
countyFIPS$FIPS <- sprintf("%05d",countyFIPS$FIPS)
colnames(countyFIPS) <- c("ID", "State", "County", "FIPS")
census2 <- plyr::join(census, countyFIPS, by = c("State", "County"))
#TranformSexGRM------
#to transform sex variable
census_sex <- census2 %>%
# clean value column
mutate(value_trim=str_trim(Value)) %>%
mutate(Value2=as.character(value_trim)) %>%
filter(Value2 != "(D)" & Value2 != "(Z)" & Value2 != "(NA)") %>%
select(Year, State, County, Data.Item, Value2) %>%
# filter what you want
filter(Data.Item %in% c("OPERATORS, (ALL) - NUMBER OF OPERATORS", "OPERATORS, (ALL), FEMALE - NUMBER OF OPERATORS")) %>%
spread(Data.Item, Value2) %>%
rename(female_operators=`OPERATORS, (ALL), FEMALE - NUMBER OF OPERATORS`) %>%
rename(all_operators=`OPERATORS, (ALL) - NUMBER OF OPERATORS`) %>%
mutate(percent_female=as.integer(female_operators)/as.integer(all_operators))
census3 <- census2 %>%
select(FIPS, Year, Data.Item, Value)
census4 <- na.omit(census3)
census5 <- census4[ which(census4$Data.Item == c("OPERATORS, AMERICAN INDIAN OR ALASKA NATIVE - NUMBER OF OPERATORS",
"OPERATORS, BLACK OR AFRICAN AMERICAN - NUMBER OF OPERATORS",
"OPERATORS, HISPANIC - NUMBER OF OPERATORS",
"OPERATORS, MULTI-RACE - NUMBER OF OPERATORS",
"OPERATORS, ASIAN - NUMBER OF OPERATORS",
"OPERATORS, NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER - NUMBER OF OPERATORS",
"OPERATORS, WHITE - NUMBER OF OPERATORS")), ]
census2002 <- census5[ which(census5$Year=='2002'), ] #select for only 2002
#eliminate rows with NAs in FIPS
census2002 <- census2002 %>%
select(FIPS, Data.Item, Value) #reduce to 3 variables
census2007 <- census5[ which(census5$Year=='2007'), ] #select for only 2002
#eliminate rows with NAs in FIPS
census2007 <- census2007 %>%
select(FIPS, Data.Item, Value) #reduce to 3 variables
census2012 <- census5[ which(census5$Year=='2012'), ] #select for only 2002
#eliminate rows with NAs in FIPS
census2012 <- census2012 %>%
select(FIPS, Data.Item, Value) #reduce to 3 variables
div2002 <- diversity(census2002, type = "simpson") #saves diversity measures as dataframe
div2007 <- diversity(census2007, type = "simpson")
div2012 <- diversity(census2012, type = "simpson")
div2002$FIPS <- rownames(div2002)
div2007$FIPS <- rownames(div2007)
div2012$FIPS <- rownames(div2012)
## need to rename column headings to include years!!!!
div2002$year <- 2002
div2007$year <- 2007
div2012$year <- 2012
div2002_div2007 <- plyr::join(div2002, div2007, by = "FIPS")
racediv <- plyr::join(div2002_div2007, div2012, by = "FIPS")
head(racediv)
<file_sep>/SHEAF_census_race_divindex.R
library(dplyr)
library(diverse)
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
census <- read.csv("https://nextcloud.sesync.org/index.php/s/iEpDeymRJG6oKFr/download")
colnames(census)[4] <- "State"
colnames(census)[8] <- "County"
census$County <- as.character(census$County)
census$State <- tolower(census$State)
census$State <- sapply(census$State, simpleCap)
census$County <- tolower(census$County)
census$County <- sapply(census$County, simpleCap)
#convert ansi fields to integer for adding leading zeros
census$State.ANSI <- as.integer(census$State.ANSI)
census$County.ANSI <- as.integer(census$County.ANSI)
#add leading zeros to make state 2 digits and county 3 digits
census$State.ANSI <- sprintf("%02d",census$State.ANSI)
census$County.ANSI <- sprintf("%03d",census$County.ANSI)
#create a FIPS column
census$FIPS <- paste(census$State.ANSI, census$County.ANSI, sep="")
#countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
#countyFIPS$FIPS <- sprintf("%05d",countyFIPS$FIPS)
#colnames(countyFIPS) <- c("ID", "State", "County", "FIPS")
#census2 <- plyr::join(census, countyFIPS, by = c("State", "County"))
census3 <- census %>%
dplyr::select(FIPS, Year, Data.Item, Value)
census4 <- na.omit(census3)
census5 <- census4[ which(census4$Data.Item == c("OPERATORS, AMERICAN INDIAN OR ALASKA NATIVE - NUMBER OF OPERATORS",
"OPERATORS, BLACK OR AFRICAN AMERICAN - NUMBER OF OPERATORS",
"OPERATORS, HISPANIC - NUMBER OF OPERATORS",
"OPERATORS, MULTI-RACE - NUMBER OF OPERATORS",
"OPERATORS, ASIAN - NUMBER OF OPERATORS",
"OPERATORS, NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER - NUMBER OF OPERATORS",
"OPERATORS, WHITE - NUMBER OF OPERATORS")), ]
census2002 <- census5[ which(census5$Year=='2002'), ] #select for only 2002
#eliminate rows with NAs in FIPS
census2002 <- census2002 %>%
dplyr::select(FIPS, Data.Item, Value) #reduce to 3 variables
census2007 <- census5[ which(census5$Year=='2007'), ] #select for only 2002
#eliminate rows with NAs in FIPS
census2007 <- census2007 %>%
dplyr::select(FIPS, Data.Item, Value) #reduce to 3 variables
census2012 <- census5[ which(census5$Year=='2012'), ] #select for only 2002
#eliminate rows with NAs in FIPS
census2012 <- census2012 %>%
dplyr::select(FIPS, Data.Item, Value) #reduce to 3 variables
div2002 <- diversity(census2002, type = "entropy") #saves diversity measures as dataframe
div2007 <- diversity(census2007, type = "entropy") #entropy = the Shannon entropy per entity measure, denoted by "H"
div2012 <- diversity(census2012, type = "entropy")
div2002$FIPS <- rownames(div2002)
div2007$FIPS <- rownames(div2007)
div2012$FIPS <- rownames(div2012)
div2002$year <- 2002
div2007$year <- 2007
div2012$year <- 2012
div2002_div2007 <- rbind(div2002, div2007, by = "FIPS")
racediv <- rbind(div2002_div2007, div2012, by = "FIPS")
head(racediv)
racediv <- lapply(racediv, function(x) as.numeric(as.character(x))) # convert to numberic variables
summary(racediv)
write.csv(racediv, file = paste("/nfs/soilsesfeedback-data/transformed_data/census_racediversity.csv", sep=""))
<file_sep>/data cleaning code.R
# !diagnostics off
soilnonscaled<-MIDWEST_CORN_SOYBEANS_Model2_nonscaled_new
##rescaled farm cost variables to be dollars per acre
soilnonscaled$FARMCOSTS_Chemicals_1000Doll_2012_peracre<-(soilnonscaled$FARMCOSTS_Chemicals_1000Doll_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_Depreciation_expenses_1000Doll_2012_peracre<-(soilnonscaled$FARMCOSTS_Depreciation_expenses_1000Doll_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012_peracre<-(soilnonscaled$FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_Interest_Expenses_1000Dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_Interest_Expenses_1000Dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_Utilities_expenses_1000Dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_Utilities_expenses_1000Dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_FeedExpenses_1000Dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_FeedExpenses_1000Dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMVALUE_farmincome_peracre<-(soilnonscaled$FARMVALUE_income_farmsources_gross*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$PAYMENTS_payments_reserve_total_peracre<-(soilnonscaled$PAYMENTS_payments_reserve_total_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$PAYMENTS_payments_fedfarmprograms_total_peracre<-(soilnonscaled$PAYMENTS_payments_fedfarmprograms_total_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_ContractLaborExpense_1000Doll_2012_peracre<-(soilnonscaled$FARMCOSTS_ContractLaborExpense_1000Doll_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_Property_taxes_paid_1000Dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_Property_taxes_paid_1000Dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012_peracre<-(soilnonscaled$FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
soilnonscaled$FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012_peracre<-(soilnonscaled$FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012*1000)/soilnonscaled$AGCENSUS_Cropland_Acres
####reduce skew in dependent variables####
####cover crops
skewness(soilnonscaled$AGCENSUS_Cover_Acres_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
h<-hist(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
h
soilnonscaled$AGCENSUS_Cover_Acres_Ratio[soilnonscaled$AGCENSUS_Cover_Acres_Ratio>=1] <- NA
skewness(soilnonscaled$AGCENSUS_Cover_Acres_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
## to find optimal lambda
lambda = BoxCox.lambda(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
lambda
## now to transform vector
soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed<-BoxCox(soilnonscaled$AGCENSUS_Cover_Acres_Ratio, lambda=0)
skewness(soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed, na.rm=T)
summary(soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed)
hist(soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed)
###no till
skewness(soilnonscaled$AGCENSUS_Notill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Notill_Ratio)
h<-hist(soilnonscaled$AGCENSUS_Notill_Ratio)
h
soilnonscaled$AGCENSUS_Notill_Ratio[soilnonscaled$AGCENSUS_Notill_Ratio>=.5] <- NA
skewness(soilnonscaled$AGCENSUS_Notill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Notill_Ratio)
## to find optimal lambda
lambda = BoxCox.lambda(soilnonscaled$AGCENSUS_Notill_Ratio)
lambda
## now to transform vector
soilnonscaled$AGCENSUS_Notill_Ratio_transformed<-BoxCox(soilnonscaled$AGCENSUS_Notill_Ratio, lambda=0)
skewness(soilnonscaled$AGCENSUS_Notill_Ratio_transformed, na.rm=T)
summary(soilnonscaled$AGCENSUS_Notill_Ratio_transformed)
hist(soilscaled$AGCENSUS_Notill_Ratio_transformed)
###multitill
skewness(soilnonscaled$AGCENSUS_Multitill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Multitill_Ratio)
h<-hist(soilnonscaled$AGCENSUS_Multitill_Ratio)
h
soilnonscaled$AGCENSUS_Multitill_Ratio[soilnonscaled$AGCENSUS_Multitill_Ratio>=.8] <- NA
skewness(soilnonscaled$AGCENSUS_Multitill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Multitill_Ratio)
## to find optimal lambda
lambda = BoxCox.lambda(soilnonscaled$AGCENSUS_Multitill_Ratio)
lambda
## now to transform vector
soilnonscaled$AGCENSUS_Multitill_Ratio_transformed<-BoxCox(soilnonscaled$AGCENSUS_Multitill_Ratio, lambda=0)
skewness(soilnonscaled$AGCENSUS_Multitill_Ratio_transformed, na.rm=T)
summary(soilnonscaled$AGCENSUS_Multitill_Ratio_transformed)
hist(soilnonscaled$AGCENSUS_Multitill_Ratio_transformed)
hist(soilscaled$AGCENSUS_Multitill_Ratio_transformed)
##look at distributions and remove outliers
#chemicals
hist(soilnonscaled$FARMCOSTS_Chemicals_1000Doll_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Chemicals_1000Doll_2012_peracre)
soilnonscaled$FARMCOSTS_Chemicals_1000Doll_2012_peracre[soilnonscaled$FARMCOSTS_Chemicals_1000Doll_2012_peracre>=100] <- NA
#rent
hist(soilnonscaled$FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012_peracre)
summary(soilnonscaled$FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012_peracre)
soilnonscaled$FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012_peracre[soilnonscaled$FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012_peracre>=200] <- NA
#fertilizer
hist(soilnonscaled$FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012_peracre)
soilnonscaled$FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012_peracre[soilnonscaled$FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012_peracre>=200] <- NA
#feed
hist(soilnonscaled$FARMCOSTS_FeedExpenses_1000Dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_FeedExpenses_1000Dolls_2012_peracre)
soilnonscaled$FARMCOSTS_FeedExpenses_1000Dolls_2012_peracre[soilnonscaled$FARMCOSTS_FeedExpenses_1000Dolls_2012_peracre>=600] <- NA
#interest
hist(soilnonscaled$FARMCOSTS_Interest_Expenses_1000Dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Interest_Expenses_1000Dolls_2012_peracre)
soilnonscaled$FARMCOSTS_Interest_Expenses_1000Dolls_2012_peracre[soilnonscaled$FARMCOSTS_Interest_Expenses_1000Dolls_2012_peracre>=100] <- NA
#fuel
hist(soilnonscaled$FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012_peracre)
soilnonscaled$FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012_peracre[soilnonscaled$FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012_peracre>=120] <- NA
#utilities
hist(soilnonscaled$FARMCOSTS_Utilities_expenses_1000Dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Utilities_expenses_1000Dolls_2012_peracre)
soilnonscaled$FARMCOSTS_Utilities_expenses_1000Dolls_2012_peracre[soilnonscaled$FARMCOSTS_Utilities_expenses_1000Dolls_2012_peracre>=60] <- NA
#depreciation
hist(soilnonscaled$FARMCOSTS_Depreciation_expenses_1000Doll_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Depreciation_expenses_1000Doll_2012_peracre)
soilnonscaled$FARMCOSTS_Depreciation_expenses_1000Doll_2012_peracre[soilnonscaled$FARMCOSTS_Depreciation_expenses_1000Doll_2012_peracre>=200] <- NA
#contract labor
hist(soilnonscaled$FARMCOSTS_ContractLaborExpense_1000Doll_2012_peracre)
summary(soilnonscaled$FARMCOSTS_ContractLaborExpense_1000Doll_2012_peracre)
soilnonscaled$FARMCOSTS_ContractLaborExpense_1000Doll_2012_peracre[soilnonscaled$FARMCOSTS_ContractLaborExpense_1000Doll_2012_peracre>=20] <- NA
#property taxes
hist(soilnonscaled$FARMCOSTS_Property_taxes_paid_1000Dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Property_taxes_paid_1000Dolls_2012_peracre)
soilnonscaled$FARMCOSTS_Property_taxes_paid_1000Dolls_2012_peracre[soilnonscaled$FARMCOSTS_Property_taxes_paid_1000Dolls_2012_peracre>=60] <- NA
#rent machinery
hist(soilnonscaled$FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012_peracre)
summary(soilnonscaled$FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012_peracre)
soilnonscaled$FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012_peracre[soilnonscaled$FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012_peracre>=20] <- NA
#hauling
hist(soilnonscaled$FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012_peracre)
summary(soilnonscaled$FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012_peracre)
soilnonscaled$FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012_peracre[soilnonscaled$FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012_peracre>=50] <- NA
#net income per acre
hist(soilnonscaled$FARMVALUE_farmincome_peracre)
summary(soilnonscaled$FARMVALUE_farmincome_peracre)
soilnonscaled$FARMVALUE_farmincome_peracre[soilnonscaled$FARMVALUE_farmincome_peracre>=600] <- NA
#reserve program payments
hist(soilnonscaled$PAYMENTS_payments_reserve_total_peracre)
summary(soilnonscaled$PAYMENTS_payments_reserve_total_peracre)
soilnonscaled$PAYMENTS_payments_reserve_total_peracre[soilnonscaled$PAYMENTS_payments_reserve_total_peracre>=200] <- NA
#federal farm program payments
hist(soilnonscaled$PAYMENTS_payments_fedfarmprograms_total_peracre)
summary(soilnonscaled$PAYMENTS_payments_fedfarmprograms_total_peracre)
soilnonscaled$PAYMENTS_payments_fedfarmprograms_total_peracre[soilnonscaled$PAYMENTS_payments_fedfarmprograms_total_peracre>=150] <- NA
#race
hist(soilnonscaled$RACE_Entropy)
summary(soilnonscaled$RACE_Entropy)
#farmvalue
hist(soilnonscaled$FARMVALUE_marketvalue_aveperacre)
summary(soilnonscaled$FARMVALUE_marketvalue_aveperacre)
#look at farm income distribution
hist(soilnonscaled$FARMVALUE_farmincome_peracre)
summary(soilnonscaled$FARMVALUE_farmincome_peracre)
soilnonscaled$FARMVALUE_farmincome_peracre[soilnonscaled$FARMVALUE_farmincome_peracre>=400] <- NA
#save
write.csv(soilnonscaled,"soilnonscaledupdated11_22.csv")
<file_sep>/models.R
library("lavaan")
library("semPlot")
library("DescTools")
library("MASS")
library("car")
###nonscaled data###
soilnonscaled<-read.csv("C:\\Users\\kjone\\OneDrive\\Desktop\\Soil health team\\soilnonscaled.csv", header=T)
##no-till models
#Model 1 - beta conceptual model
model1<-'#latent variables
Water_Stress =~ PDSI_TOTALS + RMA_Droughtperacre + RMA_Failure_Irrig_Supplyperacre
Water_Surplus =~ PRECIP_max + RMA_Excess_Moistureperacre + RMA_Floodperacre + RMA_Hailperacre
Land_Use_Diversity =~ CDI_2012 + NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Irr_Pastureland_Estimate+ NRI_Prime_Rangeland_Estimate +NRI_Prime_CRP_Estimate
Resource_Rich_County =~ NRCS_EQIP_FA_PAYMENTS_peracre + NRCS_CStP_FA_Payments_peracre + RMA_Lossperacre + RMA_Acresperclaim
High_Cost_County =~ RENT_average + +FEMALE_Total_farm_production_expense_farms_2012
#regressions
Land_Use_Diversity ~ Water_Stress + Water_Surplus + RENT_Percent.rented.2012
High_Cost_County ~ HDI_Education.Index + HDI_Income.Index + HDI_Health.Index + RACE_Entropy
Resource_Rich_County ~ High_Cost_County + HDI_Education.Index + HDI_Income.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy
AGCENSUS_percent_notill ~ Resource_Rich_County + High_Cost_County+ Land_Use_Diversity + HDI_Health.Index + HDI_Income.Index + HDI_Education.Index + RACE_Entropy + FEMALE_percent_female + RENT_Percent.rented.2012 + Water_Stress + Water_Surplus
#covariance
HDI_Health.Index ~~ HDI_Income.Index
HDI_Health.Index ~~ HDI_Education.Index
HDI_Health.Index ~~ RACE_Entropy
HDI_Income.Index ~~ HDI_Education.Index
HDI_Income.Index ~~ RACE_Entropy
HDI_Education.Index ~~ RACE_Entropy
High_Cost_County ~~ RENT_Percent.rented.2012
Water_Stress ~~ Resource_Rich_County
Water_Surplus ~~ Resource_Rich_County'
fitmodel1<-sem(model1,data=soilnonscaled)
summary(fitmodel1,standardized=T,fit.measures=T)
parameterestimates(fitmodel1)
#CFA for each factor
model2<-'Water_Stress =~ PDSI_TOTALS + RMA_Droughtperacre + RMA_Failure_Irrig_Supplyperacre'
fitmodel2<-cfa(model2, data=soilnonscaled)
summary(fitmodel2,fit.measures=T)
waterstress<-soilnonscaled[c("PDSI_TOTALS","RMA_Droughtperacre","RMA_Failure_Irrig_Supplyperacre")]
waterstresscor<-cor(waterstress)
waterstresscor
model3<-'Water_Surplus =~ PRECIP_max + RMA_Excess_Moistureperacre + RMA_Floodperacre + RMA_Hailperacre'
fitmodel3<-cfa(model3, data=soilnonscaled)
summary(fitmodel3,fit.measures=T)
watersurplus<-soilnonscaled[c("PRECIP_max","RMA_Excess_Moistureperacre","RMA_Floodperacre","RMA_Hailperacre")]
watersurpluscor<-cor(watersurplus)
watersurpluscor
model4<-'Land_Use_Diversity =~ CDI_2012 + NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Irr_Pastureland_Estimate+ NRI_Prime_Rangeland_Estimate +NRI_Prime_CRP_Estimate'
fitmodel4<-cfa(model4, data=soilnonscaled)
summary(fitmodel4,fit.measures=T)
landusediv<-soilnonscaled[c("CDI_2012","NRI_Irr_Cropland_Estimate","NRI_Prime_Pastureland_Estimate","NRI_Irr_Pastureland_Estimate","NRI_Prime_Rangeland_Estimate","NRI_Prime_CRP_Estimate")]
landusedivcor<-cor(landusediv)
landusedivcor
model5<-'Resource_Rich_County =~ NRCS_EQIP_FA_PAYMENTS_peracre + NRCS_CStP_FA_Payments_peracre + RMA_Lossperacre + RMA_Acresperclaim'
fitmodel5<-cfa(model5, data=soilnonscaled)
summary(fitmodel5,fit.measures=T, standardized=T)
resourcerich<-soilnonscaled[c("NRCS_EQIP_FA_PAYMENTS_peracre","NRCS_CStP_FA_Payments_peracre","RMA_Lossperacre","RMA_Acresperclaim")]
resourcerichcor<-cor(resourcerich)
resourcerichcor
model6<-'High_Cost_County =~ RENT_average + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index'
fitmodel6<-cfa(model6, data=soilnonscaled)
summary(fitmodel6,fit.measures=T, standardized=T)
soilnonscaled$RMA_L
#new model with one latent factor
model7<-'
#latent factors
High_Cost_County =~ RENT_average + +FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#regressions
CDI_2012 ~ PDSI_TOTALS + RMA_Droughtperacre + PRECIP_ave + RMA_Floodperacre + RENT_Percent.rented.2012
NRI_Prime_Pastureland_Estimate ~ PDSI_TOTALS + RMA_Droughtperacre + PRECIP_ave + RMA_Floodperacre + RENT_Percent.rented.2012
NRI_Prime_Rangeland_Estimate ~ PDSI_TOTALS + RMA_Droughtperacre + PRECIP_ave + RMA_Floodperacre + RENT_Percent.rented.2012
High_Cost_County ~ HDI_Education.Index + HDI_Health.Index + RACE_Entropy
NRCS_EQIP_cstp_combined_peracre ~ High_Cost_County + HDI_Education.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy
RMA_Lossperacre ~ High_Cost_County + HDI_Education.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy
AGCENSUS_percent_notill ~ NRCS_EQIP_cstp_combined_peracre + RMA_Lossperacre + High_Cost_County + CDI_2012 + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate + HDI_Health.Index + HDI_Education.Index + RACE_Entropy + FEMALE_percent_female + RENT_Percent.rented.2012
#covariance
HDI_Health.Index ~~ HDI_Education.Index
HDI_Health.Index ~~ RACE_Entropy
HDI_Education.Index ~~ RACE_Entropy
High_Cost_County ~~ RENT_Percent.rented.2012'
fitmodel7<-sem(model7,data=soilnonscaled)
summary(fitmodel7,standardized=T,fit.measures=T)
parameterestimates(fitmodel1)
model8<-'#latent factors
High_Cost_County =~ RENT_average + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#regressions
CDI_2012 ~ PDSI_TOTALS + RMA_Droughtperacre + PRECIP_ave + RMA_Floodperacre + RENT_Percent.rented.2012
High_Cost_County ~ HDI_Education.Index + HDI_Health.Index + RACE_Entropy
NRCS_EQIP_cstp_combined_peracre ~ PDSI_TOTALS + PRECIP_ave + HDI_Education.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate
RMA_Lossperacre ~ PDSI_TOTALS + PRECIP_ave + HDI_Education.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ NRCS_EQIP_cstp_combined_peracre + RMA_Lossperacre + High_Cost_County + CDI_2012 + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate + HDI_Health.Index + HDI_Education.Index + RACE_Entropy + FEMALE_percent_female + RENT_Percent.rented.2012
#covariance
HDI_Health.Index ~~ HDI_Education.Index
HDI_Health.Index ~~ RACE_Entropy
HDI_Education.Index ~~ RACE_Entropy
High_Cost_County ~~ RENT_Percent.rented.2012
RMA_Lossperacre ~~ High_Cost_County
NRCS_EQIP_cstp_combined_peracre ~~ High_Cost_County'
fitmodel8<-sem(model8,data=soilnonscaled)
summary(fitmodel8,standardized=T,fit.measures=T)
parameterestimates(fitmodel8)
model9<-'#latent factors
High_Cost_County =~ RENT_average + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#regressions
High_Cost_County ~ HDI_Education.Index + HDI_Health.Index + RACE_Entropy
CDI_2012 ~ PDSI_TOTALS + PRECIP_ave + RENT_Percent.rented.2012 + High_Cost_County
NRCS_EQIP_cstp_combined_peracre ~ PDSI_TOTALS + PRECIP_ave + HDI_Education.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy
RMA_Lossperacre ~ PDSI_TOTALS + PRECIP_ave
AGCENSUS_percent_notill ~ NRCS_EQIP_cstp_combined_peracre + RMA_Lossperacre + High_Cost_County + CDI_2012 + HDI_Health.Index + HDI_Education.Index + RACE_Entropy + FEMALE_percent_female + RENT_Percent.rented.2012
#covariance
HDI_Health.Index ~~ HDI_Education.Index
HDI_Health.Index ~~ RACE_Entropy
HDI_Education.Index ~~ RACE_Entropy
High_Cost_County ~~ RENT_Percent.rented.2012'
fitmodel9<-sem(model9,data=soilnonscaled)
summary(fitmodel9,standardized=T,fit.measures=T)
conservation<-soilnonscaled[c("NRCS_EQIP_cstp_combined_peracre","AGCENSUS_percent_notill","AGCENSUS_percent_cc")]
conservationcor<-cor(conservation)
conservationcor
summary(soilnonscaled$NRCS_EQIP_cstp_combined_peracre)
skewness(soilnonscaled$AGCENSUS_percent_notill)
cor(soilnonscaled$RMA_Lossperacre,soilnonscaled$PDSI_TOTALS)
####scaled data###
soilscaled<-read.csv("C:\\Users\\kjone\\OneDrive\\Desktop\\Soil health team\\soilscaled.csv", header=T)
##no-till models
#beta conceptual model
model10<-'#latent variables
Water_Stress =~ PDSI_TOTALS + RMA_Drought + RMA_Failure_Irrig_Supply
Water_Surplus =~ PRECIP_max + RMA_Excess_Moisture + RMA_Flood + RMA_Hail
Land_Use_Diversity =~ CDI_2012 + NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Irr_Pastureland_Estimate+ NRI_Prime_Rangeland_Estimate +NRI_Prime_CRP_Estimate
Resource_Rich_County =~ NRCS_EQIP_FA_PAYMENTS_total + NRCS_CStP_FA_Payments_total + RMA_Lossperacre + RMA_Acresperclaim
High_Cost_County =~ RENT_average + +FEMALE_Total_farm_production_expense_farms_2012
#regressions
Land_Use_Diversity ~ Water_Stress + Water_Surplus + RENT_Percent.rented.2012
High_Cost_County ~ HDI_Education.Index + HDI_Income.Index + HDI_Health.Index + RACE_Entropy
Resource_Rich_County ~ High_Cost_County + HDI_Education.Index + HDI_Income.Index + HDI_Health.Index + RENT_Percent.rented.2012 + RACE_Entropy
AGCENSUS_notill_acres ~ Resource_Rich_County + High_Cost_County+ Land_Use_Diversity + HDI_Health.Index + HDI_Income.Index + HDI_Education.Index + RACE_Entropy + FEMALE_percent_female + RENT_Percent.rented.2012 + Water_Stress + Water_Surplus
#covariance
HDI_Health.Index ~~ HDI_Income.Index
HDI_Health.Index ~~ HDI_Education.Index
HDI_Health.Index ~~ RACE_Entropy
HDI_Income.Index ~~ HDI_Education.Index
HDI_Income.Index ~~ RACE_Entropy
HDI_Education.Index ~~ RACE_Entropy
High_Cost_County ~~ RENT_Percent.rented.2012
Water_Stress ~~ Resource_Rich_County
Water_Surplus ~~ Resource_Rich_County'
fitmodel10<-sem(model10,data=soilscaled)
summary(fitmodel10,standardized=T,fit.measures=T)
#CFA with each factor
model11<-'Water_Stress =~ PDSI_TOTALS + RMA_Drought + RMA_Failure_Irrig_Supply'
fitmodel11<-cfa(model11, data=soilscaled)
summary(fitmodel11,fit.measures=T)
waterstressscaled<-soilscaled[c("PDSI_TOTALS","RMA_Drought","RMA_Failure_Irrig_Supply")]
waterstressscaledcor<-cor(waterstressscaled)
waterstressscaledcor
model12<-'Water_Surplus =~ PRECIP_max + RMA_Excess_Moisture + RMA_Flood + RMA_Hail'
fitmodel12<-cfa(model12, data=soilscaled)
summary(fitmodel12,fit.measures=T)
watersurplus<-soilnonscaled[c("PRECIP_max","RMA_Excess_Moistureperacre","RMA_Floodperacre","RMA_Hailperacre")]
watersurpluscor<-cor(watersurplus)
watersurpluscor
model13<-'Land_Use_Diversity =~ CDI_2012 + NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate +NRI_Prime_CRP_Estimate'
fitmodel13<-cfa(model13, data=soilscaled)
summary(fitmodel13,fit.measures=T)
landusedivscaled<-soilscaled[c("CDI_2012","NRI_Irr_Cropland_Estimate","NRI_Prime_Pastureland_Estimate","NRI_Prime_Rangeland_Estimate","NRI_Prime_CRP_Estimate")]
landusedivscaledcor<-cor(landusedivscaled)
landusedivscaledcor
model14<-'Resource_Rich_County =~ NRCS_EQIP_FA_PAYMENTS_total + NRCS_CStP_FA_Payments_total + RMA_Lossperacre + RMA_Acresperclaim'
fitmodel14<-cfa(model14, data=soilscaled)
summary(fitmodel14,fit.measures=T, standardized=T)
resourcerichscaled<-soilscaled[c("NRCS_EQIP_FA_PAYMENTS_total","NRCS_CStP_FA_Payments_total","RMA_Lossperacre","RMA_Acresperclaim")]
resourcerichscaledcor<-cor(resourcerichscaled)
resourcerichscaledcor
model15<-'High_Cost_County =~ RENT_average + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index'
fitmodel15<-cfa(model15, data=soilscaled)
summary(fitmodel15,fit.measures=T, standardized=T)
##EFA with scaled data
#correlation matrix
exogcor<-soilscaled[c("PDSI_TOTALS","RMA_Drought","RMA_Failure_Irrig_Supply","PRECIP_max","RMA_Excess_Moisture","RMA_Flood","RMA_Hail",
"CDI_2012","NRI_Irr_Cropland_Estimate","NRI_Prime_Pastureland_Estimate","NRI_Prime_Rangeland_Estimate","NRI_Prime_CRP_Estimate",
"NRCS_EQIP_FA_PAYMENTS_total","NRCS_CStP_FA_Payments_total","RMA_Lossperacre","RMA_Acresperclaim",
"RENT_average","FEMALE_Total_farm_production_expense_farms_2012","HDI_Income.Index",
"HDI_Health.Index","HDI_Education.Index","RACE_Entropy","FEMALE_percent_female","RENT_Percent.rented.2012")]
soilscaledcor<-cor(exogcor)
soilscaledcor
skewness(exogcor)
#EFA
parallel <- fa.parallel(exogcor, fm = 'wls', fa = 'fa')
sevenfactor <- fa(exogcor,nfactors = 7,rotate = "oblimin",fm="wls")
print(sevenfactor)
#try five factors
fivefactor <- fa(efa3,nfactors = 5,rotate = "oblimin",fm="wls")
print(fivefactor)
print(fivefactor$loadings,cutoff = 0.3)
print(fourfactor$loadings,cutoff = 0.3)
#try six factors
sixfactor2 <- fa(efa3,nfactors = 6,rotate = "oblimin",fm="wls")
print(sixfactor2)
print(sixfactor2$loadings,cutoff = 0.3)
#try two factors
twofactor<-fa(efa3,nfactors = 2,rotate = "oblimin",fm="wls")
print(twofactor$loadings,cutoff = 0.3)
##New model with EFA factor
model16<-'SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 +FEMALE_percent_female'
fitmodel16<-cfa(model16, data=soilscaled)
summary(fitmodel16,fit.measures=T, standardized=T)
model17<-'
#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ PDSI_TOTALS + PRECIP_max + NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ Commodification + NRCS_EQIP_cstp_combined + RMA_Lossperacre + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel17<-sem(model17, data=soilscaled)
summary(fitmodel17,fit.measures=T, standardized=T)
semPaths(fitmodel17, what="std", whatLabels="std", layout="tree", intercepts=F, residuals=F, nCharNodes=0, filetype="R", label.color="black")
model18<-'
#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ PDSI_TOTALS + PRECIP_max + NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ SustainableInvestment + NRCS_EQIP_cstp_combined + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel18<-sem(model18, data=soilscaled)
summary(fitmodel18,fit.measures=T, standardized=T)
model19<-'
#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ SustainableInvestment + NRCS_EQIP_cstp_combined + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel19<-sem(model19, data=soilscaled)
summary(fitmodel19,fit.measures=T, standardized=T)
semPaths(fitmodel19, what="std", whatLabels="std", layout="tree", intercepts=F, residuals=F, nCharNodes=0, filetype="R", label.color="black")
model20<-'
#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ NRI_Irr_Cropland_Estimate + NRI_Prime_Pastureland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ SustainableInvestment + NRCS_EQIP_cstp_combined + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index + PDSI_TOTALS + PRECIP_max
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel20<-sem(model20, data=soilscaled)
summary(fitmodel20,fit.measures=T, standardized=T)
#best fit no-till model
model21<-'
#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ NRI_Irr_Cropland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ SustainableInvestment + NRCS_EQIP_cstp_combined + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel21<-sem(model21, data=soilscaled)
summary(fitmodel21,fit.measures=T, standardized=T)
#constill model
model22<-'#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ NRI_Irr_Cropland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_constill ~ SustainableInvestment + NRCS_EQIP_cstp_combined + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel22<-sem(model22, data=soilscaled)
summary(fitmodel22,fit.measures=T,standardized=T)
#noandconstill model
skewness(soilscaled$AGCENSUS_percent_cc)
model23<-'#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ NRI_Irr_Cropland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_noandconstill ~ SustainableInvestment + NRCS_EQIP_cstp_combined + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel23<-sem(model23, data=soilscaled)
summary(fitmodel23,fit.measures=T,standardized=T)
#print a model
semPaths(fitmodel21, what="std", whatLabels="std", layout="tree", intercepts=F, residuals=F, nCharNodes=0, filetype="R", label.color="black", edge.label.cex = 1, label.cex=5)
#Box Cox to deal with skewed cover crop data
soilscaled$AGCENSUS_percent_cc_transformed<-BoxCox(soilscaled$AGCENSUS_percent_cc, lambda=.33)
skewness(soilscaled$AGCENSUS_percent_cc_transformed)
model21<-'
#latent factors
SustainableInvestment=~CDI_2012 + RENT_average + RENT_Percent.rented.2012 + FEMALE_percent_female
#regressions
NRCS_EQIP_cstp_combined ~ NRI_Irr_Cropland_Estimate + NRI_Prime_Rangeland_Estimate
AGCENSUS_percent_notill ~ SustainableInvestment + NRCS_EQIP_cstp_combined_peracre + FEMALE_Total_farm_production_expense_farms_2012 + HDI_Income.Index
#covariance
SustainableInvestment ~~ HDI_Income.Index'
fitmodel21<-sem(model21, data=soilnonscaled)
summary(fitmodel21,fit.measures=T, standardized=T)
<file_sep>/SHEAF_SEM_beta3.R
#SEM BETA
#Need to construct a SEM Measurement Model in our first phase of SEM development
#A Measurement model examines the relationships of manifest (observed) variables to their latent variables.
#we "Saturate" the SEM model intially in order to
#library(shiny)
#library(shinyAce)
library(psych)
library(lavaan)
library(semPlot)
#library(shinyjs)
#scaled data
data2 <- read.csv("/nfs/soilsesfeedback-data/Model_data/MIDWEST_CORN_SOYBEANS_Model2_lossperacre_scaled.csv")
#data2 <- data1[,-87] #remove FIPS
data2 <- data2[,-1] #remove ID
#transform dependent by log10
#data2$AGCENSUS_CC_Cropland_Acres_Ratio <- log10(data2$AGCENSUS_CC_Cropland_Acres_Ratio)
#data2$AGCENSUS_NOTILL_Cropland_Acres_Ratio <- log10(data2$AGCENSUS_notill_acres/data2$AGCENSUS_Cropland_Acres)
data2$RENT_Total <- data2$RENT_average * data2$RENT_acres.rented.2012
data2$RENT_Inverse_percent.rented.2012 <- 1-data2$RENT_acres.rented.2012
#non-scaled data
#data1 <- read.csv("/nfs/soilsesfeedback-data/Model_data/MIDWEST_CORN_SOYBEANS_Model_acres_nonscaled.csv")
#data1 <- data1[,-88] #remove FIPS
#data1 <- data1[,-1] #remove ID
hist(data2$AGCENSUS_NOTILL_Cropland_Acres_Ratio)
hist(data2$AGCENSUS_CC_Cropland_Acres_Ratio)
#normalizing dependent variables
shapiro.test(data2$AGCENSUS_CC_Cropland_Acres_Ratio)
shapiro.test(data2$AGCENSUS_NOTILL_Cropland_Acres_Ratio)
colnames(data2)[74] <- "CENSUS_FEMALE"
colnames(data2)[75] <- "CENSUS_ALL"
colnames(data2)[76] <- "CENSUS_INDIAN"
colnames(data2)[77] <- "CENSUS_ASIAN"
colnames(data2)[78] <- "CENSUS_BLACK"
colnames(data2)[79] <- "CENSUS_FEMALE2"
colnames(data2)[80] <- "CENSUS_HISPANIC"
colnames(data2)[81] <- "CENSUS_MULTIRACE"
colnames(data2)[82] <- "CENSUS_HAWAIIAN"
colnames(data2)[83] <- "CENSUS_WHITE"
#-model formulation
SHEAFModel_CFA <- ' WEATHER =~ PDSI_TOTALS + RMA_Acres
DIVERSITY =~ RENT_Total + CDI_2012 + CDI_2011
GENDER =~ CENSUS_FEMALE + CENSUS_ALL
RACE =~ CENSUS_INDIAN + CENSUS_ASIAN +
CENSUS_BLACK + CENSUS_HISPANIC + CENSUS_MULTIRACE +
CENSUS_HAWAIIAN + CENSUS_WHITE '
SHEAFModel_cc <- '
#Latent Variables
#ex: Weather is measured by PDSI_Totals + RMA_Acres
WEATHER =~ PDSI_TOTALS + RMA_Acres
DIVERSITY =~ RENT_Total + CDI_2012 + CDI_2011 + RENT_Inverse_percent.rented.2012
#Management =~ Residue.and.Tillage.Management..No.Till + Residue.and.Tillage.Management..Reduced.Till
#EQIP =~ Conservation.Crop.Rotation + Cover.Crop
GENDER =~ CENSUS_FEMALE + CENSUS_ALL
RACE =~ CENSUS_INDIAN + CENSUS_ASIAN +
CENSUS_BLACK + CENSUS_HISPANIC + CENSUS_MULTIRACE +
CENSUS_HAWAIIAN + CENSUS_WHITE
# regressions
# residual correlations
WEATHER ~~ RMA_Count
DIVERSITY ~~ RENT_Total
AGCENSUS_CC_Cropland_Acres_Ratio ~ DIVERSITY + GENDER + RACE + WEATHER + RMA_Count + RENT_Total'
SHEAFModel_NOTILL <- '
#Latent Variables
#ex: Weather is measured by PDSI_Totals + RMA_Acres
WEATHER =~ PDSI_TOTALS + RMA_Acres
DIVERSITY =~ RENT_Total + CDI_2012 + CDI_2011
#Management =~ Residue.and.Tillage.Management..No.Till + Residue.and.Tillage.Management..Reduced.Till
#EQIP =~ Conservation.Crop.Rotation + Cover.Crop
GENDER =~ CENSUS_FEMALE + CENSUS_ALL
RACE =~ CENSUS_INDIAN + CENSUS_ASIAN +
CENSUS_BLACK + CENSUS_HISPANIC + CENSUS_MULTIRACE +
CENSUS_HAWAIIAN + CENSUS_WHITE
# regressions
# residual correlations
WEATHER ~~ RMA_Count
DIVERSITY ~~ RENT_Total
AGCENSUS_NOTILL_Cropland_Acres_Ratio ~ DIVERSITY + GENDER + RACE + WEATHER + RMA_Count + RENT_Total'
#y3 ~~ y7
#y4 ~~ y8
#y6 ~~ y8
#CFA
fit_cfa <- lavaan::cfa(SHEAFModel_CFA, data=data2)
fit_notill <- lavaan::sem(model = SHEAFModel_NOTILL, data=data2, std.lv =TRUE)
fit_cc <- lavaan::sem(model = SHEAFModel_cc, data=data2, std.lv =TRUE)
#standardized estimates
semPlot::semPaths(fit_cfa, "std", bifactor = "g", fade = FALSE, style = "lisrel", label.cex = 1.5, nCharNodes = 10, what = "std", layout="tree2", curvePivot = TRUE, edge.label.cex=.85)
summary(fit_cfa, fit.measures = TRUE)
semPlot::semPaths(fit_cc, "std", bifactor = "g", fade = FALSE, style = "lisrel", label.cex = 1.5, nCharNodes = 10, what = "std", layout="tree3", curvePivot = TRUE, edge.label.cex=.85)
summary(fit_cc, fit.measures = TRUE)
semPlot::semPaths(fit_notill, bifactor = "g", "std", fade = FALSE, style = "lisrel", label.cex = 1.5, nCharNodes = 10, what = "std", layout="tree3", curvePivot = TRUE, edge.label.cex=.85)
summary(fit_notill, fit.measures = TRUE)
# Compare models:
layout(t(1:2))
semPaths(fit_notill, "std", title = FALSE)
title("No till", line = 3)
semPaths(fit_cc, "std", title = FALSE)
title("Cover crop", line = 3)
#---fit indices and standardized summaries
#change fit to examine differing models
<file_sep>/SHEAF_SEM_beta2.R
#loading the library
library(semPlot)
library(lavaan)
library(clusterGeneration) #this is to generate a positive definite covariance matrix
#simulate some data
set.seed(1222)
sig<-genPositiveDefMat("onion",dim=5,eta=4)$Sigma #the covariance matrix
mus<-c(10,5,120,35,6) #the vector of the means
data<-as.data.frame(mvrnorm(100,mu=mus,Sigma=sig)) #the dataset
names(data)<-c("CO2","Temp","Nitro","Biom","Rich") #giving it some names
#building an SEM with a latent variable
m<-'Abiot =~ CO2 + Temp + Nitro
Biom ~ Abiot
Rich ~ Abiot + Biom'
m.fit<-sem(m,data)
#the plot
#basic version, the what arguments specify what should be plotted, here we choose to look at the standardized path coefficients
semPaths(m.fit,what="std",layout="circle")
#define the label that will go into the nodes
lbls<-c("CO2\nconcentration","Temperature","Nitrogen\ncontent","Plant\nbiomass","Plant\nrichness","Abiotic\nenvironment")
#define the groups
grps<-list(Abiotic=c("CO2","Temp","Nitro","Abiot"),Plant=c("Biom","Rich"))
#define the layout
ly<-matrix(c(-0.5,-0.5,0,-0.5,0.5,-0.5,0,0.5,-0.5,0.5,0,0),ncol=2,byrow=TRUE)
#new plot
semPaths(m.fit,what="std",layout=ly,residuals=FALSE,nCharNodes=0,groups=grps,color=c("brown","green"),nodeLabels=lbls,sizeMan=8,posCol=c("blue","red"),edge.label.cex=1.5,legend=FALSE)
text(0.9,0.9,labels="Some text about\nthe model or\nthe weather in Indonesia")
semPaths(m.fit,what="std",nodeLabels=letters[1:6],edgeLabels=1:12,edge.label.cex=1.5,fade=FALSE)
<file_sep>/README.md
<<<<<<< HEAD
EXPLORATORY DATA ANALYSIS AND DATA EXTRACTION
=======
The function below combines all datasets into one data frame. Datasets that have factors that are pertinent
(farming practices, types of ag census categories), are transformed into columns. In this case, there are some values that are NA
for some factored columns, which means that, for that county/year/state combo, there was no value for that factor.
Running the function generates a dataset that is placed in the /soilsesfeedback-data/Model_data folder. This folder ONLY contains datasets generated
using this function. After generation, the dataset can then be called using the SHEAF_SEM model code, for analysis. It can also be used in the
SHEAF SEM web tool - which runs an SEM model on a selected dataset (http://soilhealthfeedback.org/sheaf-structural-equation-modeling-dashboard-alpha/)
**SHEAF_model_data_creation.R:** this function generates a crop-specific model output, by combining and aggregating a fixed list of datasets.
As we increase model functionality, we will increase the datasets merged and aggregated. The function is used as such:
SHEAF_model_data_creation("WHEAT")
For now, the modeled dataset is crop specific, but we can extend this to include all commodities. In that case, we would need to delineate
unique columns for each crop (e.g. WHEAT_Dollars.Paid, WHEAT_Drought, WHEAT_Vegetative Barrier). This will result in very large number of variables,
but that may not be an issue if it is scientifically valid.
NOTE: the local version of this function uses local pathways vs. a downloadable URL. This means that, if you are on the SESYNC Rstudio server, you may run this function.
**SHEAF_model_data_creation_local.R:** this function generates a crop-specific model output, by combining and aggregating a fixed list of datasets. As we increase model functionality, we will increase the datasets merged and aggregated. The function is used as such:
SHEAF_model_data_creation_local ("WHEAT")
Otherwise, use SHEAF_model_data_creation.R
=======
# SHEAF_SEM
<<<<<<< HEAD
SHEAF SEM code management
=======
SHEAF structural equation modeling code
>>>>>>> 59334e2636e6000d2908edf01d09fdf90058a87d
>>>>>>> 85d499fe3367257d5a274b958a1d38e45a5cff2f
<file_sep>/9 19 models and data normalization_GRM_RES.R
library(e1071)
library(forecast)
#fit model with scaled data
soilscaled<-read.csv("https://files.sesync.org/index.php/s/Y8mwK98kkajNafs/download", header=T)
soilnonscaled<-read.csv("https://files.sesync.org/index.php/s/L2iX5GC85JbYGwZ/download", header=T)
#reduce skew in dependent variables
#cover crops
skewness(soilnonscaled$AGCENSUS_Cover_Acres_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
h<-hist(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
h
soilnonscaled$AGCENSUS_Cover_Acres_Ratio[soilnonscaled$AGCENSUS_Cover_Acres_Ratio>=1] <- NA
skewness(soilnonscaled$AGCENSUS_Cover_Acres_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
# to find optimal lambda
lambda = BoxCox.lambda(soilnonscaled$AGCENSUS_Cover_Acres_Ratio)
lambda
# now to transform vector
soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed<-BoxCox(soilnonscaled$AGCENSUS_Cover_Acres_Ratio, lambda=-.1)
skewness(soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed, na.rm=T)
summary(soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed)
hist(soilscaled$AGCENSUS_Cover_Acres_Ratio_transformed)
#no till
skewness(soilnonscaled$AGCENSUS_Notill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Notill_Ratio)
h<-hist(soilnonscaled$AGCENSUS_Notill_Ratio)
h
soilnonscaled$AGCENSUS_Notill_Ratio[soilnonscaled$AGCENSUS_Notill_Ratio>=.5] <- NA
skewness(soilnonscaled$AGCENSUS_Notill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Notill_Ratio)
# to find optimal lambda
lambda = BoxCox.lambda(soilnonscaled$AGCENSUS_Notill_Ratio)
lambda
# now to transform vector
soilnonscaled$AGCENSUS_Notill_Ratio_transformed<-BoxCox(soilnonscaled$AGCENSUS_Notill_Ratio, lambda=-.1)
skewness(soilnonscaled$AGCENSUS_Notill_Ratio_transformed, na.rm=T)
summary(soilnonscaled$AGCENSUS_Notill_Ratio_transformed)
hist(soilscaled$AGCENSUS_Notill_Ratio_transformed)
#multitill
skewness(soilnonscaled$AGCENSUS_Multitill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Multitill_Ratio)
h<-hist(soilnonscaled$AGCENSUS_Multitill_Ratio)
h
soilnonscaled$AGCENSUS_Multitill_Ratio[soilnonscaled$AGCENSUS_Multitill_Ratio>=.8] <- NA
skewness(soilnonscaled$AGCENSUS_Multitill_Ratio, na.rm=T)
summary(soilnonscaled$AGCENSUS_Multitill_Ratio)
# to find optimal lambda
lambda = BoxCox.lambda(soilnonscaled$AGCENSUS_Multitill_Ratio)
lambda
# now to transform vector
soilnonscaled$AGCENSUS_Multitill_Ratio_transformed<-BoxCox(soilnonscaled$AGCENSUS_Multitill_Ratio, lambda=-.1)
skewness(soilnonscaled$AGCENSUS_Multitill_Ratio_transformed, na.rm=T)
summary(soilnonscaled$AGCENSUS_Multitill_Ratio_transformed)
hist(soilnonscaled$AGCENSUS_Multitill_Ratio_transformed)
hist(soilscaled$AGCENSUS_Multitill_Ratio_transformed)
#add new outcomes to soilscaled data
soilscaled$AGCENSUS_Cover_Acres_Ratio_transformed<-soilnonscaled$AGCENSUS_Cover_Acres_Ratio_transformed
soilscaled$AGCENSUS_Notill_Ratio_transformed<-soilnonscaled$AGCENSUS_Notill_Ratio_transformed
soilscaled$AGCENSUS_Multitill_Ratio_transformed<-soilnonscaled$AGCENSUS_Multitill_Ratio_transformed
#new model
model50<-'
#latent variables
Water_Stress=~PDSI_TOTALS + RMA_revised_loss_cost_hot_dry
Water_Surplus=~PRECIP_max + RMA_revised_loss_cost_wet
Gov_Subsidy_Dependence=~RMA_revised_total_indem_2012 + NRCS_EQIP_FA_PAYMENTS_total + NRCS_CStP_FA_Payments_total
Input_Costs=~FARMCOSTS_Chemicals_1000Doll_2012 + FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012 + FARMCOSTS_FeedExpenses_1000Dolls_2012 + FARMCOSTS_Property_taxes_paid_1000Dolls_2012
Land_Costs=~RENT_average + RENT_Percent.rented.2012 + FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012 + FARMCOSTS_Interest_Expenses_1000Dolls_2012
Equipment_Services=~FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012 + FARMCOSTS_Utilities_expenses_1000Dolls_2012 + FARMCOSTS_Depreciation_expenses_1000Doll_2012 + FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012 + FARMCOSTS_hired_labor_expenses_1000Dolls_2012 + FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012 + FARMCOSTS_ContractLaborExpense_1000Doll_2012
Input_Dependence=~Input_Costs + Land_Costs + Equipment_Services
#regressions
CDI_2012~Water_Stress + Water_Surplus
Gov_Subsidy_Dependence~Input_Dependence
AGCENSUS_Notill_Ratio_transformed~CDI_2012 + Gov_Subsidy_Dependence + Water_Stress + Water_Surplus + HDI_Health.Index + HDI_Income.Index + HDI_Education.Index +
RACE_Entropy + FEMALE_percent_female + RMA_revised_loss_cost
#covariance
HDI_Health.Index ~~ HDI_Income.Index
HDI_Health.Index ~~ HDI_Education.Index
HDI_Income.Index ~~ HDI_Education.Index
Water_Stress ~~ Water_Surplus
RACE_Entropy ~~ FEMALE_percent_female
RMA_revised_total_indem_2012 ~~ RMA_revised_loss_cost
'
fitmodel50<-sem(model50, data=soilscaled)
summary(fitmodel50,fit.measures=T,standardized=T)
#CFA with each latent factor
#Water Stress with loss
model51<-'Water_Stress=~PDSI_TOTALS + RMA_revised_loss_cost_hot_dry'
fitmodel51<-cfa(model51, data=soilscaled)
summary(fitmodel51,fit.measures=T)
waterstressscaled<-soilscaled[c("PDSI_TOTALS","RMA_revised_loss_cost_hot_dry")]
waterstressscaledcor<-cor(waterstressscaled, use="complete.obs")
waterstressscaledcor
#Water stress with loss ratio
model52<-'Water_Stress=~PDSI_TOTALS + RMA_revised_mean_loss_ratio_hot_dry'
fitmodel52<-cfa(model52, data=soilscaled)
summary(fitmodel52,fit.measures=T)
waterstressscaled<-soilscaled[c("PDSI_TOTALS","RMA_revised_mean_loss_ratio_hot_dry")]
waterstressscaledcor<-cor(waterstressscaled, use="complete.obs")
waterstressscaledcor
#Water surplus with loss
model53<-'Water_Surplus=~PRECIP_max + RMA_revised_loss_cost_wet'
fitmodel53<-cfa(model53, data=soilscaled)
summary(fitmodel53,fit.measures=T)
watersurplusscaled<-soilscaled[c("PRECIP_max","RMA_revised_loss_cost_wet")]
watersurplusscaledcor<-cor(watersurplusscaled, use="complete.obs")
watersurplusscaledcor
#Water surplus with loss ratio
model54<-'Water_Surplus=~PRECIP_max + RMA_revised_mean_loss_ratio_wet'
fitmodel54<-cfa(model54, data=soilscaled)
summary(fitmodel54,fit.measures=T)
watersurplusscaled<-soilscaled[c("PRECIP_max","RMA_revised_mean_loss_ratio_wet")]
watersurplusscaledcor<-cor(watersurplusscaled, use="complete.obs")
watersurplusscaledcor
#Government Subsidy Dependence
model55<-'Gov_Subsidy_Dependence=~RMA_revised_total_indem_2012 + NRCS_EQIP_FA_PAYMENTS_total + NRCS_CStP_FA_Payments_total'
fitmodel55<-cfa(model55, data=soilscaled)
summary(fitmodel55,fit.measures=T)
govsubscaled<-soilscaled[c("RMA_revised_total_indem_2012","NRCS_EQIP_FA_PAYMENTS_total","NRCS_CStP_FA_Payments_total")]
govsubscaledcor<-cor(govsubscaled, use="complete.obs")
govsubscaledcor
#Input costs
model56<-'Input_Costs=~FARMCOSTS_Chemicals_1000Doll_2012 + FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012 + FARMCOSTS_FeedExpenses_1000Dolls_2012 + FARMCOSTS_Property_taxes_paid_1000Dolls_2012'
fitmodel56<-cfa(model56, data=soilscaled)
summary(fitmodel56,fit.measures=T)
#Land costs
model57<-'Land_Costs=~RENT_average + RENT_Percent.rented.2012 + FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012 + FARMCOSTS_Interest_Expenses_1000Dolls_2012'
fitmodel57<-cfa(model57,data=soilscaled)
summary(fitmodel57,fit.measures=T)
landcostsscaled<-soilscaled[c("RENT_average","RENT_Percent.rented.2012","FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012","FARMCOSTS_Interest_Expenses_1000Dolls_2012")]
landcostsscaledcor<-cor(landcostsscaled, use="complete.obs")
landcostsscaledcor
#modify land costs to remove percent rented land
model58<-'Land_Costs=~RENT_average + FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012 + FARMCOSTS_Interest_Expenses_1000Dolls_2012'
fitmodel58<-cfa(model58,data=soilscaled)
summary(fitmodel58,fit.measures=T)
#Equipment services
model59<-'Equipment_Services=~FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012 + FARMCOSTS_Utilities_expenses_1000Dolls_2012 + FARMCOSTS_Depreciation_expenses_1000Doll_2012 + FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012 + FARMCOSTS_hired_labor_expenses_1000Dolls_2012 + FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012 + FARMCOSTS_ContractLaborExpense_1000Doll_2012'
fitmodel59<-cfa(model59,data=soilscaled)
summary(fitmodel59,fit.measures=T)
#Input dependence
model60<-'
Input_Costs=~FARMCOSTS_Chemicals_1000Doll_2012 + FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012 + FARMCOSTS_FeedExpenses_1000Dolls_2012 + FARMCOSTS_Property_taxes_paid_1000Dolls_2012
Land_Costs=~RENT_average + FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012 + FARMCOSTS_Interest_Expenses_1000Dolls_2012
Equipment_Services=~FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012 + FARMCOSTS_Utilities_expenses_1000Dolls_2012 + FARMCOSTS_Depreciation_expenses_1000Doll_2012 + FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012 + FARMCOSTS_hired_labor_expenses_1000Dolls_2012 + FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012 + FARMCOSTS_ContractLaborExpense_1000Doll_2012
Input_Dependence=~Input_Costs + Land_Costs + Equipment_Services'
fitmodel60<-cfa(model60,data=soilscaled)
summary(fitmodel60,fit.measures=T)
##Water stress, water surplus and government subsidies don't hang together##
##Updated input costs, equipment costs and land costs - latent construct not great##
#newer model - RES and GRM
model62<-'
#latent variables
Input_Costs=~FARMCOSTS_Chemicals_1000Doll_2012 + FARMCOSTS_Fert_lime_soilcond_purchased_1000dolls_2012 + FARMCOSTS_FeedExpenses_1000Dolls_2012 + FARMCOSTS_Property_taxes_paid_1000Dolls_2012
Land_Costs=~RENT_average + FARMCOSTS_cashrent_land_building_pasture_1000Doll_2012 + FARMCOSTS_Interest_Expenses_1000Dolls_2012
Equipment_Services=~FARMCOSTS_gas_fuel_oil_purchased_1000Dolls_2012 + FARMCOSTS_Utilities_expenses_1000Dolls_2012 + FARMCOSTS_Depreciation_expenses_1000Doll_2012 + FARMCOSTS_rent_lease_machinery_equipment_Expense_1000Dolls_2012 + FARMCOSTS_hired_labor_expenses_1000Dolls_2012 + FARMCOSTS_Customwork_hauling_expenses_1000Doll_2012 + FARMCOSTS_ContractLaborExpense_1000Doll_2012
#regressions
CDI_2012~ RMA_revised_loss_cost_hot_dry + RMA_revised_loss_cost_wet
RMA_revised_total_indem_2012~Input_Costs + Land_Costs + Equipment_Services
NRCS_EQIP_cstp_combined~Input_Costs + Land_Costs + Equipment_Services
AGCENSUS_Cover_Acres_Ratio_transformed~CDI_2012 + NRCS_EQIP_cstp_combined + RMA_revised_total_indem_2012 + PDSI_TOTALS + RMA_revised_loss_cost_hot_dry + PRECIP_max + RMA_revised_loss_cost_wet + HDI_Health.Index + HDI_Income.Index + HDI_Education.Index +
RACE_Entropy + FEMALE_percent_female
#covariance
HDI_Health.Index ~~ HDI_Income.Index
HDI_Health.Index ~~ HDI_Education.Index
HDI_Income.Index ~~ HDI_Education.Index
RMA_revised_total_indem_2012 ~~ RMA_revised_loss_cost_hot_dry
RMA_revised_total_indem_2012 ~~ RMA_revised_loss_cost_wet
RMA_revised_loss_cost_hot_dry ~~ RMA_revised_loss_cost_wet
RACE_Entropy ~~ FEMALE_percent_female
Input_Costs ~~ Land_Costs
Input_Costs ~~ Equipment_Services
Land_Costs ~~ Equipment_Services'
fitmodel62<-sem(model62,data=soilscaled)
summary(fitmodel62, fit.measures=T, standardized=T)
semPlot::semPaths(fitmodel62, "std", bifactor = "g", fade = FALSE, style = "lisrel", label.cex = 3, nCharNodes = 10, what = "std", layout="tree", curvePivot = TRUE, edge.label.cex=.85)
summary(fitmodel62, fit.measures = TRUE)
<file_sep>/SHEAF_model_data_creation.R
#--SHEAF_eda_model_data_creation.R
#--loads some data, subsets and merges,and outputs a file to Model_data folder.
#--Then this dataset can be used in SEM model analysis
# Initial regional analysis is for Illinois, Indiana, Iowa, Michigan, Minnesota, Missouri, Ohio, and Wisconsin
#--author: <NAME>, University of Idaho
#--updated: August 2019
#
#
library(rgdal)
library(leaflet)
library(maptools)
library(classInt)
library(leaflet)
library(dplyr)
library(Hmisc)
library(RColorBrewer)
library(raster)
library (RCurl)
library(maptools)
library(tidyr)
library(plyr)
library(maps)
arrange.vars <- function(data, vars){
##stop if not a data.frame (but should work for matrices as well)
stopifnot(is.data.frame(data))
##sort out inputs
data.nms <- names(data)
var.nr <- length(data.nms)
var.nms <- names(vars)
var.pos <- vars
##sanity checks
stopifnot( !any(duplicated(var.nms)),
!any(duplicated(var.pos)) )
stopifnot( is.character(var.nms),
is.numeric(var.pos) )
stopifnot( all(var.nms %in% data.nms) )
stopifnot( all(var.pos > 0),
all(var.pos <= var.nr) )
##prepare output
out.vec <- character(var.nr)
out.vec[var.pos] <- var.nms
out.vec[-var.pos] <- data.nms[ !(data.nms %in% var.nms) ]
stopifnot( length(out.vec)==var.nr )
##re-arrange vars by position
data <- data[ , out.vec]
return(data)
}
#alter this list to subset RMA data for only particular commodities. Also changes the model file output name
#and includes these commodities in the string
croplist <- list("CORN", "SOYBEANS")
options(scipen=999)
#CAPITIALIZATION FUNCTION
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
#ADD FIPS
statefips <- read.csv("https://files.sesync.org/index.php/s/HpxsTFNqzZn7XRt/download")
statefips$StateFips <- sprintf("%02d", statefips$StateFips)
#ADD NRI
nri_tfact <- read.csv("https://nextcloud.sesync.org/index.php/s/ESranGDWaMcyDNj/download", strip.white=TRUE)
nri_tfact <- read.csv("https://nextcloud.sesync.org/index.php/s/ESranGDWaMcyDNj/download", strip.white=TRUE)
nri_tfact$Year <- c("2015")
nri_prime <- read.csv("https://nextcloud.sesync.org/index.php/s/YQCjJzwztpSfwpe/download", strip.white=TRUE)
nri_lcc <- read.csv("https://nextcloud.sesync.org/index.php/s/RGb2eKkZtLpQ7X9/download", strip.white=TRUE)
nri_irr <- read.csv("https://nextcloud.sesync.org/index.php/s/8EwQkxxsXa6XaRb/download", strip.white=TRUE)
nri_eros <- read.csv("https://nextcloud.sesync.org/index.php/s/R8aASsxtMbiebYr/download", strip.white=TRUE)
nri_dbl <- read.csv("https://nextcloud.sesync.org/index.php/s/tnge8GngoS2ozKg/download", strip.white=TRUE)
nri_crpcov <- read.csv("https://nextcloud.sesync.org/index.php/s/GKroT2c8kRmHBPX/download", strip.white=TRUE)
nri_brd <- read.csv("https://nextcloud.sesync.org/index.php/s/CedCm5X2PR6T37x/download", strip.white=TRUE)
nri_combined <- Reduce(function(x,y) merge(x = x, y = y, by = c("State", "County", "Year", "Fips"), all = TRUE),
list(nri_tfact, nri_prime, nri_lcc, nri_irr, nri_eros, nri_dbl, nri_crpcov, nri_brd))
#subset nri for only midwest states
nri <- subset(nri_combined, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#remove Fips column
#nri <- subset( nri, select = -Fips )
nri <- subset(nri, Year == 2012)
#---
#AGCENSUS
#agcensus load via url - best if you are NOT on SESYNC rstudio server
agcensus <- read.csv("https://nextcloud.sesync.org/index.php/s/SFiSow3f4aSTdCK/download")
#agcensus load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/agcensus")
#agcensus <- read.csv("Agcensus2012.csv")
#agcensus_metadata <- read.csv("Agcensus2012_metadata.csv")
#removes ancillary columns at the end of the agcensus
agcensus <- agcensus[,1:25]
#AGCENSUS CHANGE COLUMN NAMES, FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
colnames(agcensus)[3] <- "State"
colnames(agcensus)[2] <- "Year"
colnames(agcensus)[4] <- "County"
agcensus$State <- tolower(agcensus$State)
agcensus$State <- sapply(agcensus$State, simpleCap)
agcensus$County <- tolower(agcensus$County)
agcensus$County <- sapply(agcensus$County, simpleCap)
agcensus <- merge(agcensus, statefips, by=("State"))
agcensus$CountyFips <- sprintf("%03d", agcensus$CountyFips)
agcensus$Fips <- paste(agcensus$StateFips, agcensus$CountyFips, sep="")
#subset only to midwest states
agcensus <- subset(agcensus, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#AGCENSUS AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
agcensus <- aggregate(cbind(agcensus$tile_farms, agcensus$tile_acres, agcensus$tile_acres_avgfarm, agcensus$ditches_farms,
agcensus$ditches_acres, agcensus$ditches_acres_avgfarm, agcensus$consease_farms, agcensus$consease_acres,
agcensus$consease_avgfarm, agcensus$notill_farms, agcensus$notill_acres, agcensus$notill_avgfarm,
agcensus$constill_farms, agcensus$constill_acres, agcensus$constill_avgfarm, agcensus$convtill_farms,
agcensus$convtill_acres, agcensus$convtill_acres.1, agcensus$cc_farms, agcensus$cc_acres,
agcensus$cc_avgfarm), by=list(agcensus$Year, agcensus$Fips), FUN = "sum")
colnames(agcensus) <- c("Year", "Fips", "tile_farms", "tile_acres",
"tile_acres_avgfarm", "ditches_farms", "ditches_acres", "ditches_acres_avgfarm", "consease_farms", "consease_acres",
"consease_avgfarm", "notill_farms", "notill_acres", "notill_avgfarm", "constill_farms", "constill_acres",
"constill_avgfarm", "convtill_farms", "convtill_acres", "convtill_acres.1", "cc_farms", "cc_acres",
"cc_avgfarm")
#EQIP
#eqip load via url - best if you are NOT on SESYNC rstudio server
eqip <- read.csv("https://nextcloud.sesync.org/index.php/s/os5ZxFXAAEgc2y4/download")
#eqip load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/eqip")
#eqip <- read.csv("eqip.csv")
#converts to lower case and then caps the first letters of words
eqip$County <- tolower(eqip$County)
eqip$County <- sapply(eqip$County, simpleCap)
eqip$Fips <- sprintf("%05d", eqip$county_code)
#EQIP SUBSET TO ONLY STUDY AREA
eqip <- subset(eqip, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#EQIP AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
eqip <- aggregate(eqip$Dollars.Paid, by=list(eqip$Fips, eqip$Applied.Amount, eqip$Applied.Year, eqip$practice_name), FUN = "sum")
colnames(eqip) <- c("Fips", "Applied.Amount", "Year", "Practice_Name", "Dollars_Paid")
eqip$id <- seq_len(nrow(eqip))
library(reshape2) ; eqip <- dcast(eqip, Fips + Year ~ Practice_Name, value.var = "Dollars_Paid", sum)
eqip <- subset(eqip, Year == 2012)
#eqip <- spread(eqip, Practice_Name, Dollars_Paid)
#eqip load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/eqip")
#eqip <- read.csv("eqip.csv")
#EQIP-CSP
eqip_csp_revised <- read.csv("https://files.sesync.org/index.php/s/JQysQDBmLMcfrGd/download")
eqip_csp_revised$Fips <- sprintf("%05d", eqip_csp_revised$county_code)
eqip_csp_revised_2010_2012 <- subset(eqip_csp_revised, fy == 2010 | fy == 2011 | fy == 2012)
eq_eqip_fa <- aggregate(eqip_csp_revised_2010_2012$EQIP_FA_PAYMENTS, by=list(eqip_csp_revised_2010_2012$Fips), FUN = "sum" )
eq_cstp <- aggregate(eqip_csp_revised_2010_2012$CStP_FA_Payments, by=list(eqip_csp_revised_2010_2012$Fips), FUN = "sum" )
colnames(eq_eqip_fa) <- c("Fips", "EQIP_FA_PAYMENTS_total")
colnames(eq_cstp) <- c("Fips", "CStP_FA_Payments_total")
eq_combined <- cbind(eq_eqip_fa, eq_cstp[,2])
colnames(eq_combined) <- c("Fips", "EQIP_FA_PAYMENTS_total", "CStP_FA_Payments_total")
eq_combined[is.na(eq_combined)] <- 0
eq_combined$EQIP_cstp_combined <- eq_combined$EQIP_FA_PAYMENTS_total + eq_combined$CStP_FA_Payments_total
eq_combined <- merge(eq_combined, countyFIPS, by = "Fips")
eq_combined <- subset(eq_combined, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
eq_combined <- eq_combined[-(5:7)]
#eq_combined$County <- tolower(eq_combined$County)
#eq_combined$County <- sapply(eq_combined$County, simpleCap)
#eqip_csp <- read.csv("https://files.sesync.org/index.php/s/5Rjpp4z5xe7KCC8/download")
#eqip_csp$County <- tolower(eqip_csp$County)
#eqip_csp$County <- sapply(eqip_csp$County, simpleCap)
#eqip_csp <- eqip_csp[,2:8]
#remove extraneous columns other that state, year, county, and variables
#eqip_csp <- cbind.data.frame(eqip_csp[,4], eqip_csp[,6], eqip_csp[,7:10])
#colnames(eqip_csp) <- c("Year", "State", "County", "EQIP_CSP_Contracts", "EQIP_CSP_CONTRACT_ACRES", "EQIP_CSP_FA_OBLIGATIONS", "EQIP_CSP_FA_PAYMENTS" )
#EQIP-Cons-security
#eqip_cons_security <- read.csv("https://files.sesync.org/index.php/s/ZsX6SYFmc8Tsr77/download")
#eqip_cons_security$County <- tolower(eqip_cons_security$County)
#eqip_cons_security$County <- sapply(eqip_cons_security$County, simpleCap)
#eqip_cons_security <- eqip_cons_security[,2:8]
#EQIP-Cons-stewardship
#eqip_cons_steward <- read.csv("https://files.sesync.org/index.php/s/oHnCkS5sDFgX44c/download")
#eqip_cons_steward$County <- tolower(eqip_cons_steward$County)
#eqip_cons_steward$County <- sapply(eqip_cons_steward$County, simpleCap)
#eqip_cons_steward <- eqip_cons_steward[,2:8]
#CENSUS
#census load - best if you are NOT on SESYNC rstudio server
census <- read.csv("https://nextcloud.sesync.org/index.php/s/tnEESyD34JFoNLf/download")
#census load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/census")
#census <- read.csv("Census_States_CountyDem.csv")
#CENSUS FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
census$State <- tolower(census$State)
census$State <- sapply(census$State, simpleCap)
census$County <- tolower(census$County)
census$County <- sapply(census$County, simpleCap)
census$State.ANSI <- sprintf("%02d", census$State.ANSI)
census$County.ANSI <- sprintf("%03d", census$County.ANSI)
census$Fips <- paste(census$State.ANSI, census$County.ANSI, sep="")
#subsets to midwest
census <- subset(census, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
census$Value <- as.numeric(census$Value)
#CENSUS AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
census <- aggregate(census$Value, by=list(census$Fips, census$Year, census$Data.Item), FUN = "sum")
colnames(census) <- c("Fips", "Year", "census_Grouping", "census_Value")
#reshapes so census groupings are actually columns with their aggregated values as observations - by state, county and year
library(reshape2) ; census <- dcast(census, Fips + Year ~ census_Grouping, value.var = "census_Value", sum)
census <- subset(census, Year == 2012)
#census <- spread(census, census_Grouping, census_Value)
#census load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/census")
#census <- read.csv("Census_States_CountyDem.csv")
#RMA COMMODITY
countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
colnames(countyFIPS) <- c("ID", "State", "County", "Fips")
countyFIPS$Fips <- sprintf("%05d",countyFIPS$Fips)
#RMA by commodity and damage cause, includes claim counts
commodity <- read.csv("https://nextcloud.sesync.org/index.php/s/zFwyd64NZJEyrgr/download")
#commodity load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/RMA/RMA_csvfiles")
#commodity <- read.csv("RMA_combined.csv")
colnames(commodity) <- c("ID", "Year", "State", "County", "Commodity", "Loss", "Count", "Acres", "Lossperacre", "Lossperclaim", "Acresperclaim")
commodity$State <- state.name[match(commodity$State,state.abb)]
commodity <- merge(commodity, countyFIPS, by=c("State", "County"))
#RMA COMMODITY FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
commodity <- subset(commodity, State == "Illinois" | State == "Indiana" | State == "Iowa" |
State == "Michigan" | State == "Minnesota" | State == "Missouri" |
State == "Ohio" | State == "Wisconsin" | State =="Nebraska" | State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#colnames(commodity) <- c("ID", "Year", "State", "County", "Commodity", "Loss_commodity", "Count_commodity")
commodity_loss_total <- aggregate(list(commodity$Acres, commodity$Loss, commodity$Lossperacre, commodity$Lossperclaim, commodity$Acresperclaim, commodity$Count), by = list(commodity$Fips, commodity$Year), FUN ="sum")
colnames(commodity_loss_total) <- c("Fips", "Year", "RMA_Acres", "RMA_Loss", "RMA_Lossperacre", "RMA_Lossperclaim", "RMA_Acresperclaim", "RMA_Count")
commodity_loss_total <- subset(commodity_loss_total, Year == 2012)
#RMA DAMAGE
#RMA by damage cause, includes claim counts
damage <- read.csv("https://nextcloud.sesync.org/index.php/s/W5kztdb5ZkxRptT/download")
#damage load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/RMA/")
#damage <- read.csv("RMA_damage_combined.csv", strip.white=TRUE)
colnames(damage) <- c("ID", "Year", "State", "County", "Commodity", "Damagecause", "Loss", "Count", "Acres", "Lossperacre", "Lossperclaim", "Acresperclaim")
damage$State <- state.name[match(damage$State,state.abb)]
damage <- merge(damage, countyFIPS, by=c("State", "County"))
#RMA DAMAGE FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
damage <- subset(damage, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#colnames(damage) <- c("ID", "Year", "State", "County", "Commodity", "Damagecause", "Loss_damagecause", "Count_damagecause")
#damage <- aggregate(damage$Loss, by=list(damage$Commodity, damage$Damagecause, damage$County, damage$State, damage$Year), FUN = "sum")
#colnames(damage) <- c("Commodity", "Damagecause", "County", "State", "Year", "Loss")
#creates four variations of loss outputs - total loss, lossperacres, loss per claim, and acreage
library(reshape2) ; damage_Loss <- dcast(damage, Fips + Year + Commodity ~ Damagecause, value.var = c("Loss"), sum)
library(reshape2) ; damage_Lossperacre <- dcast(damage, Fips + Year + Commodity ~ Damagecause, value.var = c("Lossperacre"), sum)
library(reshape2) ; damage_Lossperclaim <- dcast(damage, Fips + Year + Commodity ~ Damagecause, value.var = c("Lossperclaim"), sum)
library(reshape2) ; damage_Acres <- dcast(damage, Fips + Year + Commodity ~ Damagecause, value.var = c("Acres"), sum)
#damage <- spread(damage, Damagecause, Loss_damagecause)
#subset for only commodities in croplist - set in beginning of script
crop_damage_Acres <- subset(damage_Acres, Commodity == croplist)
crop_damage_Loss <- subset(damage_Loss, Commodity == croplist)
crop_damage_Lossperacre <- subset(damage_Lossperacre, Commodity == croplist)
crop_damage_Lossperclaim <- subset(damage_Lossperclaim, Commodity == croplist)
#aggregates each by state and county and year
crop_damage_Acres <- aggregate(crop_damage_Acres[,4:37], by = list(crop_damage_Acres$Fips, crop_damage_Acres$Year), FUN = 'sum' )
colnames(crop_damage_Acres)[1:2] <- c("Fips", "Year")
crop_damage_Loss <- aggregate(crop_damage_Loss[,4:37], by = list(crop_damage_Loss$Fips, crop_damage_Loss$Year), FUN = 'sum' )
colnames(crop_damage_Loss)[1:2] <- c("Fips", "Year")
crop_damage_Lossperacre <- aggregate(crop_damage_Lossperacre[,4:37], by = list(crop_damage_Lossperacre$Fips, crop_damage_Lossperacre$Year), FUN = 'sum' )
colnames(crop_damage_Lossperacre)[1:2] <- c("Fips", "Year")
crop_damage_Lossperclaim <- aggregate(crop_damage_Lossperclaim[,4:37], by = list(crop_damage_Lossperclaim$Fips, crop_damage_Lossperclaim$Year), FUN = 'sum' )
colnames(crop_damage_Lossperclaim)[1:2] <- c("Fips", "Year")
crop_damage_Acres <- subset(crop_damage_Acres, Year == 2012)
crop_damage_Loss <- subset(crop_damage_Loss, Year == 2012)
crop_damage_Lossperacre <- subset(crop_damage_Lossperacre, Year == 2012)
crop_damage_Lossperclaim <- subset(crop_damage_Lossperclaim, Year == 2012)
#countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
#countyFIPS$FIPS <- sprintf("%05d",countyFIPS$FIPS)
#LANDUSE CORN BELT!
ag_land_corn_IN <- read.csv("https://files.sesync.org/index.php/s/G9gPNofZSgQHK7y/download")
colnames(ag_land_corn_IN) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_IN$Acres <- as.numeric(ag_land_corn_IN$Acres)
ag_land_corn_IA <- read.csv("https://files.sesync.org/index.php/s/fBjo8rScMqgb7w9/download")
colnames(ag_land_corn_IA) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_IA$Acres <- as.numeric(ag_land_corn_IA$Acres)
ag_land_corn_IL <- read.csv("https://files.sesync.org/index.php/s/nasXnagFAMC5Lio/download")
colnames(ag_land_corn_IL) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_IL$Acres <- as.numeric(ag_land_corn_IL$Acres)
ag_land_corn_MN <- read.csv("https://files.sesync.org/index.php/s/FFcwPBdc5nGJLmE/download")
colnames(ag_land_corn_MN) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_MN$Acres <- as.numeric(ag_land_corn_MN$Acres)
ag_land_corn_MI <- read.csv("https://files.sesync.org/index.php/s/kJbR3GtGyHiLr8L/download")
colnames(ag_land_corn_MI) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_MI$Acres <- as.numeric(ag_land_corn_MI$Acres)
ag_land_corn_KS <- read.csv("https://files.sesync.org/index.php/s/8r8yPptfAKWm7kj/download")
colnames(ag_land_corn_KS) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_KS$Acres <- as.numeric(ag_land_corn_KS$Acres)
ag_land_corn_NE <- read.csv("https://files.sesync.org/index.php/s/c5wXofrWryXXfjd/download")
colnames(ag_land_corn_NE) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_NE$Acres <- as.numeric(ag_land_corn_NE$Acres)
ag_land_corn_MO <- read.csv("https://files.sesync.org/index.php/s/6Q4NNxETBBwPdQ5/download")
colnames(ag_land_corn_MO) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_MO$Acres <- as.numeric(ag_land_corn_MO$Acres)
ag_land_corn_WI <- read.csv("https://files.sesync.org/index.php/s/NCNmpLBP2nQLN8Q/download")
colnames(ag_land_corn_WI) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_WI$Acres <- as.numeric(ag_land_corn_WI$Acres)
ag_land_corn_SD <- read.csv("https://files.sesync.org/index.php/s/3YtXDXTkEELNGXB/download")
colnames(ag_land_corn_SD) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_SD$Acres <- as.numeric(ag_land_corn_SD$Acres)
ag_land_corn_OH <- read.csv("https://files.sesync.org/index.php/s/mtQmqa2EmXXP9Ai/download")
colnames(ag_land_corn_OH) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_OH$Acres <- as.numeric(ag_land_corn_OH$Acres)
ag_land_corn_ND <- read.csv("https://files.sesync.org/index.php/s/Gf5JWTjAX92JxTr/download")
colnames(ag_land_corn_ND) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_ND$Acres <- as.numeric(ag_land_corn_ND$Acres)
ag_land_corn_merged <- rbind(ag_land_corn_IN, ag_land_corn_IA, ag_land_corn_IL, ag_land_corn_MN, ag_land_corn_MI, ag_land_corn_KS, ag_land_corn_NE, ag_land_corn_MO, ag_land_corn_WI, ag_land_corn_SD, ag_land_corn_OH, ag_land_corn_ND)
colnames(ag_land_corn_merged) <- c("StateFips", "CountyFips", "StateCountyName", "Description", "Acres")
ag_land_corn_merged$StateCountyName <- as.character(ag_land_corn_merged$StateCountyName)
ag_land_corn_merged$Acres <- as.numeric(ag_land_corn_merged$Acres)
ag_land_corn_merged$StateFips <- sprintf("%02d", ag_land_corn_merged$StateFips)
ag_land_corn_merged$CountyFips <- sprintf("%03d", ag_land_corn_merged$CountyFips)
ag_land_corn_merged$FIPS <- paste(ag_land_corn_merged$StateFips, ag_land_corn_merged$CountyFips, sep="")
alc_new <- cbind(ag_land_corn_merged[,4:6])
AGCENSUS_county_covercrop_acres <- subset(alc_new, Description == "Land planted to a cover crop (excluding CRP), Acres, 2012")
colnames(AGCENSUS_county_covercrop_acres) <- c("Description", "Cover_Acres", "Fips")
AGCENSUS_county_covercrop_acres <- cbind.data.frame(AGCENSUS_county_covercrop_acres[,2:3])
AGCENSUS_county_notill_acres <- subset(alc_new, Description == "Land on which no-till practices were used, Acres, 2012")
colnames(AGCENSUS_county_notill_acres) <- c("Description", "Notill_Acres", "Fips")
AGCENSUS_county_notill_acres <- cbind.data.frame(AGCENSUS_county_notill_acres[,2:3])
AGCENSUS_county_conservationtill_acres <- subset(alc_new, Description == "Land on which conservation tillage was used, Acres, 2012")
colnames(AGCENSUS_county_conservationtill_acres) <- c("Description", "Conservationtill_Acres", "Fips")
AGCENSUS_county_conservationtill_acres <- cbind.data.frame(AGCENSUS_county_conservationtill_acres[,2:3])
AGCENSUS_county_conventionaltill_acres <- subset(alc_new, Description == "Land on which conventional tillage was used, Acres, 2012")
colnames(AGCENSUS_county_conventionaltill_acres) <- c("Description", "Conventionaltill_Acres", "Fips")
AGCENSUS_county_conventionaltill_acres <- cbind.data.frame(AGCENSUS_county_conventionaltill_acres[,2:3])
AGCENSUS_ac1 <- cbind.data.frame(AGCENSUS_county_covercrop_acres, AGCENSUS_county_notill_acres, AGCENSUS_county_conservationtill_acres, AGCENSUS_county_conventionaltill_acres )
AGCENSUS_ac2 <- cbind.data.frame(AGCENSUS_ac1[,1], AGCENSUS_ac1[,3], AGCENSUS_ac1[,5], AGCENSUS_ac1[,7:8])
colnames(AGCENSUS_ac2) <- c("Cover_Acres", "Notill_Acres", "Conservationtill_Acres", "Conventionaltill_Acres", "Fips")
#total cropland acres
totalcropland <- read.csv("https://files.sesync.org/index.php/s/Ly4TyC3RipXdkSG/download")
totalcropland$state_fips_code <- sprintf("%02d", totalcropland$state_fips_code)
totalcropland$county_code <- sprintf("%03d", totalcropland$county_code)
totalcropland$Fips <- paste(totalcropland$state_fips_code, totalcropland$county_code, sep="")
totalcropland <- cbind.data.frame(totalcropland[,13], totalcropland[,21], totalcropland[,41])
colnames(totalcropland) <- c("Year", "Cropland_Acres", "Fips")
totalcropland$Cropland_Acres <- as.numeric(gsub(",","",totalcropland$Cropland_Acres))
totalcropland <- subset(totalcropland, Year == 2012)
totalcropland <- merge(totalcropland, countyFIPS, by = "Fips")
totalcropland <- subset(totalcropland, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
totalcropland <- totalcropland[-(4:6)]
#alc_new <- aggregate(ag_land_corn_merged$Acres, by=list(ag_land_corn_merged$StateCountyName), FUN = "sum")
#ag_land_corn <- read.csv("https://nextcloud.sesync.org/index.php/s/P92Df7gYgXKjYXa/download")
#colnames(ag_land_corn) <- c("FIPS", "countycode", "row", "column", "type", "State", "Statecode", "label", "County", "cpubval", "Cropland_Acres", "Percent")
#ag_land_corn$Cropland_Acres <- as.numeric(as.character(ag_land_corn$Cropland_Acres))
#ag_land_corn2 <- subset(ag_land_corn, Cropland_Acres != "NA")
#alc <- merge(ag_land_corn2, countyFIPS, by = "FIPS")
#takes the mean of cropland_acres across all practices by state, county
#alc2 <- aggregate(alc$Cropland_Acres, by = list(alc$STATE_NAME, alc$NAME, alc$FIPS), FUN = 'mean')
#colnames(alc2) <- c("State", "County", "FIPS", "AGCENSUS_Cropland_Acres")
#alc2$FIPS <- sprintf("%05d",alc2$FIPS)
#climate - pdsi
pdsi_moderate_drought_2007_2012 <- read.csv("https://nextcloud.sesync.org/index.php/s/TYa9pBNQHBc4efj/download")
colnames(pdsi_moderate_drought_2007_2012) <- c("ID", "2007", "2008", "2009", "2010", "2011", "2012", "Fips")
#merges pdsi to fips
#pdsi <- merge(pdsi_moderate_drought_2007_2012, countyFIPS, by = "Fips")
pdsi <- pdsi_moderate_drought_2007_2012
#sums the number of days of moderate to extreme drought (-2 or below) for 2007 to 2012
pdsi$PDSI_TOTALS <- rowSums(pdsi[,c("2007","2008","2009","2010","2011", "2012" )])
#removes extraneous columns so we only have state and county and PDSI totals
pdsi <- pdsi[,8:9]
colnames(pdsi) <- c("Fips", "PDSI_TOTALS")
pdsi <- merge(pdsi, countyFIPS, by = "Fips")
pdsi <- subset(pdsi, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
pdsi <- pdsi[-(3:5)]
#female operators
femaleop <- read.csv("https://files.sesync.org/index.php/s/fZLfsteAExAg5PJ/download")
femaleop <- subset(femaleop, Year == "2012")
femaleop <- femaleop[-1]
femaleop <- femaleop[-3]
femaleop <- merge(femaleop, countyFIPS, by=c("State", "County"))
femaleop <- cbind.data.frame(femaleop[,3:5], femaleop[,7])
colnames(femaleop) <- c("all_operators", "female_operators", "percent_female", "Fips")
femaleop <- merge(femaleop, countyFIPS, by = "Fips")
femaleop <- subset(femaleop, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
femaleop <- femaleop[-(5:7)]
#diversity index
racediversity <- read.csv("https://files.sesync.org/index.php/s/a2Hrd75kAeTWNaD/download")
colnames(racediversity) <- c("ID", "entropy", "Fips", "Year")
racediversity <- subset(racediversity, Year == "2012")
racediversity$Fips <- as.character(racediversity$Fips)
#racediversity <- merge(countyFIPS, racediversity, by=c("FIPS"))
racediversity <- cbind.data.frame(racediversity[,2], racediversity[,3])
colnames(racediversity) <- c("RACE_Entropy", "Fips")
racediversity <- merge(racediversity, countyFIPS, by = "Fips")
racediversity <- subset(racediversity, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#
#
#HDI
HDI <- read.csv("https://files.sesync.org/index.php/s/FGn3SZsZj7cLGEB/download")
HDI$County <- gsub( " County", "", as.character(HDI$County))
HDI <- HDI[-1]
HDI <- HDI[-4]
HDI <- HDI[-3]
HDI <- merge(HDI, countyFIPS, by=c("State", "County"))
HDI <- cbind.data.frame(HDI[,3:6], HDI[,8])
colnames(HDI) <- c("Health.Index", "Education.Index", "Income.Index", "WB.Index", "Fips")
HDI <- merge(HDI, countyFIPS, by = "Fips")
HDI <- subset(HDI, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
HDI <- HDI[-(6:8)]
#farmproductioncosts
FARMCOSTS <- read.csv("https://files.sesync.org/index.php/s/cK5Xgp7Axqx3zs6/download")
#FARMCOSTS <- FARMCOSTS[-1]
FARMCOSTS$long_state <- as.character(FARMCOSTS$long_state)
FARMCOSTS$county <- as.character(FARMCOSTS$county)
FARMCOSTS$State <- sapply(FARMCOSTS$long_state, simpleCap)
FARMCOSTS$County <- sapply(FARMCOSTS$county, simpleCap)
FARMCOSTS <- FARMCOSTS[-68]
FARMCOSTS <- FARMCOSTS[-68]
FARMCOSTS <- FARMCOSTS[-68]
FARMCOSTS <- FARMCOSTS[-68]
FARMCOSTS <- FARMCOSTS[-68]
FARMCOSTS <- FARMCOSTS[-69]
#FARMCOSTS <- merge(FARMCOSTS, countyFIPS, by=c("State", "County"))
#FARMCOSTS <- cbind.data.frame(FARMCOSTS[,3:69], FARMCOSTS[,71])
colnames(FARMCOSTS)[1] <- "Fips"
#FARMCOSTS <- merge(FARMCOSTS, countyFIPS, by = "Fips")
FARMCOSTS <- subset(FARMCOSTS, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
FARMCOSTS <- FARMCOSTS[-(68)]
#cdl
countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
colnames(countyFIPS) <- c("ID", "State", "County", "Fips")
countyFIPS$Fips <- sprintf("%05d",countyFIPS$Fips)
cdl_diversity <- read.csv("https://files.sesync.org/index.php/s/RWyocfcwpAobCrq/download")
colnames(cdl_diversity)[2] <- "Fips"
cdl_diversity$Fips <- sprintf("%05d", cdl_diversity$Fips)
cdl_div2 <- cdl_diversity
#merges with fips
#reshapes so we have a CDI 2011 and CDI 2012 for each state/county combo
#library(reshape2) ; cdl_div2 <- dcast(cdl_div, Fips ~ Year, value.var = c("CDI"))
cdl_div2 <- cbind.data.frame(cdl_div2[,2], cdl_div2[,4])
#changes column names
colnames(cdl_div2) <- c("Fips", "CDI_2012")
cdl_div2 <- merge(cdl_div2, countyFIPS, by = "Fips")
cdl_div2 <- subset(cdl_div2, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
cdl_div2 <- cdl_div2[,1:2]
#cash rent
countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
colnames(countyFIPS) <- c("ID", "State", "County", "Fips")
countyFIPS$Fips <- sprintf("%05d",countyFIPS$Fips)
#countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
#countyFIPS$FIPS <- sprintf("%05d",countyFIPS$FIPS)
cash_rent <- read.csv("https://nextcloud.sesync.org/index.php/s/rbGosZCQoqT5S8T/download")
cash_rent <- merge(cash_rent, countyFIPS, by=c("State", "County"))
#cash_rent <- cash_rent[,c(2,5,6,7,8,9,10,11,12)]
cash_rent <- cash_rent[,c(5,8,9,10,11,12,13,15)]
#cash_rent <- merge(cash_rent, countyFIPS, by=c("State", "County"))
colnames(cash_rent) <- c("Year", "RENT_Irrigated_Rent_Cropland", "RENT_NonIrrigated_Rent_Cropland", "RENT_Pastureland", "RENT_average", "RENT_Total_Cropland_Acres", "RENT_Total", "Fips")
cash_rent <- subset(cash_rent, Year == 2012)
#rented land
rented_land <- read.csv("https://nextcloud.sesync.org/index.php/s/wWnWqPHwWXPytmQ/download")
rented_land$Fips <- sprintf("%05d",rented_land$FIPS)
rented_land <- merge(rented_land, countyFIPS, by = "Fips")
rented_land <- subset(rented_land, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
rented_land <- rented_land[-(2:25)]
rented_land_revised <- rented_land[,1:5]
#rented_land_revised <- cbind(rented_land$acres.rented.2012, rented_land$Percent.rented.2012, rented_land$STATE_NAME, rented_land$NAME)
colnames(rented_land_revised) <- c("Fips", "RENT_acres.rented.2007", "RENT_acres.rented.2012", "RENT_percent.rented.2007", "RENT_Percent.rented.2012")
# extreme precip
precip_extreme <- read.csv("https://files.sesync.org/index.php/s/eJzjzcooY3feoHR/download")
#removes unnecessary columns
precip_extreme <- cbind.data.frame(precip_extreme[,2], precip_extreme[,8], precip_extreme[,11:12])
#renames columns
colnames(precip_extreme) <- c("Fips", "PRECIP_max", "PRECIP_ave", "PRECIP_cov")
#merges with fips
precip_extreme <- merge(precip_extreme, countyFIPS, by = "Fips")
precip_extreme <- subset(precip_extreme, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#
#revised RMA
RMA_revised <- read.csv("https://files.sesync.org/index.php/s/LDCrcXRgy2Pwp3F/download")
RMA_revised <- RMA_revised[-1]
RMA_revised <- RMA_revised[-1]
RMA_revised <- RMA_revised[-9]
RMA_revised$fips <- sprintf("%05d",RMA_revised$fips)
colnames(RMA_revised)[1] <- "Fips"
#soils
soils <- read.csv("https://files.sesync.org/index.php/s/z3fZWwXHnBAD8TG/download")
colnames(soils)[2] <- "Fips"
soils <- merge(soils, countyFIPS, by = "Fips")
soils <- subset(soils, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
soils <- soils[-2]
soils <- soils[-(8:10)]
#--agcensus tables provided by <NAME> in October 2019.
agcensus_table1 <- read.csv2("https://files.sesync.org/index.php/s/tFRELytxbWAgyMY/download", header = TRUE, sep = ",")
agcensus_table1 <- agcensus_table1[-2]
agcensus_table1 <- agcensus_table1[-2]
agcensus_table1 <- agcensus_table1[-2]
colnames(agcensus_table1) <- c("Fips", "Type", "Value" )
agcensus_table1 <- subset(agcensus_table1, Type == "Commodity credit corporation loans \\ Total ($1,000, 2012)" |
Type == "Government payments \\ Total received \\ Amount from conservation reserve, wetlands reserve, farmable wetlands, and conservation reserve enhancement programs ($1,000, 2012)" |
Type == "Government payments \\ Total received \\ Amount from conservation reserve, wetlands reserve, farmable wetlands, and conservation reserve enhancement programs \\ Average per farm (dollars, 2012)" |
Type == "Government payments \\ Total received \\ Amount from other federal farm programs ($1,000, 2012)" |
Type == "Government payments \\ Total received \\ Amount from other federal farm programs \\ Average per farm (dollars, 2012)" |
Type == "Government payments \\ Total received \\ Average per farm (dollars, 2012)")
levels(agcensus_table1$Type)[levels(agcensus_table1$Type)=="Commodity credit corporation loans \\ Total ($1,000, 2012)"] <- "corp_loans_2012"
levels(agcensus_table1$Type)[levels(agcensus_table1$Type)=="Government payments \\ Total received \\ Amount from conservation reserve, wetlands reserve, farmable wetlands, and conservation reserve enhancement programs ($1,000, 2012)"] <- "payments_reserve_total_2012"
levels(agcensus_table1$Type)[levels(agcensus_table1$Type)=="Government payments \\ Total received \\ Amount from conservation reserve, wetlands reserve, farmable wetlands, and conservation reserve enhancement programs \\ Average per farm (dollars, 2012)"] <- "payments_reserve_aveperfarm_2012"
levels(agcensus_table1$Type)[levels(agcensus_table1$Type)=="Government payments \\ Total received \\ Amount from other federal farm programs ($1,000, 2012)"] <- "payments_fedfarmprograms_total_2012"
levels(agcensus_table1$Type)[levels(agcensus_table1$Type)=="Government payments \\ Total received \\ Amount from other federal farm programs \\ Average per farm (dollars, 2012)"] <- "payments_fedfarmprograms_aveperfarm_2012"
levels(agcensus_table1$Type)[levels(agcensus_table1$Type)=="Government payments \\ Total received \\ Average per farm (dollars, 2012)"] <- "payments_received_aveperfarm_2012"
agcensus_table1$Type <- factor(agcensus_table1$Type)
agcensus_table1$Value <- as.numeric(agcensus_table1$Value)
#agcensus_table1 <- merge(agcensus_table1, countyFIPS, by = "Fips")
library(reshape2) ; agcensus_table1 <- dcast(agcensus_table1, Fips ~ Type, value.var = "Value", sum)
#state summaries
agcensus_table2 <- read.csv2("https://files.sesync.org/index.php/s/jc6nCzbqHqanzoD/download", header = TRUE, sep = ",")
agcensus_table2 <- agcensus_table2[-2]
agcensus_table2 <- agcensus_table2[-2]
agcensus_table2 <- agcensus_table2[-2]
colnames(agcensus_table2) <- c("Fips", "Type", "Value" )
agcensus_table2 <- subset(agcensus_table2, Type == "Land in farms \\ Average size of farm (acres)" |
Type == "Land in farms \\ Median size of farm (acres)" |
Type == "Estimated market value of land and buildings \\ Average per farm (dollars)" |
Type == "Estimated market value of land and buildings \\ Average per acre (dollars)" |
Type == "Estimated market value of all machinery and equipment \\ Average per farm (dollars)" |
Type == "Market value of agricultural products sold (see text) \\ Average per farm (dollars)" |
Type == "Market value of agricultural products sold (see text) \\ Crops, including nursery and greenhouse crops ($1,000)" |
Type == "Market value of agricultural products sold (see text) \\ Livestock, poultry, and their products ($1,000)" |
Type == "Total income from farm-related sources, gross before taxes and expenses (see text) ($1,000)" |
Type == "Total farm production expenses ($1,000)" |
Type == "Total farm production expenses \\ Average per farm (dollars)" |
Type == "Net cash farm income of operation (see text) \\ Average per farm (dollars)")
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Land in farms \\ Average size of farm (acres)"] <- "farmland_avesizefarm"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Land in farms \\ Median size of farm (acres)"] <- "farmland_mediansizefarm"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Estimated market value of land and buildings \\ Average per farm (dollars)"] <- "marketvalue_aveperfarm"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Estimated market value of land and buildings \\ Average per acre (dollars)"] <- "marketvalue_aveperacre"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Estimated market value of all machinery and equipment \\ Average per farm (dollars)"] <- "marketvalue_equip_aveperfarm"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Market value of agricultural products sold (see text) \\ Average per farm (dollars)"] <- "marketvalue_agproducts_aveperfarm"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Market value of agricultural products sold (see text) \\ Crops, including nursery and greenhouse crops ($1,000)"] <- "marketvalue_agproducts_crops"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Market value of agricultural products sold (see text) \\ Livestock, poultry, and their products ($1,000)"] <- "marketvalue_agproducts_livestock"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Total income from farm-related sources, gross before taxes and expenses (see text) ($1,000)"] <- "income_farmsources_gross"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Total farm production expenses ($1,000)"] <- "farm_expenses"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Total farm production expenses \\ Average per farm (dollars)"] <- "farmproduction_aveperfarm"
levels(agcensus_table2$Type)[levels(agcensus_table2$Type)=="Net cash farm income of operation (see text) \\ Average per farm (dollars)"] <- "netincome_aveperfarm"
agcensus_table2$Type <- factor(agcensus_table2$Type)
agcensus_table2$Value <- as.numeric(agcensus_table2$Value)
#agcensus_table2 <- merge(agcensus_table2, countyFIPS, by = "Fips")
library(reshape2) ; agcensus_table2 <- dcast(agcensus_table2, Fips ~ Type, value.var = "Value", sum)
#--MERGE!
library(tidyverse)
losstype <- "Acres"
#merge acensus with RMA damages. Need to define WHICH losstype: Acres, loss, lossperacre, lossperclaim
merge1 <- merge(eval(parse(text=paste("crop_damage_", losstype, sep=""))), agcensus, by = c("Fips", "Year"), all=T)
#merge previous merge with eqip
merge2 <- merge(eqip, merge1, by = c("Fips", "Year"), all=T)
#merge previous merge with ag landuse in cornbelt states
merge3 <- merge(merge2, AGCENSUS_ac2, by = c("Fips"), all=T)
merge3a <- merge(merge3, totalcropland, by = c("Fips"), all=T)
#merge previous merge with eqip_csp
merge3c <- merge(merge3a, eq_combined, by = c("Fips"))
#merge previous merge with census
merge4 <- merge(merge3c, census, by = c("Fips"), all=T)
#merge previous merge with nri
merge5 <- merge(merge4, nri, by = c("Fips"), all=T)
#merge previous merge with commodity loss totals FOR ALL COMMODITIES
merge6 <- merge(merge5, commodity_loss_total, by = c("Fips"), all=T)
#merge previous merge with PDSI
merge6a <- merge(merge6, pdsi, by = c("Fips"), all=T)
#merge previous merge with cash rent
merge6b <- merge(merge6a, cash_rent, by = c("Fips"), all=T)
#merge previous merge with cropland diversity for 2011 and 2012
merge6c <- merge(merge6b, cdl_div2, by = c("Fips"), all=T)
#merge with previous merge for rented land revised
merge7 <- merge(merge6c, rented_land_revised, by = c("Fips"), all=T)
#merge previous merge with extreme precip for 2008-2012
merge7a <- merge(merge7, precip_extreme, by = c("Fips"), all=T)
merge7b <- merge(merge7a, HDI, by=c("Fips"), all=T)
merge7c <- merge(merge7b, racediversity, by=c("Fips"), all=T)
merge7d <- merge(merge7c, femaleop, by=c("Fips"), all=T)
merge7e <- merge(merge7d, FARMCOSTS, by=c("Fips"), all=T)
merge7f <- merge(merge7e, RMA_revised, by=c("Fips"), all=T)
merge7f1 <- merge(merge7f, soils, by=c("Fips"), all=T)
merge7f2 <- merge(merge7f1, agcensus_table1, by=c("Fips"), all=T)
merge7f3 <- merge(merge7f2, agcensus_table2, by=c("Fips"), all=T)
merge7f <- subset(merge7f3, Year.x == "2012")
merge7f <- merge(merge7f, countyFIPS, by=c("Fips"))
merge7f <- subset(merge7f, State.y == "Illinois" | State.y == "Indiana" | State.y == "Iowa" |
State.y == "Michigan" | State.y == "Minnesota" | State.y == "Missouri" |
State.y == "Ohio" | State.y == "Wisconsin" | State.y =="Nebraska" | State.y == "Kansas"
| State.y == "North Dakota" | State.y == "South Dakota")
#removes the FIPS column
#merge7 <- subset( merge7e, select = -FIPS )
#converts NA to zero
#merge7f[is.na(merge7f)] <- 0
merge7 <- merge7f
#removing a bunch of extraneous columns that are mostly ID, and duplicate state and county and year columns
merge7 <- merge7[, -c(92,97,108,109,110,205,213,228,229,230,236,237,238,339)]
# merge7 <- merge7[-92]
# merge7 <- merge7[-96]
# merge7 <- merge7[-106]
# merge7 <- merge7[-106]
# merge7 <- merge7[-106]
# merge7 <- merge7[-200]
# merge7 <- merge7[-207]
# merge7 <- merge7[-221]
# merge7 <- merge7[-221]
# merge7 <- merge7[-221]
# merge7 <- merge7[-226]
# merge7 <- merge7[-226]
# merge7 <- merge7[-226]
# merge7 <- merge7[-308]
colnames(merge7)[326] <- "State"
colnames(merge7)[327] <- "County"
colnames(merge7)[2] <- "Year"
#this adds a prefix to a set of datasets. Make sure to change the column strings if you
#happen to add other datasets.
colnames(merge7)[3:32] <- paste("EQIP_", colnames(merge7)[3:32], sep = "")
colnames(merge7)[33:66] <- paste("RMA_", colnames(merge7)[33:66], sep = "")
colnames(merge7)[67:92] <- paste("AGCENSUS_", colnames(merge7)[67:92], sep = "")
colnames(merge7)[93:95] <- paste("NRCS_", colnames(merge7)[93:95], sep = "")
colnames(merge7)[96:105] <- paste("CENSUS_", colnames(merge7)[96:105], sep = "")
colnames(merge7)[106:199] <- paste("NRI_", colnames(merge7)[106:199], sep = "")
colnames(merge7)[221:224] <- paste("HDI_", colnames(merge7)[221:224], sep = "")
colnames(merge7)[226:228] <- paste("FEMALE_", colnames(merge7)[226:228], sep = "")
colnames(merge7)[229:294] <- paste("FARMCOSTS_", colnames(merge7)[229:294], sep = "")
colnames(merge7)[295:301] <- paste("RMA_revised_", colnames(merge7)[295:301], sep = "")
colnames(merge7)[302:307] <- paste("SOILS_", colnames(merge7)[302:307], sep = "")
colnames(merge7)[308:313] <- paste("PAYMENTS_", colnames(merge7)[308:313], sep = "")
colnames(merge7)[314:325] <- paste("FARMVALUE_", colnames(merge7)[314:325], sep = "")
#--transformed variables
#dependent variable 1
#cover crops / total cropland
merge7$AGCENSUS_Cover_Acres_Ratio <- merge7$AGCENSUS_Cover_Acres / merge7$AGCENSUS_Cropland_Acres
merge7$AGCENSUS_Notill_Ratio <- merge7$AGCENSUS_Notill_Acres / merge7$AGCENSUS_Cropland_Acres
merge7$AGCENSUS_Multitill_Ratio <- (merge7$AGCENSUS_Notill_Acres + merge7$AGCENSUS_Conservationtill_Acres) / merge7$AGCENSUS_Cropland_Acres
merge7 <- arrange.vars(merge7, c("State"=3, "County"=4))
#create name of crops used for RMA - example - for Midwest, we are using corn and soybeans
croplist_name <- paste(croplist[[1]], "_", croplist[[2]], sep="")
library( taRifx )
#make sure all independent variables are numeric and state and county are factors
merge8 <- japply( merge7[,5:330], which(sapply(merge7[,5:330], class)=="factor"), as.numeric )
merge9 <- japply( merge8, which(sapply(merge8, class)=="integer"), as.numeric )
#puts independent variables and factors (year, state, county, back together)
merge9 <- cbind(merge7$Fips, merge7$State, merge7$County, merge7$Year, merge9)
#makes sure state county year are named correctly and factored
colnames(merge9)[1:4] <- c("Fips", "State", "County", "Year")
merge9$State <- factor(merge9$State)
merge9$County <- factor(merge9$County)
#replace Inf with zero for RMA_lossperacre
merge9$RMA_Lossperacre[which(!is.finite(merge9$RMA_Lossperacre))] <- 0
#removes columns that have zero data for all counties. An example might be an RMA loss type like Hurricanes
remove_zero_cols <- function(df) {
rem_vec <- NULL
for(i in 1:ncol(df)){
this_sum <- summary(df[,i])
zero_test <- length(which(this_sum == 0))
if(zero_test == 6) {
rem_vec[i] <- names(df)[i]
}
}
features_to_remove <- rem_vec[!is.na(rem_vec)]
rem_ind <- which(names(df) %in% features_to_remove)
df <- df[,-rem_ind]
return(df)
}
merge9 <- remove_zero_cols(merge9)
#Converts cropland acreage ratios for cc and no till to log transformed, to derive a more normal distribution. Optional
#and commented out for now
#merge9$AGCENSUS_CC_Cropland_Acres_Ratio <- log10(merge9$AGCENSUS_CC_Cropland_Acres_Ratio)
#merge9$AGCENSUS_NOTILL_Cropland_Acres_Ratio <- log10(merge9$AGCENSUS_notill_acres/data2$AGCENSUS_Cropland_Acres)
#scales and centers the full output in case thats effective. Creates a separate file
merge9a <- merge9
scaled_merge10 <- merge9[, -c(1:4)] <- scale(merge9[, -c(1:4)], center = TRUE, scale = TRUE)
scaled_merge10 <- cbind(merge9$Fips, merge9$State, merge9$County, merge9$Year, scaled_merge10)
colnames(scaled_merge10)[1:4] <- c("Fips", "State", "County", "Year")
#write the combined file to the model_data location for SEM
#for both scaled and non-scaled. TWO files are generated below.
write.csv(merge9a, file = paste("/nfs/soilsesfeedback-data/Model_data/MIDWEST_", croplist_name, "_Model2", "_nonscaled_new.csv", sep=""))
write.csv(scaled_merge10, file = paste("/nfs/soilsesfeedback-data/Model_data/MIDWEST_", croplist_name, "_Model2", "_scaled_new.csv", sep=""))
<file_sep>/backups/SHEAF_model_data_creation.R
#--SHEAF_eda_model_data_creation_rev2.R
#--loads some data, subsets and merges,and outputs a file to Model_data folder.
#--Then this dataset can be used in SEM model analysis
# Initial regional analysis is for Illinois, Indiana, Iowa, Michigan, Minnesota, Missouri, Ohio, and Wisconsin
#--author: <NAME>, University of Idaho
#--date: October 2018
#
#--USAGE
#
#--SHEAF_model_data_creaton <- (crop, losstype)
#
#--crop = WHEAT, CORN, BARLEY, etc
#--losstype = acres, loss, lossperacre, lossperclaim
#
#--example
#
#--SHEAF_model_data_creation <- ("WHEAT", "acres")
#we are awesome descriptors
library(rgdal)
library(leaflet)
library(maptools)
library(classInt)
library(leaflet)
library(dplyr)
library(Hmisc)
library(RColorBrewer)
library(raster)
library (RCurl)
library(maptools)
library(tidyr)
library(plyr)
SHEAF_model_data_creation <- function(losstype) {
croplist <- list("CORN", "SOYBEANS")
options(scipen=999)
#CAPITIALIZATION FUNCTION
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
#ADD NRI
nri_tfact <- read.csv("https://nextcloud.sesync.org/index.php/s/ESranGDWaMcyDNj/download", strip.white=TRUE)
nri_tfact$Year <- c("2015")
nri_prime <- read.csv("https://nextcloud.sesync.org/index.php/s/YQCjJzwztpSfwpe/download", strip.white=TRUE)
nri_lcc <- read.csv("https://nextcloud.sesync.org/index.php/s/RGb2eKkZtLpQ7X9/download", strip.white=TRUE)
nri_irr <- read.csv("https://nextcloud.sesync.org/index.php/s/8EwQkxxsXa6XaRb/download", strip.white=TRUE)
nri_eros <- read.csv("https://nextcloud.sesync.org/index.php/s/R8aASsxtMbiebYr/download", strip.white=TRUE)
nri_dbl <- read.csv("https://nextcloud.sesync.org/index.php/s/tnge8GngoS2ozKg/download", strip.white=TRUE)
nri_crpcov <- read.csv("https://nextcloud.sesync.org/index.php/s/GKroT2c8kRmHBPX/download", strip.white=TRUE)
nri_brd <- read.csv("https://nextcloud.sesync.org/index.php/s/CedCm5X2PR6T37x/download", strip.white=TRUE)
nri_combined <- Reduce(function(x,y) merge(x = x, y = y, by = c("State", "County", "Year", "Fips"), all = TRUE),
list(nri_tfact, nri_prime, nri_lcc, nri_irr, nri_eros, nri_dbl, nri_crpcov, nri_brd))
nri <- subset(nri_combined, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#---
#AGCENSUS
#agcensus load via url - best if you are NOT on SESYNC rstudio server
agcensus <- read.csv("https://nextcloud.sesync.org/index.php/s/SFiSow3f4aSTdCK/download")
#agcensus load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/agcensus")
#agcensus <- read.csv("Agcensus2012.csv")
#agcensus_metadata <- read.csv("Agcensus2012_metadata.csv")
#removes ancillary columns at the end of the agcensus
agcensus <- agcensus[,1:25]
#AGCENSUS CHANGE COLUMN NAMES, FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
colnames(agcensus)[3] <- "State"
colnames(agcensus)[2] <- "Year"
colnames(agcensus)[4] <- "County"
agcensus$State <- tolower(agcensus$State)
agcensus$State <- sapply(agcensus$State, simpleCap)
agcensus$County <- tolower(agcensus$County)
agcensus$County <- sapply(agcensus$County, simpleCap)
agcensus <- subset(agcensus, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#AGCENSUS AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
agcensus <- aggregate(cbind(agcensus$tile_farms, agcensus$tile_acres, agcensus$tile_acres_avgfarm, agcensus$ditches_farms,
agcensus$ditches_acres, agcensus$ditches_acres_avgfarm, agcensus$consease_farms, agcensus$consease_acres,
agcensus$consease_avgfarm, agcensus$notill_farms, agcensus$notill_acres, agcensus$notill_avgfarm,
agcensus$constill_farms, agcensus$constill_acres, agcensus$constill_avgfarm, agcensus$convtill_farms,
agcensus$convtill_acres, agcensus$convtill_acres.1, agcensus$cc_farms, agcensus$cc_acres,
agcensus$cc_avgfarm), by=list(agcensus$State, agcensus$Year, agcensus$County), FUN = "sum")
colnames(agcensus) <- c("State", "Year", "County", "tile_farms", "tile_acres",
"tile_acres_avgfarm", "ditches_farms", "ditches_acres", "ditches_acres_avgfarm", "consease_farms", "consease_acres",
"consease_avgfarm", "notill_farms", "notill_acres", "notill_avgfarm", "constill_farms", "constill_acres",
"constill_avgfarm", "convtill_farms", "convtill_acres", "convtill_acres.1", "cc_farms", "cc_acres",
"cc_avgfarm")
#EQIP
#eqip load via url - best if you are NOT on SESYNC rstudio server
eqip <- read.csv("https://nextcloud.sesync.org/index.php/s/os5ZxFXAAEgc2y4/download")
#eqip load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/eqip")
#eqip <- read.csv("eqip.csv")
eqip$County <- tolower(eqip$County)
eqip$County <- sapply(eqip$County, simpleCap)
#EQIP SUBSET TO ONLY STUDY AREA
eqip <- subset(eqip, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#EQIP AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
eqip <- aggregate(eqip$Dollars.Paid, by=list(eqip$State, eqip$County, eqip$Applied.Amount, eqip$Applied.Year, eqip$practice_name), FUN = "sum")
colnames(eqip) <- c("State", "County", "Applied.Amount", "Year", "Practice_Name", "Dollars_Paid")
eqip$id <- seq_len(nrow(eqip))
library(reshape2) ; eqip <- dcast(eqip, State + County + Year ~ Practice_Name, value.var = "Dollars_Paid", sum)
#eqip <- spread(eqip, Practice_Name, Dollars_Paid)
#eqip load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/eqip")
#eqip <- read.csv("eqip.csv")
#CENSUS
#census load - best if you are NOT on SESYNC rstudio server
census <- read.csv("https://nextcloud.sesync.org/index.php/s/tnEESyD34JFoNLf/download")
#census load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/census")
#census <- read.csv("Census_States_CountyDem.csv")
#CENSUS FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
census$State <- tolower(census$State)
census$State <- sapply(census$State, simpleCap)
census$County <- tolower(census$County)
census$County <- sapply(census$County, simpleCap)
census <- subset(census, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
census$Value <- as.numeric(census$Value)
#CENSUS AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
census <- aggregate(census$Value, by=list(census$State, census$County, census$Year, census$Data.Item), FUN = "sum")
colnames(census) <- c("State", "County", "Year", "census_Grouping", "census_Value")
library(reshape2) ; census <- dcast(census, State + County + Year ~ census_Grouping, value.var = "census_Value", sum)
#census <- spread(census, census_Grouping, census_Value)
#census load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/census")
#census <- read.csv("Census_States_CountyDem.csv")
#RMA COMMODITY
#RMA by commodity and damage cause, includes claim counts
commodity <- read.csv("https://nextcloud.sesync.org/index.php/s/zFwyd64NZJEyrgr/download")
#commodity load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/RMA/RMA_csvfiles")
#commodity <- read.csv("RMA_combined.csv")
colnames(commodity) <- c("ID", "Year", "State", "County", "Commodity", "Loss", "Count", "Acres", "Lossperacre", "Lossperclaim", "Acresperclaim")
commodity$State <- state.name[match(commodity$State,state.abb)]
#RMA COMMODITY FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
commodity <- subset(commodity, State == "Illinois" | State == "Indiana" | State == "Iowa" |
State == "Michigan" | State == "Minnesota" | State == "Missouri" |
State == "Ohio" | State == "Wisconsin" | State =="Nebraska" | State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#colnames(commodity) <- c("ID", "Year", "State", "County", "Commodity", "Loss_commodity", "Count_commodity")
commodity_loss_total <- aggregate(list(commodity$Acres, commodity$Loss, commodity$Lossperacre, commodity$Lossperclaim, commodity$Acresperclaim, commodity$Count), by = list(commodity$State, commodity$County, commodity$Year), FUN ="sum")
colnames(commodity_loss_total) <- c("State", "County", "Year", "RMA_Acres", "RMA_Loss", "RMA_Lossperacre", "RMA_Lossperclaim", "RMA_Acresperclaim", "RMA_Count")
#RMA DAMAGE
#RMA by damage cause, includes claim counts
damage <- read.csv("https://nextcloud.sesync.org/index.php/s/W5kztdb5ZkxRptT/download")
#damage load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/RMA/")
#damage <- read.csv("RMA_damage_combined.csv", strip.white=TRUE)
colnames(damage) <- c("ID", "Year", "State", "County", "Commodity", "Damagecause", "Loss", "Count", "Acres", "Lossperacre", "Lossperclaim", "Acresperclaim")
damage$State <- state.name[match(damage$State,state.abb)]
#RMA DAMAGE FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
damage <- subset(damage, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin" | State == "Nebraska"| State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
#colnames(damage) <- c("ID", "Year", "State", "County", "Commodity", "Damagecause", "Loss_damagecause", "Count_damagecause")
#damage <- aggregate(damage$Loss, by=list(damage$Commodity, damage$Damagecause, damage$County, damage$State, damage$Year), FUN = "sum")
#colnames(damage) <- c("Commodity", "Damagecause", "County", "State", "Year", "Loss")
library(reshape2) ; damage_loss <- dcast(damage, State + County + Year + Commodity ~ Damagecause, value.var = c("Loss"), sum)
library(reshape2) ; damage_lossperacre <- dcast(damage, State + County + Year + Commodity ~ Damagecause, value.var = c("Lossperacre"), sum)
library(reshape2) ; damage_lossperclaim <- dcast(damage, State + County + Year + Commodity ~ Damagecause, value.var = c("Lossperclaim"), sum)
library(reshape2) ; damage_acres <- dcast(damage, State + County + Year + Commodity ~ Damagecause, value.var = c("Acres"), sum)
#damage <- spread(damage, Damagecause, Loss_damagecause)
crop_damage_acres <- subset(damage_acres, Commodity == croplist)
crop_damage_loss <- subset(damage_loss, Commodity == croplist)
crop_damage_lossperacre <- subset(damage_lossperacre, Commodity == croplist)
crop_damage_lossperclaim <- subset(damage_lossperclaim, Commodity == croplist)
crop_damage_acres <- aggregate(crop_damage_acres[,5:38], by = list(crop_damage_acres$State, crop_damage_acres$County, crop_damage_acres$Year), FUN = 'sum' )
colnames(crop_damage_acres)[1:3] <- c("State", "County", "Year")
crop_damage_loss <- aggregate(crop_damage_loss[,5:38], by = list(crop_damage_loss$State, crop_damage_loss$County, crop_damage_loss$Year), FUN = 'sum' )
colnames(crop_damage_loss)[1:3] <- c("State", "County", "Year")
crop_damage_lossperacre <- aggregate(crop_damage_lossperacre[,5:38], by = list(crop_damage_lossperacre$State, crop_damage_lossperacre$County, crop_damage_lossperacre$Year), FUN = 'sum' )
colnames(crop_damage_lossperacre)[1:3] <- c("State", "County", "Year")
crop_damage_lossperclaim <- aggregate(crop_damage_lossperclaim[,5:38], by = list(crop_damage_lossperclaim$State, crop_damage_lossperclaim$County, crop_damage_lossperclaim$Year), FUN = 'sum' )
colnames(crop_damage_lossperclaim)[1:3] <- c("State", "County", "Year")
#climate - pdsi
pdsi_moderate_drought_2007_2012 <- read.csv("https://nextcloud.sesync.org/index.php/s/TYa9pBNQHBc4efj/download")
countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
pdsi <- merge(pdsi_moderate_drought_2007_2012, countyFIPS, by = "FIPS")
pdsi$PDSI_TOTALS <- rowSums(pdsi[,c("X2007","X2008","X2009","X2010","X2011", "X2012" )])
pdsi <- pdsi[,10:12]
colnames(pdsi) <- c("State", "County", "PDSI_TOTALS")
#cdl
cdl_diversity <- read.csv("https://nextcloud.sesync.org/index.php/s/RWyocfcwpAobCrq/download")
cdl_div <- merge(cdl_diversity, countyFIPS, by = "FIPS")
library(reshape2) ; cdl_div2 <- dcast(cdl_div, STATE_NAME + NAME ~ Year, value.var = c("CDI"))
colnames(cdl_div2) <- c("State", "County", "CDI_2011", "CDI_2012")
#cash rent
cash_rent <- read.csv("https://nextcloud.sesync.org/index.php/s/rbGosZCQoqT5S8T/download")
cash_rent <- cash_rent[,c(2,5,6,7,8,9,10,11,12)]
colnames(cash_rent) <- c("Year", "RENT_Irrigated_Rent_Cropland", "RENT_NonIrrigated_Rent_Cropland", "RENT_Pastureland", "RENT_average", "State", "County", "RENT_Total_Cropland_Acres", "RENT_Total")
#--MERGE!
library(tidyverse)
merge1 <- merge(eval(parse(text=paste("crop_damage_", losstype, sep=""))), agcensus, by = c("State", "County", "Year"))
merge2 <- merge(eqip, merge1, by = c("State", "County", "Year") )
merge3 <- merge(merge2, alc2, by = c("State", "County"))
merge4 <- merge(merge3, census, by = c("State", "County", "Year"))
merge5 <- merge(merge4, nri, by = c("State", "County", "Year"))
merge6 <- merge(merge5, commodity_loss_total, by = c("State", "County", "Year"))
merge6a <- merge(merge6, pdsi, by = c("State", "County"))
merge6b <- merge(merge6a, cash_rent, by = c("State", "County", "Year"))
merge7 <- merge(merge6b, cdl_div2, by = c("State", "County"))
merge7[is.na(merge7)] <- 0
colnames(merge7)[4:33] <- paste("EQIP_", colnames(merge7)[4:33], sep = "")
colnames(merge7)[34:67] <- paste("RMA_", colnames(merge7)[34:67], sep = "")
colnames(merge7)[68:89] <- paste("AGCENSUS_", colnames(merge7)[68:89], sep = "")
colnames(merge7)[91:101] <- paste("CENSUS_", colnames(merge7)[91:101], sep = "")
colnames(merge7)[101:195] <- paste("NRI_", colnames(merge7)[101:195], sep = "")
#--transformed variables
#dependent variable 1
#cover crops / total cropland
merge7$AGCENSUS_CC_Cropland_Acres_Ratio <- merge7$AGCENSUS_cc_acres / merge7$AGCENSUS_Cropland_Acres
#WRITE FILE TO MODEL_DATA FOLDER FOR SEM ANALYSIS
#create name of crops used for RMA - example - for Midwest, we are using corn and soybeans
croplist_name <- paste(croplist[[1]], "_", croplist[[2]], sep="")
library( taRifx )
#make sure all exogenous variables are numeric and state and county are factors
merge8 <- japply( merge7[,4:211], which(sapply(merge7[,4:211], class)=="factor"), as.numeric )
merge9 <- japply( merge8, which(sapply(merge8, class)=="integer"), as.numeric )
merge9 <- cbind(merge7$State, merge7$County, merge7$Year, merge9)
colnames(merge9)[1:3] <- c("State", "County", "Year")
merge9$State <- factor(merge9$State)
merge9$County <- factor(merge9$County)
#replace Inf with zero for RMA_lossperacre
merge9$RMA_Lossperacre[which(!is.finite(merge9$RMA_Lossperacre))] <- 0
remove_zero_cols <- function(df) {
rem_vec <- NULL
for(i in 1:ncol(df)){
this_sum <- summary(df[,i])
zero_test <- length(which(this_sum == 0))
if(zero_test == 6) {
rem_vec[i] <- names(df)[i]
}
}
features_to_remove <- rem_vec[!is.na(rem_vec)]
rem_ind <- which(names(df) %in% features_to_remove)
df <- df[,-rem_ind]
return(df)
}
merge9 <- remove_zero_cols(merge9)
merge9 <- merge9[,-86] #remove FIPS
scaled_merge10 <- merge9[, -c(1:3)] <- scale(merge9[, -c(1:3)], center = TRUE, scale = TRUE)
#write the combined file to the model_data location for SEM
write.csv(merge9, file = paste("/nfs/soilsesfeedback-data/model_data/MIDWEST_", croplist_name, "_Model_", losstype, "_nonscaled.csv", sep=""))
write.csv(scaled_merge10, file = paste("/nfs/soilsesfeedback-data/model_data/MIDWEST_", croplist_name, "_Model_", losstype, "_scaled.csv", sep=""))
}
<file_sep>/backups/SHEAF_model_data_creation_rev2.R
#--SHEAF_eda_model_data_creation_rev2.R
#--loads some data, subsets and merges,and outputs a file to Model_data folder.
#--Then this dataset can be used in SEM model analysis
# Initial regional analysis is for Illinois, Indiana, Iowa, Michigan, Minnesota, Missouri, Ohio, and Wisconsin
#--author: <NAME>, University of Idaho
#--date: October 2018
#--MB change
library(rgdal)
library(leaflet)
library(maptools)
library(classInt)
library(leaflet)
library(dplyr)
library(Hmisc)
library(RColorBrewer)
library(raster)
library (RCurl)
library(maptools)
library(tidyr)
SHEAF_model_data_creation <- function(crop) {
options(scipen=999)
#CAPITIALIZATION FUNCTION
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
#AGCENSUS
#agcensus load via url - best if you are NOT on SESYNC rstudio server
#agcensus <- read.csv("https://nextcloud.sesync.org/index.php/s/THpGDspGXFtLSGF/download")
#agcensus load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/agcensus")
agcensus <- read.csv("Agcensus2012.csv")
agcensus_metadata <- read.csv("Agcensus2012_metadata.csv")
#removes ancillary columns at the end of the agcensus
agcensus <- agcensus[,1:25]
#AGCENSUS CHANGE COLUMN NAMES, FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
colnames(agcensus)[3] <- "State"
colnames(agcensus)[2] <- "Year"
colnames(agcensus)[4] <- "County"
agcensus$State <- tolower(agcensus$State)
agcensus$State <- sapply(agcensus$State, simpleCap)
agcensus$County <- tolower(agcensus$County)
agcensus$County <- sapply(agcensus$County, simpleCap)
agcensus <- subset(agcensus, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin")
#AGCENSUS AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
agcensus <- aggregate(cbind(agcensus$tile_farms, agcensus$tile_acres, agcensus$tile_acres_avgfarm, agcensus$ditches_farms,
agcensus$ditches_acres, agcensus$ditches_acres_avgfarm, agcensus$consease_farms, agcensus$consease_acres,
agcensus$consease_avgfarm, agcensus$notill_farms, agcensus$notill_acres, agcensus$notill_avgfarm,
agcensus$constill_farms, agcensus$constill_acres, agcensus$constill_avgfarm, agcensus$convtill_farms,
agcensus$convtill_acres, agcensus$convtill_acres.1, agcensus$cc_farms, agcensus$cc_acres,
agcensus$cc_avgfarm), by=list(agcensus$State, agcensus$Year, agcensus$County), FUN = "sum")
colnames(agcensus) <- c("State", "Year", "County", "tile_farms", "tile_acres",
"tile_acres_avgfarm", "ditches_farms", "ditches_acres", "ditches_acres_avgfarm", "consease_farms", "consease_acres",
"consease_avgfarm", "notill_farms", "notill_acres", "notill_avgfarm", "constill_farms", "constill_acres",
"constill_avgfarm", "convtill_farms", "convtill_acres", "convtill_acres.1", "cc_farms", "cc_acres",
"cc_avgfarm")
#EQIP
#eqip load via url - best if you are NOT on SESYNC rstudio server
#eqip <- read.csv("https://nextcloud.sesync.org/index.php/s/bgWSzqdqYDifJwz/download")
#eqip load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/eqip")
eqip <- read.csv("eqip.csv")
eqip$County <- tolower(eqip$County)
eqip$County <- sapply(eqip$County, simpleCap)
#EQIP SUBSET TO ONLY STUDY AREA
eqip <- subset(eqip, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin")
#EQIP AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
eqip <- aggregate(eqip$Dollars.Paid, by=list(eqip$State, eqip$County, eqip$Applied.Amount, eqip$Applied.Year, eqip$practice_name), FUN = "sum")
colnames(eqip) <- c("State", "County", "Applied.Amount", "Year", "Practice_Name", "Dollars_Paid")
eqip$id <- seq_len(nrow(eqip))
library(reshape2) ; eqip <- dcast(eqip, State + County + Year ~ Practice_Name, value.var = "Dollars_Paid", sum)
#eqip <- spread(eqip, Practice_Name, Dollars_Paid)
#eqip load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/eqip")
#eqip <- read.csv("eqip.csv")
#CENSUS
#census load - best if you are NOT on SESYNC rstudio server
#census <- read.csv("https://nextcloud.sesync.org/index.php/s/C3jHtLfRToPkrJa/download")
#census load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/census")
census <- read.csv("Census_States_CountyDem.csv")
#CENSUS FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
census$State <- tolower(census$State)
census$State <- sapply(census$State, simpleCap)
census$County <- tolower(census$County)
census$County <- sapply(census$County, simpleCap)
census <- subset(census, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin")
census$Value <- as.numeric(census$Value)
#CENSUS AGGREGATE BASED ON STATE AND COUNTY USING DOLLARS PAID AS THE SUMMARIZED OUTPUT
census <- aggregate(census$Value, by=list(census$State, census$County, census$Year, census$Data.Item), FUN = "sum")
colnames(census) <- c("State", "County", "Year", "census_Grouping", "census_Value")
library(reshape2) ; census <- dcast(census, State + County + Year ~ census_Grouping, value.var = "census_Value", sum)
#census <- spread(census, census_Grouping, census_Value)
#census load using csv - use if you ARE on SESYNC Rstudio server
#setwd("/nfs/soilsesfeedback-data/data/census")
#census <- read.csv("Census_States_CountyDem.csv")
#RMA COMMODITY
#RMA by commodity and damage cause, includes claim counts
#commodity <- read.csv("https://nextcloud.sesync.org/index.php/s/niLjWBSwmCoxQyC/download")
#commodity load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/RMA")
commodity <- read.csv("commodities.csv")
colnames(commodity) <- c("ID", "Year", "State", "County", "Commodity", "Loss_commodity", "Count_commodity")
commodity$State <- state.name[match(commodity$State,state.abb)]
#RMA COMMODITY FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
commodity <- subset(commodity, State == "Illinois" | State == "Indiana" | State == "Iowa" |
State == "Michigan" | State == "Minnesota" | State == "Missouri" |
State == "Ohio" | State == "Wisconsin" | State =="Nebraska" | State == "Kansas"
| State == "North Dakota" | State == "South Dakota")
colnames(commodity) <- c("ID", "Year", "State", "County", "Commodity", "Loss_commodity", "Count_commodity")
#RMA DAMAGE
#RMA by damage cause, includes claim counts
#damage <- read.csv("https://nextcloud.sesync.org/index.php/s/YErYqQYB9PAkmH9/download")
#damage load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/RMA")
damage <- read.csv("commodities_damagecause.csv", strip.white=TRUE)
colnames(damage) <- c("ID", "Year", "State", "County", "Commodity", "Damagecause", "Loss_damagecause", "Count_damagecause")
damage$State <- state.name[match(damage$State,state.abb)]
#RMA DAMAGE FIX CAPITIALIZATION AND THEN SUBSET TO ONLY STUDY AREA
damage <- subset(damage, State == "Illinois" | State == "Indiana" | State == "Iowa" | State == "Michigan" | State == "Minnesota" | State == "Missouri" | State == "Ohio" | State == "Wisconsin")
colnames(damage) <- c("ID", "Year", "State", "County", "Commodity", "Damagecause", "Loss_damagecause", "Count_damagecause")
damage <- aggregate(damage$Loss_damagecause, by=list(damage$Commodity, damage$Damagecause, damage$County, damage$State, damage$Year), FUN = "sum")
colnames(damage) <- c("Commodity", "Damagecause", "County", "State", "Year", "Loss_damagecause")
library(reshape2) ; damage <- dcast(damage, State + County + Year + Commodity ~ Damagecause, value.var = "Loss_damagecause", sum)
#damage <- spread(damage, Damagecause, Loss_damagecause)
crop_damage <- subset(damage, Commodity == crop)
#--MERGE!
library(tidyverse)
merge1 <- merge(crop_damage,agcensus, by = c("State", "County", "Year"))
merge2 <- merge(eqip, merge1, by = c("State", "County", "Year") )
merge3 <- merge(merge2, census, by = c("State", "County", "Year"))
merge3[is.na(merge3)] <- 0
#WRITE FILE TO MODEL_DATA FOLDER FOR SEM ANALYSIS
write.csv(merge3, file = paste("/nfs/soilsesfeedback-data/model_data/", crop, "_Model_dataset1.csv", sep=""))
}
<file_sep>/SHEAF_census_female_operators.R
library(dplyr)
library(tidyr)
## Rscript to transform Census data
## Create percent female operators by extracting those rows for All operators, and Female operators
## Note: Don't need to merge with FIPS, just create FIPS from ANSI columns
## NB2: ISsues b/t county names for NASS vs FIPS file from SESYNC (!!!)
## Last updated 20190307 JJR
## Read census data and transform variables for pecent female operators
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
census <- read.csv("https://nextcloud.sesync.org/index.php/s/iEpDeymRJG6oKFr/download")
colnames(census)[4] <- "State"
colnames(census)[8] <- "County"
census$County <- as.character(census$County)
census$State <- tolower(census$State)
census$State <- sapply(census$State, simpleCap)
census$County <- tolower(census$County)
census$County <- sapply(census$County, simpleCap)
#convert ansi fields to integer for adding leading zeros
census$State.ANSI <- as.integer(census$State.ANSI)
census$County.ANSI <- as.integer(census$County.ANSI)
#add leading zeros to make state 2 digits and county 3 digits
census$State.ANSI <- sprintf("%02d",census$State.ANSI)
census$County.ANSI <- sprintf("%03d",census$County.ANSI)
#create a FIPS column
census$FIPS <- paste(census$State.ANSI, census$County.ANSI, sep="")
#countyFIPS <- read.csv("https://nextcloud.sesync.org/index.php/s/wcFmKrSZW6Pr6D2/download")
#countyFIPS$FIPS <- sprintf("%05d",countyFIPS$FIPS)
#colnames(countyFIPS) <- c("ID", "State", "County", "FIPS")
#census2 <- full_join(census %>% filter(!State %in% c("Alaska", "Hawaii")), countyFIPS, by = c("State", "County"))
## check NA
colSums(is.na(census))
## jsut fips and year
census_female_operators <- census %>%
# clean value column
mutate(value_trim=str_trim(Value)) %>%
mutate(Value2=as.character(value_trim)) %>%
## clean up value column
## only select numbers in value column
filter(Value2 != "(D)" & Value2 != "(Z)" & Value2 != "(NA)") %>%
# remove commas from number values and convert to R numeric class
mutate(Value2 = as.numeric(str_remove(Value2, ","))) %>%
select(Year, State, County, FIPS, Data.Item, Value2) %>%
# filter what you want
filter(Data.Item %in% c("OPERATORS, (ALL) - NUMBER OF OPERATORS", "OPERATORS, (ALL), FEMALE - NUMBER OF OPERATORS")) %>%
spread(Data.Item, Value2) %>%
rename(female_operators=`OPERATORS, (ALL), FEMALE - NUMBER OF OPERATORS`) %>%
rename(all_operators=`OPERATORS, (ALL) - NUMBER OF OPERATORS`) %>%
mutate(percent_female=as.integer(female_operators)/as.integer(all_operators))
write.csv(census_female_operators, file="census_percent_female_operators.csv", row.names=FALSE)
<file_sep>/.Rproj.user/6B20C1D1/sources/s-79a83ff9/4E75039A-contents
#--SHEAF_eda.R
#--loads some initial datasets and merges them, combines with spatial data for visualization
#--author: <NAME>, University of Idaho
#--date: October 2018
library(rgdal)
library(leaflet)
library(maptools)
library(classInt)
library(leaflet)
library(dplyr)
library(Hmisc)
library(RColorBrewer)
library(raster)
library (RCurl)
library(maptools)
#AGCENSUS
#agcensus load via url - best if you are NOT on SESYNC rstudio server
agcensus_download <- read.csv("https://nextcloud.sesync.org/index.php/s/THpGDspGXFtLSGF/download")
#agcensus load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/agcensus")
agcensus <- read.csv("Agcensus2012.csv")
agcensus_metadata <- read.csv("Agcensus2012_metadata.csv")
#removes ancillary columns at the end of the agcensus
agcensus_download <- agcensus_download[,1:25]
agcensus <- agcensus[,1:25]
#EQIP
#eqip load via url - best if you are NOT on SESYNC rstudio server
eqip <- read.csv("https://nextcloud.sesync.org/index.php/s/bgWSzqdqYDifJwz/download")
#eqip load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/eqip")
eqip <- read.csv("eqip.csv")
#census load - best if you are NOT on SESYNC rstudio server
census_download <- read.csv("https://nextcloud.sesync.org/index.php/s/C3jHtLfRToPkrJa/download")
#census load using csv - use if you ARE on SESYNC Rstudio server
setwd("/nfs/soilsesfeedback-data/data/census")
census <- read.csv("Census_States_CountyDem.csv")
setwd("/nfs/soilsesfeedback-data/data/RMA")
commodity <- read.csv("commodities.csv")
damage <- read.csv("commodities_damagecause.csv")
#want to save the eqip data as an RDS file for faster usage?
#saveRDS(eqip, file = "Eqip.rds")
#load spatial county data
setwd("/nfs/soilsesfeedback-data/data/counties")
counties_conus <- readShapePoly('UScounties_conus.shp',
proj4string=CRS
("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))
projection = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
#AGGREGATING EQIP - THIS CODE AGGREGATES EQIP DATA BY STATE, COUNTY, PLANNED YEAR, AND PRACTICE NAME
xx_eqip2 <- aggregate(eqip$Dollars.Paid, by=list(eqip$State, eqip$County, eqip$planned_year, eqip$practice_name), FUN = "sum")
colnames(xx_eqip2) <- c("State", "County", "Year", "Practice_Name", "Dollars_Paid")
#xx_eqip3 <- subset(xx_eqip2, Practice_Name == "Residue Management, No-Till/Strip Till" & Planned_Year == "2010")
#AGGREGATING EQIP - THIS CODE AGGREGATES BY A PARTICULAR PRACTICE. HERE WE ARE AGGREGATING BY THREE PRACTICE CODES COMBINED.
xx_eqip3a <- subset(xx_eqip2, Practice_Name %in% c("Residue Management, No-Till/Strip Till", "Conservation Cover") & Year == 2010)
xx_eqip3 <- aggregate(xx_eqip3a$Dollars_Paid, by = list(xx_eqip3a$State, xx_eqip3a$County), FUN = "sum")
colnames(xx_eqip3) <- c("State", "County", "Dollars_Paid")
#--need to deal with units ft vs acres
#eqip_ft <- subset(xx_eqip, units == "ft")
#eqip_ft$units
xx_eqip3$County <- tolower(xx_eqip3$County)
xx_eqip3$County <- capitalize(xx_eqip3$County)
colnames(xx_eqip3)[2] <- "NAME"
colnames(xx_eqip3)[1] <- "STATE_NAME"
m <- merge(counties_conus, xx_eqip3, by=c("STATE_NAME", "NAME"))
palz1 <- brewer.pal(9, "GnBu")
palz <- colorRampPalette(palz1)
m$Dollars_Paid[is.na(m$Dollars_Paid)] <- 0
m$Dollars_Paid <- as.numeric(m$Dollars_Paid)
palData <- classIntervals(eval(parse(text=paste("m$", "Dollars_Paid", sep=""))), style="hclust")
colors <- findColours(palData, palz(100))
pal2 <- colorNumeric(brewer.pal(9, "GnBu"), na.color = "#ffffff",
domain = eval(parse(text=paste("m$", "Dollars_Paid", sep=""))))
exte <- as.vector(extent(counties_conus))
label <- paste(sep = "<br/>", m$STATE_NAME, round(eval(parse(text=paste("m$", "Dollars_Paid", sep=""))), 0))
markers <- data.frame(label)
labs <- as.list(eval(parse(text=paste("m$", "Dollars_Paid", sep=""))))
leaflet(data = m) %>% addProviderTiles("Stamen.TonerLite") %>% fitBounds(exte[1], exte[3], exte[2], exte[4]) %>% addPolygons(color = ~pal2(eval(parse(text=paste("m$", "Dollars_Paid", sep="")))), popup = markers$label, weight = 1) %>%
addLegend(pal = pal2, values = ~eval(parse(text=paste("m$", "Dollars_Paid", sep=""))), opacity = 1, title = NULL,
position = "bottomright")
<file_sep>/SHEAF_SEM_measurement.R
#SEM Measurement Model
#Need to construct a SEM Measurement Model in our first phase of SEM development
#A Measurement model examines the relationships of manifest (observed) variables to their latent variables.
#we "Saturate" the SEM model intially in order to
#library(shiny)
#library(shinyAce)
library(psych)
library(lavaan)
library(semPlot)
#library(shinyjs)
data1 <- read.csv("/nfs/soilsesfeedback-data/Model_data/MIDWEST_CORN_SOYBEANS_Model_acres.csv")
data1 <- data1[,-87] #remove FIPS
data1 <- data1[,-1] #remove ID
data1_nonscaled <- read.csv("/nfs/soilsesfeedback-data/Model_data/MIDWEST_CORN_SOYBEANS_Model_acres_nonscaled.csv")
data1_nonscaled <- data1_nonscaled[,-87] #remove FIPS
data1_nonscaled <- data1_nonscaled[,-1] #remove ID
data2 <- data1[,4:185]
data2 <- data.frame(data2)
data2_nonscaled <- data1_nonscaled[,4:185]
data2_nonscaled <- data.frame(data2_nonscaled)
chisq.test(data2_nonscaled)
myModel <- '
# measurement model
#Latent Variables
#ex: Weather is measured by PDSI_Totals + RMA_Acres
WEATHER =~ PDSI_TOTALS + RMA_Acres
DIVERSITY =~ notill_farms + constill_farms
Management =~ Residue.and.Tillage.Management..No.Till + Residue.and.Tillage.Management..Reduced.Till
EQIP =~ Conservation.Crop.Rotation + Cover.Crop
GENDER =~ OPERATORS...ALL...FEMALE...NUMBER.OF.OPERATORS + OPERATORS...ALL....NUMBER.OF.OPERATORS
RACE =~ OPERATORS..AMERICAN.INDIAN.OR.ALASKA.NATIVE...NUMBER.OF.OPERATORS + OPERATORS..ASIAN...NUMBER.OF.OPERATORS +
OPERATORS..BLACK.OR.AFRICAN.AMERICAN...NUMBER.OF.OPERATORS + OPERATORS..HISPANIC...NUMBER.OF.OPERATORS + OPERATORS..MULTI.RACE...NUMBER.OF.OPERATORS +
OPERATORS..NATIVE.HAWAIIAN.OR.OTHER.PACIFIC.ISLANDER...NUMBER.OF.OPERATORS + OPERATORS..WHITE...NUMBER.OF.OPERATORS
# regressions
WEATHER ~ Diversity + Management
AgCensus ~ Management + Weather + Race + Gender + Diversity
AgCensus <~ Weather
# residual correlations
notill_farms ~~ constill_farms
Drought ~~ Heat
DIVERSITY ~~ RMA_Count
Conservation.Crop.Rotation ~~ Cover.Crop
AGCENSUS_CC_Cropland_Acres_Ratio ~ Diversity + Gender + Race + Weather + RMA_Count'
#y3 ~~ y7
#y4 ~~ y8
#y6 ~~ y8
#fit <- cfa(model = myModel, data = data, missing = "fiml")
#summary(fit, fit.measures = TRUE)
fit <- sem(model = myModel, data=data1, std.lv =TRUE)
#summary(fit, standardized=TRUE)
semPaths(fit, "std", style = "mx", label.cex = 1.5, nCharNodes = 10, what = "cons", layout="tree", curvePivot = TRUE, edge.label.cex=.7)
| 3a28197b0054bb9ec0aeb7b9cd4e0804b67019f0 | [
"Markdown",
"R"
] | 14 | R | soilhealthfeedback/SHEAF_DATA_CREATION | bcc16c433630aba7bc51c6f15a4b5e70ec8f747b | c73ce3b40a71c2816b29d28e02cbfd3a7f99bbd2 |
refs/heads/master | <repo_name>thurgarion2/ch.epfl.javass<file_sep>/src/ch/epfl/javass/jass/Player.java
package ch.epfl.javass.jass;
import java.util.Map;
import ch.epfl.javass.jass.Card.Color;
/**
* défini le minimum pour se compoter comme un joueur
*
* @author <NAME> (296100)
*
*/
public interface Player {
/**
* retourne la carte que le joueur désire jouer selon l'état du tour et sa
* main
*
* @param state
* l'état courant du tour
* @param hand
* la main du joueur
* @return la carte que le joueur désire jouer selon l'état du tour et sa
* main
*/
public abstract Card cardToPlay(TurnState state, CardSet hand);
/**
* (appelée seulement en début de partie) informe le joueur qu'il a
* l'identité ownId et que les autres joueurs sont nommés conformément au
* conteus de la table associative playerNames
*
* @param ownId
* l'identité du joueur
* @param playerNames
* le nom de chaque joueur lié à leur identité
*/
public default void setPlayers(PlayerId ownId,
Map<PlayerId, String> playerNames) {
}
/**
* informe le joueur de sa nouvelle main après un changement
*
* @param newHand
* la nouvelle main du joueur
*/
public default void updateHand(CardSet newHand) {
}
/**
* informe le joeur du changement d'atout
*
* @param trump
* le nouvel atout
*/
public default void setTrump(Color trump) {
}
/**
* informe le joueur du changement du pli
*
* @param newTrick
* l'état du pli mis à jour
*/
public default void updateTrick(Trick newTrick) {
}
/**
* informe le joueur du changement du score
*
* @param score
* l'état du score mis à jour
*/
public default void updateScore(Score score) {
}
/**
* informe le joueur qu'une équipe à gagner (appelé qu'une seule fois)
*
* @param winningTeam
* l'équipe gagante
*/
public default void setWinningTeam(TeamId winningTeam) {
}
}
<file_sep>/src/ch/epfl/javass/bits/Bits32.java
package ch.epfl.javass.bits;
import ch.epfl.javass.Preconditions;
/**
* plusieurs méthodes utiles pour traiter avec des entier (int) sous forme
* binaire
*
* @author <NAME> (296100)
*
*/
public final class Bits32 {
private Bits32() {
}
// vérifie si le nombre n'occcupe pas plus de valeur que sa taille (cf pack)
//bits le nombre size la taille
private static void checkSize(int bits, int size) {
Preconditions.checkArgument(size > 0 && size < Integer.SIZE);
int mask = mask(size, Integer.SIZE - size);
Preconditions.checkArgument((bits & mask) == 0);
}
/**
* retourne un entier dont les bits d'index allant de start (inclus) à start
* + size (exclus) valent 1
*
* @param start
* le départ (inclus) (doit positif et plus petit que 33)
* @param size
* la taille (doit positif et start+size<=32)
* @return un entier dont les bits d'index allant de start (inclus) à start
* + size (exclus) valent 1
* @throws IllegalArgumentException
* si les conditions ne sont pas respectés cf start, size
*/
public static int mask(int start, int size) {
Preconditions.checkArgument(start >= 0 && start <= Integer.SIZE);
Preconditions.checkArgument(start + size <= Integer.SIZE && size >= 0);
long mask = (1L << size) - 1;
return (int) mask << start;
}
/**
* extrait de bits les bits allant de start (inclus) à start+size (exclus)
*
* @param bits
* le nombre où il faut extraire les bits
* @param start
* le début de la plage (inclus) (doit positif et plus petit que
* 33)
* @param size
* la taille de la plage (doit positif et start+size<=32)
* @return une valeur dont les size bits de poids faible sont égaux à ceux
* de bits allant de l'index start (inclus) à l'index start + size
* (exclus)
* @throws IllegalArgumentException
* si les conditions ne sont pas respectés cf start, size
*/
public static int extract(int bits, int start, int size) {
Preconditions.checkArgument(start >= 0 && start <= Integer.SIZE);
Preconditions.checkArgument(start + size <= Integer.SIZE && size >= 0);
return (bits & mask(start, size)) >>> start;
}
/**
* retourne les valeurs v1 et v2 empaquetées dans un entier de type int
*
* @param v1
* le nombre (int) qui occupe les s1 premier bits de poids faible
* @param s1
* le nombre de bit occupé par v1 (doit être plus grand ou égale
* à la taille de v1)
* @param v2
* le nombre (int) qui occupe les s2 bits de poids faible (à
* partire de s1)
* @param s2
* le nombre de bit occupé par v2 (doit être plus grand ou égale
* à la taille de v2)
* @return retourne les valeurs v1 et v2 empaquetées dans un entier de type
* int
* @throws IllegalArgumentException
* si s1 ou s2 negatif ou s1+s2>32 ou ne respecte pas les
* conditions de tailles de v1 et v2 cf s1,s2
*/
public static int pack(int v1, int s1, int v2, int s2) {
checkSize(v1, s1);
checkSize(v2, s2);
Preconditions.checkArgument(s1 + s2 <= Integer.SIZE);
return v1 | v2 << s1;
}
/**
* retourne les valeurs v1 et v2 et v3 empaquetées dans un entier de type
* int
*
* @param v1
* le nombre (int) qui occupe les s1 premier bits de poids faible
* @param s1
* le nombre de bit occupé par v1 (doit être plus grand ou égale
* à la taille de v1)
* @param v2
* le nombre (int) qui occupe les s2 bits de poids faible (à
* partire de s1)
* @param s2
* le nombre de bit occupé par v2 (doit être plus grand ou égale
* à la taille de v2)
* @param v3
* le nombre (int) qui occupe les s3 bits de poids faible (à
* partire de s1+s2)
* @param s3
* le nombre de bit occupé par v3 (doit être plus grand ou égale
* à la taille de v3)
* @return retourne les valeurs v1 et v2 et v3 empaquetées dans un entier de
* type int
*
* @throws IllegalArgumentException
* si s1 ou s2 ou s3 negatif ou s1+s2+s3>32 ou ne respecte pas
* les conditions de tailles de v1 et v2 et v3 cf s1,s2,s3
*/
public static int pack(int v1, int s1, int v2, int s2, int v3, int s3) {
Preconditions.checkArgument(s1 + s2 + s3 <= Integer.SIZE);
int v1ToV2 = pack(v1, s1, v2, s2);
return pack(v1ToV2, s1 + s2, v3, s3);
}
/**
* retourne les valeurs v1 et v2 et v3 et v4 et v6 et v7 empaquetées dans un
* entier de type int
*
* @param v1
* le nombre (int) qui occupe les s1 premier bits de poids faible
* @param s1
* le nombre de bit occupé par v1 (doit être plus grand ou égale
* à la taille de v1)
* @param v2
* le nombre (int) qui occupe les s2 bits de poids faible (à
* partire de s1)
* @param s2
* le nombre de bit occupé par v2 (doit être plus grand ou égale
* à la taille de v2)
* @param v3
* le nombre (int) qui occupe les s3 bits de poids faible (à
* partire de s1+s2)
* @param s3
* le nombre de bit occupé par v3 (doit être plus grand ou égale
* à la taille de v3)
* @param v4
* le nombre (int) qui occupe les s4 bits de poids faible à
* partire de s1+s2+s3
* @param s4
* le nombre de bit occupé par v4 (doit être plus grand ou égale
* à la taille de v4)
* @param v5
* le nombre (int) qui occupe les s5 bits de poids faible à
* partire de s1+s2+s3+s4
* @param s5
* le nombre de bit occupé par v5 (doit être plus grand ou égale
* à la taille de v5)
* @param v6
* le nombre (int) qui occupe les s6 bits de poids faible à
* partire de s1+s2+s3+s4+s5
* @param s6
* le nombre de bit occupé par v6 (doit être plus grand ou égale
* à la taille de v6)
* @param v7
* le nombre (int) qui occupe les s7 bits de poids faible à
* partire de s1+s2+s3+s4+s5+s6
* @param s7
* le nombre de bit occupé par v7 (doit être plus grand ou égale
* à la taille de v7)
*
* @return retourne les valeurs v1 et v2 et v3 et v4 et v6 et v7 empaquetées
* dans un entier de type int
* @throws IllegalArgumentException
* si les s1,...s7<0 ou s1+...+s7>32 ou ne respecte pas les
* conditions de tailles de v1,..v7 cf s1,...,s7
*/
public static int pack(int v1, int s1, int v2, int s2, int v3, int s3,
int v4, int s4, int v5, int s5, int v6, int s6, int v7, int s7) {
Preconditions.checkArgument(
s1 + s2 + s3 + s4 + s5 + s6 + s7 <= Integer.SIZE);
int v1ToV3 = pack(v1, s1, v2, s2, v3, s3);
int v4ToV6 = pack(v4, s4, v5, s5, v6, s6);
int v1ToV7 = pack(v1ToV3, s1 + s2 + s3, v4ToV6, s4 + s5 + s6, v7, s7);
return v1ToV7;
}
}
<file_sep>/test/ch/epfl/javass/simulation/PrintingPlayer.java
package ch.epfl.javass.simulation;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import ch.epfl.javass.jass.Card;
import ch.epfl.javass.jass.CardSet;
import ch.epfl.javass.jass.Player;
import ch.epfl.javass.jass.PlayerId;
import ch.epfl.javass.jass.Score;
import ch.epfl.javass.jass.TeamId;
import ch.epfl.javass.jass.Trick;
import ch.epfl.javass.jass.TurnState;
import ch.epfl.javass.jass.Card.Color;
public final class PrintingPlayer implements Player {
private final Player underlyingPlayer;
public PrintingPlayer(Player underlyingPlayer) {
this.underlyingPlayer = underlyingPlayer;
}
@Override
public Card cardToPlay(TurnState state, CardSet hand) {
System.out.print("C'est à moi de jouer... Je joue : ");
Card c = underlyingPlayer.cardToPlay(state, hand);
System.out.println(c);
return c;
}
@Override
public void setPlayers(PlayerId ownId,
Map<PlayerId, String> playerNames) {
System.out.println("Les joueurs sont : ");
for(String each : playerNames.values()) {
System.out.println(each);
}
System.out.println("je suis : "+playerNames.get(ownId));
this.underlyingPlayer.setPlayers(ownId, playerNames);
}
@Override
public void updateHand(CardSet newHand) {
System.out.println("Ma nouvelle main : "+newHand);
this.underlyingPlayer.updateHand(newHand);
}
@Override
public void setTrump(Color trump) {
System.out.println("Atout : "+trump);
this.underlyingPlayer.setTrump(trump);
}
@Override
public void updateTrick(Trick newTrick) {
System.out.println(newTrick);
this.underlyingPlayer.updateTrick(newTrick);
}
@Override
public void updateScore(Score score) {
System.out.println("Scores: "+score);
this.underlyingPlayer.updateScore(score);
}
@Override
public void setWinningTeam(TeamId winningTeam) {
System.out.println("L'équipe gagnante est : "+winningTeam);
this.underlyingPlayer.setWinningTeam(winningTeam);
}
}<file_sep>/src/ch/epfl/javass/RemoteMain.java
package ch.epfl.javass;
import ch.epfl.javass.gui.GraphicalPlayerAdapter;
import ch.epfl.javass.net.RemotePlayerServer;
import javafx.application.Application;
import javafx.stage.Stage;
/**
* permet à un joueur humain de jouer à distance jeux de jass
*
* @author <NAME> (296100)
*
*/
public final class RemoteMain extends Application{
/**
* @param args
* n'influence rien du tout
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Thread player = new Thread(
()->{
RemotePlayerServer p =
new RemotePlayerServer(new GraphicalPlayerAdapter());
p.run();
}
);
System.out.println("La partie commencera à la connexion du client…");
player.setDaemon(true);
player.start();
}
}
<file_sep>/test/ch/epfl/javass/jass/JassGameTest.java
package ch.epfl.javass.jass;
import org.junit.jupiter.api.Test;
public class JassGameTest {
@Test
void isGameOverWorks() {
}
}
<file_sep>/README.md
# ch.epfl.javass
Javass a fully playable jass game written in java with a graphic interface, IA-player and a client allowing to play with friends online.
<file_sep>/src/ch/epfl/javass/jass/PackedScore.java
package ch.epfl.javass.jass;
import ch.epfl.javass.bits.Bits32;
import ch.epfl.javass.bits.Bits64;
/**
* plusieurs méthodes utiles pour représenter un score dans un seul long
*
* @author <NAME> (296100)
*
*/
// 2 équipes 2 fois 32 bits
// pour une équipe,
// bits : 0 à 3 nb Plis gagné
// bits : 4 à 12 points du tour
// bits : 12 à 23 points de la partie
// bits : 24 32 des zéro
public final class PackedScore {
/**
* le score initiale
*/
public static final long INITIAL = 0;
private static final int START_OF_TEAM1 = 0;
private static final int START_OF_TEAM2 = 32;
private static final int NB_BITS_PER_TEAM = Integer.SIZE;
private static final int BIT_SIZE_OF_TRICKS = 4;
private static final int BIT_SIZE_OF_TURN = 9;
private static final int BIT_SIZE_OF_GAME = 11;
private static final int START_OF_TRICK = 0;
private static final int START_OF_TURN = BIT_SIZE_OF_TRICKS + START_OF_TRICK;
private static final int START_OF_GAME = START_OF_TURN + BIT_SIZE_OF_TURN;
private static final int MAX_TRICK_PER_TURN = Jass.TRICKS_PER_TURN;
private static final int MAX_POINT_PER_TURN = 257;
private static final int MAX_POINT_PER_GAME = 2000;
private PackedScore() {
}
// teste si le score d'une équipe est correct sur 32 bits
private static boolean isValid(int pkScore) {
if (Bits32.extract(pkScore, START_OF_TRICK,BIT_SIZE_OF_TRICKS)
> MAX_TRICK_PER_TURN) {
return false;
}
if (Bits32.extract(pkScore, START_OF_TURN,BIT_SIZE_OF_TURN)
> MAX_POINT_PER_TURN) {
return false;
}
if (Bits32.extract(pkScore, START_OF_GAME,BIT_SIZE_OF_GAME)
> MAX_POINT_PER_GAME) {
return false;
}
// le 8 dernier bits sont nuls
if (Bits32.extract(pkScore, 24, 8) != 0) {
return false;
}
return true;
}
/**
* retourne vraie si les champ de pkScore contiennent des valeurs valides
* (pli<=9,point<=257,le totale des points<=2000)
*
* @param pkScore
* le score empaqueté dans un long
* @return vraie si les champ de pkScore contiennent des valeurs valides
* (pli<=9,point<=257,le totale des points<=2000)
*/
public static boolean isValid(long pkScore) {
int B0To31 = (int) Bits64.extract(pkScore, START_OF_TEAM1, NB_BITS_PER_TEAM);
int B32To63 = (int) Bits64.extract(pkScore, START_OF_TEAM2, NB_BITS_PER_TEAM);
return isValid(B0To31) && isValid(B32To63);
}
private static int oneTeamScorePk(int turnTricks, int turnPoints, int gamePoints) {
assert (turnTricks >= 0 && turnTricks <= MAX_TRICK_PER_TURN);
assert (turnPoints >= 0 && turnPoints <= MAX_POINT_PER_TURN);
assert (gamePoints >= 0 && gamePoints <= MAX_POINT_PER_GAME);
return Bits32.pack(turnTricks, BIT_SIZE_OF_TRICKS, turnPoints,
BIT_SIZE_OF_TURN, gamePoints, BIT_SIZE_OF_GAME);
}
/**
* retourne un score empaqueté dans un long
*
* @param turnTricks1
* le nombre de pli gagné par l'équipe 1
* @param turnPoints1
* le nombre de points (durant le tour) de l'équipe 1
* @param gamePoints1
* le nombre de points (durant la partie) de l'équipe 1
* @param turnTricks2
* le nombre de pli gagné par l'équipe 2
* @param turnPoints2
* le nombre de points (durant le tour) de l'équipe 2
* @param gamePoints2
* le nombre de points (durant la partie) de l'équipe 1
* @return un score empaqueté dans un long
*/
public static long pack(int turnTricks1, int turnPoints1, int gamePoints1,
int turnTricks2, int turnPoints2, int gamePoints2) {
long B0To31 = oneTeamScorePk(turnTricks1, turnPoints1, gamePoints1);
long B32To63 = oneTeamScorePk(turnTricks2, turnPoints2, gamePoints2);
return Bits64.pack(B0To31, NB_BITS_PER_TEAM, B32To63, NB_BITS_PER_TEAM);
}
private static int extractPkTeam(long pkScore, TeamId t) {
assert isValid(pkScore);
if (t == TeamId.TEAM_1) {
return (int) Bits64.extract(pkScore, START_OF_TEAM1, NB_BITS_PER_TEAM);
}
return (int) Bits64.extract(pkScore, START_OF_TEAM2, NB_BITS_PER_TEAM);
}
/**
* retourne le nombre de pli gagné par l'équipe donnée
*
* @param pkScore
* le score empaqueté (valide)
* @param t
* l'équipe
* @return le nombre de pli gagné par l'équipe donnée
*/
public static int turnTricks(long pkScore, TeamId t) {
assert isValid(pkScore);
return Bits32.extract(extractPkTeam(pkScore, t), START_OF_TRICK, BIT_SIZE_OF_TRICKS);
}
/**
* retourne le nombre de points (durant le tour) gagné par l'équipe donnée
*
* @param pkScore
* le score empaqueté (valide)
* @param t
* l'équipe
* @return le nombre de point (durant le tour) gagné par l'équipe donnée
*/
public static int turnPoints(long pkScore, TeamId t) {
assert isValid(pkScore);
return Bits32.extract(extractPkTeam(pkScore, t), START_OF_TURN, BIT_SIZE_OF_TURN);
}
/**
* retourne le nombre de points (durant la partie) gagné par l'équipe donnée
*
*
* @param pkScore
* le score empaqueté (valide)
* @param t
* l'équipe
* @return le nombre de points (durant la partie) gagné par l'équipe donnée
*
*/
public static int gamePoints(long pkScore, TeamId t) {
assert isValid(pkScore);
return Bits32.extract(extractPkTeam(pkScore, t), START_OF_GAME, BIT_SIZE_OF_GAME);
}
/**
* retourne le nombre de points gagné au totale durant la partie par
* l'équipe donnée (ceux du tour + partie)
*
* @param pkScore
* le score empaqueté (valide)
* @param t
* l'équipe
* @return le nombre de points gagné au totale durant la partie par l'équipe
* donnée (ceux du tour + partie)
*/
public static int totalPoints(long pkScore, TeamId t) {
assert isValid(pkScore);
return gamePoints(pkScore, t) + turnPoints(pkScore, t);
}
/**
* retourne un score empqueté avec les champs mis à jour
*
* @param pkScore
* le score empaqueté de départ (valide)
* @param winningTeam
* l'équipe gagante
* @param trickPoints
* le nombre de points supplémentaire pour l'équipe gagnante
* @return un score empqueté avec les champs mis à jour en tenant compte que
* l'équipe gagante à gagner trickPoints
*/
public static long withAdditionalTrick(long pkScore, TeamId winningTeam, int trickPoints) {
assert isValid(pkScore);
assert trickPoints <= MAX_POINT_PER_TURN;
int turnTricks = turnTricks(pkScore, winningTeam) + 1;
int turnPoints = turnPoints(pkScore, winningTeam) + trickPoints;
int totalPoints = gamePoints(pkScore, winningTeam);
if (turnTricks == Jass.TRICKS_PER_TURN) {
turnPoints += Jass.MATCH_ADDITIONAL_POINTS;
}
int winningTeamPk = oneTeamScorePk(turnTricks, turnPoints, totalPoints);
int losingTeamPk = extractPkTeam(pkScore, winningTeam.other());
if (winningTeam == TeamId.TEAM_1) {
return Bits64.pack(winningTeamPk, NB_BITS_PER_TEAM, losingTeamPk, NB_BITS_PER_TEAM);
}
return Bits64.pack(losingTeamPk, NB_BITS_PER_TEAM, winningTeamPk, NB_BITS_PER_TEAM);
}
/**
* retourne les scores empaquetés donnés mis à jour pour le tour prochain
*
* @param pkScore
* le score empqueté
* @return les scores empaquetés donnés mis à jour pour le tour prochain
*/
public static long nextTurn(long pkScore) {
assert isValid(pkScore);
// les points du tour et le nb plis gagné sont mis à zéro
int team1Pk = oneTeamScorePk(0, 0, totalPoints(pkScore, TeamId.TEAM_1));
int team2Pk = oneTeamScorePk(0, 0, totalPoints(pkScore, TeamId.TEAM_2));
return Bits64.pack(team1Pk, NB_BITS_PER_TEAM, team2Pk, NB_BITS_PER_TEAM);
}
private static String teamToString(long pkScore, TeamId t) {
return "plie: " + turnTricks(pkScore, t) + " tour: "
+ turnPoints(pkScore, t) + " partie: " + gamePoints(pkScore, t);
}
/**
* retourne une chaine de caractère représantant le score
*
* @param pkScore
* le score empaqueté
* @return retourne une chaine de caractère représantant le score
*/
public static String toString(long pkScore) {
assert isValid(pkScore);
return teamToString(pkScore, TeamId.TEAM_1) + " / "
+ teamToString(pkScore, TeamId.TEAM_2);
}
}
<file_sep>/src/ch/epfl/javass/net/Protocol.java
package ch.epfl.javass.net;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* contient la plupart des constantes necessaires à la communication du client
* avec le joueur distant
*
* @author <NAME> (296100)
*
*/
// necessaire de connaitre le protocol pour pouvoir interpreter la plupart des
// messages
public interface Protocol {
/**
* le port sur lequel le client et le serveur communique
*/
public static final int PORT = 5108;
/**
* la base dans la quelle sont sérialisé les entiers
*/
public static final int BASE = 16;
/**
* le jeu de caractère utilisé pour la communication
*/
public static final Charset CHARSET = StandardCharsets.US_ASCII;
/**
* l'index de la commande dans un message
*/
public static final int COMMAND_INDEX = 0;
/**
* l'index de l'id du joueur dans un message
*/
public static final int ID_INDEX = 1;
/**
* l'index des noms des joueurs dans un message
*/
public static final int NAMES_INDEX = 2;
/**
* l'index du score du joueur dans un message
*/
public static final int SCORE_INDEX = 1;
/**
* l'index du pli du joueur dans un message
*/
public static final int TRCIK_INDEX = 1;
/**
* l'index de l'atout dans un message
*/
public static final int TRUMP_INDEX = 1;
/**
* l'index d'une équipe dans un message
*/
public static final int TEAM_INDEX = 1;
/**
* l'index de l'état du tour dans message
*/
public static final int TURNSTATE_INDEX = 1;
/**
* l'index de la main du joueur dans message (avec la commande HAND)
*/
public static final int HAND_INDEX = 1;
/**
* l'index de la main du joueur dans message (avec la commande CARD)
*/
public static final int HAND_WHEN_CARD = 2;
/**
* représente la fin d'un message
*/
public static final char END_MESSAGE = '\n';
/**
* sépare deux composants d'un messages
*/
public static final char SEPARATOR = ' ';
}
<file_sep>/test/ch/epfl/javass/simulation/Serveur.java
package ch.epfl.javass.simulation;
import ch.epfl.javass.net.RemotePlayerServer;
public class Serveur {
public static void main(String[] args) {
RemotePlayerServer player=new RemotePlayerServer(new RandomPlayer(2019));
player.run();
}
}
<file_sep>/test/ch/epfl/javass/jass/TrickTest.java
package ch.epfl.javass.jass;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.List;
import ch.epfl.javass.jass.*;
import org.junit.jupiter.api.Test;
public class TrickTest {
private static List<Integer> tricks(){
List<Integer> tricks = new ArrayList<>();
for(Card.Color color : Card.Color.ALL) {
for(PlayerId id : PlayerId.ALL) {
int trick = PackedTrick.firstEmpty(color, id);
int nb=36;
while(nb>0) {
int sum=nb%3+1;
int nextTrick=trick;
for(int i=0; i<sum && nb>0; i++) {
nextTrick=PackedTrick.withAddedCard(nextTrick,CardSet.ALL_CARDS.get(nb-1).packed());
nb--;
}
tricks.add(nextTrick);
}
}
}
return tricks;
}
private static Trick full() {
Trick t1= Trick.firstEmpty(Card.Color.CLUB, PlayerId.PLAYER_1);
for(int i=0; i<4; i++) {
t1=t1.withAddedCard(Card.ofPacked(0));
}
return t1;
}
private static Trick last() {
int trick=0b00001000;
trick<<=24;
return Trick.ofPacked(trick);
}
private static Trick empty() {
return Trick.firstEmpty(Card.Color.CLUB, PlayerId.PLAYER_1);
}
@Test
void invalidIsGood() {
assertEquals(PackedTrick.INVALID,Trick.INVALID.packed());
}
@Test
void firstEmptyWorksOnAllPossibility() {
for(Card.Color color : Card.Color.ALL) {
for(PlayerId id : PlayerId.ALL) {
Trick trick = Trick.firstEmpty(color, id);
assertEquals(color,trick.trump());
assertEquals(id, trick.player(0));
}
}
}
@Test
void failsWithInvalidTrick() {
assertThrows(IllegalArgumentException.class, ()->{Trick.ofPacked(PackedTrick.INVALID);});
}
@Test
void ofPackedWorksOnSomeCases() {
for(Integer i : tricks()) {
Integer second=Trick.ofPacked(i).packed();
assertEquals(i, second);
}
}
@Test
void nextEmptyFailsWithNotFullTrick() {
for(Integer i : tricks()) {
Integer second=Trick.ofPacked(i).packed();
if(!PackedTrick.isFull(second)) {
assertThrows(IllegalStateException.class,()->{Trick.ofPacked(second).nextEmpty();});
}
}
}
@Test
void playerIdFailsOnInvalidCases() {
assertThrows(IndexOutOfBoundsException.class,()->{Trick.INVALID.player(-1);});
assertThrows(IndexOutOfBoundsException.class,()->{Trick.INVALID.player(4);});
}
@Test
void cardFailsWithInvalidIndex() {
Trick t1= Trick.firstEmpty(Card.Color.CLUB, PlayerId.PLAYER_1);
Trick t2=t1;
assertThrows(IndexOutOfBoundsException.class,()->{t2.card(-1);});
assertThrows(IndexOutOfBoundsException.class,()->{t2.card(1);});
t1=t1.withAddedCard(Card.ofPacked(0));
Trick t3=t1;
assertThrows(IndexOutOfBoundsException.class,()->{t3.card(2);});
t1=t1.withAddedCard(Card.ofPacked(0));
Trick t4=t1;
assertThrows(IndexOutOfBoundsException.class,()->{t4.card(3);});
t1=t1.withAddedCard(Card.ofPacked(0));
Trick t5=t1;
assertThrows(IndexOutOfBoundsException.class,()->{t5.card(4);});
}
@Test
void withAddedCardFailsOnFullTrick() {
assertThrows(IllegalStateException.class,()->{full().withAddedCard(Card.ofPacked(0));});
}
@Test
void baseColorFailsOnEmptyTrick() {
assertThrows(IllegalStateException.class,()->{empty().baseColor();});
}
@Test
void winningPlayerFailsOnEmptyTrick() {
assertThrows(IllegalStateException.class,()->{empty().winningPlayer();});
}
@Test
void playableCardsFailsOnFullTrick() {
assertThrows(IllegalStateException.class,()->{full().playableCards(CardSet.ofPacked(0));});
}
@Test
void nextEmptyWorksForLastTrick() {
assertEquals(Trick.INVALID, last().nextEmpty());
}
@Test
void playableCardsWorksWithOnlyJack() {
List <Card> cards = new ArrayList<>();
cards.add(Card.of(Card.Color.CLUB, Card.Rank.JACK));
cards.add(Card.of(Card.Color.HEART, Card.Rank.JACK));
cards.add(Card.of(Card.Color.DIAMOND, Card.Rank.JACK));
cards.add(Card.of(Card.Color.SPADE, Card.Rank.JACK));
CardSet hand=CardSet.of(cards);
Trick t=empty();
t=t.withAddedCard(Card.of(Card.Color.CLUB, Card.Rank.EIGHT));
assertEquals(hand, t.playableCards(hand));
}
@Test
void playableCardsWorksOnTrumpAsBaseColor() {
List <Card> cards = new ArrayList<>();
cards.add(Card.of(Card.Color.CLUB, Card.Rank.JACK));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.KING));
cards.add(Card.of(Card.Color.DIAMOND, Card.Rank.JACK));
cards.add(Card.of(Card.Color.SPADE, Card.Rank.JACK));
CardSet hand1=CardSet.of(cards);
CardSet hand2=CardSet.of(cards.subList(0, 2));
Trick t=empty();
t=t.withAddedCard(Card.of(Card.Color.CLUB, Card.Rank.EIGHT));
assertEquals(hand2, t.playableCards(hand1));
}
@Test
void playableCardsWorksOnTrivial() {
List <Card> cards = new ArrayList<>();
cards.add(Card.of(Card.Color.CLUB, Card.Rank.JACK));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.KING));
cards.add(Card.of(Card.Color.SPADE, Card.Rank.JACK));
cards.add(Card.of(Card.Color.SPADE, Card.Rank.QUEEN));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.SIX));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.SEVEN));
cards.add(Card.of(Card.Color.DIAMOND, Card.Rank.JACK));
CardSet hand1=CardSet.of(cards);
CardSet hand2=CardSet.of(cards.subList(0, 4));
Trick t=empty();
t=t.withAddedCard(Card.of(Card.Color.SPADE, Card.Rank.EIGHT));
t=t.withAddedCard(Card.of(Card.Color.CLUB, Card.Rank.QUEEN));
assertEquals(hand2, t.playableCards(hand1));
}
@Test
void playableCardsWorksOnNoCardsOfRequestColor() {
List <Card> cards = new ArrayList<>();
cards.add(Card.of(Card.Color.CLUB, Card.Rank.JACK));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.KING));
cards.add(Card.of(Card.Color.DIAMOND, Card.Rank.JACK));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.SIX));
cards.add(Card.of(Card.Color.CLUB, Card.Rank.SEVEN));
CardSet hand1=CardSet.of(cards);
CardSet hand2=CardSet.of(cards.subList(0, 3));
Trick t=empty();
t=t.withAddedCard(Card.of(Card.Color.SPADE, Card.Rank.EIGHT));
t=t.withAddedCard(Card.of(Card.Color.CLUB, Card.Rank.QUEEN));
assertEquals(hand2, t.playableCards(hand1));
}
}
<file_sep>/test/ch/epfl/javass/jass/PackedScoreTest.java
package ch.epfl.javass.jass;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PackedScoreTest {
@Test
void isValidTest() {
//pli
long score = 0b1011;
assertFalse(PackedScore.isValid(score));
score = 0b0100;
assertTrue(PackedScore.isValid(score));
score= 0b1_0000_0000_0000;
assertTrue(PackedScore.isValid(score));
//points ggame
score = 0b1_0000_0000_0000_0000_0000_0000;
assertFalse(PackedScore.isValid(score));
score = 0b1000_0000_0000_0000_0000;
assertTrue(PackedScore.isValid(score));
//bits nuls
score = 0b1_0000_0000_0000_0000_0000_0000_0000;
assertFalse(PackedScore.isValid(score));
}
// t1 : 2 19 131 t2 4 50 50
@Test
void packTest() {
long expected = 0b0000_0000_0000_0110_0100_0011_0010_0100_0000_0000_0001_0000_0110_0001_0011_0010L;
assertEquals(expected, PackedScore.pack(2, 19, 131, 4, 50, 50));
}
@Test
void turnTricksTest() {
long score = 0b0000_0000_0000_0110_0100_0011_0010_0100_0000_0000_0001_0000_0110_0001_0011_0010L;
TeamId t = TeamId.TEAM_1;
assertEquals(2, PackedScore.turnTricks(score, t));
t = TeamId.TEAM_2;
assertEquals(4, PackedScore.turnTricks(score, t));
}
@Test
void turnPointsTest() {
long score = 0b0000_0000_0000_0110_0100_0011_0010_0100_0000_0000_0001_0000_0110_0001_0011_0010L;
TeamId t = TeamId.TEAM_1;
assertEquals(19, PackedScore.turnPoints(score, t));
t = TeamId.TEAM_2;
assertEquals(50, PackedScore.turnPoints(score, t));
}
@Test
void gamePoints() {
long score = 0b0000_0000_0000_0110_0100_0011_0010_0100_0000_0000_0001_0000_0110_0001_0011_0010L;
TeamId t = TeamId.TEAM_1;
assertEquals(131, PackedScore.gamePoints(score, t));
t = TeamId.TEAM_2;
assertEquals(50, PackedScore.gamePoints(score, t));
}
@Test
void withAdditionalTrickTest() {
// team1 win
// pack must have been checked -- je prends pas en compte les 5 de der
long score = PackedScore.pack(8,132,300, 0,0,200);
assertEquals(PackedScore.pack(9, 252, 300, 0,0,200), PackedScore.withAdditionalTrick(score, TeamId.TEAM_1, 20));
//team2 win the last trick
assertEquals(PackedScore.pack(8, 132, 300, 1, 20, 200),PackedScore.withAdditionalTrick(score, TeamId.TEAM_2, 20));
}
@Test
void nextTurnTest() {
// pack must have been checked
long score = PackedScore.pack(8,132,300, 1,20,200);
assertEquals(PackedScore.pack(0, 0, 432, 0, 0, 220), PackedScore.nextTurn(score));
score = PackedScore.pack(9, 252, 300, 0,0,200);
assertEquals(PackedScore.pack(0, 0, 552, 0, 0, 200), PackedScore.nextTurn(score));
}
}
<file_sep>/test/ch/epfl/javass/simulation/WinningPlayer.java
package ch.epfl.javass.simulation;
import java.util.Map;
import ch.epfl.javass.jass.*;
public class WinningPlayer implements Player {
private Player underlying;
private boolean hasWin=false;
private PlayerId ownId;
private Score score;
public WinningPlayer(Player underlying, PlayerId ownId) {
this.underlying=underlying;
this.ownId=ownId;
}
@Override
public void setPlayers(PlayerId ownId,
Map<PlayerId, String> playerNames) {
hasWin=false;
}
@Override
public Card cardToPlay(TurnState state, CardSet hand) {
return underlying.cardToPlay(state, hand);
}
@Override
public void setWinningTeam(TeamId winningTeam) {
if(ownId.team()==winningTeam)
hasWin=true;
System.out.println(score);
}
@Override
public void updateScore(Score score) {
this.score=score;
}
public boolean hasWin() {
return hasWin;
}
}
<file_sep>/src/ch/epfl/javass/gui/HandBean.java
package ch.epfl.javass.gui;
import ch.epfl.javass.jass.Card;
import ch.epfl.javass.jass.CardSet;
import ch.epfl.javass.jass.Jass;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
/**
* met en place les prorpiétés JavaFX pour la main du joueur
*
* @author <NAME>(301480)
*
*/
public final class HandBean {
private ObservableList<Card> handProperty;
private ObservableSet<Card> playableCardsProperty;
/**
*
*/
public HandBean() {
handProperty = FXCollections.observableArrayList();
playableCardsProperty = FXCollections.observableSet();
for(int i = 0; i<Jass.HAND_SIZE; ++i) {
handProperty.add(null);
}
}
/**
* retourne une vue non modifiable sur la propriété playableCards
*
* @return une vue non modifiable sur la propriété hand
*/
public ObservableList<Card> hand() {
return FXCollections.unmodifiableObservableList(handProperty);
}
/**
* retourne une vue non modifiable sur la propriété playableCards
*
* @return une vue non modifiable sur la propriété playableCards
*/
public ObservableSet<Card> playableCards(){
return FXCollections.unmodifiableObservableSet(playableCardsProperty);
}
/**
* met à jour hand, en fonction du CardSet passé en argument
*
* @param newHand
* met à jour hand, en fonction du CardSet passé en argument
*/
public void setHand(CardSet newHand) {
//handProperty se comporte comme un tableau
for(int i=0; i<Jass.HAND_SIZE; i++) {
Card current=handProperty.get(i);
Card isIn = newHand.contains(current) ? current : null;
handProperty.set(i, newHand.size()==Jass.HAND_SIZE ? newHand.get(i) : isIn);
}
}
/**
* met à jour playableCards, en fonction du CardSet passé en argument
*
* @param newPlayableCards
* met à jour playableCards, en fonction du CardSet passé en
* argument
*/
public void setPlayableCards(CardSet newPlayableCards) {
//l'ordre n'importe pas soit une carte est jouable soit non
playableCardsProperty.clear();
for(int i=0; i<newPlayableCards.size(); i++) {
playableCardsProperty.add(newPlayableCards.get(i));
}
}
}
<file_sep>/src/ch/epfl/javass/net/RemotePlayerServer.java
package ch.epfl.javass.net;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UncheckedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import ch.epfl.javass.jass.Card;
import ch.epfl.javass.jass.CardSet;
import ch.epfl.javass.jass.Player;
import ch.epfl.javass.jass.PlayerId;
import ch.epfl.javass.jass.TeamId;
import ch.epfl.javass.jass.Trick;
import ch.epfl.javass.jass.TurnState;
/**
* représente le serveur d'un joueur
*
* @author <NAME> (296100)
*
*/
public final class RemotePlayerServer {
private final Player underlyingPlayer;
private static Map<PlayerId, String> deseralizePlayersNames(String map){
Map<PlayerId, String> playersNames = new HashMap<>();
String[] names =StringSerializer.splitString(map,',');
for(PlayerId id : PlayerId.ALL) {
playersNames.put(id, StringSerializer.deserializeString(names[id.ordinal()]));
}
return playersNames;
}
/**
* @param underlyingPlayer
* le joueur sous-jacent qui doit être piloter
*/
public RemotePlayerServer(Player underlyingPlayer) {
this.underlyingPlayer = underlyingPlayer;
}
/**
* met en marche le serveur jusqu'à la fin de la partie
*/
public void run() {
boolean end=false;
try (ServerSocket s0 = new ServerSocket(Protocol.PORT);
Socket s = s0.accept();
BufferedReader r =
new BufferedReader(
new InputStreamReader(s.getInputStream(),
Protocol.CHARSET));
BufferedWriter w =
new BufferedWriter(
new OutputStreamWriter(s.getOutputStream(),
Protocol.CHARSET))) {
while(!end) {
String line = r.readLine();
String[] message = StringSerializer.splitString(line, Protocol.SEPARATOR);
JassCommand cmd = JassCommand
.valueOf(message[Protocol.COMMAND_INDEX]);
switch (cmd) {
case PLRS:
PlayerId own = Serializer.deserializeEnum(
message[Protocol.ID_INDEX], PlayerId.values());
Map<PlayerId, String> names = deseralizePlayersNames(
message[Protocol.NAMES_INDEX]);
underlyingPlayer.setPlayers(own, names);
break;
case TRMP:
underlyingPlayer.setTrump(Serializer.deserializeEnum(
message[Protocol.TRUMP_INDEX],
Card.Color.values()));
break;
case HAND:
underlyingPlayer.updateHand(Serializer
.deserializeCardSet(message[Protocol.HAND_INDEX]));
break;
case TRCK:
underlyingPlayer.updateTrick(Serializer
.deserializeTrick(message[Protocol.TRCIK_INDEX]));
break;
case CARD:
CardSet hand = Serializer.deserializeCardSet(
message[Protocol.HAND_WHEN_CARD]);
Card c = underlyingPlayer.cardToPlay(Serializer
.deserializeTurnState(message[Protocol.TURNSTATE_INDEX]),
hand);
w.write(Serializer.serializeCard(c));
w.write(Protocol.END_MESSAGE);
w.flush();
break;
case SCOR:
underlyingPlayer.updateScore(Serializer
.deserializeScore(message[Protocol.SCORE_INDEX]));
break;
case WINR:
underlyingPlayer.setWinningTeam(Serializer.deserializeEnum(
message[Protocol.TEAM_INDEX], TeamId.values()));
end = true;
break;
}
}
}catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
<file_sep>/test/ch/epfl/javass/simulation/RandomJassGame.java
package ch.epfl.javass.simulation;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ch.epfl.javass.jass.JassGame;
import ch.epfl.javass.jass.MctsPlayer;
import ch.epfl.javass.jass.Player;
import ch.epfl.javass.jass.PlayerId;
import ch.epfl.javass.jass.TeamId;
import ch.epfl.javass.net.RemotePlayerClient;
/**
* plusieurs méthodes utiles pour empaqueté un pli dans un int
*
* @author <NAME> (296100)
*
*/
public final class RandomJassGame {
public static void main(String[] args) throws Exception {
Map<PlayerId, Player> players = new HashMap<>();
Map<PlayerId, String> playerNames = new HashMap<>();
for (PlayerId pId: PlayerId.ALL) {
Player player=new RandomPlayer(2019);
players.put(pId, player);
playerNames.put(pId, pId.name());
}
try(RemotePlayerClient player= new RemotePlayerClient("localhost")){
players.put(PlayerId.PLAYER_1, new PrintingPlayer(player));
JassGame g = new JassGame(2019, players, playerNames);
while (! g.isGameOver()) {
g.advanceToEndOfNextTrick();
System.out.println("----");
}
}catch(IOException e){
throw new UncheckedIOException(e);
}
}
}<file_sep>/src/ch/epfl/javass/jass/PlayerId.java
package ch.epfl.javass.jass;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* définit les joueurs du jass
*
* @author <NAME> (301480)
*
*/
public enum PlayerId {
/**
* le joueur 1
*/
PLAYER_1(),
/**
* le joueur 2
*/
PLAYER_2(),
/**
* le joueur 3
*/
PLAYER_3(),
/**
* le joueur 4
*/
PLAYER_4();
/**
* liste de chaque joueur membre de l'énumeration
*/
public static final List<PlayerId> ALL = Collections.unmodifiableList(Arrays.asList(values()));
/**
* le nombre de joueurs
*/
public static final int COUNT = ALL.size();
/**
* retourne le nom de l'équipe à la quelle appartient le joueur sur lequel la
* méthode est appelée
*
* @return le nom de l'équipe à la quelle appartient le joueur sur lequel la
* méthode est appelée
*/
public TeamId team() {
return (this.equals(PLAYER_1) || this.equals(PLAYER_3)) ? TeamId.TEAM_1 : TeamId.TEAM_2;
}
}
<file_sep>/src/ch/epfl/javass/net/Serializer.java
package ch.epfl.javass.net;
import ch.epfl.javass.jass.Card;
import ch.epfl.javass.jass.CardSet;
import ch.epfl.javass.jass.Score;
import ch.epfl.javass.jass.Trick;
import ch.epfl.javass.jass.TurnState;
/**
* plusieurs méthodes utiles pour serialiser et déserialiser des objets de
* ch.epfl.javass.jass sous forme de chaine de caractères
*
* @author <NAME> (296100)
*
*/
public final class Serializer {
private static final int SCORE_INDEX =0;
private static final int CARDS_INDEX =1;
private static final int TRCIK_INDEX =2;
/**
* sérialise un ensemble de cartes
*
* @param set
* l'ensemble de cartes
* @return une chaine de caractère représentant l'ensemble de cartes
* serialisé
*/
public static String serializeCardSet(CardSet set) {
return StringSerializer.serializeLong(set.packed());
}
/**
* désérialise un ensemble de cartes
*
* @param s
* l'ensemble de cartes sérialisé
* @return l'ensemble de cartes désérialisé
*/
public static CardSet deserializeCardSet(String s) {
return CardSet.ofPacked(StringSerializer.deserializeLong(s));
}
/**
* sérialise un état du tour
*
* @param state
* l'état du tour
* @return une chaine de caractère représentant l'état du tour serialisé
*/
public static String serializeTurnState(TurnState state) {
String score = serializeScore(state.score());
String cards = serializeCardSet(state.unplayedCards());
String trick = serializeTrick(state.trick());
return StringSerializer.combineString(',', score, cards, trick);
}
/**
* désérialise un état du tour
*
* @param s
* l'état du tour sérialisé
* @return l'état du tour désérialisé
*/
public static TurnState deserializeTurnState(String s) {
String[] comp = StringSerializer.splitString(s, ',');
Score score = deserializeScore(comp[SCORE_INDEX]);
CardSet cards = deserializeCardSet(comp[CARDS_INDEX]);
Trick trick = deserializeTrick(comp[TRCIK_INDEX]);
return TurnState.ofPackedComponents(score.packed(),
cards.packed(),
trick.packed());
}
/**
* sérialise un pli
*
* @param trick
* le pli
* @return une chaine de caractère représentant le pli sérialisé
*/
public static String serializeTrick(Trick trick) {
return StringSerializer.serializeInt(trick.packed());
}
/**
* désérialise un pli
*
* @param trick
* le pli sérialisé
* @return le pli désérialisé
*/
public static Trick deserializeTrick(String trick) {
return Trick.ofPacked(StringSerializer.deserializeInt(trick));
}
/**
* sérialise une carte
*
* @param c
* la carte
* @return une chaine de caractère représentant la carte sérialisé
*/
public static String serializeCard(Card c) {
return StringSerializer.serializeInt(c.packed());
}
/**
* désérialise une carte
*
* @param card
* la carte sérialisée
* @return la carte sérialisée
*/
public static Card deserializeCard(String card) {
return Card.ofPacked(StringSerializer.deserializeInt(card));
}
/**
* sérialise un score
*
* @param s
* le score
* @return une chaine de caractère représentant le score sérialisé
*/
public static String serializeScore(Score s) {
return StringSerializer.serializeLong(s.packed());
}
/**
* désérialise un score
*
* @param score
* le score sérialisé
* @return le score désérialisé
*/
public static Score deserializeScore(String score) {
return Score.ofPacked(StringSerializer.deserializeLong(score));
}
/**
* sérialise une énummeration quelquonc
*
* @param e
* l'énumeration
* @return une chaine de caractère représentant l'énumération sérialisé
*/
public static String serializeEnum(Enum e) {
return StringSerializer.serializeInt(e.ordinal());
}
/**
* désérialise une énumeration
*
* @param e
* l'énumération sérialisée
* @param values
* l'ensemble des valeurs de l'énummération
* @return l'énumération désérialisée
*/
public static <E extends Enum<E>> E deserializeEnum(String e, E[] values) {
return values[StringSerializer.deserializeInt(e)];
}
}
| 06589fb1ebad25a9f0faa4470942e15009234770 | [
"Markdown",
"Java"
] | 17 | Java | thurgarion2/ch.epfl.javass | 00d3a09c3dc40ba3510f1d166d83ab7da144df22 | 354efe323f5714d38dffb8594f18792783f190f1 |
refs/heads/master | <file_sep>/*
Navicat MySQL Data Transfer
Source Server : cc
Source Server Version : 50717
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2017-07-30 10:03:47
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for question
-- ----------------------------
DROP TABLE IF EXISTS `question`;
CREATE TABLE `question` (
`qid` int(11) NOT NULL AUTO_INCREMENT,
`tword` varchar(100) DEFAULT NULL,
`tpic` varchar(45) DEFAULT NULL,
`tvideo` varchar(45) DEFAULT NULL,
`taudio` varchar(45) DEFAULT NULL,
`tflag` int(11) DEFAULT NULL,
`tanswer` varchar(10) DEFAULT NULL,
`tscore` int(11) DEFAULT NULL,
`eid` int(11) NOT NULL,
PRIMARY KEY (`qid`),
KEY `frk_e_q_idx` (`eid`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of question
-- ----------------------------
INSERT INTO `question` VALUES ('52', '个人', null, null, null, null, 'B', '4', '50');
INSERT INTO `question` VALUES ('53', '日本', null, null, null, null, 'B', '5', '50');
INSERT INTO `question` VALUES ('61', '对方根本', null, null, null, null, 'C', '4', '52');
INSERT INTO `question` VALUES ('62', '士大夫VS风格的', null, null, null, null, 'C', '4', '53');
INSERT INTO `question` VALUES ('63', '让他和你', null, null, null, null, 'B', '4', '54');
INSERT INTO `question` VALUES ('64', '买到第三方公司', null, null, null, null, 'C', '5', '53');
INSERT INTO `question` VALUES ('65', '是的', '9b482c2e-bfc5-48d6-801d-c8529ef8f087.jpg', null, null, null, 'B', '4', '56');
INSERT INTO `question` VALUES ('66', '到仿宋地方', null, null, null, null, 'B', '4', '56');
INSERT INTO `question` VALUES ('68', '地方规模较大', 'b18b0072-cb3f-4b21-afd0-83ae00067e36.jpg', null, null, null, 'B', '7', '58');
INSERT INTO `question` VALUES ('69', '风格化', '7006aafe-4921-4b2f-893e-777c88e78ffb.jpg', null, null, null, 'C', '5', '58');
INSERT INTO `question` VALUES ('70', '放假吗', null, null, null, null, 'D', '5', '59');
INSERT INTO `question` VALUES ('76', '付款', null, 'd4f1071b-642f-4dcb-b20f-a7b8f3b673a4.mp4', null, null, 'C', '5', '62');
INSERT INTO `question` VALUES ('77', '风格不对', 'a4763414-5da6-4691-9205-0245d686e053.jpg', null, null, null, 'B', '4', '62');
INSERT INTO `question` VALUES ('78', '都发给你的', '7ace05ac-8c21-45a6-8e8a-bb1b11acf3ba.jpg', null, null, null, 'C', '7', '62');
INSERT INTO `question` VALUES ('79', '哒哒哒', null, null, null, null, 'B', '5', '62');
INSERT INTO `question` VALUES ('80', '得分公司', '1191f3d2-9115-412d-b3e3-88a401501f3b.jpg', '7b8cd0f0-26d1-45f1-90ca-1ff72d2a5459.mp4', null, null, 'A', '4', '63');
INSERT INTO `question` VALUES ('81', '还给你', null, '4ec51d2c-f189-45d4-8cf2-d0e699336b2d.mp4', null, null, 'C', '5', '63');
INSERT INTO `question` VALUES ('85', '59卷-题', '4503d99e-d5b6-4fe2-9765-5cdbeb820208.jpg', null, null, null, 'C', '5', '59');
INSERT INTO `question` VALUES ('86', '快速', '4841c50b-b712-432c-8ae3-491a33c2cc51.jpg', null, null, null, 'B', '5', '64');
INSERT INTO `question` VALUES ('87', '啦啦啦啦啦', null, 'c2c9d364-c63e-4601-991b-925f326442a2.mp4', null, null, 'D', '5', '64');
INSERT INTO `question` VALUES ('88', '没打扫', null, null, '6a7ab488-4eac-4260-bf33-e613bdcb9e88.mp3', null, 'B', '5', '64');
INSERT INTO `question` VALUES ('89', '选出不同类的一项:', null, null, null, null, 'B', '5', '65');
INSERT INTO `question` VALUES ('90', '如果笔相对于写字,那么书相对于', null, null, null, null, 'A', '5', '65');
INSERT INTO `question` VALUES ('91', ' 动物学家与社会学家对应,正如动物与_____相对', null, null, null, null, 'B', '5', '65');
INSERT INTO `question` VALUES ('92', '如果所有的妇女都有大衣,那么漂亮的妇女会有:', null, null, null, null, 'B', '5', '65');
INSERT INTO `question` VALUES ('93', '南之于西北,正如西之于: ', null, null, null, null, 'C', '5', '65');
INSERT INTO `question` VALUES ('94', '找出不同类的一项:', null, null, null, null, 'B', '5', '65');
INSERT INTO `question` VALUES ('95', '选项A.B.C.D.中,哪项该填在 \"XOOOOXXOOOXXX\" 后面', null, null, null, null, 'A', '5', '65');
INSERT INTO `question` VALUES ('96', '.选出不同类的一项:', null, null, '43c015c9-b153-4bd5-8ee7-1f1761e2b46d.mp3', null, 'B', '5', '65');
INSERT INTO `question` VALUES ('97', '找出不同类图片', null, null, null, null, 'B', '5', '65');
INSERT INTO `question` VALUES ('98', '看个视频', null, '61d05e2a-9984-456b-8ff1-f26f8c804910.mp4', null, null, 'D', '5', '65');
INSERT INTO `question` VALUES ('99', 'kdkhs', null, '1e314130-3fa8-4b06-b3e5-bf4de0bfc7d9.mp4', null, null, 'C', '5', '66');
INSERT INTO `question` VALUES ('100', '陌生地方', null, null, null, null, 'B', '5', '66');
<file_sep>package com.ttc.ssm.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ttc.ssm.po.Examption;
import com.ttc.ssm.service.DoTestService;
import com.ttc.ssm.service.TestService;
@Controller
@RequestMapping("/home")
public class HomeController {
@Autowired
DoTestService doTestService;
@RequestMapping("/index")
public ModelAndView index(HttpServletRequest request) throws Exception{
HttpSession session = request.getSession();
session.setAttribute("manager", null);
ModelAndView modelAndView = new ModelAndView();
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.setViewName("index");
return modelAndView;
}
@RequestMapping("/managerLogin")
public ModelAndView managerLogin(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("manager/managerLogin");
return modelAndView;
}
@RequestMapping("/manager")
public ModelAndView manager(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("user", null);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("manager/managerIndex");
return modelAndView;
}
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : cc
Source Server Version : 50717
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2017-07-30 09:58:41
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`userpasswd` varchar(45) NOT NULL,
`userage` int(11) DEFAULT NULL,
`usersex` varchar(10) DEFAULT NULL,
`role` varchar(45) DEFAULT 'normal',
`level` int(11) DEFAULT '0',
`email` varchar(45) DEFAULT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('37', 'manager', '123', '22', 'male', 'manager', '0', '<EMAIL>');
INSERT INTO `user` VALUES ('38', 'sd', '123', '252', 'female', 'issuer', '0', '<EMAIL>');
INSERT INTO `user` VALUES ('39', 'new', '123', '25', 'female', 'normal', '0', '<EMAIL>');
INSERT INTO `user` VALUES ('40', 'sdf', '123', '33', 'female', 'issuer', '0', '<EMAIL>');
INSERT INTO `user` VALUES ('41', '345', '123', '21', 'male', 'vip', '2', '<EMAIL>');
INSERT INTO `user` VALUES ('44', 'aa', '123', '23', 'female', 'normal', '0', '<EMAIL>');
INSERT INTO `user` VALUES ('45', 'as', '123', '32', 'male', 'normal', '0', '<EMAIL>');
<file_sep>package com.ttc.ssm.controller;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.management.relation.Role;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.sun.org.apache.bcel.internal.generic.INEG;
import com.ttc.ssm.po.Analysis;
import com.ttc.ssm.po.Examption;
import com.ttc.ssm.po.History;
import com.ttc.ssm.po.Options;
import com.ttc.ssm.po.Question;
import com.ttc.ssm.po.User;
import com.ttc.ssm.service.DoTestService;
import com.ttc.ssm.service.TestService;
@Controller
@RequestMapping("/dotest")
public class DoTestController {
@Autowired
DoTestService doTestService;
@Autowired
TestService testService;
// 开始测试
@RequestMapping("/startTest")
public ModelAndView startTest(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
String role = null;
ModelAndView modelAndView = new ModelAndView();
Examption examption = new Examption();
List<Question> questionsList = new ArrayList<Question>();
List<Options> optionsList = new ArrayList<Options>();
int eid = Integer.parseInt(request.getParameter("eid"));
examption = doTestService.selectExamptionByEid(eid);
int elevel = examption.getElevel();
if ((user == null && elevel > 1)) {
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.addObject("levelWrong", "levelWrong");
modelAndView.setViewName("index");
return modelAndView;
} else if (user != null) {
role = user.getRole();
if ((role.equals("normal") && elevel > 2)) {
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.addObject("levelWrong", "levelWrong");
modelAndView.setViewName("index");
return modelAndView;
} else if (role.equals("issuer")) {
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.addObject("issuer", "notsupport");
modelAndView.setViewName("index");
return modelAndView;
}
}
questionsList = testService.selectQuestionByEid(eid);
optionsList = testService.selectOptionsByEid(eid);
request.setAttribute("questionsList", questionsList);
request.setAttribute("optionsList", optionsList);
modelAndView.addObject("examption", examption);
modelAndView.setViewName("dotest/doTest");
return modelAndView;
}
// 中级测试
@RequestMapping("/midtest")
public ModelAndView midtest(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
List<Examption> examptions = new ArrayList<Examption>();
List<Examption> allExamptions = new ArrayList<Examption>();
allExamptions = testService.selectAllExamptions();
for (int i = 0; i < allExamptions.size(); i++) {
if (allExamptions.get(i).getElevel() == 2) {
examptions.add(allExamptions.get(i));
}
}
modelAndView.addObject("examptions", examptions);
modelAndView.addObject("level", "中级测试");
modelAndView.setViewName("index");
return modelAndView;
}
// 高级测试
@RequestMapping("/hightest")
public ModelAndView hightest(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
List<Examption> examptions = new ArrayList<Examption>();
List<Examption> allExamptions = new ArrayList<Examption>();
allExamptions = testService.selectAllExamptions();
for (int i = 0; i < allExamptions.size(); i++) {
if (allExamptions.get(i).getElevel() == 3) {
examptions.add(allExamptions.get(i));
}
}
modelAndView.addObject("examptions", examptions);
modelAndView.addObject("level", "高级测试");
modelAndView.setViewName("index");
return modelAndView;
}
// 查询所有中的某张试卷
@RequestMapping("/queryAllTest")
public ModelAndView queryAllTest(HttpServletRequest request)
throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
List<Examption> examptions = new ArrayList<Examption>();
String keywords = request.getParameter("ename");
if (keywords.length() != 0) {
examptions = doTestService.selectExamByKeywords(keywords);
if (examptions.size() != 0) {
modelAndView.addObject("examptions", examptions);
} else {
modelAndView.addObject("notExist", "notExist");
modelAndView.addObject("inputvoid", "notvoid");
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
}
} else {
modelAndView.addObject("inputvoid", "inputvoid");
modelAndView.addObject("notExist", "false");
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
}
modelAndView.setViewName("index");
return modelAndView;
}
// 查询历史测试
@RequestMapping("/historytest")
public ModelAndView historytest(HttpServletRequest request)
throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (user != null) {
String username = user.getUsername();
List<History> histories = doTestService
.selectHistoriesByUsername(username);
modelAndView.addObject("histories", histories);
}
modelAndView.setViewName("dotest/historyTest");
return modelAndView;
}
// 查询所有中的某张试卷
@RequestMapping("/queryHistoryTest")
public ModelAndView queryHistoryTest(HttpServletRequest request)
throws Exception {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
ModelAndView modelAndView = new ModelAndView();
List<History> histories = new ArrayList<History>();
String keywords = request.getParameter("ename");
String username = user.getUsername();
if (keywords.length() != 0) {
histories = doTestService.selectHistoriesByKeywords(keywords,
username);
if (histories.size() != 0) {
modelAndView.addObject("histories", histories);
} else {
modelAndView.addObject("notExist", "notExist");
modelAndView.addObject("inputvoid", "notvoid");
histories = doTestService.selectHistoriesByUsername(username);
modelAndView.addObject("histories", histories);
}
} else {
modelAndView.addObject("inputvoid", "inputvoid");
modelAndView.addObject("notExist", "false");
histories = doTestService.selectHistoriesByUsername(username);
modelAndView.addObject("histories", histories);
}
modelAndView.setViewName("dotest/historyTest");
return modelAndView;
}
// 查看详细历史测试信息
@RequestMapping("/detail")
public ModelAndView detail(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
int hid = Integer.parseInt(request.getParameter("hid"));
History history = doTestService.selectHistoryByHid(hid);
modelAndView.addObject("history", history);
modelAndView.setViewName("dotest/detailHistoryTest");
return modelAndView;
}
// 交卷处理
@RequestMapping("/doTestSubmit")
public ModelAndView doTestSubmit(HttpServletRequest request)
throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
int eid = Integer.parseInt(request.getParameter("eid"));
int num = doTestService.selectExamptionByEid(eid).getQnumbers();
int score = 0;
int totalScore = 0;
String choose = "num";
String value = null;
List<Question> questions = testService.selectQuestionByEid(eid);
History history = new History();
history.setEid(eid);
history.setEname(doTestService.selectExamptionByEid(eid).getEname());
if (user == null) {
history.setUsername("游客");
} else {
history.setUsername(user.getUsername());
}
for (int i = 0; i < num; i++) {
choose = choose + i;
value = request.getParameter(choose);
if (value != null && questions.get(i).getTanswer().equals(value)) {
score = score + questions.get(i).getTscore();
} else {
score = score + 0;
}
totalScore = totalScore + questions.get(i).getTscore();
choose = "num";
}
history.setHscore(score);
Analysis analysis = testService.selectAnalysisByEid(eid);
if (score <= totalScore / 4) {
history.setAnalysis(analysis.getAcontent1());
} else if (score <= totalScore / 2 && score > totalScore / 4) {
history.setAnalysis(analysis.getAcontent2());
} else if (score > totalScore / 2
&& score <= (totalScore - totalScore / 4)) {
history.setAnalysis(analysis.getAcontent3());
} else {
history.setAnalysis(analysis.getAcontent4());
}
java.sql.Timestamp testtime = new java.sql.Timestamp(
new Date().getTime());
history.setTesttime(testtime);
if (user != null) {
doTestService.inserHistory(history);
}
modelAndView.addObject("history", history);
modelAndView.setViewName("dotest/doTestResult");
return modelAndView;
}
// 删除历史
@RequestMapping("/deleteHistory")
public ModelAndView deleteHistory(HttpServletRequest request)
throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
int hid = Integer.parseInt(request.getParameter("hid"));
if (doTestService.selectHistoryByHid(hid) != null) {
doTestService.deleteHistoryByHid(hid);
}
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (user != null) {
String username = user.getUsername();
List<History> histories = doTestService
.selectHistoriesByUsername(username);
modelAndView.addObject("histories", histories);
}
modelAndView.setViewName("dotest/historyTest");
return modelAndView;
}
}
<file_sep>package com.ttc.ssm.service;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
public interface UploadService {
public String uploadPic(MultipartFile pic) throws IllegalStateException, IOException ;
}
<file_sep>package com.ttc.ssm.service;
import java.util.List;
import com.ttc.ssm.po.User;
public interface UserService {
public void insert(User user) throws Exception;
public User selectByNameAndPasswd(String name,String passwd) throws Exception;
public User selectByName(String name) throws Exception;
public void updateUser(User user) throws Exception;
public List<User> selectAllUser() throws Exception;
public void deleteUser(int userid) throws Exception;
public void updateUserRole(User user) throws Exception;
public List<User> selectAllIssuer() throws Exception;
public List<User> selectUserByKeywords(String keywords) throws Exception;
}
<file_sep>package com.ttc.ssm.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ttc.ssm.po.User;
public interface UserMapper {
void insertuser(User user);
User selectByNameAndPasswd(@Param("name")String name, @Param("passwd")String passwd);
User selectByName(@Param("name")String name);
void updateUser(User user);
List<User> selectAllUser();
List<User> selectAllIssuer();
void deleteUser(int userid);
void updateUserRole(User user);
List<User> selectUserByKeywords(@Param("keywords")String keywords);
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : cc
Source Server Version : 50717
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2017-07-30 10:03:40
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for options
-- ----------------------------
DROP TABLE IF EXISTS `options`;
CREATE TABLE `options` (
`oid` int(11) NOT NULL AUTO_INCREMENT,
`qid` int(11) NOT NULL,
`eid` int(11) NOT NULL,
`aword` varchar(100) DEFAULT NULL,
`apic` varchar(45) DEFAULT NULL,
`bword` varchar(100) DEFAULT NULL,
`bpic` varchar(45) DEFAULT NULL,
`cword` varchar(100) DEFAULT NULL,
`cpic` varchar(45) DEFAULT NULL,
`dword` varchar(100) DEFAULT NULL,
`dpic` varchar(45) DEFAULT NULL,
`ascore` int(11) DEFAULT NULL,
`bscore` int(11) DEFAULT NULL,
`cscore` int(11) DEFAULT NULL,
`dscore` int(11) DEFAULT NULL,
PRIMARY KEY (`oid`)
) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of options
-- ----------------------------
INSERT INTO `options` VALUES ('34', '52', '50', '地方', null, '日坛北', null, '儿童版', null, '额', null, null, null, null, null);
INSERT INTO `options` VALUES ('35', '53', '50', '根本', null, '而不', null, '本题', null, '儿童版', null, null, null, null, null);
INSERT INTO `options` VALUES ('43', '61', '52', '覆盖发', null, '让他和', null, '人体内', null, '恶霸 ', null, null, null, null, null);
INSERT INTO `options` VALUES ('44', '62', '53', '根本大法', null, 'berg', null, '而不', null, '被', null, null, null, null, null);
INSERT INTO `options` VALUES ('45', '63', '54', ' 若与', null, '柔滑凝乳', null, '你让他和你', null, '谈话内容', null, null, null, null, null);
INSERT INTO `options` VALUES ('46', '64', '53', '哦对粉丝vhi', null, 'v哦多少积分v', null, '更好的风格', null, '是豆腐干士大夫', null, null, null, null, null);
INSERT INTO `options` VALUES ('47', '65', '56', '更换', null, '就明天', null, '郭敬明', null, '环境', null, null, null, null, null);
INSERT INTO `options` VALUES ('48', '66', '56', '法国队', null, '梵蒂冈', null, '发给对方 ', null, '法国队', null, null, null, null, null);
INSERT INTO `options` VALUES ('50', '68', '58', '更换', null, '还给你', null, '规范化', null, '风格化', null, null, null, null, null);
INSERT INTO `options` VALUES ('51', '69', '58', '规范化', null, '风格化', null, '烦恼', null, '你让他', null, null, null, null, null);
INSERT INTO `options` VALUES ('52', '70', '59', '干活呢', null, '凤凰男', null, '风格化', null, '免费', null, null, null, null, null);
INSERT INTO `options` VALUES ('58', '76', '62', '豆腐干', null, '豆腐干豆腐干', null, '的风格不符的根本', null, '对方', null, null, null, null, null);
INSERT INTO `options` VALUES ('59', '77', '62', '对方根本', '25d494d6-0d00-453b-af76-97fe9a665eea.jpg', '怪不得', 'e0015202-cf6f-42fd-8575-824c899ba07e.jpg', '豆腐干', '19d6bcd2-4532-4134-9bfe-dcf68a1f99fd.jpg', '豆腐干 ', 'cadd2c72-0149-4b31-a7c5-9896a20a984e.jpg', null, null, null, null);
INSERT INTO `options` VALUES ('60', '78', '62', '干活呢', 'c3daba86-d518-4f6b-b0bd-62f92b845c35.jpg', '6好几个', 'ff58638f-7177-4d24-9211-cbda191c6e3d.jpg', '规划局个', 'dc6034ec-07a5-48e9-833b-e27b1a6fc199.jpg', '规划局', '24f74cf3-bb9c-48b2-8b45-458f19f06389.jpg', null, null, null, null);
INSERT INTO `options` VALUES ('61', '79', '62', '得分', null, '是', null, '发山东', null, '是的', null, null, null, null, null);
INSERT INTO `options` VALUES ('62', '80', '63', '放荡', null, '怪不得', null, '对方根本', null, '的', null, null, null, null, null);
INSERT INTO `options` VALUES ('63', '81', '63', '就看过', '69688a1e-68eb-43f5-b17e-567f5574640f.jpg', '就的', 'c7505096-453a-41b6-89e5-529759ada44f.jpg', '丰田预计', 'f42d4df3-9f50-4a7c-8d4e-d1a148449138.jpg', '还能', 'ccb34b03-4acd-4393-98c8-a06941d02f1b.jpg', null, null, null, null);
INSERT INTO `options` VALUES ('67', '85', '59', '更方便的', null, '豆腐干', null, '覆盖', null, '覆盖', null, null, null, null, null);
INSERT INTO `options` VALUES ('68', '86', '64', '股东股份', '4b3f382c-100f-4c86-9235-7242283a4b35.jpg', '梵蒂冈', 'd8f23d33-33c5-4a7a-80dc-709c66216701.jpg', '对方根本', 'a2655740-0e2b-4d45-be98-9434af7d5f3a.jpg', '怪不得', '97b418d3-f698-4696-9c7e-0f731ca20d56.jpg', null, null, null, null);
INSERT INTO `options` VALUES ('69', '87', '64', '发个广告', null, '嘎嘎嘎f', null, 'f\'f方法', null, '烦烦烦', null, null, null, null, null);
INSERT INTO `options` VALUES ('70', '88', '64', '看看到了', null, '的酒店家具', null, '发的地方', null, '的方法对付的', null, null, null, null, null);
INSERT INTO `options` VALUES ('71', '89', '65', '蛇', null, '大树', null, '狮子', null, '老虎', null, null, null, null, null);
INSERT INTO `options` VALUES ('72', '90', '65', '娱乐', null, '阅读', null, '学文化', null, '解除疲劳', null, null, null, null, null);
INSERT INTO `options` VALUES ('73', '91', '65', '人类', null, '问题', null, '社会', null, '社会学', null, null, null, null, null);
INSERT INTO `options` VALUES ('74', '92', '65', '.给多的大衣', null, '时髦的大衣 ', null, '大衣', null, '昂贵的大衣', null, null, null, null, null);
INSERT INTO `options` VALUES ('75', '93', '65', '西北', null, '东北', null, '西南', null, '东南', null, null, null, null, null);
INSERT INTO `options` VALUES ('76', '94', '65', '铁锅', null, '小勺', null, '米饭', null, '碟子', null, null, null, null, null);
INSERT INTO `options` VALUES ('77', '95', '65', 'XXO', null, 'OOX', null, 'XOX', null, 'OXO', null, null, null, null, null);
INSERT INTO `options` VALUES ('78', '96', '65', '地板', null, '壁橱', null, '窗户', null, '窗帘', null, null, null, null, null);
INSERT INTO `options` VALUES ('79', '97', '65', 'sodium', 'dff110ba-7cc7-411d-851d-acf8c8f5dd9c.jpg', 'sdf', '0d215a7e-ae87-438e-b7e0-c29499d1e875.jpg', 'fgdsdf', '922aa84f-b7ce-4726-b759-995d398b7661.jpg', 'sdfv', '257ec38c-6ea2-44b8-a392-4d3feec5349d.jpg', null, null, null, null);
INSERT INTO `options` VALUES ('80', '98', '65', '电风扇', null, '是的覅', null, '是的覅', null, '是的覅', null, null, null, null, null);
INSERT INTO `options` VALUES ('81', '99', '66', 'sdffsd', null, 'sdf', null, 'sdfdfg', null, 'sdfg', null, null, null, null, null);
INSERT INTO `options` VALUES ('82', '100', '66', '山东覅是', null, '山东分公司', null, '山东分公司', null, '士大夫敢死队', null, null, null, null, null);
<file_sep>package com.ttc.ssm.service.impl;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;
import com.ttc.ssm.service.UploadService;
public class UploadServiceImpl implements UploadService{
public String uploadPic(MultipartFile pic) throws IllegalStateException, IOException {
String originalFilename = pic.getOriginalFilename();
if (pic != null && originalFilename != null
&& originalFilename.length() > 0) {
String pic_path = "C:\\TEMP\\";
String newFileName = UUID.randomUUID()
+ originalFilename.substring(originalFilename
.lastIndexOf("."));
File newFile = new File(pic_path + newFileName);
pic.transferTo(newFile);
return newFileName;
}
return null;
}
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : cc
Source Server Version : 50717
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2017-07-30 10:03:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for history
-- ----------------------------
DROP TABLE IF EXISTS `history`;
CREATE TABLE `history` (
`hid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`eid` int(11) NOT NULL,
`hscore` int(11) DEFAULT NULL,
`ename` varchar(100) DEFAULT NULL,
`analysis` varchar(100) DEFAULT NULL,
`testtime` datetime(6) DEFAULT NULL,
PRIMARY KEY (`hid`)
) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of history
-- ----------------------------
INSERT INTO `history` VALUES ('42', 'new', '45', '10', '东方闪电', 'sdfg如果被', '2017-07-29 11:26:32.000000');
INSERT INTO `history` VALUES ('43', 'new', '45', '10', '东方闪电', 'sdfg如果被', '2017-07-29 11:27:53.000000');
INSERT INTO `history` VALUES ('47', 'new', '49', '4', 'vwe十大发的', '不然根本怪不得', '2017-07-29 14:04:12.000000');
INSERT INTO `history` VALUES ('49', 'sdf', '52', '0', '不太热', '女哦司法v搜索的', '2017-07-29 20:27:42.000000');
INSERT INTO `history` VALUES ('50', '345', '45', '10', '东方闪电', 'sdfg如果被', '2017-07-29 20:38:57.000000');
INSERT INTO `history` VALUES ('51', '345', '58', '0', 'j哦i地方', '更换', '2017-07-29 20:40:51.000000');
INSERT INTO `history` VALUES ('52', '345', '54', '4', '那天', '人谈话内容', '2017-07-29 20:41:30.000000');
INSERT INTO `history` VALUES ('53', '345', '52', '0', '不太热', '女哦司法v搜索的', '2017-07-29 20:50:33.000000');
INSERT INTO `history` VALUES ('54', '345', '50', '5', 'fvwev', ' 人根本不 e', '2017-07-29 20:52:16.000000');
INSERT INTO `history` VALUES ('55', 'new', '58', '0', 'j哦i地方', '更换', '2017-07-29 21:00:00.000000');
INSERT INTO `history` VALUES ('56', 'new', '56', '0', '莫', '规划局', '2017-07-29 21:01:47.000000');
INSERT INTO `history` VALUES ('57', 'new', '61', '4', '发v哦是', '是不是yio', '2017-07-29 21:03:08.000000');
INSERT INTO `history` VALUES ('59', '345', '58', '7', 'j哦i地方', 'try内容提要', '2017-07-29 21:51:05.000000');
INSERT INTO `history` VALUES ('61', 'as', '59', '0', 'gfn', '十大城市', '2017-07-30 08:46:54.000000');
INSERT INTO `history` VALUES ('62', 'as', '58', '0', 'j哦i地方', '更换', '2017-07-30 08:58:26.000000');
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : cc
Source Server Version : 50717
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2017-07-30 10:03:14
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for examption
-- ----------------------------
DROP TABLE IF EXISTS `examption`;
CREATE TABLE `examption` (
`eid` int(11) NOT NULL AUTO_INCREMENT,
`ename` varchar(45) DEFAULT NULL,
`username` varchar(45) NOT NULL,
`ekind` varchar(45) DEFAULT NULL,
`elevel` int(11) DEFAULT NULL,
`qnumbers` int(11) DEFAULT NULL,
PRIMARY KEY (`eid`)
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of examption
-- ----------------------------
INSERT INTO `examption` VALUES ('50', 'fvwev', 'sd', '性格', '3', '2');
INSERT INTO `examption` VALUES ('52', '不太热', 'sd', '智商', '1', '1');
INSERT INTO `examption` VALUES ('53', 'VS送到', 'sd', '智商', '1', '2');
INSERT INTO `examption` VALUES ('54', '那天', 'sd', '性格', '3', '1');
INSERT INTO `examption` VALUES ('56', '莫', 'sd', '性格', '1', '2');
INSERT INTO `examption` VALUES ('58', 'j哦i地方', 'sd', '性格', '2', '2');
INSERT INTO `examption` VALUES ('59', 'gfn', 'sd', '性格', '2', '2');
INSERT INTO `examption` VALUES ('62', '副书记', 'sdf', '智商', '1', '4');
INSERT INTO `examption` VALUES ('63', '搜索', 'sdf', '性格', '1', '2');
INSERT INTO `examption` VALUES ('64', '坎坎坷坷', 'sdf', '性格', '3', '3');
INSERT INTO `examption` VALUES ('65', '智力测试', 'sdf', '智商', '1', '10');
INSERT INTO `examption` VALUES ('66', 'kkk', 'sd', '性格', '3', '2');
<file_sep>package com.ttc.ssm.po;
public class Examption {
private Integer eid;
private String ename;
private String username;
private String ekind;
private Integer elevel;
private Integer qnumbers;
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEkind() {
return ekind;
}
public void setEkind(String ekind) {
this.ekind = ekind;
}
public Integer getElevel() {
return elevel;
}
public void setElevel(Integer elevel) {
this.elevel = elevel;
}
public Integer getQnumbers() {
return qnumbers;
}
public void setQnumbers(Integer qnumbers) {
this.qnumbers = qnumbers;
}
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : cc
Source Server Version : 50717
Source Host : localhost:3306
Source Database : ssm
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2017-07-30 10:03:25
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for analysis
-- ----------------------------
DROP TABLE IF EXISTS `analysis`;
CREATE TABLE `analysis` (
`aid` int(11) NOT NULL AUTO_INCREMENT,
`eid` int(11) NOT NULL,
`acontent1` varchar(100) DEFAULT NULL,
`acontent2` varchar(100) DEFAULT NULL,
`acontent3` varchar(100) DEFAULT NULL,
`acontent4` varchar(100) DEFAULT NULL,
PRIMARY KEY (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of analysis
-- ----------------------------
INSERT INTO `analysis` VALUES ('10', '50', '日本人怪不得', 'berg不e', ' 人根本不 e', '而被人');
INSERT INTO `analysis` VALUES ('12', '52', '女哦司法v搜索的', '呢士大夫VS付款VS', '上岛咖啡v斯蒂夫VS', '索尼单反v斯蒂芬不是');
INSERT INTO `analysis` VALUES ('13', '53', 'b如果被', '额度', '怪不得', '的风格不对');
INSERT INTO `analysis` VALUES ('14', '54', ' 如何让他', ' 让他', '让他和你', '人谈话内容');
INSERT INTO `analysis` VALUES ('15', '56', '规划局', '复合弓', '风格化', '返回');
INSERT INTO `analysis` VALUES ('16', '58', '更换', '刚好符合名人堂', 'try内容提要', '让她已经人');
INSERT INTO `analysis` VALUES ('19', '62', '就会发动的fog不', '是覅不是比', '觉得奴工', '的覅u避风港好吧');
INSERT INTO `analysis` VALUES ('20', '63', '豆腐干', ' 豆腐干', '法国队', ' 豆腐干');
INSERT INTO `analysis` VALUES ('22', '59', '十大城市', '是v的 ', '山东覅是', '似懂非懂');
INSERT INTO `analysis` VALUES ('23', '64', '。。。打开快点快点快点快点', '流量代理端口打开附件附件发', '大家都觉得减肥减肥', '等等看看打开大开打开');
INSERT INTO `analysis` VALUES ('24', '65', '智力非常优秀', '智力优秀', '智力中上', '弱智');
INSERT INTO `analysis` VALUES ('25', '66', '佛VS地方vi', '史蒂夫VS的', '法定税率hi士大夫', '是的覅哦VS的');
<file_sep>package com.ttc.ssm.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.ttc.ssm.po.Examption;
import com.ttc.ssm.po.User;
import com.ttc.ssm.service.DoTestService;
import com.ttc.ssm.service.TestService;
import com.ttc.ssm.service.UserService;
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userservice;
@Autowired
DoTestService doTestService;
// 注册
@RequestMapping("/register")
public ModelAndView register(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("err", null);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("register");
return modelAndView;
}
// 注册处理
@RequestMapping(value = "/registersubmit", method = RequestMethod.POST)
public ModelAndView registersubmit(HttpServletRequest request)
throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
User user = new User();
String passwderror = "<PASSWORD>";
String usererror = "usererror";
HttpSession session = request.getSession();
String pasd = request.getParameter("repassword");
user.setUsername(request.getParameter("username"));
user.setUserpasswd(request.getParameter("userpasswd"));
user.setUserage(Integer.parseInt(request.getParameter("userage")));
user.setUsersex(request.getParameter("usersex"));
user.setEmail(request.getParameter("email"));
user.setRole("normal");
if (pasd.equals(user.getUserpasswd())
&& (userservice.selectByName(user.getUsername())) == null) {
userservice.insert(user);
session.setAttribute("user", user);
modelAndView.addObject("registsuccess", "registsuccess");
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.setViewName("index");
return modelAndView;
} else if (!pasd.equalsIgnoreCase(user.getUserpasswd())
&& (userservice.selectByName(user.getUsername())) == null) {
session.setAttribute("err", passwderror);
modelAndView.addObject("userinfo", user);
modelAndView.setViewName("register");
return modelAndView;
} else {
session.setAttribute("err", usererror);
modelAndView.setViewName("register");
return modelAndView;
}
}
// 登录
@RequestMapping("/login")
public ModelAndView login() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
// 登录处理
@RequestMapping(value = "/loginsubmit", method = RequestMethod.POST)
public ModelAndView loginsubmit(HttpServletRequest request,
ServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
String role = "manager";
User user = new User();
String username = request.getParameter("username");
String password = request.getParameter("userpasswd");
user = userservice.selectByNameAndPasswd(username, password);
if (user != null && (!user.getRole().equals(role))) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
session.setAttribute("manager", null);
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.setViewName("index");
return modelAndView;
} else {
modelAndView.addObject("passwdWrong", "passwdWrong");
modelAndView.setViewName("login");
return modelAndView;
}
}
// 用户注销
@RequestMapping("/logout")
public ModelAndView logout(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
session.setAttribute("user", null);
ModelAndView modelAndView = new ModelAndView();
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.setViewName("index");
return modelAndView;
}
// 更新用户信息
@RequestMapping("/updateuser")
public ModelAndView updateuaer(HttpServletRequest request) throws Exception {
String username = request.getParameter("username");
User user = new User();
user = userservice.selectByName(username);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", user);
modelAndView.setViewName("updateuser");
return modelAndView;
}
// 更新用户信息提交处理
@RequestMapping("/updateusersubmit")
public ModelAndView updateusersubmit(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("utf-8");
ModelAndView modelAndView = new ModelAndView();
User user = new User();
user.setUserid(Integer.parseInt(request.getParameter("userid")));
user.setUsername(request.getParameter("username"));
user.setUserage(Integer.parseInt(request.getParameter("userage")));
user.setUsersex(request.getParameter("usersex"));
user.setEmail(request.getParameter("email"));
if (user.getUserid() != null
&& userservice.selectByName(user.getUsername()) != null) {
userservice.updateUser(user);
HttpSession session = request.getSession();
session.setAttribute("user",
userservice.selectByName(user.getUsername()));
List<Examption> examptions = new ArrayList<Examption>();
examptions = doTestService.selectLowExamption();
modelAndView.addObject("examptions", examptions);
modelAndView.setViewName("index");
return modelAndView;
} else {
modelAndView.setViewName("updateuser");
return modelAndView;
}
}
}
<file_sep>package com.ttc.ssm.po;
public class Analysis {
private Integer aid;
private Integer eid;
private String acontent1;
private String acontent2;
private String acontent3;
private String acontent4;
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getAcontent1() {
return acontent1;
}
public void setAcontent1(String acontent1) {
this.acontent1 = acontent1;
}
public String getAcontent2() {
return acontent2;
}
public void setAcontent2(String acontent2) {
this.acontent2 = acontent2;
}
public String getAcontent3() {
return acontent3;
}
public void setAcontent3(String acontent3) {
this.acontent3 = acontent3;
}
public String getAcontent4() {
return acontent4;
}
public void setAcontent4(String acontent4) {
this.acontent4 = acontent4;
}
}
<file_sep>package com.ttc.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.ttc.ssm.mapper.TestMapper;
import com.ttc.ssm.po.Examption;
import com.ttc.ssm.po.History;
import com.ttc.ssm.service.DoTestService;
public class DoTestServiceImpl implements DoTestService{
@Autowired
TestMapper testMapper;
public Examption selectExamptionByEid(int eid) {
return testMapper.selectExamptionByEid(eid);
}
public List<Examption> selectLowExamption() {
return testMapper.selectLowExamption();
}
public void inserHistory(History history) throws Exception{
testMapper.inserHistory(history);
}
public List<Examption> selectExamByKeywords(String keywords) throws Exception{
return testMapper.selectExamByKeywords(keywords);
}
public List<History> selectHistoriesByUsername(String username) throws Exception{
return testMapper.selectHistoriesByUsername(username);
}
public History selectHistoryByHid(int hid) throws Exception{
return testMapper.selectHistoryByHid(hid);
}
public List<History> selectHistoriesByKeywords(String keywords,String username) throws Exception{
return testMapper.selectHistoriesByKeywords(keywords,username);
}
public void deleteHistoryByHid(int hid) throws Exception{
testMapper.deleteHistoryByHid(hid);
}
}
<file_sep>package com.ttc.ssm.po;
public class User {
private Integer userid;
private String username;
private String userpasswd;
private Integer userage;
private String usersex;
private String role;
private Integer level;
private String email;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpasswd() {
return userpasswd;
}
public void setUserpasswd(String userpasswd) {
this.userpasswd = userpasswd;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
public String getUsersex() {
return usersex;
}
public void setUsersex(String usersex) {
this.usersex = usersex;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 319e8871ac1a5a8b7659afb750773d9c5c15a79a | [
"Java",
"SQL"
] | 17 | SQL | SuperTaory/Online-Test | ec179b15fac27000e9645edc5d88305edebb253d | 55fb3e949c8c30c48d29e875b5070e6a12e865eb |
refs/heads/master | <file_sep>import streamlit as st
import pandas as pd
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
import io
import base64
import time
st.set_option('deprecation.showfileUploaderEncoding', False)
# All the function needed
#--------------------------------------------------------------------------------
# Define image size
IMG_SIZE = 224
# Define a batch size , 32 is a good start
BATCH_SIZE = 32
# Import labels and create an array of 120 dog breeds
labels_csv = pd.read_csv("/home/gagan/Desktop/Ml-Sample/labels.csv")
labels = labels_csv["breed"].to_numpy()
unique_breeds = np.unique(labels)
# Prediction label function
def get_pred_label(prediction_probabilities):
"""
Turn an array of prediction probabilities into a label.
"""
return unique_breeds[np.argmax(prediction_probabilities)]
#---------------------------------------------------------------------------------
st.title("Welcome to Dog 🐕 Vision 👁️ AI")
st.write("")
st.write("Upload your dog's image")
file = st.file_uploader("", type=["jpg", "png"])
if file is None:
st.text("Please upload an image file")
else:
custom_image = Image.open(file)
st.text("Are you excited?😀...🐶...")
if file:
# Data preprocessing
image = tf.io.decode_image(file.getvalue(), channels=3, dtype=tf.float32)
image= tf.image.resize(image, size=[IMG_SIZE, IMG_SIZE])
data = tf.data.Dataset.from_tensor_slices([image])
data_batch = data.batch(BATCH_SIZE)
# Load pretrained model and make predictions
loaded_full_model = tf.keras.models.load_model('/home/gagan/Desktop/Ml-Sample/20200727-18521595875929-full-image-set-mobilenetv2-Adam.h5',custom_objects={'KerasLayer':hub.KerasLayer})
custom_preds = loaded_full_model.predict(data_batch)
# Get predicted label
custom_pred_labels = [get_pred_label(custom_preds[i]) for i in range(len(custom_preds))]
# Starting a long computation...'
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Hold tight....{i+1}')
bar.progress(i + 1)
time.sleep(0.1)
# '...and now we\'re done!'
st.title(f'Your dog is a {custom_pred_labels[0]}')
# st.write(custom_pred_labels[0])
st.image(custom_image, use_column_width=True)
<file_sep>

# Project Dog Vision AI
## This project builds an End-to-end Multi-Class Image Classifier using Tensorflow2, Google Colab and Streamlit
**Problem :**
Identifying the breed of a dog given an image of a dog
**Scenario,** When I am sitting at the Starbucks and I take a photo of a dog, want to know what breed of a dog it is.
# Demo Preview

##
**Project dataset** is available for download at : https://drive.google.com/drive/folders/1--pc8zFIYLXk8QL2XlG3vE2BDBsR7WuO?usp=sharing
| 6bb45b9cc18dab718c45d38886a91f7fe32e1d7d | [
"Markdown",
"Python"
] | 2 | Python | GaganSingh11/Project-dog-vision | ec0c79951f99614524b4b2af235a868ab3d7417a | 7061f296362205a349c3e55acfa8f984f97bbb38 |
refs/heads/master | <repo_name>panella/Algoritmos-UFES<file_sep>/06_Interpolação de Newton(ok)/InterpolaçãoNewton.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
int m = 5;
double z = 2,result = 0.0;
double x[m] = {0.1,0.6,0.8,1.2,1.8};
double y[m] = {1.221,3.32,4.953,6.2,7.1};
double aux_y[m] = {1.221,3.32,4.953,6.2,7.1};
for (int k = 0;k<m;k++) {
for (int i = m-1;i>k;i--) {
aux_y[i] = (aux_y[i] - aux_y[i-1]) / (x[i] - x[i-k-1]);
}
}
result = aux_y[m-1];
for (int i = m-2;i>=0;i--) {
result = result * (z - x[i]) + aux_y[i];
}
cout << "\n";
cout << fixed << setprecision(10) << "\nResultado: " << result;
}
<file_sep>/04_Gauss-Pivo(ok)/Gauss_Pivoteamento.c
#include <stdio.h>
#include <stdlib.h>
float* criaVetor(int Tamanho){ //Recebe a quantidade de Linhas e Colunas como Parâmetro
int i; //Variáveis Auxiliares
float *v = (float*)malloc(Tamanho * sizeof(float)); //Aloca um Vetor de Ponteiros
for (i = 0; i < Tamanho; i++){ //Percorre as linhas do Vetor de Ponteiros
printf("Digite o valor de b[%d]:",i+1);
scanf("%f",&v[i]);
}
return v; //Retorna o Ponteiro para a Matriz Alocada
}
float ** criaMatriz(int Tamanho){
int i,j; //Variáveis Auxiliares
float **m = (float**)malloc(Tamanho * sizeof(float*)); //Aloca um Vetor de Ponteiros
//Aloca memoria para a matriz
for (i = 0; i < Tamanho; i++){ //Percorre as linhas do Vetor de Ponteiros
m[i] = (float*) malloc(Tamanho * sizeof(float)); //Aloca um Vetor de Inteiros para cada posição do Vetor de Ponteiros.
}
//Preenche os valores da matriz
for (i = 0; i < Tamanho; i++){ //Percorre as linhas do Vetor de Ponteiros
for (j = 0; j < Tamanho; j++){ //Percorre o Vetor de Inteiros atual.
printf("Digite o valor de a[%d][%d]:",i+1,j+1);
scanf("%f",&m[i][j]);
}
}
return m;
}
void printaMatriz (float** m,int Tamanho){
int i,j;
for (i = 0; i < Tamanho; i++){ //Percorre as linhas do Vetor de Ponteiros
printf("\n");
for (j = 0; j < Tamanho; j++){ //Percorre o Vetor de Inteiros atual.
printf("%f | ",m[i][j]);
}
}
}
void printaVetor (float* v, int Tamanho){
int i;
printf("\n");
for (i = 0; i < Tamanho; i++){ //Percorre as linhas do Vetor de Ponteiros
printf("%f | ",v[i]);
}
}
int main (){
float **a;
float *b;
float *x;
int n,i,j,k;
float s,m;
printf("Digite o tamanho 'n' da matriz[n][n]: ");
scanf("%d",&n);
x = (float*)malloc(n * sizeof(float));
a = criaMatriz(n);
b = criaVetor(n);
n--;//Só porque os indices vao ate tam-1
//printf("foi 0");
printf("Matriz A:");
printaMatriz(a,n+1);
printf("\nVetor B:");
printaVetor(b,n+1);
//Pivoteamento
int *aux;
aux = (int*)malloc(sizeof(int)*n);
for(i=0;i>n;i++){//Percorre as linhas e dita o termo da diagonal
for(j=0;j>n;j++){//Percorre a coluna da linha,checando valores de referencia
if (a[j][i]>a[i][i]){
for(k = 0;k>n;k++){//percorre o vetor auxiliar o preenchendo com os valores a serem substituidos
aux[k] = a[i][k];//Linha fixa, coluna variavel.(linha da diagongal)
a[i][k] = a[j][k];//Linha fixa, coluna variavel.(linha fora da diagonal)
a[j][k] = aux[k];//Retorna a linha originaria da diagonal para a posicao da fora da diagonal
}
}
}
}
printf("\nMatriz A-pivoteada:");
printaMatriz(a,n+1);
x[n] = b[n]/a[n][n];
//Eliminação
k = 0;
//for(k=0;k<=n-1;k++){
while(k<=n-1){
i = k+1;
while(i<=n){
m = a[i][k]/a[k][k];
a[i][k] = 0;
j = k+1;
while(j<=n){
a[i][j]= a[i][j]-(m*a[k][j]);
j++;
}
b[i]=b[i]-(m*b[k]);
i++;
}
k++;
}
//Sistema triangulado
printf("\nMatriz A-triang:");
printaMatriz(a,n+1);
//Resolução do sistema
i = n;
while(i != -1){
//printf("foi 1");
s = 0;
j = i;
while (j<=n){
s = s + (a[i][j]*x[j]);
//printf("foi 2");
j++;
}
x[i] = (b[i] - s)/ a[i][i];
i = i-1;
}
printf("\nVetor X:");
printaVetor(x,n+1);
}
/*
A
Digite o tamanho 'n' da matriz[n][n]: 3
Digite o valor de a[1][1]:3
Digite o valor de a[1][2]:2
Digite o valor de a[1][3]:4
Digite o valor de a[2][1]:0
Digite o valor de a[2][2]:0.333333
Digite o valor de a[2][3]:0.666666
Digite o valor de a[3][1]:0
Digite o valor de a[3][2]:0
Digite o valor de a[3][3]:-8
Digite o valor de b[1]:1
Digite o valor de b[2]:1.666667
Digite o valor de b[3]:0
Matriz A:
3.000000 | 2.000000 | 4.000000 |
0.000000 | 0.333333 | 0.666666 |
0.000000 | 0.000000 | -8.000000 |
Vetor B:
1.000000 | 1.666667 | 0.000000 |
Vetor X:
-3.000004 | 5.000006 | -0.000000 |
Process returned 0 (0x0) execution time : 21.167 s
Press any key to continue.
B
Digite o tamanho 'n' da matriz[n][n]: 3
Digite o valor de a[1][1]:3
Digite o valor de a[1][2]:2
Digite o valor de a[1][3]:4
Digite o valor de a[2][1]:1
Digite o valor de a[2][2]:1
Digite o valor de a[2][3]:2
Digite o valor de a[3][1]:4
Digite o valor de a[3][2]:3
Digite o valor de a[3][3]:2
Digite o valor de b[1]:1
Digite o valor de b[2]:2
Digite o valor de b[3]:3
Matriz A:
3.000000 | 2.000000 | 4.000000 |
1.000000 | 1.000000 | 2.000000 |
4.000000 | 3.000000 | 2.000000 |
Vetor B:
1.000000 | 2.000000 | 3.000000 |
Matriz A-triang:
3.000000 | 2.000000 | 4.000000 |
0.000000 | 0.333333 | 0.666667 |
0.000000 | 0.000000 | -4.000000 |
Vetor X:
-3.000000 | 8.000000 | -1.500000 |
Process returned 0 (0x0) execution time : 23.070 s
Press any key to continue.
*/
<file_sep>/02_Newton&Pegaso(ok)/Metodo_Newton.c
#include<stdio.h>
#include<math.h>
float funcao(float x){
return (2 * pow(x,3) - cos(x+1) - 3);
}
float funcaoDerivada(float x){
return (6*pow(x,2) + sin(x+1));
}
int main(){
float x0,x1,precisaoA,precisaoB;
float resultado;
int k;
printf("Valor de x0:");
scanf("%f",&x0);
printf("Precisao A:");
scanf("%f",&precisaoA);
printf("Precisao B:");
scanf("%f",&precisaoB);
if (fabs(funcao(x0)) < precisaoA){
resultado = x0;
printf("%f",fabs(funcao(x0)));
printf("%f",precisaoA);
}
else{
k = 1;
while(fabs(funcao(x1)) > precisaoA || fabs(x1 - x0) > precisaoB){
x1 = x0 - (funcao(x0)/funcaoDerivada(x0));
x0 = x1;
k = k + 1;
}
}
printf("Resultado: %f",resultado);
printf("\nContador: %d",k);
}
<file_sep>/README.md
# Algoritmos_UFES
Algorítmos propostos pelo professor <NAME>
Onde há um "(ok)" é que o algorítmo está funcional e terminado
<file_sep>/02_Newton&Pegaso(ok)/Metodo_Pegaso.c
#include<stdio.h>
#include<math.h>
float funcao(float x){
return cos(x) - x;
}
int main(){
float a,b,x;
float Fa,Fb,Fx;
float tolerancia,Del_x,interMax;
int inter;
printf("Digite o valor do parametro A:");
scanf("%f",&a);
printf("Digite o valor do parametro B:");
scanf("%f",&b);
printf("Digite o valor da toleranciaancia:");
scanf("%f",&tolerancia);
printf("Digite o valor Maximo de Interacoes:");
scanf("%f",&interMax);
Fa = funcao(a);
Fb = funcao(b);
x = b;
Fx = Fb;
inter = 0;
while((fabs(Del_x) > tolerancia && fabs(Fx) > tolerancia) || inter < interMax){
Del_x = (-Fx/((Fb - Fa)) * (b - a));
x = x + Del_x;
Fx = funcao(x);
if((Fx * Fb) < 0){
a = b;
Fa = Fb;
}
else{
Fa = (Fa * Fb) / (Fb + Fx);
}
b = x;
Fb = Fx;
inter = inter + 1;
}
printf("\nResultado: %f",x);
printf("\nInteracoes: %d",inter);
}
<file_sep>/01_Bisserção&Regula(ok)/Regula-Falsi-X.c
#include<stdio.h>
#include<math.h>
float f(float a){
//função (2*(a^3))-(4*(a^2))+3*a;
a = (2*(a*a*a))-(4*(a*a))+3*a;
return a;
}
void regula (float *x, float x0, float x1, float fx0, float fx1, int *itr)
{
*x = x0 - ((x1 - x0) / (fx1 - fx0))*fx0;
++(*itr);
printf("Iteração numero %3d X = %7.5f \n", *itr, *x);
}
void main ()
{
int itr = 0, maxmitr;
float x0,x1,x2,x3,allerr;
printf("\nentre os valores de x0, x1, precisao e iterações maximas:\n");
scanf("%f %f %f %d", &x0, &x1, &allerr, &maxmitr);
regula (&x2, x0, x1, f(x0), f(x1), &itr);
do
{
if (f(x0)*f(x2) < 0)
x1=x2;
else
x0=x2;
regula (&x3, x0, x1, f(x0), f(x1), &itr);
if (fabs(x3-x2) < allerr)
{
printf("Depois de %d iteração, raiz = %6.4f\n", itr, x3);
return 0;
}
x2=x3;
}
while (itr<maxmitr);
printf("Solução não converge ou sem iterações o suficiente:\n");
return 1;
}
<file_sep>/07_InterPolação de Lagrange(ok)/InterpolaçõLagrange.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
int m = 5;
double z = 2,result = 0.0, c, d;
double x[m] = {0.1,0.6,0.8,1.2,1.8};
double y[m] = {1.221,3.32,4.953,6.2,7.1};
for (int i = 0;i<m;i++) {
c = 1.0;
d = 1.0;
for (int j = 0;j<m;j++) {
if (i != j) {
c = c * (z - x[j]);
d = d * (x[i] - x[j]);
}
}
result = result + ((y[i] * c) / d);
}
cout << fixed << setprecision(10) << "\nResultado: " << result;
}
<file_sep>/15_Trabalho_Final(ok)/Presa_Predador_Trabalho.py
#!/usr/bin/env python
# coding: utf-8
# Importação das bibliotecas necessárias
#
# matplotlib - Biblioteca para gerar gráficos
#
# scipy - Biblioteca de resolução de cálculos matemáticos
# In[133]:
import matplotlib.pyplot as plt
import scipy as sp
# Representação matemática das Presas
# In[134]:
def fX(x, y, a, b):
return x * a - b * y * x
# Representação matemática dos Predadores
# In[135]:
def fY(x, y, d, g):
return y * d * x - y * g
# Instanciação das taxas do animais
#
# a - Taxa de Reprodução das Presas
#
#
# b - Taxa de Sucesso dos Predadores
#
#
# d - Taxa de Reprodução dos Predadores
#
#
# g- Taxa de Mortalidade dos Predadores
# In[136]:
a = 0.9990
b = 0.0035
d = 0.0030
g = 0.9000
# Instanciação do Tempo Inicial e Populações Iniciais (Base Estática)
#
# t0 - Instante de Tempo Inicial
#
# x0 - População Inicial de Presas
#
# y0 - População Inicial de predadores
# In[137]:
t0 = 0
x0 = 1200
y0 = 750
# Instanciação do Tempo e Populações (Base Dinâmica)
# In[138]:
t= t0
x = x0
y = y0
# Resolvendo a equação diferencial usando o método Runge-Kutta de Quarta Ordem
#
# h - Precisão
#
# tempo - Lista com a variação do tempo
#
# popX - Lista com a variação de população das presas
#
# popY - Lista com a variação de população dos predadores
#
# i - Número máximo de repetições
# In[139]:
h = 0.01
tempo = []
popX = []
popY = []
i = 1
while (y > 0.0000001) and (x > 0.0000001) and (i < 100000):
k11 = fX(x, y, a, b)
k12 = fY(x, y, d, g)
t = t + 0.5 * h
k21 = fX(x + h * 0.5 * k11, y + h * 0.5 * k12, a, b)
k22 = fY(x + h * 0.5 * k11, y + h * 0.5 * k12, d, g)
k31 = fX(x + h * 0.5 * k21, y + h * 0.5 * k22, a, b)
k32 = fY(x + h * 0.5 * k21, y + h * 0.5 * k22, d, g)
t = t + 0.5 * h
k41 = fX(x + h * k31, y + h * k32, a, b)
k42 = fY(x + h * k31, y + h * k32, d, g)
x = x + (1.0/6.0) * h * ( 1.0 * k11 + 2.0 * k21 + 2.0 * k31 + 1.0 * k41 )
y = y + (1.0/6.0) * h * ( 1.0 * k12 + 2.0 * k22 + 2.0 * k32 + 1.0 * k42 )
i = i + 1
tempo.append(t)
popX.append(x)
popY.append(y)
# Representação gráfica
# In[140]:
fig = plt.figure()
plt.title("Representação da Periodicidade entre Presas e Predadores")
plt.plot(popX, popY,'C0',linewidth=2)
plt.xlabel("Numero de Presas")
plt.ylabel("Numero de Predadores")
fig = plt.figure()
plt.title("Relação de População x Tempo")
plt.plot(tempo, popY,'C0',label = "Predadores", linewidth=2)
plt.plot(tempo, popX,'C3',label = "Presas", linewidth=2)
plt.xlabel("Tempo")
plt.ylabel("População")
plt.xlim(0,30)
plt.legend()
plt.show()
<file_sep>/11_GaussLegendre(ok)/GaussLegandre.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct peso {
double *A;
double *T;
};
double f(double x){
return 2*pow(x,3) + 3*pow(x,2) + 6*x + 1;
}
struct peso pesAbs(int n){
struct peso Peso;
int i, j, k;
int m = floor((n+1)*0.5);
double z, z1, p1, p2, p3, pp;
Peso.A = (double*)calloc(n,sizeof(double));
Peso.T = (double*)calloc(n,sizeof(double));
for(i=1 ; i<=m ; i++){
z = cos(M_PI * ((i - 0.25)/(n + 0.5)));
z1 = 100;
while(fabs(z-z1) > pow(10,-15)){
p1 = 1.0;
p2 = 0.0;
for(j=1 ; j<=n ; j++ ){
p3 = p2;
p2 = p1;
p1 = ((2*j-1) * z * p2 - (j-1) * p3) / j;
}
pp = n*(z*p1 - p2) / (pow(z,2) - 1);
z1 = z;
z = z1 - (p1/pp);
}
k = m + 1 - i;
Peso.T[i] = z;
Peso.A[i] = (2.0 / ((1 - pow(z,2)) * pow(pp,2)));
}
return Peso;
}
int sign(double x){
if(x < 0.0) return -1;
if(x > 0.0) return 1;
return 0;
}
double gaussLegendre(double a, double b, int n, double *T, double *A){
int i, k;
double integral = 0.0;
double c, c1, c2, t, x, y;
double e1 = (b-a) * 0.5;
double e2 = (b+a) * 0.5;
if(n%2 == 0){
c1 = 1.0;
c2 = 0.5;
}else{
c1 = 0.0;
c2 = 1.0;
}
for(i=1; i<=n; i++){
k = floor(i - 0.5 * (n+1) + sign(i - 0.5 * (n + c1)) * c2);
t = sign(k) * T[abs(k)];
x = (e1 * t) + e2;
y = f(x);
c = A[abs(k)];
integral = integral + c * y;
}
integral = e1 * integral;
return integral;
}
int main(){
double result;
struct peso Peso;
int n = 2;
double intervalo_a = 1;
double intervalo_b = 5;
Peso = pesAbs(n);
result = gaussLegendre(intervalo_a,intervalo_b,n,Peso.T, Peso.A);
printf("\nResultado: %f",result);
return 0;
}
| b322a2a812f26e2e136725f0c4dd3f6318d23145 | [
"Markdown",
"C",
"Python",
"C++"
] | 9 | C++ | panella/Algoritmos-UFES | 2816a8cb185b6e8cb75f09060c27e61ae1a5a9bf | b9d899b8d3c11c67e7ebad319024a5692208adc8 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { Image, Button } from 'semantic-ui-react'
import { Card, Icon, message, Popconfirm, Tooltip } from 'antd'
import { Link, withRouter, Route } from 'react-router-dom'
import axios from 'axios'
import DjProfile from './DjProfile.js'
class Artist extends Component {
componentDidMount() {
console.log(this.props.roster)
console.log(this.props.artistId)
}
render(props) {
const findArtist = (artist) => {
return artist.id === this.props.artistId
}
let owned = this.props.roster.find(findArtist)
let button = null
// conditional rendering for artist_roster
if (owned) {
button =
<Popconfirm title="Are you sure you want to remove this dj from your roster?" onConfirm={removeConfirm} onCancel={artistCancel} okText="Yes" cancelText="No" roster={this.props.userRoster.id} ownedRoster={this.props.roster} artist={this.props.artistId} render={this.props.render} find={this.props.findArtist} artistRoster={this.props.artistRoster} >
<Tooltip title="Remove DJ from roster">
<Icon style={{ fontSize: 20, color: 'red' }} type="minus-circle"/>
</Tooltip>
</Popconfirm>
} else {
button =
<Popconfirm title="Are you sure add this dj to Roster?" onConfirm={artistConfirm} onCancel={artistCancel} okText="Yes" cancelText="No" roster={this.props.userRoster.id} artist={this.props.artistId} render={this.props.render} >
<Tooltip title="Add artist to roster">
<Icon style={{ fontSize: 20 }} type="plus-circle"/>
</Tooltip>
</Popconfirm>
}
function artistConfirm(e) {
let self = this
//
// const findArtist = (artist) => {
// return artist.id === this.props.artist
// }
//
// console.log(this.props.ownedRoster.find(findArtist).id)
// console.log(this)
let data = {
artist_roster: {
roster_id: this.props.roster,
artist_id: this.props.artist
}
}
axios.post('https://vinyl-backend-api.herokuapp.com/artist_rosters/', data)
.then(function (response) {
console.log(response)
})
.then(this.props.render)
.catch(function (error) {
console.log(error);
})
}
function removeConfirm(e) {
let self = this
console.log(this.props.artistRoster)
const findArtist = (artist) => {
return artist.artist.id === this.props.artist
}
let targetArtist = this.props.artistRoster.find(findArtist).id
console.log(targetArtist)
let data = {
artist_roster: {
roster_id: this.props.roster,
artist_id: this.props.artist
}
}
axios.delete('https://vinyl-backend-api.herokuapp.com/artist_rosters/' + targetArtist, data)
.then(function (response) {
console.log(response)
})
.then(this.props.render)
.catch(function (error) {
console.log(error);
})
}
function artistCancel(e) {
console.log(this.props);
}
return(
<Card style={{ margin: '15px', width: 240 }} bodyStyle={{ padding: 0 }}>
<div className="custom-image dim">
<img alt="example" width="100%" src={this.props.image} />
<div class="overlay"></div>
<Icon style={{ fontSize: 30 }} type="plus" className='text'/>
</div>
<div className="custom-card">
<h3>{this.props.name}</h3>
{button}
</div>
<Link to={'/dashboard/profile/' + this.props.artistId }>Profile</Link>
</Card>
)
}
}
export default withRouter(Artist)
<file_sep>import React from 'react'
import { withRouter, Link } from 'react-router-dom'
import { Col, Row, Tag } from 'antd'
import { Divider } from 'semantic-ui-react'
import axios from 'axios'
class DjProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
artist: [],
};
}
componentDidMount () {
let self = this
let artistId = this.props.match.params.id
// GET Artists
axios.get('https://vinyl-backend-api.herokuapp.com/artists/' + artistId)
.then(response => {
this.setState({artist: response.data.artist})
console.log(response.data)
})
.catch(error => {
console.log('Error fetching and parsing data', error)
})
}
render() {
return(
<div>
<Row>
<Col span={24}>
<div style={{ padding: 24, background: '#fff', minHeight: 400, margin: '6px 6px', textAlign: 'left'}}>
<Row>
<Col span={8}>
<img alt="example" width="100%" src={this.state.artist.image} />
</Col>
<Col span={1}></Col>
<Col span={6}>
<h1>{this.state.artist.name}</h1>
<p>{this.state.artist.bio}</p>
<Tag color='#108ee9'>{this.state.artist.genre}</Tag>
</Col>
<Col span={6}></Col>
<Col span={2}>
<Link to='/dashboard'>Go Back</Link>
</Col>
</Row>
<Divider horizontal>Music</Divider>
<Row>
<Col span={24} style={{ margin: '20px' }}>
<iframe width="100%" height="120" src="https://www.mixcloud.com/widget/iframe/?hide_cover=1&light=1&feed=%2Fwheresnasty%2F" frameborder="0" ></iframe>
<iframe width="100%" height="120" src="https://www.mixcloud.com/widget/iframe/?hide_cover=1&light=1&feed=%2Frubradiobrooklynradio%2F" frameborder="0" ></iframe>
<iframe width="100%" height="120" src="https://www.mixcloud.com/widget/iframe/?hide_cover=1&light=1&feed=%2Fdjemilyrawson%2Fsupa-dupa-fly-mix-90s-hip-hop-rnb-jan-2012-mixed-live-at-supa-dupa-fly%2F" frameborder="0" ></iframe>
</Col>
</Row>
</div>
</Col>
</Row>
</div>
);
}
}
export default withRouter(DjProfile)
<file_sep>import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Item, Header, Button, Icon } from 'semantic-ui-react'
import axios from 'axios'
import MyEvents from './MyEvents.js'
const MyEventsList = props => {
const results = props.data;
// ////////////////////////
// Create Event & User Event
// /////////////////////////
const onCreateEvent = () => {
let self = this
let data = {
'event': {
'name': 'After Dark',
'venue': 'Room 112'
}
}
axios.post('http://localhost:4741/events/', data)
.then(function (response) {
console.log(response);
let eventData = {
'user_event': {
'user_id': props.user,
'event_id': response.data.event.id
}
}
axios.post('http://localhost:4741/user_events/', eventData)
.then(function (response) {
console.log(response)
})
})
.catch(function (error) {
console.log(error);
})
}
const toCreateEvent = () => {
console.log(this)
}
// ///////////////////////////////
// Maps every instance of my events
// ///////////////////////////////
let myEvents = results.map(event =>
<MyEvents name={event.name} id={event.id} venue={event.venue} user={props.user} artists={props.artists} />
)
return(
<div>
<Header as='h2'>My Events</Header>
<div>
<Link to='/dashboard/createevent'>Create Event</Link>
</div>
<Item.Group divided>
{myEvents}
</Item.Group>
</div>
)
}
export default MyEventsList
<file_sep>import React, { Component } from 'react'
import {
Link
} from 'react-router-dom'
import { Menu, Icon, Layout} from 'antd';
const { Header } = Layout;
const Sidebar_nav = props => {
return(
<div>
<Header style={{ background: '#1A1F24', padding: 0, color: 'white', textAlign: "center" }}>
<img src={ require('./../../images/vinyl-logo.png') } />
</Header>
<Menu theme="dark" defaultSelectedKeys={['1']} mode="inline" style={{ background: '#272F42'}}>
<div style={{ height: '40px' }}>
</div>
<Menu.Item key="1"><Link to={'/dashboard'}>
<Icon type="pie-chart" />
<span>Dashboard</span>
</Link></Menu.Item>
<Menu.Item key="2"><Link to={'/dashboard/'}>
<Icon type="environment-o" />
<span>Map</span>
</Link></Menu.Item>
</Menu>
</div>
);
}
export default Sidebar_nav
<file_sep>import React, { Component } from 'react';
import './App.css';
import PropTypes from 'prop-types'
import {
BrowserRouter,
Route,
withRouter
} from 'react-router-dom'
import{ message } from 'antd'
// importing components
import SignUpForm from './components/login/Sign-up.js'
import SignInForm from './components/login/Sign-in.js'
import Dashboard from './components/dashboard/Dashboard.js'
import Landing from './components/login/Landing.js'
class App extends Component {
constructor(props) {
super(props)
this.state = {
user_id: '',
token: ''
}
this.setToken = this.setToken.bind(this)
}
setToken (token, user_id, next) {
this.setState({
token: token,
user_id: user_id
})
message.success('Signed in')
next.history.push(`/dashboard`)
}
render() {
return (
<BrowserRouter>
<div className="App">
<Route exact path="/sign-up" render={ () => <SignUpForm />} />
<Route path="/sign-in" render={ () => <SignInForm data={this.setToken} />} />
<Route path="/dashboard" render={ () => <Dashboard data={this.state} />} />
<Route exact path='/' component={Landing} />
</div>
</BrowserRouter>
);
}
}
export default App;
<file_sep>import React, { Component } from 'react';
import axios from 'axios'
import { Link, withRouter } from 'react-router-dom'
import { message } from 'antd'
import { Button, Form, Grid, Header, Image, Loader, Message, Segment } from 'semantic-ui-react'
class SignInForm extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: '',
}
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
// listens for changes and field and changes state
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
}
// Submits credentials to api
onSubmit = () => {
let self = this
// pust json data into data variable
let data = {
credentials: {
email: this.state.email,
password: <PASSWORD>
}
}
axios.post('https://vinyl-backend-api.herokuapp.com/sign-in/', data)
.then(function (response) {
console.log(response);
// add token to local storage for authenicated requests
console.log(response.data.user.token)
console.log(response.data.user.id)
self.props.data(response.data.user.token, response.data.user.id, self.props )
console.log('het')
})
.catch(function (error) {
message.error('Invaild Email or Password')
console.log(error);
})
}
render() {
return (
<div className='login-form'>
<style>{`
body > div,
body > div > div,
body > div > div > div.login-form {
height: 100%;
}
`}</style>
<Grid
textAlign='center'
style={{ height: '100%' }}
verticalAlign='middle'
>
<Grid.Column style={{ maxWidth: 450 }}>
<Header as='h2' color='teal' textAlign='center'>
<Image src='/logo.png' />
{' '}Log-in to your account
</Header>
<Form size='large'>
<Segment stac ked>
<Form.Input
fluid
icon='user'
iconPosition='left'
name='email'
placeholder='E-mail address'
onChange={e => this.onChange(e)}
value={this.state.email}
/>
<Form.Input
fluid
icon='lock'
iconPosition='left'
name="password"
placeholder='<PASSWORD>'
type='password'
value={this.state.password}
onChange={e => this.onChange(e)}
/>
<Button color='teal' fluid size='large' onClick={() => this.onSubmit()}>Login</Button>
<Loader inverted content='Loading' />
</Segment>
</Form>
<Message>
New to us? <Link to='/sign-up'>login here</Link>
</Message>
</Grid.Column>
</Grid>
</div>
)
}
}
export default withRouter(SignInForm)
<file_sep>import React, { Component } from 'react'
import { Form, Header, Segment, Button, Image} from 'semantic-ui-react'
import { message } from 'antd'
import axios from 'axios'
import { withRouter, Link } from 'react-router-dom'
import 'react-datepicker/dist/react-datepicker.css';
import DatePicker from 'react-datepicker';
import moment from 'moment';
class CreateEvent extends Component {
constructor(props) {
super(props)
this.state = {
name: '',
venue: '',
Startdate: moment()
}
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
this.pickDate = this.pickDate.bind(this)
}
// listens for changes and field and changes state
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
}
pickDate = (date) => {
this.setState({
startDate: date
})
console.log(this.state)
}
onSubmit = () => {
let self = this
let data = {
event: {
name: this.state.name,
venue: this.state.venue,
date: this.state.startDate
}
}
axios.post('https://vinyl-backend-api.herokuapp.com/events/', data)
.then(function (response) {
console.log(response);
console.log(self.props.user)
let eventData = {
'user_event': {
'user_id': self.props.user,
'event_id': response.data.event.id
}
}
axios.post('https://vinyl-backend-api.herokuapp.com/user_events/', eventData)
.then(function (response) {
console.log(response)
})
})
.then(self.props.getUserEvents)
.then(this.props.history.push(`/dashboard`))
.then(message.success('Event Created'))
.catch(function (error) {
console.log(error);
})
}
render() {
return(
<div>
<Form size={'small'}>
<Form.Group>
<Form.Input
name='name'
placeholder='Name'
onChange={e => this.onChange(e)}
value={this.state.name}
width={16} />
</Form.Group>
<Form.Group>
<Form.Input
name='venue'
placeholder='Venue'
onChange={e => this.onChange(e)}
value={this.state.venue}
width={16} />
</Form.Group>
<Form.Group>
<DatePicker
name='date'
dateFormat="MM/DD/YY"
placeholder='Date'
onChange={this.pickDate}
selected={this.state.startDate}
value={this.state.startDate}
width={16} />
</Form.Group>
<Button color='blue' fluid size='large' style={{ margin: '15px 0' }} onClick={() => this.onSubmit()}>Create</Button>
<Link to='/dashboard'>Cancel</Link>
</Form>
</div>
)
}
}
export default withRouter(CreateEvent)
<file_sep>import React, { Component } from 'react'
import { Header, Card } from 'semantic-ui-react'
import axios from 'axios'
import Artists from './Artists.js'
const ArtistList = props => {
const results = props.data;
let artists = results.map((artist, index) =>
<Artists name={artist.name} genre={artist.genre} key={index} />
);
return(
<div>
<div style={{ padding: 24, background: '#fff', minHeight: 400, margin: '12px' }}>
<Header as='h2' style={{ textAlign: 'left' }}>Artists</Header>
<Card.Group>
{artists}
</Card.Group>
</div>
</div>
);
}
export default ArtistList
<file_sep>import _ from 'lodash'
import React from 'react'
import { Label, Item, Modal, Header, Image, Button, Icon} from 'semantic-ui-react'
import axios from 'axios'
class Events extends React.Component {
deleteEvents = () => {
let self = this
let data = {
id: self.props.id
}
// Delete Event
axios.delete('https://vinyl-backend-api.herokuapp.com/events/' + self.props.id, data)
.then(function (response) {
console.log(response);
})
.then(self.props.getUserEvents)
.catch(function (error) {
console.log(error)
})
}
// Create Event
// onCreateEvent = () => {
// let self = this
// let data = {
// 'event': {
// 'name': 'After Dark',
// 'venue': 'Room 112'
// }
// }
// axios.post('https://vinyl-backend-api.herokuapp.com/events/', data)
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// })
// }
// Create Button
// Create Event
// <Button primary size="mini" onClick={() => this.toCreateEvent()}>
// Create Event
// <Icon name='right chevron' />
// </Button>
// Delete Button
render() {
return(
<Item>
<Item.Image src='https://react.semantic-ui.com/assets/images/wireframe/image.png' />
<Item.Content>
<Item.Header as='a'>{this.props.name}</Item.Header>
<Item.Meta>
<span className='cinema'>{this.props.venue}</span>
</Item.Meta>
<Item.Description>Warehouse party at an undisclosed location</Item.Description>
<Item.Extra>
<Label></Label>
<Label content='Live Music' />
</Item.Extra>
<Button negative size="mini" onClick={() => this.deleteEvents()}>
Delete Event
<Icon name='right chevron' />
</Button>
</Item.Content>
</Item>
)
}
}
export default Events
<file_sep>import React from 'react'
import { Table, Icon, Popconfirm, message } from 'antd';
import axios from 'axios'
class EventDash extends React.Component {
render() {
// Event Columns
const columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
}, {
title: 'Type',
dataIndex: 'type',
key: 'type',
}, {
title: 'Venue',
dataIndex: 'venue',
key: 'venue',
},
// {
// title: 'Date',
// dataIndex: 'date',
// key: 'date',
// },
{
title: 'Action',
key: 'action',
render: (text, record) => (
<span>
<Popconfirm title="Are you sure delete this event?" onConfirm={eventConfirm} onCancel={eventCancel} okText="Yes" cancelText="No" event={record.id} render={this.props.render} >
<a href="">Delete</a>
</Popconfirm>
</span>
)}];
function eventConfirm(e) {
console.log(this.props.event)
console.log(this.props.render)
let self = this
let data = {
id: self.props.event
}
// Delete Event
axios.delete('https://vinyl-backend-api.herokuapp.com/events/' + self.props.event, data)
.then(function (response) {
console.log(response);
})
.then(self.props.render)
.catch(function (error) {
console.log(error)
})
message.success('Event Deleted');
}
function eventCancel(e) {
console.log(e);
message.error('Canceled');
}
return(
<Table dataSource={this.props.data} pagination={{ pageSize: 4 }} columns={columns} />
)
}
}
export default EventDash
<file_sep>import React, { Component } from 'react'
import { Item, Header, Button, Icon } from 'semantic-ui-react'
import axios from 'axios'
import Events from './Events.js'
class EventsList extends Component {
results = this.props.data;
events = this.results.map(event =>
<Events name={event.name} id={event.id} venue={event.venue} user={this.props.user} artists={this.props.artists} getUserEvents={this.props.getUserEvents} />
)
render() {
return(
<div>
<div style={{ padding: 24, background: '#fff', minHeight: 400, margin: '12px' }}>
<Header as='h2' style={{ textAlign: 'left' }}>Events</Header>
<Item.Group divided>
{this.events}
</Item.Group>
</div>
</div>
)
}
}
export default EventsList
| 8e2dd3fbce7e2f52c16fc938c7f1a7057e06943c | [
"JavaScript"
] | 11 | JavaScript | slayTheSensei/vinyl-frontend | 2c9ead19b96f0078211c7658bed2951da86e6135 | 6aee8d3dceb39cb76a127dd34df5c990252d04f1 |
refs/heads/master | <repo_name>Tyraeel/BookLister<file_sep>/README.md
# BookApp
Application pour livre
<file_sep>/BookLister/src/objects/Book.java
package objects;
public class Book {
private int idBook;
private String titleBook;
private String authorBook;
private String descriptionBook;
private String readingDateBook;
private boolean readStateBook;
public Book(int id, String nameBook, String authorBook, String descriptionBook, String readingDateBook, boolean readStateBook) {
this.idBook = id;
this.titleBook = nameBook;
this.authorBook = authorBook;
this.descriptionBook = descriptionBook;
this.readingDateBook = readingDateBook;
this.readStateBook = readStateBook;
}
/*GETTERS AND SETTERS*/
public int getId(){
return this.idBook;
}
public String getTitle() {
return this.titleBook;
}
public String getAuthor() {
return this.authorBook;
}
public String getDescription() {
return this.descriptionBook;
}
public String getReadingDate() {
return this.readingDateBook;
}
public String getReadState() {
if(this.readStateBook)
return "Lu";
else
return "Non lu";
}
}
| 2dada746ff20235493cbc3b2f121a80a741322db | [
"Markdown",
"Java"
] | 2 | Markdown | Tyraeel/BookLister | 614171088e28bb254a01eba3fe65fe32dd2dfc51 | d6b836612d00d92e2673cd8083c81061214bccbf |
refs/heads/main | <file_sep>from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Try to make projection of political parties or people in avector space in order to enable visualisation.',
author='<NAME>',
license='MIT',
entry_points={
'console_scripts': [
'vizualize=src.visualization.visualize:run',
],
},
)
<file_sep>import os
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import click
import networkx as nx
from dotenv import load_dotenv, find_dotenv
from pathlib import Path
from networkx import draw, draw_spectral, draw_planar, draw_spring, draw_shell, adjacency_matrix, draw_kamada_kawai, \
kamada_kawai_layout, spectral_layout, bipartite_layout, spring_layout
from sklearn.manifold import Isomap, TSNE
from sklearn.decomposition import PCA
project_dir = Path(os.getcwd())
def show_alliance_matrix(df_alliance_matrix_A):
fig = px.imshow(df_alliance_matrix_A.values,
labels=dict(x="Nuances listes municipales", y="Nuances candidat législative",
color="Nombre d'alliance total"),
x=df_alliance_matrix_A.columns,
y=df_alliance_matrix_A.index
)
fig.update_xaxes(side="top")
fig.show()
def show_projection(df_alliance_matrix_A, method='tsne', n_components=2):
assert 0 < n_components <= 2
arr_alliance_matrix = df_alliance_matrix_A.values
if method == 'tsne':
lst_projectors = [(TSNE(n_components=n_components, perplexity=x), f"TSNE: perplexity:{x}") for x in [3, 4]]
elif method == "isomap":
lst_projectors = [(Isomap(n_components=n_components, n_neighbors=x), f"Isomap: neighbors:{x}") for x in
[3, 4, 5]]
elif method == "pca":
lst_projectors = [(PCA(n_components=n_components), "PCA")]
else:
raise ValueError(f"Unknown projection method {method}")
for projector, projector_desc in lst_projectors:
proj_arr_alliance_matrix = projector.fit_transform(arr_alliance_matrix)
fig = go.Figure()
if n_components == 1:
x_vals = proj_arr_alliance_matrix[:, 0]
y_vals = proj_arr_alliance_matrix[:, 0]
else:
x_vals = proj_arr_alliance_matrix[:, 0]
y_vals = proj_arr_alliance_matrix[:, 1]
fig.add_trace(go.Scatter(x=x_vals,
y=y_vals,
mode='markers+text',
# marker_color=df_alliance_matrix_A.index,
marker=dict(
size=20,
color='LightSkyBlue',
line=dict(
color="MediumPurple",
width=2
)
),
text=df_alliance_matrix_A.index,
textposition='top center'))
fig.update_layout(title=projector_desc)
fig.show()
def show_graph(df_alliance_matrix_A):
G = nx.Graph()
for party_name in df_alliance_matrix_A.index:
G.add_node(party_name)
for i_col, nb_alliance_first_party in enumerate(df_alliance_matrix_A.loc[party_name]):
if nb_alliance_first_party == 0:
continue
list_name = df_alliance_matrix_A.columns[i_col]
G.add_edge(party_name, list_name, weight=nb_alliance_first_party)
# for i_row, nb_alliance_2nd_party in enumerate(df_alliance_matrix_A.loc[:, list_name]):
# second_party_name = df_alliance_matrix_A.index[i_row]
# cumulated_alliances = nb_alliance_first_party + nb_alliance_2nd_party
# G.add_edge(party_name, second_party_name, weight=cumulated_alliances)
# draw_kamada_kawai(G)
# A = adjacency_matrix(G).toarray()
dct_layout = spring_layout(G)
fig = go.Figure()
for node in dct_layout:
if node in df_alliance_matrix_A.columns:
color = "red"
else:
color = "green"
fig.add_trace(go.Scatter(
x=(dct_layout[node][0],),
y=(dct_layout[node][1],),
name=node,
text=node,
mode="markers+text",
textposition="top center",
marker=dict(
size=20,
color=color
)))
fig.show()
print()
@ click.command()
@ click.argument("method", type=click.Choice(["matrix", "pca", "tsne", "isomap", "graph"]))
def main(method):
path_output_alliances_matrix = project_dir / "data/processed/alliance_matrix.csv"
df_alliance_matrix_A = pd.read_csv(path_output_alliances_matrix, index_col=0)
df_alliance_matrix_A /= np.sum(df_alliance_matrix_A.values, axis=1).reshape(-1, 1)
# df_alliance_matrix_A = df_alliance_matrix_A.drop("EXG")
# df_alliance_matrix_A = df_alliance_matrix_A.drop("FN")
if method == "matrix":
show_alliance_matrix(df_alliance_matrix_A)
elif method == "graph":
show_graph(df_alliance_matrix_A)
else:
show_projection(df_alliance_matrix_A, method=method, n_components=2)
def run():
global project_dir
load_dotenv(find_dotenv())
project_dir = Path(os.environ["project_dir"])
main()
if __name__ == "__main__":
run()
<file_sep># -*- coding: utf-8 -*-
import click
import os
import pandas as pd
import numpy as np
import unidecode
from loguru import logger
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
def create_id_from_row(row, cols_names_for_id, dct_col_names_as_is):
"""
Function to be applied row-wise on a dataframe to produce the pairs (id_candidate, party)
id_candidate is produced by concatenating the column values in `cols_names_for_id` and interspace them with "_".
:param row:
:param cols_names_for_id:
:param col_name_for_label:
:return:
"""
id_candidate = "_".join(map(lambda x: str.lower(unidecode.unidecode(str(row[x]))),
cols_names_for_id))
dct_other_cols = dict((key, row[value]) for key, value in dct_col_names_as_is.items())
return dict(id_candidate=id_candidate, **dct_other_cols)
def prepare_sanitized_list_of_candidates():
"""Write processed file of candidates with their party.
"""
path_candidates_list = project_dir / "data/external/Leg_2017_candidatures_T1_c2.csv"
# path_nuance_association = project_dir / "data/external/Leg_2017_candidatures_T1_c2_nuances.csv"
path_output_sanitized_candidates_list = project_dir / "data/interim/sanitized_candidates.csv"
path_output_sanitized_candidates_list.parent.mkdir(parents=True, exist_ok=True)
with open(path_candidates_list, 'rb') as candidates_file:
df_candidates = pd.read_csv(candidates_file, sep=",", skiprows=0)
# with open(path_nuance_association, 'rb') as nuance_file:
# df_nuance_association = pd.read_csv(nuance_file, sep=",", skiprows=0)
#
# dct_nuance_association = dict(line for line in df_nuance_association.values)
cols_for_id_candidates = (
"Code du département",
"Nom candidat",
"Prénom candidat"
)
dct_col_for_label = {
"party_candidate": "Nuance candidat"
}
df_final = df_candidates.apply(lambda x: create_id_from_row(x, cols_for_id_candidates, dct_col_for_label), axis=1, result_type='expand')
assert df_final["id_candidate"].unique().size == len(df_final) # assert there is no duplicate name
# df_final["party_long"] = df_final.apply(lambda row: dct_nuance_association[row["party_short"]], axis=1)
df_final.set_index("id_candidate", inplace=True)
df_final.to_csv(path_output_sanitized_candidates_list, index=True)
def prepare_sanitized_list_of_lists():
"""
Write processed file of the list candidates with their list.
:return:
"""
path_candidates_list = project_dir / "data/external/livre-des-listes-et-candidats.txt"
path_output_sanitized_list_of_lists = project_dir / "data/interim/sanitized_lists.csv"
path_output_sanitized_list_of_lists.parent.mkdir(parents=True, exist_ok=True)
with open(path_candidates_list, 'rb') as list_file:
df_lists = pd.read_csv(list_file, sep="\t", encoding="ISO-8859-1", skiprows=2)
cols_for_id_candidates = (
"Code du département",
"Nom candidat",
"Prénom candidat"
)
dct_col_for_label = {
"party_list": "Nuance Liste",
# "short_list_name": "Libellé abrégé liste",
# "long_list_name": "Libellé Etendu Liste"
}
df_final = df_lists.apply(lambda x: create_id_from_row(x, cols_for_id_candidates, dct_col_for_label), axis=1,
result_type='expand')
duplicated = df_final.duplicated(subset=["id_candidate"], keep=False)
# I remove the lists without any party (cities with less than 3500 capita)
df_final.dropna(inplace=True)
# there is no way to identify the duplicate candidates so I just drop them in order to keep the data clean
df_final = df_final[~duplicated]
assert df_final["id_candidate"].unique().size == len(df_final) # assert there is no duplicate name
df_final.set_index("id_candidate", inplace=True)
df_final.to_csv(path_output_sanitized_list_of_lists, index=True)
def prepare_alliance_matrix():
path_output_sanitized_candidates_list = project_dir / "data/interim/sanitized_candidates.csv"
path_output_sanitized_list_of_lists = project_dir / "data/interim/sanitized_lists.csv"
path_output_alliances_matrix = project_dir / "data/processed/alliance_matrix.csv"
path_output_alliances_matrix.parent.mkdir(parents=True, exist_ok=True)
with open(path_output_sanitized_candidates_list, 'r') as in_candidates:
df_candidates = pd.read_csv(in_candidates)
with open(path_output_sanitized_list_of_lists, 'r') as in_lists:
df_lists = pd.read_csv(in_lists)
dct_candidate_party_list = dict(df_lists.values)
del df_lists
df_candidates["party_list"] = df_candidates.apply(lambda row: dct_candidate_party_list.get(row["id_candidate"], np.nan), axis=1)
logger.debug(f"Total number of considered candidates: {len(df_candidates)}")
df_candidates.dropna(inplace=True)
logger.debug(f"Number of candidates for both city councel and national assembly: {len(df_candidates)}")
unique_party_list_L = list(df_candidates["party_list"].unique())
unique_party_candidate_C = list(df_candidates["party_candidate"].unique())
alliance_matrix_A = np.zeros((len(unique_party_candidate_C), len(unique_party_list_L)))
df_count_by_alliance = df_candidates.groupby(by=["party_candidate", "party_list"]).count()
for (party_candidate, party_list), row_count in df_count_by_alliance.iterrows():
idx_party_candidate = unique_party_candidate_C.index(party_candidate)
idx_party_list = unique_party_list_L.index(party_list)
alliance_matrix_A[idx_party_candidate, idx_party_list] = row_count.values[0]
df_alliance_matrix_A = pd.DataFrame(alliance_matrix_A)
df_alliance_matrix_A.rename(inplace=True, columns=lambda x: unique_party_list_L[x], index=lambda x: unique_party_candidate_C[x])
df_alliance_matrix_A.to_csv(path_output_alliances_matrix, index=True)
@click.command()
def main():
logger.info("Creating sanitized list of candidates.")
prepare_sanitized_list_of_candidates()
logger.info("Creating sanitized list of city election lists.")
prepare_sanitized_list_of_lists()
logger.info("Building the alliance matrix")
prepare_alliance_matrix()
if __name__ == '__main__':
# find .env automagically by walking up directories until it's found, then
# load up the .env entries as environment variables
load_dotenv(find_dotenv())
project_dir = Path(os.environ["project_dir"])
main()
| ba4a3cd9051fd04ae7787b2e492866109489aef7 | [
"Python"
] | 3 | Python | lucgiffon/propol | d531bef8cc96e3e80f32961edcf98d42f697d3e6 | e9d27d0e89e5ca379cfe5e6f2a5157d441ff6b81 |
refs/heads/master | <repo_name>joaoGabriel55/NurtureKeep<file_sep>/src/util/MessageUtil.java
package util;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
* @author lber
*/
//Classe respoável por setar mensagens no contexto da aplicação
public class MessageUtil {
public static void MensagemErro(String mensagem) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, mensagem, null);
FacesContext.getCurrentInstance().addMessage(null, fm);
}
public static void MensagemSucesso(String mensagem) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, mensagem, null);
FacesContext.getCurrentInstance().addMessage(null, fm);
}
public static void MensagemPerigo(String mensagem) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, mensagem, null);
FacesContext.getCurrentInstance().addMessage(null, fm);
}
}
<file_sep>/src/daoImplementation/FornecedorDAOimp.java
package daoImplementation;
import dao.FornecedorDAO;
import modelo.Fornecedor;
public class FornecedorDAOimp extends GenericDAOimp<Fornecedor, Integer> implements FornecedorDAO {
public FornecedorDAOimp() {
super(Fornecedor.class);
}
public void save(Fornecedor fornecedor) {
Integer codigo = fornecedor.getIdPessoa();
System.out.println("Fornecedor é: " + codigo);
if (codigo == null || codigo == 0) {
fornecedor.setRole("ROLE_FORNECEDOR");
System.out.println("Salvar usuário");
super.save(fornecedor);
} else {
System.out.println("Atualizar usuário");
System.out.println(fornecedor.getRole());
super.update(fornecedor);
}
}
}
<file_sep>/src/modelo/Tarefa.java
package modelo;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
public class Tarefa implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6142036381277478394L;
@Id
@GeneratedValue
@Column(name = "id_tarefa")
private int id;
@Column(nullable = false, length = 200)
@NotNull(message = "Campo descrição não preenchido.")
private String descricao;
@Column(nullable = false)
private Date dataHoraRealizacao;
@Column(nullable = false)
private Date dataLimite;
@Column(nullable = true)
private Date dataRemocao;
@ManyToOne
@JoinColumn(name = "usuario_id")
@NotNull(message = "Não foi selecionado nenhum usuario preenchido.")
private Usuario user;
public Tarefa(String descricao, Date dataHoraRealizacao, Date dataLimite, Date dataRemocao, Usuario user) {
super();
this.descricao = descricao;
this.dataHoraRealizacao = dataHoraRealizacao;
this.dataLimite = dataLimite;
this.dataRemocao = dataRemocao;
this.user = user;
}
public Tarefa() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Date getDataHoraRealizacao() {
return dataHoraRealizacao;
}
public void setDataHoraRealizacao(Date dataHoraRealizacao) {
this.dataHoraRealizacao = dataHoraRealizacao;
}
public Date getDataLimite() {
return dataLimite;
}
public void setDataLimite(Date dataLimite) {
this.dataLimite = dataLimite;
}
public Date getDataRemocao() {
return dataRemocao;
}
public void setDataRemocao(Date dataRemocao) {
this.dataRemocao = dataRemocao;
}
public Usuario getUser() {
return user;
}
public void setUser(Usuario user) {
this.user = user;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dataHoraRealizacao == null) ? 0 : dataHoraRealizacao.hashCode());
result = prime * result + ((dataLimite == null) ? 0 : dataLimite.hashCode());
result = prime * result + ((dataRemocao == null) ? 0 : dataRemocao.hashCode());
result = prime * result + ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + id;
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tarefa other = (Tarefa) obj;
if (dataHoraRealizacao == null) {
if (other.dataHoraRealizacao != null)
return false;
} else if (!dataHoraRealizacao.equals(other.dataHoraRealizacao))
return false;
if (dataLimite == null) {
if (other.dataLimite != null)
return false;
} else if (!dataLimite.equals(other.dataLimite))
return false;
if (dataRemocao == null) {
if (other.dataRemocao != null)
return false;
} else if (!dataRemocao.equals(other.dataRemocao))
return false;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (id != other.id)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
}
<file_sep>/src/daoImplementation/TarefaDAOimp.java
package daoImplementation;
import dao.TarefaDAO;
import modelo.Tarefa;
public class TarefaDAOimp extends GenericDAOimp<Tarefa, Integer> implements TarefaDAO {
public TarefaDAOimp() {
super(Tarefa.class);
}
}
<file_sep>/README.md
# NurtureKeep
# NurtureKeep
<file_sep>/src/examplesDesignPatterns/RunnableFacade.java
package examplesDesignPatterns;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import modelo.Fornecedor;
import modelo.Usuario;
public class RunnableFacade {
@SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
FacadeExample facadeExample = new FacadeExample();
Usuario usuario = new Usuario();
List<Usuario> listUsuarios = new ArrayList<Usuario>();
//Singleton
Fornecedor fornecedor = Fornecedor.getInstance();
List<Fornecedor> listFornecedores = new ArrayList<Fornecedor>();
usuario.setNome("Joao");
usuario.setCpf("1151665161");
usuario.setEmail("<EMAIL>");
usuario.setSenha("<PASSWORD>");
listUsuarios.add(usuario);
fornecedor.setNome("Nicolas");
fornecedor.setCpf("1151665161");
fornecedor.setCnpj("887744444");
fornecedor.setEmail("<EMAIL>");
fornecedor.setSenha("<PASSWORD>");
listFornecedores.add(fornecedor);
System.out.println(usuario.toString());
System.out.println(fornecedor.toString());
Scanner entrada = new Scanner(System.in);
System.out.println("FOR DELETE: 1-Usuario, 2-Fornecedor, 3- All");
int op = entrada.nextInt();
facadeExample.delete(listUsuarios, listFornecedores, usuario, fornecedor, op);
}
}
<file_sep>/src/daoImplementation/AlimentoDAOimp.java
package daoImplementation;
import dao.AlimentoDAO;
import modelo.Alimento;
public class AlimentoDAOimp extends GenericDAOimp<Alimento, Integer> implements AlimentoDAO {
public AlimentoDAOimp() {
super(Alimento.class);
}
}
<file_sep>/src/controle/AlimentoCtrl.java
package controle;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import dao.AlimentoDAO;
import daoImplementation.AlimentoDAOimp;
import modelo.Alimento;
@ManagedBean
@SessionScoped
public class AlimentoCtrl {
private Alimento alimento;
private List<Alimento> listaAlimento;
public AlimentoCtrl() {
this.alimento = new Alimento.Builder(alimento.getNome(), alimento.getFabricacao(), alimento.getValidade(),
alimento.getFornecedor()).build();
AlimentoDAO alimentodao = new AlimentoDAOimp();
this.listaAlimento = alimentodao.listAll();
}
public void reset() {
this.alimento = new Alimento.Builder(alimento.getNome(), alimento.getFabricacao(), alimento.getValidade(),
alimento.getFornecedor()).build();
}
public Alimento getAlimento() {
return alimento;
}
public void setAlimento(Alimento alimento) {
this.alimento = alimento;
}
public List<Alimento> getListaAlimento() {
AlimentoDAO alimentodao = new AlimentoDAOimp();
this.listaAlimento = alimentodao.listAll();
return listaAlimento;
}
public void setListaAlimento(List<Alimento> listaAlimento) {
this.listaAlimento = listaAlimento;
}
public void salvar() {
AlimentoDAO alimentodao = new AlimentoDAOimp();
alimentodao.save(this.alimento);
reset();
}
public void removerPermanente(Alimento alimento) {
AlimentoDAO alimentodao = new AlimentoDAOimp();
alimentodao.delete(alimento);
}
public void editar(Alimento alimento) {
this.alimento = alimento;
}
}
<file_sep>/src/dao/AlimentoDAO.java
package dao;
import modelo.Alimento;
public interface AlimentoDAO extends GenericDAO<Alimento, Integer> {
}
<file_sep>/src/examplesDesignPatterns/BuilderExample.java
package examplesDesignPatterns;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import modelo.Alimento;
import modelo.Fornecedor;
public class BuilderExample {
@SuppressWarnings("deprecation")
public static final void main(String[] args) {
Date fabricacao = new Date();
fabricacao.getTime();
Date validade = new Date();
validade.setDate(30);
validade.setMonth(01);
validade.setYear(2020);
Fornecedor fornecedor = Fornecedor.getInstance();
fornecedor.setNome("Lucas");
fornecedor.setCnpj("12121212121");
List<Fornecedor> list = new ArrayList<Fornecedor>();
list.add(fornecedor);
Alimento builder = new Alimento.Builder("Macarr„o", fabricacao, validade, list).build();
Alimento builder2 = new Alimento.Builder("Arroz", fabricacao, validade, list).comCarboidratos(50.0).build();
Alimento builder3 = new Alimento.Builder("Feij„o", fabricacao, validade, list).comCarboidratos(100.0)
.comGordurasTotais(44.0).build();
System.out.println(builder.toString());
System.out.println(builder2.toString());
System.out.println(builder3.toString());
}
}
<file_sep>/src/modelo/Animal.java
package modelo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "animal")
public class Animal implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6169160019152757705L;
@Id
@GeneratedValue
@Column(name = "id_animal")
private int id;
@Column(length = 15, nullable = false)
@NotNull(message = "Campo apelido não preenchido.")
private String apelido;
@Column(nullable = false)
private Date dataNascimento;
@Column(nullable = true)
private Date dataRemocao;
@Column(nullable = false)
@NotNull(message = "Campo raça não preenchido.")
private String raca;
@Column(nullable = false)
@NotNull(message = "Campo peso não preenchido.")
private Double peso;
@Column(nullable = false)
@NotNull(message = "Campo altura não preenchido.")
private Double altura;
@Column(nullable = false)
private ArrayList<Alimento> lista = new ArrayList<Alimento>();
public Animal(String apelido, Date dataNascimento, Date dataRemocao, String raca, Double peso, Double altura,
ArrayList<Alimento> lista) {
this.apelido = apelido;
this.dataNascimento = dataNascimento;
this.dataRemocao = dataRemocao;
this.raca = raca;
this.peso = peso;
this.altura = altura;
this.lista = lista;
}
public Animal() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getApelido() {
return apelido;
}
public void setApelido(String apelido) {
this.apelido = apelido;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getRaca() {
return raca;
}
public void setRaca(String raca) {
this.raca = raca;
}
public Double getPeso() {
return peso;
}
public void setPeso(Double peso) {
this.peso = peso;
}
public Double getAltura() {
return altura;
}
public void setAltura(Double altura) {
this.altura = altura;
}
public ArrayList<Alimento> getLista() {
return lista;
}
public void setLista(ArrayList<Alimento> lista) {
this.lista = lista;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public Date getDataRemocao() {
return dataRemocao;
}
public void setDataRemocao(Date dataRemocao) {
this.dataRemocao = dataRemocao;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((altura == null) ? 0 : altura.hashCode());
result = prime * result + ((apelido == null) ? 0 : apelido.hashCode());
result = prime * result + ((dataNascimento == null) ? 0 : dataNascimento.hashCode());
result = prime * result + ((dataRemocao == null) ? 0 : dataRemocao.hashCode());
result = prime * result + id;
result = prime * result + ((lista == null) ? 0 : lista.hashCode());
result = prime * result + ((peso == null) ? 0 : peso.hashCode());
result = prime * result + ((raca == null) ? 0 : raca.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Animal other = (Animal) obj;
if (altura == null) {
if (other.altura != null)
return false;
} else if (!altura.equals(other.altura))
return false;
if (apelido == null) {
if (other.apelido != null)
return false;
} else if (!apelido.equals(other.apelido))
return false;
if (dataNascimento == null) {
if (other.dataNascimento != null)
return false;
} else if (!dataNascimento.equals(other.dataNascimento))
return false;
if (dataRemocao == null) {
if (other.dataRemocao != null)
return false;
} else if (!dataRemocao.equals(other.dataRemocao))
return false;
if (id != other.id)
return false;
if (lista == null) {
if (other.lista != null)
return false;
} else if (!lista.equals(other.lista))
return false;
if (peso == null) {
if (other.peso != null)
return false;
} else if (!peso.equals(other.peso))
return false;
if (raca == null) {
if (other.raca != null)
return false;
} else if (!raca.equals(other.raca))
return false;
return true;
}
}
<file_sep>/src/controle/UsuarioCtrl.java
package controle;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import dao.UsuarioDAO;
import daoImplementation.UsuarioDAOimp;
import modelo.Usuario;
@ManagedBean
@SessionScoped
/**Template Method*/
public class UsuarioCtrl extends TemplateCtrl {
private Usuario usuario = new Usuario();
private List<Usuario> listausers;
private String confirmarSenha;
private String destinoSalvar;
public UsuarioCtrl() {
this.destinoSalvar = "usuariosucesso";
this.usuario = new Usuario();
this.usuario.setAtivo(true);
}
public String novo() {
this.destinoSalvar = "usuariosucesso";
this.usuario = new Usuario();
this.usuario.setAtivo(true);
return "/publico/cadastrarUsuario";
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public List<Usuario> getListausers() {
UsuarioDAO usuariodao = new UsuarioDAOimp();
this.listausers = usuariodao.listAll();
return listausers;
}
public void setListausers(List<Usuario> listausers) {
this.listausers = listausers;
}
public String getConfirmarSenha() {
return confirmarSenha;
}
public void setConfirmarSenha(String confirmarSenha) {
this.confirmarSenha = confirmarSenha;
}
public String getDestinoSalvar() {
return destinoSalvar;
}
public void setDestinoSalvar(String destinoSalvar) {
this.destinoSalvar = destinoSalvar;
}
@Override
public String salvar() {
FacesContext context = FacesContext.getCurrentInstance();
if (!this.usuario.getSenha().equals(this.confirmarSenha)) {
FacesMessage facesMessage = new FacesMessage("A senha não foi confirmada corretamente");
context.addMessage(null, facesMessage);
return null;
}
UsuarioDAO usuariodao = new UsuarioDAOimp();
usuariodao.save(this.usuario);
return "publico/login.xhtml?faces-redirect=true";
}
// public void remover(Usuario usuario) {
//
// UsuarioDAO usuariodao = new UsuarioDAOimp();
// usuario.setDataRemocao(Calendar.getInstance().getTime());
// usuariodao.save(usuario);
// }
public void removerPermanente(Usuario usuario) {
UsuarioDAO usuariodao = new UsuarioDAOimp();
usuariodao.delete(usuario);
}
@Override
public String editar() {
this.confirmarSenha = "";
usuario.setSenha("");
return "/publico/cadastrarUsuario";
}
}
<file_sep>/src/controle/AnimalCtrl.java
package controle;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import dao.AnimalDAO;
import daoImplementation.AnimalDAOimp;
import modelo.Animal;
@ManagedBean
@SessionScoped
public class AnimalCtrl {
private Animal animal;
private List<Animal> listaAnimal;
public AnimalCtrl() {
this.animal = new Animal();
AnimalDAO animaldao = new AnimalDAOimp();
this.listaAnimal = animaldao.listAll();
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
public List<Animal> getListaAnimal() {
AnimalDAO animaldao = new AnimalDAOimp();
this.listaAnimal = animaldao.listAll();
return listaAnimal;
}
public void setListaAnimal(List<Animal> listaAnimal) {
this.listaAnimal = listaAnimal;
}
public void salvar() {
AnimalDAO animaldao = new AnimalDAOimp();
animaldao.save(this.animal);
this.animal = new Animal();
}
public void removerPermanente(Animal animal) {
AnimalDAO animaldao = new AnimalDAOimp();
animaldao.delete(animal);
}
public void editar(Animal animal) {
this.animal = animal;
}
}
| ebf7467c0a5b0c124fe38d2abaeb3154c7f4b765 | [
"Markdown",
"Java"
] | 13 | Java | joaoGabriel55/NurtureKeep | e6025508f02600ff1afd81b9c5b83f8852caccf1 | 36d6c90fd5ab16d3fb92dff93fb410eef2281f92 |
refs/heads/master | <file_sep>require 'gdshowsdb'
require 'pry'
class Trivia
Gdshowsdb.init()
Gdshowsdb.load()
def europe_72_hash
hash = {}
shows_1972 = Show.all.where(year: 1972).where(("country != ?"), "US")
shows_1972.each do |show|
show_set = ShowSet.all.find {|showset| showset.show_uuid == show.uuid}
song_match = Song.where(show_set_uuid: show_set.uuid)
song_match.each do |song|
song_ref_match = SongRef.find_by(uuid: song.song_ref_uuid).name
if hash[show] == nil
hash[show] = []
hash[show] << song_ref_match
else
hash[show] << "#{song_ref_match}"
end
end
end
hash
end
def shows
hash = europe_72_hash
date_hash = {}
hash.map do |key, value|
if date_hash["#{key.venue}, #{key.city} on #{key.month}/#{key.day}"] == nil
date_hash["#{key.venue}, #{key.city} on #{key.month}/#{key.day}"] = value
else
date_hash["#{key.venue}, #{key.city} on #{key.month}/#{key.day}"] << value
end
end
date_hash
end
def select_random_show
show_array = ["Wembley Empire Pool, London on 4/7", "Tivoli Concert Hall, Copenhagen on 4/17", "The Strand Lyceum, London on 5/26", "Olympia Theater, Paris on 5/3", "Bickershaw Festival, Wigan on 5/7", "Rotterdam Civic Hall, Rotterdam on 5/11"]
show_array.sample
end
def first_song
show = select_random_show
shows_hash = shows
show_match = shows_hash.select {|key, value| key == show}
hash = {show => show_match.values[0][0]}
end
def select_random_song
song_array = ["<NAME>", "Bertha", "<NAME>", "I Know You Rider", "Sugaree", "Not Fade Away"]
song_array.sample
end
def song_count
song = select_random_song
song_shows = SongRef.find_by_name(song).shows
match = song_shows.select {|show| show.title[0..3] == "1972" && show.country != "US"}.length
hash = {song => match}
end
def easy_questions
{
1 => {
:"Who got lost in a museum in Amsterdam hours before a show, and had to be found by the police?" => "<NAME>"},
2 => {:"Who met their doppelganger in Germany?" => "<NAME>"},
3 => {:"Who is missing half of their right middle finger?" => "<NAME>"},
4 => {:"Who dosed the security guards at a show in Belgium?" => "<NAME>"},
5 => {:"Who is displayed on the Europe '72 album cover?" => "Ice Cream Kid"},
6 =>{:"To which song do these lyrics belong: 'Like a crazy quilt star gown through a dream night wind'?" => "China Cat Sunflower"}
}
end
def easy_questions_sample
easy_questions[rand(1..6)]
end
end
<file_sep>class Player
attr_accessor :name, :lives, :username, :item
def initialize(username=nil)
@username = username
@lives = 3
@item = 0
end
def get_next_item
last_item = player_items.last != nil ? player_items.last.id_number : 0
next_id = last_item + 1
next_item = Item.all.find {|item| item.id_number == next_id}
end
def return_item
get_next_item.name
end
def remove_life
@lives = @lives - 1
end
def player_items
Item.all.select {|item| item.user == self}
end
end
<file_sep>require_relative '../config/environment.rb'
require_relative '../lib/trivia.rb'
require_relative '../lib/gdshowsdb.db'
require 'pry'
<file_sep>require_relative './trivia.rb'
require 'colorize'
require 'lolize/auto'
require 'pry'
class Question
TRIVIA = Trivia.new()
colorizer = Lolize::Colorizer.new
def self.ask_question_first_class
fake_array = [15, 17, 19, 21, 9, 6]
song = TRIVIA.song_count
question = "How many times was #{song.keys[0]} played during the Europe '72 tour?"
if Game.asked_questions.include?(question)
self.ask_question_first_class
else
puts question
answer_array = [song.values[0], fake_array.sample]
var = answer_array.sample
other = answer_array.find {|el| el != var}
puts "1. #{var}"
puts "2. #{other}"
response = STDIN.gets.chomp
if response.to_s == song.values[0].to_s
self.correct
elsif response == "exit"
self.exit
else
self.incorrect
end
end
Game.add_to_asked_questions(question)
end
def self.ask_question_second_class
fake_array = ["One More Saturday Night", "Mexicali Blues", "<NAME>", "Big Railroad Blues", "Mr. Charlie", "He's Gone"]
show = TRIVIA.first_song
question = "What song did they open with at #{show.keys[0]} during the Europe '72 tour?"
if Game.asked_questions.include?(question)
self.ask_question_second_class
else
puts question
answer_array = [show.values[0], fake_array.sample]
var = answer_array.sample
other = answer_array.find {|el| el != var}
puts "1. #{var}"
puts "2. #{other}"
response = STDIN.gets.chomp
if response == show.values[0]
self.correct
elsif response == "exit"
self.exit
else
self.incorrect
end
end
Game.add_to_asked_questions(question)
end
def self.ask_question_third_class
fake_array = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"]
band = TRIVIA.easy_questions_sample
question = "#{band.keys[0]}"
if Game.asked_questions.include?(question)
self.ask_question_third_class
else
puts question
answer_array = [band.values[0], fake_array.sample]
var = answer_array.sample
other = answer_array.find {|el| el != var}
puts "1. #{var}"
puts "2. #{other}"
response = STDIN.gets.chomp
if response == band.values[0]
self.correct
elsif response == "exit"
self.exit
else
self.incorrect
end
end
Game.add_to_asked_questions(question)
end
def self.correct
puts "You are correct!"
end
def self.incorrect
puts "Sorry, you have lost a life"
end
def self.exit
#break
end
end
<file_sep>require_relative './trivia.rb'
require_relative './question.rb'
require_relative './item.rb'
require_relative './player.rb'
require 'colorized_string'
require 'colorize'
require 'pry'
class Game < Question
def initialize(player=nil)
@@asked_questions = []
@@player = player || Player.new()
end
def stealyourface
puts " ...............
.,;;######################;;.,
.;##'' ,/| ``##;.
.;#' ,/##|__ `#;.
.;#' /######/' `#;.
;#' ,/##/__ `#;
;#' ,/######/' `#;
;#' /######/' `#;
;#' ,/##/___ `#;
;# ,/#######/' #;
;# /#######/' #;
;# ,/##/__ #;
`#; ,/######/' ;#'
`#;. /######/' ,;#'
`#;. ,/##/__ ,;#'
`#;. /######/' ,;#'
##;_ |##/' _;##
:#`-;#;... |/' ...;#;-'#:
:`__ `-#### __ __ ####-' __':
: ``------.. `' ..------'' :
`.. `--------`..'--------' ..'
: :
`:.. /: :\ ..:'
`. :: :: .'
#. .#
`'##;##;##;##;##`'
`' `' `' `' `' "
end
##Welcome
def welcome
puts "Oh no!\n The Grateful Dead have a big show tonight but manager Rock Scully can't find anyone in the band.\n It appears a crazed fan has kidnapped them and is holding the members hostage!\n Help Scully get the band back before the show tonight,\n by answering some of these questions!\n Remember, without Jerry, there is no Grateful Dead."
end
def prompt_user
puts "To play, please enter a groovy username:"
end
##Enter username
def enter_username
response = STDIN.gets.chomp
@@player.username = response
puts "You'll only have #{@@player.lives} chances to get it right."
end
##Story line
def question_1
puts "Look's like the first one's an easy one, here you go:"
end
def question_array
array = ["If you get this one, I'll see you on Shakedown Street", "C'mon and answer so we can go dancing in the street", "If you miss this, Bertha don't you come around here anymore", "I know you rider, you can get the next one", "Me and my uncle know the answer, do you?", "Here comes the sunshine. I mean... The next question!"]
puts array.sample
end
##Question
def question_first_class
Question.ask_question_first_class
end
def self.asked_questions
@@asked_questions
end
def self.add_to_asked_questions(question)
@@asked_questions << question
end
def question_second_class
Question.ask_question_second_class
end
def question_third_class
Question.ask_question_third_class
end
def random_question
[question_first_class, question_second_class, question_third_class].sample
end
def Question.correct
next_item = @@player.get_next_item
next_item.add_user(@@player)
puts "Congratulations! You now have saved #{@@player.return_item} and you have #{@@player.lives} chances left to rescue them all."
# if @@player.return_item == "<NAME>"
# puts "Fire on the mountain! But hurry up and answer the rest before the Dead misses their show!"
# elsif @@player.return_item == "<NAME>"
# puts "What a miracle! Now, let's see if you can get the next one."
if @@player.return_item == "<NAME>"
puts "RIGHT ON! We've got a show to put on!"
pid = fork{ exec 'killall', "afplay" }
abort("You won, thanks for rescuing the band!")
end
end
def Question.incorrect
@@player.remove_life
puts "Uh oh, you lost a chance. You now only have #{@@player.lives} chance(s) left."
# if @@player.lives == 2
# puts "Can a box of rain ease this pain?"
# elsif @@player.lives == 1
# puts "Let me sing your blues away!"
if @@player.lives == 0
pid = fork{ exec 'killall', "afplay" }
abort("The show wont' go on. Play again, and better luck next time!")
end
end
def Question.exit
pid = fork{ exec 'killall', "afplay" }
abort("Sorry to see you go!")
end
def runner
pid = fork{ exec 'afplay', "media/(Disc 7) 05 - Scarlet Begonias.mp3" }
stealyourface
welcome
prompt_user
enter_username
question_1
until @@player.lives == 0 || @@player.return_item == "<NAME>" do
random_question
question_array
end
end
end
b = Game.new
b.runner
<file_sep>require 'bundler'
require "sinatra/activerecord"
require "active_record"
# require 'require_all'
# require 'catpix'
# require 'rmagick'
# require 'rake'
require 'gdshowsdb'
Bundler.require
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'db/development.db')
require_all 'lib'
<file_sep>Item.create(name: "Guitar Pick", points: 5)
Item.create(name: "Tie Dye Shirt", points: 10)
Item.create(name: "China Cat Sunflower", points: 15)
Item.create(name: "Steal Your Face", points: 20)
Item.create(name: "Scarlet Begonia", points: 25)
<file_sep>class Item
attr_accessor :player, :name, :id_number, :user
@@all = []
def initialize(name, id_number, user=nil)
@name = name
@id_number = id_number
@user = user
@@all << self
end
def self.all
@@all
end
def add_user(user)
self.user = user
end
end
testing = Item.new("Test Case", 1)
guitar_pick = Item.new("<NAME>", 2)
tie_dye = Item.new("<NAME>", 3)
china_cat = Item.new("<NAME>", 4)
steal_your_face = Item.new("<NAME>", 5)
scarlet = Item.new("<NAME>", 6)
bear = Item.new("<NAME>", 7)
| 9c591c45ee47b5b6c93aa86bb612dc327e71c42a | [
"Ruby"
] | 8 | Ruby | melissames/module-one-final-project-guidelines-web-012918 | 14354a0a381c31aec9b98090aa40eb4d338453b5 | 668838f7b42d079055afec438f5d8099e3e3b2c0 |
refs/heads/master | <file_sep>//
// ViewController.swift
// Prime number
//
// Created by D7703_23 on 2018. 3. 29..
// Copyright © 2018년 D7703_23. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var txtF: UITextField!
@IBOutlet weak var Resultlabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func Check(_ sender: Any) {
var isPrime = true
let num = Int(txtF.text!)
if num == 1 {
isPrime = false
}
if num != 1 && num != 2 {
for i in 2 ..< num! {
if num! % i == 0 {
isPrime = false
}
}
}
if isPrime == true {
Resultlabel.text = "prime number"
} else {
Resultlabel.text = "Not prime number"
}
}
@IBAction func Reset(_ sender: Any) {
Resultlabel.text = ""
txtF.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 8664a664bb983f53efadb1f1d4d5137b79bc0112 | [
"Swift"
] | 1 | Swift | cjf8012/PrimeNumber | e070a816952ccb91a579eb618251786c3169ba59 | ab06933c48e7fb394d02d547dd94025bc16f6865 |
refs/heads/master | <repo_name>danailvidev/movies-PWA<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment as env } from '../../environments/environment'
import { MoviesResponse, MovieModel } from './models';
@Component({
selector: 'home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.scss']
})
export class HomeComponent implements OnInit {
searchForm: FormGroup;
movies: Array<MovieModel>;
info: any;
constructor(private fb: FormBuilder,
private http: HttpClient) { }
ngOnInit() {
this.searchForm = this.fb.group({
title: new FormControl('', Validators.required),
plot: new FormControl(false),
})
}
search() {
console.log(this.searchForm.value)
let plot = this.searchForm.value.plot == true ? 'full' : 'short';
return this.http.get(`https://www.omdbapi.com/?s=${this.searchForm.value.title}&plot=${plot}&apikey=${env.omdbapiApikey}`).subscribe((res: MoviesResponse) => {
if (res.Response == 'True') {
this.movies = res.Search;
this.info = res.totalResults
}
})
}
}<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
omdbapiApikey: 'fee8d867' // http://www.omdbapi.com/
};
<file_sep>/src/app/home/models.ts
export interface MoviesResponse {
Search: Array<MovieModel>,
totalResults: string | number,
Response: string | boolean,
Error?: string
}
export class MovieModel {
Title: string;
Year: string;
imdbID: string;
Type: string;
Poster: string;
} | 174fed2e55265fe50965216af24639180bae09e3 | [
"TypeScript"
] | 3 | TypeScript | danailvidev/movies-PWA | b772f524eca65928d755480dd356b31f4eb9e7d2 | 5b0163c23990c994591e0f4023933fdc86234a3c |
refs/heads/main | <repo_name>keshab101/CMSC420-Advanced-Data-Structures<file_sep>/pqueue/README.md
# Heaps and Priority Queues
## Overview
This is a "warmup" project, and covers material you should have
learned in CMSC132 and CMSC351. The goals are to ensure that you are:
* familiar with the basic data structures on which we will
build,
* able to navigate git, and
* able to upload your code to the submit server.
Please note that, per the syllabus, we **do not** accept late
submissions without an approved reason for an extension. This is
different than what you might be used to from other classes, so
ensure that you know what the deadline is on the submit server.
You will need to implement four classes:
* `LinkedMinHeap.java`
* `ArrayMinHeap.java`
* `LinearPriorityQueue.java`
* `MinHeapPriorityQueue.java`
If you are reading this on Gitlab, you will need to clone your own
copy. There are two ways to do this:
1. You can simply clone this repository using either the HTTPS or SSH urls, or
2. You can first create a personal fork, and clone that.
The second option is better, because you can then push your changes back to Gitlab, which means you now have a remote backup. This has several advantages:
* If you ask a question on the discussion forum, we can see your
code and provide a more precise response.
* If your computer dies (which is going to happen to at least one
person this semester, probably more), you have only lost the work
you did since your last push.
* If you want to work on multiple machines, it's as easy as pushing
from one and pulling on the other. This is why git exists in the
first place.
The starter code is in the `src/` directory, with the actual project
code in `src/pqueue/`. There is also JavaDoc in the `doc/` directory.
The code you need to modify is in `src/pqueue/heaps/` and
`src/pqueue/priorityqueues/`. You are welcome to add more directories,
files, and classes if you wish, but you are not required to.
## Prerequisites
We expect you to be familiar with Binary Search Trees, Stacks, Lists,
FIFO queues and programming in Java. Skills harnessed by a typical
UMD freshman course such as CMSC 131/132 are more than sufficient.
You will need to remind yourselves of what a binary heap is and how
insertions and min-deletions work, as well as the ways in which they
can be represented in computer memory. The structure and operation of
heaps are briefly touched upon in the next section.
In this class, we do not aim to test your programming, OOP or Java
expertise. We want to teach you Data Structures. However, a minimal
amount of familiarity with certain OOP/Java constructs will be
required. You would probably benefit from ensuring that you understand
the basics of Iterators and checked Exceptions. You should also be
familiar with what an interface is, what an anonymous inner class is,
how it differs from a functional interface, etc.
## A Brief Review of Heaps and Priority Queues
While we assume you are already familiar with these structures, we
will present a brief review, to refresh your memory.
### Heaps
#### Insertion
A *heap* is a complete binary tree (but *not* a complete binary search
tree). Insertions occur at the "leftmost" unoccupied space at the
leaf level. For example, in the diagram
```mermaid
graph TD;
3 --> 10;
3 --> 4;
10 --> 16;
```
we would add the next element below 10, to the right of 16. Let's
say we add 8 as the next value. This would then yield
```mermaid
graph TD;
3 --> 10;
3 --> 4;
10 --> 16;
10 --> 8;
```
However, heaps have another invariant: the subtree below an element
contains only elements that are greater than or equal to its value.
(Technically, this means we have a *minheap*. A *maxheap* would invert
this invariant.)
Because 8 is less than its parent 10, we need to *percolate* it
upwards.
```mermaid
graph TD;
3 --> 8;
3 --> 4;
8 --> 16;
8 --> 10;
```
8 is now less than or equal to all of the elements below it, and
greater than its parent 3. If we were now to insert 2, it would
become the first child of 4 (since the subtree under 8 is complete).
```mermaid
graph TD;
3 --> 8;
3 --> 4;
8 --> 16;
8 --> 10;
4 --> 2;
```
Again, this element is less than its parent (4), so it needs to
percolate upwards.
```mermaid
graph TD;
3 --> 8;
3 --> 2;
8 --> 16;
8 --> 10;
2 --> 4;
```
2 is still less than its parent (3), so we have to percolate again
```mermaid
graph TD;
2 --> 8;
2 --> 3;
8 --> 16;
8 --> 10;
3 --> 4;
```
#### Deletion
When deleting an element from the heap, we always delete the root element. Let's complete
the tree above as a starting point:
```mermaid
graph TD;
2 --> 8;
2 --> 3;
8 --> 16;
8 --> 10;
3 --> 4;
3 --> 12;
```
We then delete the root (2), and promote the *rightmost leaf* to be the new root:
```mermaid
graph TD;
12 --> 8;
12 --> 3;
8 --> 16;
8 --> 10;
3 --> 4;
```
This violates our invariant, but rather than percolate upwards from the insertion point,
we have to percolate *downwards* from the new root. We do this by percolating the new
element to the *lesser* of its children (which will be less than or equal to its former
sibling, which is now its child).
```mermaid
graph TD;
3 --> 8;
3 --> 12;
8 --> 16;
8 --> 10;
12 --> 4;
```
We continue this until the element we moved respects the invariant
```mermaid
graph TD;
3 --> 8;
3 --> 4;
8 --> 16;
8 --> 10;
4 --> 12;
```
#### Iteration
For our heap structures, we want to be able to visit all of the nodes
in ascending order. You will need to figure out how to do this while:
* not modifying the backing structure (that is, the array or linked list), and
* detecting changes to the backing structure during iteration, and throwing
a `java.util.ConcurrentModificationException`.
#### Efficient Representation
Since heaps are complete binary trees, they can be implemented very efficiently
and compactly using an array. This is based on a breadth-first (level-order)
enumeration of the nodes in the heap. This enumeration is exemplified as follows:
```mermaid
graph TD;
8 --> 10;
8 --> 13;
10 --> 16;
10 --> 15;
13 --> 20;
```
| 0 | 1 | 2 | 3 | 4 | 5 |
| --- | --- | --- | --- | --- | --- |
| 8 | 10 | 13 | 16 | 15 | 20 |
Note that the node at index $`i`$ has children at indices $`2i+1`$ and $`2i+2`$ (one
or two children might not even exist, of course), whereas the parent of index
$`i`$ (if it exists) is at index $`\lfloor \frac{i-1}{2} \rfloor`$.
The linked structure is what you will implement in `LinkedMinHeap`, and you will need
to implement the same data structure in this array form in `ArrayMinHeap`. Obviously,
you will need to modify not only how the data is represented in memory, but how the
percolation operations work. Since the functionality provided by these data structures
is identical, you can use the same unit tests you develop for the linked version when
testing the array version. All you should need to do is change the type referenced in the
tests.
### Priority Queues
The Priority Queue is an Abstract Data Type (ADT) with a very simple property: Every
element to be enqueued is attached a certain positive integer priority, which predetermines
its order in the queue. By convention, smaller integers are considered "higher" in
terms of priority, such that, for example, priority 1 is considered a higher priority than
3. Dequeueings only happen from the top of the queue, after which the element "before"
the first one will be available for immediate processing. We see these kinds of queues all
the time in real life.
A simple FIFO (first-in, first-out) queue might look like
```mermaid
graph LR;
N --> F --> L --> D --> A --> G --> W;
```
where N is the head of the queue. Adding a new element C works as we'd expect from 132:
```mermaid
graph LR;
N --> F --> L --> D --> A --> G --> W --> C;
```
A priority queue, by contrast, assigns a priority to each of these:
```mermaid
graph LR;
N,1 --> F,2 --> L,4 --> D,6 --> A,8 --> G,11 --> W,15;
```
Now we're not just adding C, because it too has a priority (say it's 5). We would not
add C,5 at the end, because C has a higher priority (5) than W (15). Instead, we have
to insert it between L and D:
```mermaid
graph LR;
N,1 --> F,2 --> L,4 --> C,5 --> D,6 --> A,8 --> G,11 --> W,15;
```
The obvious thing to do is to scan through the queue linearly until you find the
appropriate place for the new element. This is how you will implement
`LinearPriorityQueue`. This is inefficient, however ($`\mathcal{O}(n)`$), so you will
be implementing a second version, using a binary minheap (which you have already done
in this project!). This will be `MinHeapPriorityQueue`. Since minheaps are complete and
balanced, enqueuing and dequeueing should be $`\mathcal{O}(\log_2 n)`$. This makes minheap
a very good choice for implementing a priority queue.
#### Iteration
For our priority queues, we want to be able to visit all of the nodes
in priority-FIFO order. That is, the highest priority items should be returned
first, and for items of equal priority, they should be returned in FIFO order.
The same considerations hold for these iterators as for the heap iterators.
## General Notes on Iterators
You will need to review (in any Java reference):
* How to implement an iterator
* The difference between a *fail-fast* iterator and a *fail-safe* iterator
For your first project, you will need to:
* Implement **fail-fast** Iterators for your four classes.
* Implement the `next()` and `hasNext()` methods. (You don't need to implement the
`remove()` method for this project, but may in the future.)
* This fail-fast iterator needs to throw a `java.util.ConcurrentModificationException` when appropriate.
* You also need to throw `NoSuchElementException` when appropriate.
Some observations about Iterators and `java.util.ConcurrentModificationException`:
* After you create an iterator, the iterator will return the elements in
the data structure in some order every `next()` call (see the specifics for
each type of data structure above). However, if you modify the data
structure, it could mess up what the iterator `next()` will return because
of the new elements. Therefore, we need to specify the behavior of the
iterator by specifying what kind of iterator to use.
* Fail-fast iterators will immediately report this potentially dangerous
behavior by throwing a `java.util.ConcurrentModificationException`. The error condition is
when you have an iterator created before some modification, and you attempt
to use it again (calling `next()`, `hasNext()`, etc.) after the modification.
Any modifications of a data structure invalidate all current iterators.
## Tips, Hints, and Guidelines
You may find these useful:
* Familiarize yourself with the basics of `git`. There is a tutorial at
https://gitlab.cs.umd.edu/mmarsh/git-tutorial, which was written for more git-heavy
courses, but should still be useful.
* Read the JavaDoc for the interfaces that you will be extending: `MinHeap` and `PriorityQueue`.
* We strongly suggest that employ **test-driven development**, in which you develop your
unit tests first to define the desired behavior, and then write your code so that it
passes these tests.
* For the data structures we've provided, read the source code and unit tests. This will help
you design your implementation and develop your own tests.
* Our tests will look at corner cases in the behavior of your implementation. You should try
to develop thorough **stress tests** that test *all conceivable* inputs, including
ones that are malformed. If your code should throw exceptions in certain (however unlikely)
situations, make sure you are testing for those exceptions.
* We've provided a `StudentTests` class with a number of unit tests. Take a look at this,
because it might help you develop unit tests where exceptions are expected.
* You may use any IDE you like. If you don't like Eclipse, feel free to use a different one.
The Eclipse Course Management Plugin will not work for this course.
* You will not *need* any of the functional programming features introduces in Java 8, but
you might find them useful in testing. For example:
```java
List<Integer> priorities = IntStream.range(1, MAX_PRIORITY + 1).boxed().
collect(Collectors.toList());
Collections.shuffle(priorities, r);
```
is much simpler than the equivalent with `for` loops.
## Submission and Grading
You will submit your code to the department's https://submit.cs.umd.edu server as a
zip file. Credit will be awarded based on the number of tests that your code passes.
Additionally, we will inspect your code to ensure that it meets certain criteria:
* `ArrayMinHeap` must use contiguous storage, whether an `ArrayList`, a `Vector`, or a raw array.
* `MinHeapPriorityQueue` must use one of *your* minheap implementations.
* You *may not* use built-in or third-party implementations of minheaps (or maxheaps) or
priority queues.
You should use the `src/Archiver.java` or `src/AdvancedArchiver.java` utility to create your
zip file. This will exclude the `.git` and `doc` folders, to reduce the size of your file.
It should be run from the top level of the project repository (the parent directory of `src`).
A simple way to test if you're calling `Archiver` correctly is to prepare a zip file from the skeleton code, and submit it.
The tests are all release tests, so you will not get to see the actual test code, only whether
your code ran successfully on each. You will have 5 release tokens in a 24-hour period, so
you should do thorough unit testing on your own before submitting. We will use your
highest-scoring submission before the deadline.
**No credit will be awarded for late submissions.**
We will run the MoSS Software Similarity Detection System on all of the submissions. We
*will* catch any instances of plagiarism, and don't enjoy dealing with the Office of Student
Conduct any more than you do (we're very busy).
<file_sep>/pqueue/src/pqueue/priorityqueues/MinHeapPriorityQueue.java
package pqueue.priorityqueues; // ******* <--- DO NOT ERASE THIS LINE!!!! *******
/* *****************************************************************************************
* THE FOLLOWING IMPORTS WILL BE NEEDED BY YOUR CODE, BECAUSE WE REQUIRE THAT YOU USE
* ANY ONE OF YOUR EXISTING MINHEAP IMPLEMENTATIONS TO IMPLEMENT THIS CLASS. TO ACCESS
* YOUR MINHEAP'S METHODS YOU NEED THEIR SIGNATURES, WHICH ARE DECLARED IN THE MINHEAP
* INTERFACE. ALSO, SINCE THE PRIORITYQUEUE INTERFACE THAT YOU EXTEND IS ITERABLE, THE IMPORT OF ITERATOR
* IS NEEDED IN ORDER TO MAKE YOUR CODE COMPILABLE. THE IMPLEMENTATIONS OF CHECKED EXCEPTIONS
* ARE ALSO MADE VISIBLE BY VIRTUE OF THESE IMPORTS.
** ********************************************************************************* */
import pqueue.exceptions.*;
import pqueue.heaps.ArrayMinHeap;
import pqueue.heaps.EmptyHeapException;
import pqueue.heaps.MinHeap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* <p>{@link MinHeapPriorityQueue} is a {@link PriorityQueue} implemented using a {@link MinHeap}.</p>
*
* <p>You <b>must</b> implement the methods of this class! To receive <b>any credit</b> for the unit tests
* related to this class, your implementation <b>must</b> use <b>whichever</b> {@link MinHeap} implementation
* among the two that you should have implemented you choose!</p>
*
* @author ---- <NAME> ----
*
* @param <T> The Type held by the container.
*
* @see LinearPriorityQueue
* @see MinHeap
* @see PriorityQueue
*/
public class MinHeapPriorityQueue<T> implements PriorityQueue<T>{
/* ***********************************************************************************
* Write any private data elements or private methods for MinHeapPriorityQueue here...*
* ***********************************************************************************/
private class Elements implements Comparable<Elements>{
private T value;
private int priority;
public Elements(T value, int priority) {
this.value = value;
this.priority = priority;
}
public int getPriority() {
return priority;
}
public T getValue() {
return value;
}
public int compareTo(MinHeapPriorityQueue<T>.Elements o) {
if(this.priority < o.priority) {
return -1;
} else if(this.priority > o.priority) {
return 1;
} else {
return 0;
}
}
}
private boolean modified;
private ArrayMinHeap<Elements> minQueue;
/* *********************************************************************************************************
* Implement the following public methods. You should erase the throwings of UnimplementedMethodExceptions.*
***********************************************************************************************************/
/**
* Simple default constructor.
*/
public MinHeapPriorityQueue(){
minQueue = new ArrayMinHeap<Elements>();
modified = false;
}
@Override
public void enqueue(T element, int priority) throws InvalidPriorityException { // DO *NOT* ERASE THE "THROWS" DECLARATION!
if(priority < 1) {
throw new InvalidPriorityException("Invalid Priority");
}
Elements elem = new Elements(element, priority);
minQueue.insert(elem);
modified = true;
}
@Override
public T dequeue() throws EmptyPriorityQueueException { // DO *NOT* ERASE THE "THROWS" DECLARATION!
if(isEmpty()) {
throw new EmptyPriorityQueueException("Queue is already empty");
}else {
try {
return minQueue.deleteMin().getValue();
} catch (EmptyHeapException e) {
e.printStackTrace();
}
modified = true;
}
return null;
}
@Override
public T getFirst() throws EmptyPriorityQueueException { // DO *NOT* ERASE THE "THROWS" DECLARATION!
if(isEmpty()) {
throw new EmptyPriorityQueueException("Queue is already empty");
}else {
try {
return minQueue.getMin().getValue();
} catch(EmptyHeapException e){
e.printStackTrace();
}
}
return null;
}
@Override
public int size() {
return minQueue.size();
}
@Override
public boolean isEmpty() {
return minQueue.size() == 0 ? true: false;
}
public String toString() {
String result = "";
Iterator<Elements> it = minQueue.iterator();
while(it.hasNext()) {
result += it.next().getValue() + ", "
+ it.next().getPriority() + " ";
}
return result;
}
// public String toString() {
// String result = "";
// for(int i = 0; i < size(); i++) {
// result += minQueue
// result += minQueue[i].getValue() + ","
// + queue.get(i).getPriority();
// if(i < size()-1) {
// result += "-> ";
// }
// }
// return result;
// }
@Override
public Iterator<T> iterator() {
this.modified = false;
return new Iterator<T>() {
int index = 0;
public boolean hasNext() {
return index < size();
}
public T next() {
if(modified) {
throw new ConcurrentModificationException();
}else {
ArrayList<Elements> list = new ArrayList<Elements>();
Iterator<Elements> it = minQueue.iterator();
while(it.hasNext()) {
list.add(it.next());
}
Collections.sort(list);
return list.get(index++).getValue();
}
}
};
}
}
<file_sep>/pqueue/src/pqueue/heaps/ArrayMinHeap.java
package pqueue.heaps; // ******* <--- DO NOT ERASE THIS LINE!!!! *******
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
/* *****************************************************************************************
* THE FOLLOWING IMPORT IS NECESSARY FOR THE ITERATOR() METHOD'S SIGNATURE. FOR THIS
* REASON, YOU SHOULD NOT ERASE IT! YOUR CODE WILL BE UNCOMPILABLE IF YOU DO!
* ********************************************************************************** */
import java.util.Iterator;
/**
* <p>{@link ArrayMinHeap} is a {@link MinHeap} implemented using an internal array. Since heaps are <b>complete</b>
* binary trees, using contiguous storage to store them is an excellent idea, since with such storage we avoid
* wasting bytes per {@code null} pointer in a linked implementation.</p>
*
* <p>You <b>must</b> edit this class! To receive <b>any</b> credit for the unit tests related to this class,
* your implementation <b>must</b> be a <b>contiguous storage</b> implementation based on a linear {@link java.util.Collection}
* like an {@link java.util.ArrayList} or a {@link java.util.Vector} (but *not* a {@link java.util.LinkedList} because it's *not*
* contiguous storage!). or a raw Java array. We provide an array for you to start with, but if you prefer, you can switch it to a
* {@link java.util.Collection} as mentioned above. </p>
*
* @author -- <NAME> ---
*
* @see MinHeap
* @see LinkedMinHeap
* @see demos.GenericArrays
*/
public class ArrayMinHeap<T extends Comparable<T>> implements MinHeap<T> {
/* *****************************************************************************************************************
* This array will store your data. You may replace it with a linear Collection if you wish, but
* consult this class' * JavaDocs before you do so. We allow you this option because if you aren't
* careful, you can end up having ClassCastExceptions thrown at you if you work with a raw array of Objects.
* See, the type T that this class contains needs to be Comparable with other types T, but Objects are at the top
* of the class hierarchy; they can't be Comparable, Iterable, Clonable, Serializable, etc. See GenericArrays.java
* under the package demos* for more information.
* *****************************************************************************************************************/
private T[] data;
/* *********************************************************************************** *
* Write any further private data elements or private methods for LinkedMinHeap here...*
* *************************************************************************************/
private int size;
private int INITIAL_CAPACITY = 15;
private boolean modified;
private void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/* *********************************************************************************************************
* Implement the following public methods. You should erase the throwings of UnimplementedMethodExceptions.*
***********************************************************************************************************/
/**
* Default constructor initializes the data structure with some default
* capacity you can choose.
*/
@SuppressWarnings("unchecked")
public ArrayMinHeap(){
data = (T[]) new Comparable[INITIAL_CAPACITY];
this.size = 0;
modified = false;
}
/**
* Second, non-default constructor which provides the element with which to initialize the heap's root.
* @param rootElement the element to create the root with.
*/
@SuppressWarnings("unchecked")
public ArrayMinHeap(T rootElement){
data = (T[]) new Comparable[INITIAL_CAPACITY];
data[0] = rootElement;
this.size = 1;
}
/**
* Copy constructor initializes {@code this} as a carbon copy of the {@link MinHeap} parameter.
*
* @param other The MinHeap object to base construction of the current object on.
*/
@SuppressWarnings("unchecked")
public ArrayMinHeap(MinHeap<T> other){
this.size = other.size();
T[] otherData = (T[]) new Comparable[INITIAL_CAPACITY];
Iterator<T> itr = other.iterator();
int counter = 0;
while( itr.hasNext()) {
otherData[counter++] = itr.next();
}
this.data = otherData;
}
/**
* Standard {@code equals()} method. We provide it for you: DO NOT ERASE! Consider its implementation when implementing
* {@link #ArrayMinHeap(MinHeap)}.
* @return {@code true} if the current object and the parameter object
* are equal, with the code providing the equality contract.
* @see #ArrayMinHeap(MinHeap)
*/
@Override
public boolean equals(Object other){
if(other == null || !(other instanceof MinHeap))
return false;
Iterator<T> itThis = iterator();
Iterator<T> itOther = ((MinHeap<T>) other).iterator();
while(itThis.hasNext())
if(!itThis.next().equals(itOther.next()))
return false;
return !itOther.hasNext();
}
@SuppressWarnings("unchecked")
@Override
public void insert(T element) {
if(size >= INITIAL_CAPACITY) {
T[] bigger = (T[]) new Comparable[INITIAL_CAPACITY+1];
for(int i = 0; i < size; i++) {
bigger[i] = data[i];
}
this.data = bigger;
INITIAL_CAPACITY += 1;
}
if(isEmpty()) {
data[0] = element;
size++;
return;
}
data[size++] = element;
int parent = ((size-1)-1)/2;
int child = size-1;
//While the parent is greater than the child, do a swap
while((data[parent]).compareTo(data[child]) > 0) {
swap(data, parent, child);
child = parent;
parent = (child-1)/2;
}
this.modified = true;
}
@SuppressWarnings("unchecked")
@Override
public T deleteMin() throws EmptyHeapException { // DO *NOT* ERASE THE "THROWS" DECLARATION!
if(isEmpty()) {
throw new EmptyHeapException("Empty Heap");
}
//If the heap has only one item
T min = data[0]; /*Save the min before swapping*/
if(size == 1) {
T [] empty = (T[]) new Comparable[INITIAL_CAPACITY];
data = empty;
this.size = 0;
return min;
}
//Making a new copy of the array with last element removed
swap(data, 0, size-1);
T [] copy = (T[]) new Comparable[INITIAL_CAPACITY];
for(int i = 0; i < size -1; i++) {
copy[i] = data[i];
}
this.size--;
data = copy;
int curr = 0;
int left = 2*curr+1, right = 2*curr+2;
while(data[left] != null) {
if(data[right] == null) {
if(data[left].compareTo(data[curr]) < 0) {
swap(data, left, curr);
curr = left;
left = 2*curr+1;
}
return min;
}
if(data[left].compareTo(data[right]) < 0) {
if(data[left].compareTo(data[curr])< 0) {
swap(data, left, curr);
curr = left;
left = 2*curr+1;
right = 2*curr+2;
}else {
return min;
}
} else {
if (data[right].compareTo(data[curr]) < 0) {
swap(data, right, curr);
curr = right;
left = 2*curr+1;
right = 2*curr+1;
}else {
return min;
}
}
}
this.modified = true;
return min;
}
@Override
public T getMin() throws EmptyHeapException { // DO *NOT* ERASE THE "THROWS" DECLARATION!
if(isEmpty()) {
throw new EmptyHeapException("Empty Heap");
}else {
return data[0];
}
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0 ? true : false;
}
public String toString() {
String result = "";
for(int i = 0; i < size; i++) {
result += data[i] + " ";
}
return result;
}
/**
* Standard equals() method.
* @return {@code true} if the current object and the parameter object
* are equal, with the code providing the equality contract.
*/
@Override
public Iterator<T> iterator() {
this.modified = false;
return new Iterator<T>() {
int startindex = 0;
public boolean hasNext() {
return startindex < size();
}
public T next() {
if(modified) {
throw new ConcurrentModificationException();
}else {
ArrayList<T> list = new ArrayList<T>();
for(int i = 0; i < size(); i++) {
list.add(data[i]);
}
Collections.sort(list);
return list.get(startindex++);
}
}
};
}
}
<file_sep>/README.md
# CMSC420-Advanced-Data-Structures
Implemented projects that are on advanced data structures in java.
Some of the data structures include heaps and priority queues, AVL trees, Hash tables, PR and Quad trees.
| e8254e83a542bdd919843bea053ca439b2429e2d | [
"Markdown",
"Java"
] | 4 | Markdown | keshab101/CMSC420-Advanced-Data-Structures | de00f7925e13b90c76c55e7ec54e686b56397be4 | 7f4e7153ee1034bd17e089ca389f6cf214434257 |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 3.4.10.1
-- http://www.phpmyadmin.net
--
-- Servidor: localhost
-- Tiempo de generación: 23-03-2020 a las 15:23:51
-- Versión del servidor: 5.5.20
-- Versión de PHP: 5.3.10
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `demovujs`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `snippet`
--
CREATE TABLE IF NOT EXISTS `snippet` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(30) NOT NULL,
`foto` varchar(50) NOT NULL,
`titulo` varchar(50) NOT NULL,
`codigo` text NOT NULL,
`descripcion` text NOT NULL,
`categoria` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;
--
-- Volcado de datos para la tabla `snippet`
--
INSERT INTO `snippet` (`id`, `user`, `foto`, `titulo`, `codigo`, `descripcion`, `categoria`) VALUES
(22, 'DIEGO', '../api/loginRegistro/foto_perfil/perfil.png', 'CODIGO UNO DIEGO', '<H1>TITULO</H1>', 'TITULO GRANDE 555', 'HTML5'),
(23, 'DIEGO', 'FOTO UNO', 'ghgfhd', 'sadfsfdg', 'sdfgsdfg', 'CSS');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios`
--
CREATE TABLE IF NOT EXISTS `usuarios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`pass` varchar(300) NOT NULL,
`foto` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user` (`user`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=63 ;
--
-- Volcado de datos para la tabla `usuarios`
--
INSERT INTO `usuarios` (`id`, `user`, `email`, `pass`, `foto`) VALUES
(57, 'DIEGO', '<EMAIL>', '<PASSWORD>', '../api/loginRegistro/foto_perfil/DIEGO2026.JPG'),
(59, 'DIEGO', '<EMAIL>', '<PASSWORD>', '../api/loginRegistro/foto_perfil/DIEGO7141.JPG'),
(60, 'alvaro', '<EMAIL>', '<PASSWORD>', '../api/loginRegistro/foto_perfil/alvaro6406.JPG'),
(61, 'DIEGO', '<EMAIL>', 'e10adc3949ba59abbe56e057f20f883e', '../api/loginRegistro/foto_perfil/perfil.png'),
(62, 'DIEGO', '<EMAIL>', 'e10adc3949ba59abbe56e057f20f883e', '../api/loginRegistro/foto_perfil/perfil.png');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| e1f7ff31477db00fc30ecaee5eb55120b918e6a7 | [
"SQL"
] | 1 | SQL | aldidacom619/proyectosjava | 922b576272aafcd9eb4a4ffa87251dcf74df30f8 | 218c0c21f54cbafa0031e81a2abed3bf4f8f9d79 |
refs/heads/master | <file_sep>
(function () {
'use strict';
createjs.Sound.registerSound('snd/follower.mp3', 'follower');
nodecg.listenFor('follower', 'fathom-notify', function(name) {
follower(name.user.display_name);
});
function follower(name) {
var follower = $('#follower');
follower.text('NEW FOLLOWER');
createjs.Sound.play('follower').volume = 0.02;
follower
.transition({scale: 1.2})
.transition({opacity: 255, scale: 1.4}, 300)
.transition({scale: 1}, 50)
.transition({opacity: 0, delay: 750});
setTimeout(function() {
follower.text(truncateTo16(name.toUpperCase()));
follower
.transition({scale: 1.2})
.transition({opacity: 255, scale: 1.4}, 300)
.transition({scale: 1}, 50)
.transition({opacity: 0, scale: 1.4, delay: 5000})
.css({scale: 1});
}, 2000);
}
$(document).on('click',function() {
follower('another dude');
});
function truncateTo16(text) {
var len = text.length;
if (len > 16) {
var truncated = text.substring(0, 14);
truncated += '...';
return truncated;
} else {
return text;
}
}
})();<file_sep># fathom-notify
This is my [NodeCG](http://github.com/nodecg/nodecg) notification bundle based upon [bubu-followers](https://github.com/eaceaser/bubu-followers) and [Lange-notify](https://github.com/Lange/lange-notify). It is still very much a work in progress.
## Components
- Dashboard shows the last 5 followers
- Simple view notification
## Dependencies
Depends on [lfg-twitchapi](https://github.com/SupportClass/lfg-twitchapi).
## Installation
1. Install to `nodecg/bundles/fathom-notify`.
2. Configure [lfg-twitchapi](https://github.com/SupportClass/lfg-twitchapi)
<file_sep>$('.fathom-notify .panel-heading').append('<button class="btn btn-info btn-xs test" title="Test"><i class="fa fa-eye"></i></button>');
var latestFollower = nodecg.Replicant("latestFollower", { defaultValue: null, persistent: true});
var recentFollowers = nodecg.Replicant("recentFollowers", { defaultValue: null, persistent: true });
recentFollowers.on('change', function(oldValue, newValue) {
var followerTable = '';
newValue.map( function(follower) {
followerTable = '<tr><td>'+ follower.user.display_name +'</td><td>'+ moment(follower.created_at).fromNow() +'</td></tr>' + followerTable;
});
$('#follower-list').html(followerTable);
$('#follower-list tr:first').css('font-weight','bold');
});
$('.fathom-notify .test').click(function () {
var follower = {
"created_at": "2015-11-02T01:26:18Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/impelicanproof/follows/channels/fathom_"
},
"notifications": false,
"user": {
"_id": 54456217,
"name": "impelicanproof",
"created_at": "2014-01-05T05:15:13Z",
"updated_at": "2015-09-19T19:44:33Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/impelicanproof"
},
"display_name": "12345678901234567890",
"logo": "http://static-cdn.jtvnw.net/jtv_user_pictures/impelicanproof-profile_image-f733325129c0c2db-300x300.png",
"bio": "Perikan Desu :P A.k.a (ImPelicanProof)Overly Pro Gamer:-------------------------------------Tf2-Minecraft-Anything thats interestingYoutube: https://www.youtube.com/channel/UC5F8FQcgUVBJEJMvjjKgbrg",
"type": "user"
}
};
nodecg.sendMessage('follower', follower);
});
| d11fd57a32db98ae358bad231d92d455eae8cfc0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | denolfe/fathom-notify | 0e41f76b9dca6918a8495e3bb8f460a16b25030b | 2a7726226dac53eda3186a99a4af09bd8d0528a5 |
refs/heads/master | <file_sep>from flask_wtf import FlaskForm
from wtforms import SubmitField, BooleanField, StringField, PasswordField, FloatField
from wtforms.validators import DataRequired, ValidationError, EqualTo, Email
from flask_wtf.file import FileField, FileAllowed
from biudzetas import Vartotojas, current_user
class RegistracijosForma(FlaskForm):
vardas = StringField('Vardas', [DataRequired()])
el_pastas = StringField('El. paštas', [DataRequired()])
slaptazodis = PasswordField('<PASSWORD>', [DataRequired()])
patvirtintas_slaptazodis = PasswordField("Pakartokite s<PASSWORD>žodį",
[EqualTo('slaptazodis', "Slaptažodis turi sutapti.")])
submit = SubmitField('Prisiregistruoti')
def tikrinti_varda(self, vardas):
vartotojas = Vartotojas.query.filter_by(vardas=vardas.data).first()
if vartotojas:
raise ValidationError('Šis vardas panaudotas. Pasirinkite kitą.')
def tikrinti_pasta(self, el_pastas):
vartotojas = Vartotojas.query.filter_by(el_pastas=el_pastas.data).first()
if vartotojas:
raise ValidationError('Šis el. pašto adresas panaudotas. Pasirinkite kitą.')
class PrisijungimoForma(FlaskForm):
el_pastas = StringField('El. paštas', [DataRequired()])
slaptazodis = PasswordField('<PASSWORD>', [DataRequired()])
prisiminti = BooleanField("Prisiminti mane")
submit = SubmitField('Prisijungti')
class IrasasForm(FlaskForm):
pajamos = BooleanField('Pajamos')
suma = FloatField('Suma', [DataRequired()])
submit = SubmitField('Įvesti')
class PaskyrosAtnaujinimoForma(FlaskForm):
vardas = StringField('Vardas', [DataRequired()])
el_pastas = StringField('El. paštas', [DataRequired()])
nuotrauka = FileField('Atnaujinti profilio nuotrauką', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField('Atnaujinti')
def tikrinti_varda(self, vardas):
if vardas.data != current_user.vardas:
vartotojas = Vartotojas.query.filter_by(vardas=vardas.data).first()
if vartotojas:
raise ValidationError('Šis vardas panaudotas. Pasirinkite kitą.')
def tikrinti_pasta(self, el_pastas):
if el_pastas.data != current_user.el_pastas:
vartotojas = Vartotojas.query.filter_by(el_pastas=el_pastas.data).first()
if vartotojas:
raise ValidationError('Šis el. pašto adresas panaudotas. Pasirinkite kitą.')
class UzklausosAtnaujinimoForma(FlaskForm):
el_pastas = StringField('El. paštas', validators=[DataRequired(), Email()])
submit = SubmitField('Gauti')
def validate_email(self, el_pastas):
user = Vartotojas.query.filter_by(el_pastas=el_pastas.data).first()
if user is None:
raise ValidationError('Nėra paskyros, registruotos šiuo el. pašto adresu. Registruokitės.')
class SlaptazodzioAtnaujinimoForma(FlaskForm):
slaptazodis = PasswordField('<PASSWORD>is', validators=[DataRequired()])
patvirtintas_slaptazodis = PasswordField('Pakartokite slaptažodį',
validators=[DataRequired(), EqualTo('slaptazodis')])
submit = SubmitField('Atnaujinti Slaptažodį')
<file_sep>import os
from flask import render_template, redirect, url_for, flash, request
from flask_login import current_user, logout_user, login_user, login_required
from datetime import datetime
import secrets
from PIL import Image
from flask_mail import Message
from biudzetas import forms, db, app, bcrypt
from biudzetas.models import Vartotojas, Irasas
@app.route("/registruotis", methods=['GET', 'POST'])
def registruotis():
db.create_all()
if current_user.is_authenticated:
return redirect(url_for('index'))
form = forms.RegistracijosForma()
if form.validate_on_submit():
koduotas_slaptazodis = bcrypt.generate_password_hash(form.slaptazodis.data).decode('utf-8')
vartotojas = Vartotojas(vardas=form.vardas.data, el_pastas=form.el_pastas.data,
slaptazodis=koduotas_slaptazodis)
db.session.add(vartotojas)
db.session.commit()
flash('Sėkmingai prisiregistravote! Galite prisijungti', 'success')
return redirect(url_for('index'))
return render_template('registruotis.html', title='Register', form=form)
@app.route("/prisijungti", methods=['GET', 'POST'])
def prisijungti():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = forms.PrisijungimoForma()
if form.validate_on_submit():
user = Vartotojas.query.filter_by(el_pastas=form.el_pastas.data).first()
if user and bcrypt.check_password_hash(user.slaptazodis, form.slaptazodis.data):
login_user(user, remember=form.prisiminti.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('index'))
else:
flash('Prisijungti nepavyko. Patikrinkite el. paštą ir slaptažodį', 'danger')
return render_template('prisijungti.html', title='Prisijungti', form=form)
@app.route("/atsijungti")
def atsijungti():
logout_user()
return redirect(url_for('index'))
@app.route("/admin")
@login_required
def admin():
return redirect(url_for(admin))
@app.route("/irasai")
@login_required
def records():
db.create_all()
page = request.args.get('page', 1, type=int)
visi_irasai = Irasas.query.filter_by(vartotojas_id=current_user.id).order_by(Irasas.data.asc()).paginate(page=page,
per_page=5)
return render_template("irasai.html", visi_irasai=visi_irasai, datetime=datetime)
@app.route("/naujas_irasas", methods=["GET", "POST"])
def new_record():
db.create_all()
forma = forms.IrasasForm()
if forma.validate_on_submit():
naujas_irasas = Irasas(pajamos=forma.pajamos.data, suma=forma.suma.data, vartotojas_id=current_user.id)
db.session.add(naujas_irasas)
db.session.commit()
flash(f"Įrašas sukurtas", 'success')
return redirect(url_for('records'))
return render_template("prideti_irasa.html", form=forma)
@app.route("/delete/<int:id>")
def delete(id):
irasas = Irasas.query.get(id)
db.session.delete(irasas)
db.session.commit()
return redirect(url_for('records'))
@app.route("/update/<int:id>", methods=['GET', 'POST'])
def update(id):
forma = forms.IrasasForm()
irasas = Irasas.query.get(id)
if forma.validate_on_submit():
irasas.pajamos = forma.pajamos.data
irasas.suma = forma.suma.data
db.session.commit()
return redirect(url_for('records'))
return render_template("update.html", form=forma, irasas=irasas)
@app.route("/balansas")
def balance():
try:
visi_irasai = Irasas.query.filter_by(vartotojas_id=current_user.id)
except:
visi_irasai = []
balansas = 0
for irasas in visi_irasai:
if irasas.pajamos:
balansas += irasas.suma
else:
balansas -= irasas.suma
return render_template("balansas.html", balansas=balansas)
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(app.root_path, 'static/profilio_nuotraukos', picture_fn)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn
@app.route("/paskyra", methods=['GET', 'POST'])
@login_required
def paskyra():
form = forms.PaskyrosAtnaujinimoForma()
if form.validate_on_submit():
if form.nuotrauka.data:
nuotrauka = save_picture(form.nuotrauka.data)
current_user.nuotrauka = nuotrauka
current_user.vardas = form.vardas.data
current_user.el_pastas = form.el_pastas.data
db.session.commit()
flash('Tavo paskyra atnaujinta!', 'success')
return redirect(url_for('paskyra'))
elif request.method == 'GET':
form.vardas.data = current_user.vardas
form.el_pastas.data = current_user.el_pastas
nuotrauka = url_for('static', filename='profilio_nuotraukos/' + current_user.nuotrauka)
return render_template('paskyra.html', title='Account', form=form, nuotrauka=nuotrauka)
def send_reset_email(user):
token = user.get_reset_token()
msg = Message('Slaptažodžio atnaujinimo užklausa',
sender='<EMAIL>',
recipients=[user.el_pastas])
msg.body = f'''Norėdami atnaujinti slaptažodį, paspauskite nuorodą:
{url_for('reset_token', token=token, _external=True)}
Jei jūs nedarėte šios užklausos, nieko nedarykite ir slaptažodis nebus pakeistas.
'''
print(msg.body)
# mail.send(msg)
@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = forms.UzklausosAtnaujinimoForma()
if form.validate_on_submit():
user = Vartotojas.query.filter_by(el_pastas=form.el_pastas.data).first()
send_reset_email(user)
flash('Jums išsiųstas el. laiškas su slaptažodžio atnaujinimo instrukcijomis.', 'info')
return redirect(url_for('prisijungti'))
return render_template('reset_request.html', title='Reset Password', form=form)
@app.route("/reset_password/<token>", methods=['GET', 'POST'])
def reset_token(token):
if current_user.is_authenticated:
return redirect(url_for('home'))
user = Vartotojas.verify_reset_token(token)
if user is None:
flash('Užklausa netinkama arba pasibaigusio galiojimo', 'warning')
return redirect(url_for('reset_request'))
form = forms.SlaptazodzioAtnaujinimoForma()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.slaptazodis.data).decode('utf-8')
user.slaptazodis = hashed_password
db.session.commit()
flash('Tavo slaptažodis buvo atnaujintas! Gali prisijungti', 'success')
return redirect(url_for('prisijungti'))
return render_template('reset_token.html', title='Reset Password', form=form)
@app.errorhandler(404)
def klaida_404(klaida):
return render_template("404.html"), 404
@app.errorhandler(403)
def klaida_403(klaida):
return render_template("403.html"), 403
@app.errorhandler(500)
def klaida_500(klaida):
return render_template("500.html"), 500
@app.route("/")
def index():
return render_template("index.html")
<file_sep>MAIL_USERNAME = "<EMAIL>"
MAIL_PASSWORD = "<PASSWORD>"<file_sep>{% extends "base.html" %}
{% block content %}
{% if visi_irasai %}
{% for irasas in visi_irasai.items %}
<hr>
{% if irasas.pajamos %}
<p>Pajamos: {{irasas.suma}}</p>
<p>Data: {{ datetime.strftime(irasas.data, "%Y-%m-%d %H:%M:%S")}}</p>
{% else %}
<p>Išlaidos: {{irasas.suma}}</p>
<p>Data: {{irasas.data}}</p>
{% endif %}
<a href="{{ url_for('delete', id=irasas['id']) }}">Ištrinti</a>
<a href="{{ url_for('update', id=irasas['id']) }}">Redaguoti</a>
{% endfor %}
<hr>
{% for page_num in visi_irasai.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if visi_irasai.page == page_num %}
<a class="btn btn-info mb-4" href="{{ url_for('records', page=page_num) }}">{{ page_num }}</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{{ url_for('records', page=page_num) }}">{{ page_num }}</a>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}
{% endif %}
<p><a href="{{ url_for('new_record')}}">Naujas įrašas</a></p>
{% endblock %}<file_sep>import os
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_login import LoginManager, current_user
from flask_mail import Mail
from biudzetas.email_settings import *
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = '4654f5dfadsrfasdr54e6rae'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'biudzetas.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
db.create_all()
from biudzetas.models import Vartotojas, Irasas
from biudzetas.models import *
bcrypt = Bcrypt(app)
mail = Mail(app)
login_manager = LoginManager(app)
login_manager.login_view = 'prisijungti'
login_manager.login_message_category = 'info'
@login_manager.user_loader
def load_user(vartotojo_id):
db.create_all()
return Vartotojas.query.get(int(vartotojo_id))
class ManoModelView(ModelView):
def is_accessible(self):
return current_user.is_authenticated and current_user.el_pastas == "<EMAIL>"
from biudzetas import routes
admin = Admin(app)
admin.add_view(ManoModelView(Vartotojas, db.session))
admin.add_view(ManoModelView(Irasas, db.session))
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = MAIL_USERNAME
app.config['MAIL_PASSWORD'] = MAIL_PASSWORD
| f82993146cc26d65fad26a6d95667caac7b4fced | [
"Python",
"HTML"
] | 5 | Python | DonatasNoreika/biudzetas_20200402 | 19d3ac82c798b75b6904ef71898c3ad21e6e3b8f | 6e0234e2c1c3bda8c6f47a02842592e2bd485ef7 |
refs/heads/master | <repo_name>oscarmangs/TournamentManager<file_sep>/app/src/main/java/com/example/oscarmangs/tournamentmanager/MainActivity.java
package com.example.oscarmangs.tournamentmanager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn;
public static String userId = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (userId == null) {
SharedPreferences sharedPref = this.getSharedPreferences(
"KeyValue", Context.MODE_PRIVATE);
userId = sharedPref.getString("KeyValue", null);
if (userId == null) {
userId = UUID.randomUUID().toString();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KeyValue", userId);
editor.commit();
}
}
findComponents();
}
public void findComponents(){
btn = findViewById(R.id.main_button);
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CreateActivity.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/example/oscarmangs/tournamentmanager/MatchTableActivity.java
package com.example.oscarmangs.tournamentmanager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
public class MatchTableActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MatchInfo";
private ArrayList<Player> players;
private ArrayList<String> resultat;
private DatabaseReference playersRef;
private DatabaseReference matchRef;
private DatabaseReference mDatabase;
private Button btn;
private Boolean avsluta = false;
private ListView lista;
private ArrayAdapter<String> resultatAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_table);
resultat = new ArrayList<String>();
resultatAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultat);
lista = findViewById(R.id.lista);
btn = findViewById(R.id.return_button);
btn.setOnClickListener(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = mDatabase.child(MainActivity.userId);
playersRef = userRef.child("players");
matchRef = userRef.child("matches");
matchRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChildren()) {
Toast.makeText(MatchTableActivity.this,
"Vi har en vinnare!!!", Toast.LENGTH_LONG).show();
btn.setText("Avsluta turnering");
avsluta = true;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
playersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
players = getPlayers(dataSnapshot);
playerScoreTable(players);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
ArrayList<Player> getPlayers(DataSnapshot dataSnapshot) {
ArrayList<Player> players = new ArrayList<>();
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Player p = snap.getValue(Player.class);
p.setKey(snap.getKey());
players.add(p);
Log.d("Oscar", "Value is: " + p.getName());
}
return players;
}
public void playerScoreTable(ArrayList<Player> scoreList){
// final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//layout = findViewById(R.id.match_linearlayout);
for (Player x: scoreList) {
// final TextView textView = new TextView(this);
// textView.setLayoutParams(lparams);
//textView.setText("Deltagare: " + x.getName() + " ");
//String score = String.valueOf("Poäng: " + x.getScore());
resultat.add(x.getName() + " Poäng: " + x.getScore());
//textView.append(score);
//textView.setTextSize(20);
//textView.setTextColor(Color.parseColor("#000000"));
lista.setAdapter(resultatAdapter);
}
}
@Override
public void onClick(View view) {
if (!avsluta){
Intent intent = new Intent(getApplicationContext(), ScheduleActivity.class);
startActivity(intent);
}else{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
<file_sep>/app/src/main/java/com/example/oscarmangs/tournamentmanager/WhoWonActivity.java
package com.example.oscarmangs.tournamentmanager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.Serializable;
import java.util.ArrayList;
public class WhoWonActivity extends AppCompatActivity implements View.OnClickListener {
private Button player1btn;
private Button player2btn;
private Player player1;
private Player player2;
private Match currentMatch;
private int scoreP1;
private int scoreP2;
private static final int WON = 1;
private DatabaseReference playersRef;
private DatabaseReference matchRef;
private DatabaseReference mDatabase;
ArrayList<Player> players = new ArrayList<>();
private static final String TAG = "MatchInfo";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_who_won);
Intent intent = getIntent();
currentMatch = (Match) intent.getExtras().getSerializable("match");
player1btn = findViewById(R.id.who_won_btn_player1);
player2btn = findViewById(R.id.who_won_btn_player2);
player1btn.setOnClickListener(this);
player2btn.setOnClickListener(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = mDatabase.child(MainActivity.userId);
playersRef = userRef.child("players");
matchRef = userRef.child("matches");
playersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
players = getPlayersFromFirebase(dataSnapshot);
findPlayer(currentMatch);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
ArrayList<Player> getPlayersFromFirebase (DataSnapshot dataSnapshot){
ArrayList<Player> players = new ArrayList<>();
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Player p = snap.getValue(Player.class);
p.setKey(snap.getKey());
players.add(p);
Log.d(TAG, "Value is: " + p.getName());
}
return players;
}
public void findPlayer(Match currentMatch) {
if (!(currentMatch == null)) {
player1 = Player.findPlayerFromId(currentMatch.getId1(), players);
player1btn.setText(player1.getName());
player2 = Player.findPlayerFromId(currentMatch.getId2(), players);
player2btn.setText(player2.getName());
}
}
@Override
public void onClick (View v){
switch (v.getId()) {
case R.id.who_won_btn_player1:
scoreP1 = player1.getScore();
player1.setScore(scoreP1 + WON);
playersRef.child(player1.getKey()).setValue(player1);
Intent intent = new Intent(getApplicationContext(), MatchTableActivity.class);
intent.putExtra("player", (Serializable) player1);
startActivity(intent);
break;
case R.id.who_won_btn_player2:
scoreP2 = player2.getScore();
player2.setScore(scoreP2 + WON);
playersRef.child(player2.getKey()).setValue(player2);
Intent i = new Intent(getApplicationContext(), MatchTableActivity.class);
i.putExtra("player", (Serializable) player2);
startActivity(i);
break;
}
}
}
| 9914d22084ba9ede7d2c1ee0dcf40c00e4123960 | [
"Java"
] | 3 | Java | oscarmangs/TournamentManager | 08edb015aa2df024d3dfd12aa6485a3070a4384c | 14cf4984ddda3405b08256f4c80745159624436e |
refs/heads/master | <file_sep><!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" initial-scale="1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="<?php echo $css ?>" >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title><?= $title ?></title>
</head>
<body>
<?= $content ?>
</body>
<footer>
<div class="copyright">
Marshall Group © 2018
</div>
</footer>
</html>
<file_sep><?php
require_once 'config/model.php';
class User extends modele {
public function getAdminByUsername($username) {
$sql = 'SELECT * FROM admin WHERE a_username = :username';
$admin = $this->executeRequest($sql, array(
'username' => $username
));
return $admin;
}
public function getUserByUsername($username) {
$sql = 'SELECT * FROM user WHERE u_username = :username';
$user = $this->executeRequest($sql, array(
'username' => $username
));
return $user;
}
}
?>
<file_sep><?php
require_once 'models/message.php';
require_once 'config/view.php';
class ControllerMessage {
public function getMessages() {
$last_message_id = $_POST['last_message_id'];
$messageClass = new Message();
if ($last_message_id != null) {
$messages = $messageClass->getMessages($last_message_id)->fetchAll();
echo json_encode($messages);
} else {
var_dump($last_message_id);
}
}
public function sendMessage() {
$messageClass = new Message();
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$content = $_POST['content'];
$messageClass->saveMessage($sender, $receiver, $content);
}
public function deleteMessages() {
$messageClass = new Message();
$messageClass->deleteMessages();
}
}
?>
<file_sep><?php
require_once 'models/hologram.php';
require_once 'config/view.php';
class ControllerHologram {
public function getHolograms() {
$hologramClass = new Hologram();
$holograms = $hologramClass->getHolograms()->fetchAll();
echo json_encode($holograms);
}
public function deleteHolograms() {
$hologramClass = new Hologram();
$hologramClass->deleteHolograms();
}
public function updateHolograms() {
$holograms = json_decode($_POST['holograms']);
$hologramClass = new Hologram();
$hologramClass->deleteHolograms();
foreach ($holograms as $hologram) {
$hologramClass->saveHologram($hologram->tag, $hologram->name, $hologram->position->x, $hologram->position->y, $hologram->position->z, $hologram->rotation->x, $hologram->rotation->y, $hologram->rotation->z, $hologram->rotation->w, $hologram->scale->x, $hologram->scale->y, $hologram->scale->z);
}
}
public function sendRefreshHolograms() {
$flag = $_POST['flag'];
$hologramClass = new Hologram();
$hologramClass->setFlag($flag);
}
public function receiveRefreshHolograms() {
$hologramClass = new Hologram();
$flag = $hologramClass->getFlag()->fetch();
echo $flag[0];
}
}
?>
<file_sep><?php
require_once 'controllers/controller_user.php';
require_once 'controllers/controller_message.php';
require_once 'controllers/controller_hologram.php';
require_once 'controllers/controller_media.php';
class Router {
private $controller_user;
private $conctroller_message;
private $controller_hologram;
private $controller_media;
public function __construct(){
$this->controller_user = new ControllerUser();
$this->controller_message = new ControllerMessage();
$this->controller_hologram = new ControllerHologram();
$this->controller_media = new ControllerMedia();
}
public function route_request(){
$router = new Router();
switch($_GET['page']){
case 'login':
$this->controller_user->loginUser();
break;
case 'logout':
$this->controller_user->logoutUser();
break;
case 'receivemessages':
$this->controller_message->getMessages();
break;
case 'sendmessage':
$this->controller_message->sendMessage();
break;
case 'receiveholograms':
$this->controller_hologram->getHolograms();
break;
case 'deletemessages':
$this->controller_message->deleteMessages();
break;
case 'deleteholograms':
$this->controller_hologram->deleteHolograms();
case 'updateholograms':
$this->controller_hologram->updateHolograms();
break;
case 'sendrefresh':
$this->controller_hologram->sendRefreshHolograms();
break;
case 'receiverefresh':
$this->controller_hologram->receiveRefreshHolograms();
break;
case 'sendrefreshpictures':
$this->controller_media->sendRefreshPictures();
break;
case 'receiverefreshpictures':
$this->controller_media->receiveRefreshPictures();
break;
case 'uploadpicture':
$this->controller_media->uploadPicture();
break;
case 'deletepicture':
$this->controller_media->deletePicture();
break;
}
}
}
?>
<file_sep><?php
class View {
private $file;
private $titre;
public function __construct($action) {
$this->file = "views/view_".$action.".php";
$this->css = "css/css_".$action.".css";
}
public function generate($data=[]) {
$content = $this->generateFile($this->file, $data);
$view = $this->generateFile('config/layout.php', array('title' => $this->title, 'content' => $content, 'css' => $this->css));
echo $view;
}
private function generateFile($file, $data) {
if (file_exists($file)) {
extract($data);
ob_start();
require $file;
return ob_get_clean();
}
else {
throw new Exception("File '$file' not found");
}
}
}
<file_sep><?php
require_once 'config/model.php';
class Media extends modele {
public function getFlag() {
$sql = 'SELECT r_flag_pictures, r_picture FROM refresh';
$flag = $this->executeRequest($sql);
return $flag;
}
public function setFlag($boolean, $picture) {
$sql = 'UPDATE refresh SET r_flag_pictures = :bool, r_picture = :picture';
$this->executeRequest($sql, array(
'bool' => $boolean,
'picture' => $picture
));
}
}
?>
<file_sep><?php
require 'controllers/router.php';
$routeur = new Router();
$routeur->route_request();
?>
<file_sep><?php
require_once 'models/media.php';
require_once 'config/view.php';
class ControllerMedia {
public function sendRefreshPictures() {
$flag = $_POST['flag'];
$picture = $_POST['file'];
$hologramClass = new Media();
$hologramClass->setFlag($flag, $picture);
}
public function receiveRefreshPictures() {
$hologramClass = new Media();
$flag = $hologramClass->getFlag()->fetch();
echo json_encode($flag);
}
public function uploadPicture() {
$upload_directory = "pictures/";
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
$upload_file = $upload_directory.basename($_FILES['file']['name']);
echo "File ".$_FILES['file']['name']." uploaded successfully";
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
echo "File is valid and was moved successfully";
} else {
echo "Upload failed";
}
} else {
echo "Upload failed";
}
}
public function deletePicture() {
$picture = $_POST['file'];
unlink("pictures/".$picture);
}
}
?>
<file_sep><?php
require_once 'config/model.php';
class Message extends modele {
public function getMessages($id) {
$sql = 'SELECT * FROM message WHERE m_id >= :id';
$messages = $this->executeRequest($sql, array(
'id' => $id
));
return $messages;
}
public function saveMessage($sender, $receiver, $content) {
$sql = 'INSERT INTO message (m_sender, m_receiver, m_content) VALUES (:sender, :receiver, :content)';
$this->executeRequest($sql, array(
'sender' => $sender,
'receiver' => $receiver,
'content' => $content
));
}
public function deleteMessages() {
$sql = 'TRUNCATE TABLE message';
$this->executeRequest($sql);
}
}
?>
<file_sep><?php
require_once 'models/user.php';
require_once 'config/view.php';
class ControllerUser {
public function loginUser() {
if (isset($_POST['login']) && isset($_POST['password'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$userClass = new User();
$user = $userClass->getUserByUsername($username)->fetch();
if (password_verify($password, $user['u_password'])) {
echo "true";
} else {
echo "false";
}
} else {
echo "false";
}
}
// public function sendRequestCall() {
// $sender = $_POST['sender'];
// $userClass = new User();
//
// $userClass->setRequestCall($sender);
// }
//
// public function receiverequestcall() {
//
// }
}
?>
<file_sep><?php
require_once 'config/model.php';
class Hologram extends modele {
public function getHolograms() {
$sql = 'SELECT * FROM hologram';
$holograms = $this->executeRequest($sql);
return $holograms;
}
public function saveHologram($type, $name, $px, $py, $pz, $rx, $ry, $rz, $rw, $sx, $sy, $sz) {
$sql = 'INSERT INTO hologram (h_type, h_name, h_px, h_py, h_pz, h_rx, h_ry, h_rz, h_rw, h_sx, h_sy, h_sz) VALUES (:type, :name, :px, :py, :pz, :rx, :ry, :rz, :rw, :sx, :sy, :sz)';
$this->executeRequest($sql, array(
'type' => $type,
'name' => $name,
'px' => $px,
'py' => $py,
'pz' => $pz,
'rx' => $rx,
'ry' => $ry,
'rz' => $rz,
'rw' => $rw,
'sx' => $sx,
'sy' => $sy,
'sz' => $sz
));
}
public function deleteHolograms() {
$sql = 'TRUNCATE TABLE hologram';
$this->executeRequest($sql);
}
public function getFlag() {
$sql = 'SELECT r_flag_holograms FROM refresh';
$flag = $this->executeRequest($sql);
return $flag;
}
public function setFlag($boolean) {
$sql = 'UPDATE refresh SET r_flag_holograms = :bool';
$this->executeRequest($sql, array(
'bool' => $boolean
));
}
}
?>
| 0b6c3bee07b7b5681d0f7f96b732974ce7b0ac28 | [
"PHP"
] | 12 | PHP | romainfrayssinet/smaarrc-server | 59a70c5ed4093e0eb504361af5bd582db6610f11 | a1732e3bbdc7743a416e94f993d7813ff1801c87 |
refs/heads/master | <repo_name>XxCtrlZxX/python-collision-counting<file_sep>/elastic collision count.py
# https://ko.wikipedia.org/wiki/%ED%83%84%EC%84%B1_%EC%B6%A9%EB%8F%8C
import pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 750, 450
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("elastic collision")
clock = pygame.time.Clock()
#### class def ####
class Box:
def __init__(self, img, velocity, mass):
self.img = img
self.v = velocity
self.m = mass
self.x, self.y = 0, 0
self.width = self.height = img.get_rect().size[0]
def get_pos(self):
return round(self.x), round(self.y)
#### load image ####
box1_load = pygame.image.load("D:/sunrin/Python/elastic collision count/box1.png")
box2_load = pygame.image.load("D:/sunrin/Python/elastic collision count/box2.png")
box1_load = pygame.transform.scale(box1_load, (50, 50))
box2_load = pygame.transform.scale(box2_load, (170, 170))
#### global variable ####
digits = 2
timeSteps = 1
collision_count = 0
isRunning = True
#### font ####
font_ = pygame.font.Font("D:/sunrin/Python/elastic collision count/NanumMyeongjo-Regular.ttf", 32) # (font-name, font-size)
#### create box ####
box1 = Box(box1_load, 0, 1)
box2 = Box(box2_load, -3 / timeSteps, 100**(digits - 1))
#### set start pos ####
box1.x, box1.y = 150, SCREEN_HEIGHT - box1.height
box2.x, box2.y = 350, SCREEN_HEIGHT - box2.height
start = False
while isRunning:
deltaTime = clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
isRunning = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
if not start: continue
for _ in range(timeSteps):
# 벽과 충돌
if box1.x <= 0:
box1.v *= -1
collision_count += 1
# 박스끼리 충돌
if box1.x + box1.width > box2.x:
m1, m2 = box1.m, box2.m
v1, v2 = box1.v, box2.v
total_v1 = (v1 * (m1 - m2) + 2 * m2 * v2) / (m1 + m2)
total_v2 = (v2 * (m2 - m1) + 2 * m1 * v1) / (m1 + m2)
box1.v, box2.v = total_v1, total_v2
collision_count += 1
box1.x += box1.v
box2.x += box2.v
screen.fill((0, 0, 0))
screen.blit(box1.img, box1.get_pos())
screen.blit(box2.img, box2.get_pos())
count_txt = font_.render('# ' + str(collision_count), True, (217, 220, 236))
screen.blit(count_txt, (SCREEN_WIDTH - count_txt.get_width() - 30, 20))
pygame.display.update()
# print(box1_load.get_rect().size)
print("collisions :", collision_count)
pygame.quit() | 003cf6ddba134408ec23b2c3ec6afadcec4e60ce | [
"Python"
] | 1 | Python | XxCtrlZxX/python-collision-counting | ac9867a7000b8c374828bfed9bce6268bab6e6f7 | 4f6e0e10487d75d3421ccfe00d57dbda58012e2e |
refs/heads/master | <file_sep>const {Configuration} = require('./config');
const {TournamentTypes} = require('./constants.js')
const {createTournament} = require('./tournament-factory')
const {ConfigurationManager} = require('./config-manager')
//const configuration = Configuration.buildConfiguration();
//switch по типу турнира в конфигурации
//создаем нужный экзмепляр турнира
//турнир. плэй()
const configurationManager = new ConfigurationManager();
let config = {
tournamentType: TournamentTypes.SingleElimination,
tournamentState: {currentRound: 0, numberOfRounds: 4}
}
//configurationManager.save(config);
if (configurationManager.exists())
config = configurationManager.load();
const tournament = createTournament(config);
tournament.addListener('state-changed', (newState) => {
configurationManager.save(Object.assign({}, config, {tournamentState: Object.assign({}, config.tournamentState, newState)}));
})
tournament.play()<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace QueueImplementations
{
class Program
{
static void Main(string[] args)
{
Queue<int> q = new Queue<int>();
q.
}
}
}
<file_sep>class Tournament {
constructor (configuration) {
this.numberOfPlayers = configuration.numberOfPlayers;
this.numberOfRounds = configuration.numberOfRounds;
this.currentRound = configuration.currentRound;
this.currentGame = configuration.currentGame;
this.winnersBracket = configuration.winnersBracket;
this.grid = configuration.grid;
}
play() {
this.grid.show();
for (let round = this.currentRound; round < this.numberOfRounds; round++) {
this.playRound(round);
}
}
}
class SingleElimination extends Tournament {
constructor(configuration) {
super(configuration);
}
}
class DoubleElimination extends Tournament {
constructor (configuration) {
super(configuration);
this.losersBracket = configuration.losersBracket;
}
}<file_sep>const {TournamentTypes} = require('./constants');
const {SingleElimination, DoubleElimination} = require('./tournament/tournament');
const createTournament = (config) => {
switch (config.tournamentType) {
case TournamentTypes.SingleElimination:
return new SingleElimination(config);
case TournamentTypes.DoubleElimination:
return new DoubleElimination(config);
}
}
module.exports = {
createTournament
}
<file_sep>var EventEmitter = require('events');
class Tournament extends EventEmitter {
constructor(configuration) {
super();
this.numberOfPlayers = configuration.tournamentState.numberOfPlayers;
this.numberOfRounds = configuration.tournamentState.numberOfRounds;
this.currentRound = configuration.tournamentState.currentRound;
this.currentGame = configuration.tournamentState.currentGame;
this.winnersBracket = configuration.tournamentState.winnersBracket;
this.grid = configuration.grid;
}
play() {
//this.grid.show();
for (let round = this.currentRound; round < this.numberOfRounds; round++) {
this.onStateChanged({currentRound: round});
//this.playRound(round);
}
}
onStateChanged(newState) {
this.emit('state-changed', newState);
}
}
class SingleElimination extends Tournament {
constructor(configuration) {
super(configuration);
}
play() {
console.log("Play single elimination");
super.play();
}
}
class DoubleElimination extends Tournament {
constructor(configuration) {
super(configuration);
this.losersBracket = configuration.losersBracket;
}
play() {
console.log("Play double elimination");
super.play();
}
}
module.exports = {
SingleElimination,
DoubleElimination
}<file_sep>//наверное не понадобится, потому что я при определении типа грила сразу создаю переменную нужного класса
const GridTypes = {
Olympics: 1,
DoubleBracket: 2
}
const TournamentTypes = {
SingleElimination: 1,
DoubleElimination: 2
}
module.exports = {
TypeOfGrid: GridTypes,
TypeOfTournament: TournamentTypes
}<file_sep>//наверное не понадобится, потому что я при определении типа грила сразу создаю переменную нужного класса
const TypeOfGrid = {
Olympics: 1,
DoubleBracket: 2
}
const TypeOfTournament = {
SingleElimination:1,
DoubleElimination:2
}
module.exports = {TypeOfGrid, TypeOfTournament}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueImplementations
{
class Node<T>
{
public T Data { get; set; }
public Node<T> Next { get; set; }
public Node(T data)
{
Data = data;
}
}
class Queue<T>
{
private Node<T> _head;
private Node<T> _tail;
private int count;
public void Enqueue(T data)
{
Node<T> newNode = new Node<T>(data);
Node<T> tempNode = _tail;
_tail = newNode;
if (count==0)
_head = _tail;
else
tempNode.Next = newNode;
count++;
}
public T Dequeue ()
{
if (count == 0)
throw new Exception ("Queue is empty.");
T result = _head.Data;
_head = _head.Next;
count--;
return result;
}
public int Count ()
{
return count;
}
public T First()
{
if (count == 0)
throw new InvalidOperationException();
return _head.Data;
}
public T Last()
{
if (count == 0)
throw new InvalidOperationException();
return _tail.Data;
}
public bool Contains (T data)
{
Node<T> currentNode = _head;
while (currentNode!=null)
{
if (currentNode.Data.Equals(data))
return true;
currentNode = currentNode.Next;
}
return false;
}
}
public class ArrayQueue<T>
{
private T[] _array;
private int _augmentStep;
private int count;
public ArrayQueue ()
{
_array = new T[10];
_augmentStep = 10;
}
public ArrayQueue(int arrayLength)
{
_array = new T[arrayLength];
_augmentStep = 10;
}
public ArrayQueue(int arrayLength, int augmentStep)
{
_array = new T[arrayLength];
_augmentStep = augmentStep;
}
public void Enqueue(T data)
{
if (count == _array.Length)
ExpandArray();
_array[count] = data;
count++;
}
public T Dequeue()
{
if (count == 0)
throw new InvalidOperationException();
T output = _array[0];
for (int i = 0; i < _array.Length - 1; i++)
_array[i] = _array[i + 1];
return output;
}
public T First()
{
return _array[0];
}
public T Last()
{
return _array[count - 1];
}
public int Count()
{
return count;
}
public bool Contains (T data)
{
return _array.Contains(data);
}
private void ExpandArray()
{
T[] newArray = new T[_array.Length + _augmentStep];
for (int i =0; i<_array.Length; i++)
newArray[i] = _array[i];
_array = newArray;
}
}
}
| f15cf438ec3102917991a55131352d4a75e9f15c | [
"JavaScript",
"C#"
] | 8 | JavaScript | AnnaShar/SandBox | ee2828b807007d73ff66ff3ab345d7aa025942ee | 3992a90d3f65a8ec80ad12e9a64a2d3ecf9a087f |
refs/heads/master | <file_sep>-- Table: public.departments
-- DROP TABLE public.departments;
CREATE TABLE public.departments
(
dept_no character varying(4) COLLATE pg_catalog."default" NOT NULL,
dept_name character varying COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT departments_pkey PRIMARY KEY (dept_no)
)
TABLESPACE pg_default;
ALTER TABLE public.departments
OWNER to brandontownsend;
-- Table: public.dept_emp
-- DROP TABLE public.dept_emp;
CREATE TABLE public.dept_emp
(
emp_no integer NOT NULL,
dept_no character varying(4) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT dept_manager2_dept_no_fkey FOREIGN KEY (dept_no)
REFERENCES public.departments (dept_no) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION,
CONSTRAINT dept_manager2_emp_no_fkey FOREIGN KEY (emp_no)
REFERENCES public.employees (emp_no) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
-- Table: public.dept_manager
-- DROP TABLE public.dept_manager;
CREATE TABLE public.dept_manager
(
dept_no character varying(4) COLLATE pg_catalog."default" NOT NULL,
emp_no integer NOT NULL,
CONSTRAINT dept_manager_pkey PRIMARY KEY (dept_no, emp_no),
CONSTRAINT dept_manager_dept_no_fkey FOREIGN KEY (dept_no)
REFERENCES public.departments (dept_no) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION,
CONSTRAINT dept_manager_emp_no_fkey FOREIGN KEY (emp_no)
REFERENCES public.employees (emp_no) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
-- Table: public.employees
-- DROP TABLE public.employees;
CREATE TABLE public.employees
(
emp_no integer NOT NULL,
emp_title_id character varying(10) COLLATE pg_catalog."default",
birth_date character varying(10) COLLATE pg_catalog."default" NOT NULL,
first_name character varying COLLATE pg_catalog."default" NOT NULL,
last_name character varying COLLATE pg_catalog."default" NOT NULL,
sex character varying(1) COLLATE pg_catalog."default" NOT NULL,
hire_date character varying(10) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT employees_pkey PRIMARY KEY (emp_no),
CONSTRAINT title_fkey FOREIGN KEY (emp_title_id)
REFERENCES public.titles (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
-- Table: public.salaries
-- DROP TABLE public.salaries;
CREATE TABLE public.salaries
(
emp_no integer NOT NULL,
salary integer NOT NULL,
CONSTRAINT salaries_emp_no_fkey FOREIGN KEY (emp_no)
REFERENCES public.employees (emp_no) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
-- Table: public.titles
-- DROP TABLE public.titles;
CREATE TABLE public.titles
(
id character varying COLLATE pg_catalog."default" NOT NULL,
title character varying COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT titles_pkey PRIMARY KEY (id)
)
| 2264ac573064c5f4cbcf3b2af61975ee4738cdef | [
"SQL"
] | 1 | SQL | BrandonTownsend/sql_challenge | 074a995a4d8931dc9942fab6162bfbb720e03ede | 22cc3c8cbf08f310d7ef7f62f59e94f5bef1d413 |
refs/heads/master | <file_sep>#1
CREATE TABLE STORE (
`order_no` INTEGER PRIMARY KEY AUTO_INCREMENT,
`code` VARCHAR(20) NOT NULL,
`item` VARCHAR(30) NOT NULL,
`quantity` VARCHAR(30) NOT NULL,
`price` DECIMAL(10,2) NOT NULL,
`discount` VARCHAR(30) DEFAULT 0,
`mrp` DECIMAL(10,2) NOT NULL
);
#2
INSERT INTO STORE (`code`, `item`, `quantity`, `price`, `discount`, `mrp`)
VALUES ('1031', "MAGGI", "1pkt", 23, 0, 23),('1001', "RICE", "1Kg", 51, 1, 50),('1007', "SALT", "1Kg", 10, 0, 10),('1014', "COCONUT OIL", "1ltr", 260, 5, 255),
('1019', "DIARY MILK", "1pkt", 60, 0, 60);
#3
SELECT * FROM STORE;
#4
SELECT MOD(price,9) FROM STORE;
#5
SELECT POWER(price,2) FROM STORE;
#6
SELECT ROUND(mrp DIV 7) FROM STORE;
<file_sep>#1
CREATE TABLE CLASS(`id` INT PRIMARY KEY NOT NULL,`name` VARCHAR(30) NOT NULL);
#2
INSERT INTO CLASS(`id`, `name`)VALUES (1, 'RICHARD');
SELECT*FROM CLASS;
#3
START TRANSACTION;
UPDATE CLASS SET name='SANTHOSH' WHERE id= 1;
SAVEPOINT A;
ROLLBACK TO A;
SELECT*FROM CLASS;
INSERT INTO CLASS VALUES (2, 'SUNIL');
SAVEPOINT B;
ROLLBACK TO B;
SELECT*FROM CLASS;
INSERT INTO CLASS VALUES (3, 'HARRIS');
SAVEPOINT C;
ROLLBACK TO C;
SELECT*FROM CLASS;
INSERT INTO CLASS VALUES (4, 'SMITH');
SAVEPOINT D;
ROLLBACK TO D;
SELECT*FROM CLASS;
INSERT INTO CLASS VALUES (5, 'AARON');
SAVEPOINT E;
SELECT*FROM CLASS;
ROLLBACK TO E;
COMMIT;<file_sep>#1
CREATE TABLE DEPARTMENT(`code` INT PRIMARY KEY NOT NULL,`dept_name` VARCHAR(30) UNIQUE NOT NULL,`title` VARCHAR(30),`dept_id` INT UNIQUE NOT NULL, `salary` INT,CHECK (`salary` > 2000 ));
INSERT INTO DEPARTMENT(`code`, `dept_name`, `title`, `dept_id`,`salary`)VALUES (1, "system software", "course1", 100, 20000),(2, "graph theory", "course2", 101, 25000);
#2
CREATE TABLE INSTRUCTOR(`name` VARCHAR(50) NOT NULL,`code` INT NOT NULL,`id` INT PRIMARY KEY DEFAULT 1);
INSERT INTO INSTRUCTOR(`name`, `code`)VALUES ("MSD", 7);
SELECT * FROM DEPARTMENT;
SELECT * FROM INSTRUCTOR;<file_sep>#1
CREATE TABLE EMPLOYEE(`empid` CHAR(4) NOT NULL, `name` CHAR(10) NOT NULL);
CREATE TABLE EMPLOYEE_DETAILS(`empid` CHAR(4) NOT NULL, `name` CHAR(10) NOT NULL, `designation` CHAR(30) NOT NULL, `dob` DATE NOT NULL);
INSERT INTO EMPLOYEE (`empid`, `name`)VALUES ('e1' ,'boult'),('e2','mitchell' ),('e3' ,'stark'),('e4', 'butler'),('e5','shane');
INSERT INTO EMPLOYEE_DETAILS (`empid`, `name`, `designation`, `dob`)VALUES ('e1' ,'boult' ,'HOD' ,'1990-09-08'),('e2','mitchell' ,'Manager','1991-06-04'),('e5' ,'shane' , 'Asst.Manager' ,'1991-10-18');
#2
SELECT * FROM EMPLOYEE WHERE empid IN (SELECT empid FROM EMPLOYEE_DETAILS);
#3
SELECT * FROM EMPLOYEE WHERE empid NOT IN (SELECT empid FROM EMPLOYEE_DETAILS);
<file_sep>#1
CREATE TABLE STORE (
`order_no` INTEGER PRIMARY KEY AUTO_INCREMENT,
`code` VARCHAR(20) NOT NULL,
`item` VARCHAR(30) NOT NULL,
`quantity` VARCHAR(30) NOT NULL,
`price` DECIMAL(10,2) NOT NULL,
`discount` DECIMAL(2,2) DEFAULT 0,
`mrp` DECIMAL(10,2) NOT NULL
);
#2
INSERT INTO STORE (`code`, `item`, `quantity`, `price`, `discount`, `mrp`)
VALUES ('1031', "MAGGI", "1pkt", 23, 0, 23),('1001', "RICE", "1Kg", 51, 1, 50),('1007', "SALT", "1Kg", 10, 0, 10),('1014', "COCONUT OIL", "1ltr", 260, 5, 255),
('1019', "DIARY MILK", "1pkt", 60, 0, 60);
#3
SELECT * FROM STORE;
#4
CREATE VIEW CART AS
SELECT `item`, `quantity` FROM STORE;
#5
INSERT INTO STORE (`code`, `item`, `quantity`, `price`, `discount`, `mrp`)
VALUES ('1024', "MILK", "1ltr", 48, 0, 48);
SELECT * FROM CART;
#6
DROP VIEW CART;
| 4dbce1e8d723e3d565f4664d6285cefee8697672 | [
"SQL"
] | 5 | SQL | ceccs18c22/cs232 | 7b717bd9ee2eb41d15d080f1444763a594e4ade8 | 07a8deff8f46a9b0a2d41a88351a7a21f68cdbc0 |
refs/heads/master | <file_sep>import './requirejs-config';
requirejs(['jquery', 'vendor'], ($) => {
$('.header__button--show').click(() => {
$('.popup, .overlay').show('slow');
});
$('.overlay, .popup__close, .popup__button--cancel').click(() => {
$('.popup, .overlay').hide('slow');
});
$('.popup__button--uninstall').click(() => {
$('.overlay').hide();
$('.popup').hide('slow', () => {
alert('DONE');
});
});
}); | 2963f487806e94a3258a16a27ce7a3e0ffda2940 | [
"JavaScript"
] | 1 | JavaScript | MrNightingale/ztest | 093f1d13c31df9962535ea682b7137934bc67436 | 8b5d05c14701ae855e3717832ece44e60c452b19 |
refs/heads/main | <repo_name>er-ayushmittal/assignment9-todoLIst<file_sep>/build/precache-manifest.6273110a095f507c7a0af92cf5cabcf4.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "85feed8a087636f320646ca66ea6f694",
"url": "/index.html"
},
{
"revision": "d7ce369402cd78e8aac3",
"url": "/static/css/main.273b621a.chunk.css"
},
{
"revision": "8918d0af2062251e56c3",
"url": "/static/js/2.fb5ada59.chunk.js"
},
{
"revision": "e88a3e95b5364d46e95b35ae8c0dc27d",
"url": "/static/js/2.fb5ada59.chunk.js.LICENSE.txt"
},
{
"revision": "d7ce369402cd78e8aac3",
"url": "/static/js/main.17c6016f.chunk.js"
},
{
"revision": "eb323c622e106faecb0e",
"url": "/static/js/runtime-main.341c860d.js"
},
{
"revision": "4f646371b2a2501c7acd9110625993ca",
"url": "/static/media/background.4f646371.jpg"
}
]); | e2e9584558dc08879bc555b4b02b11620249d46e | [
"JavaScript"
] | 1 | JavaScript | er-ayushmittal/assignment9-todoLIst | 9e112d134f3e703e8861ee1617a05278833f2add | 55c303d459f31ebacd3b513ea89fbd90f9249f13 |
refs/heads/master | <file_sep>#include "linkedList.h"
void helloFromLinkedList(){
printf("Hello from linked list\n");
}
<file_sep>#!/bin/bash
clear
target=$1
cmake -S . -B build
cmake --build build --config Debug --target $target
./build/$target
<file_sep># Simple C project structure example using CMake
Note that this project does not require the user to smash commands in terminal.
If the user have a IDE that supports CMake the executable will be found and added.
Required packages are CMake(version > 3.1)
Installation:
Ubuntu
> sudo apt install cmake
Arch Linux
> sudo pacman -S cmake
Other: [Select a distro that floats your boat](https://cmake.org/download/)
### How to: Define project name
1. Locate CMakeLists.txt in root directory
```bash
CMakeLists.txt <----------------- Change here
include/
inc/
build/
run.sh
README.md
source/
```
2. Change "exampleProjectName" to a suitable name
Example:
> project(**exampleProjectName** LANGUAGES C)
exampleProjectName -> realProjectName
> project(**realProjectName** LANGUAGES C)
### How to: Build, compile & run
> sh run main
#### Note that the run.sh file might not be executable
- If not executable then
> chmod +x run
*Edit shell script for custom target to be launched*
The file binary file "main" comes from source/CMakeLists.txt
> "add_executable(**main** main.c)"
#### Note: Math has been linked to target "main" by default
> target_link_libraries(sharedLibrary INTERFACE ${MATH})
<file_sep>#include "main.h"
#include "linkedList/linkedList.c"
#include "wrapper/wrapper.c"
int main(){
printf("Math Working: sqrt(5)=%f\n", sqrt(5));
printf("Hello from main\n");
helloFromWrapper();
helloFromLinkedList();
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.00)
project(exampleProjectName LANGUAGES C)
# Find math and pthread library
find_library(MATH m REQUIRED)
# Create HEADER-ONLY library
add_library(HEADER-ONLY INTERFACE)
# Add project lib
add_library(PROJECTLIB INTERFACE)
# Add directory "include/" to target library
target_include_directories(HEADER-ONLY INTERFACE ${CMAKE_SOURCE_DIR}/include)
# Add directory "lib/" to target library
target_include_directories(PROJECTLIB INTERFACE ${CMAKE_SOURCE_DIR}/lib)
# Target link math to HEADER-ONLY
target_link_libraries(HEADER-ONLY INTERFACE ${MATH})
# Target link HEADER-ONLY to PROJECTLIB
target_link_libraries(HEADER-ONLY INTERFACE PROJECTLIB)
# Create a binary executable
add_executable(main main.c)
# Link shared library to main
target_link_libraries(main PRIVATE HEADER-ONLY)
<file_sep>#ifndef WRAPPER_H_INCLUDED_CHECK
#define WRAPPER_H_INCLUDED_CHECK
/* Keep stuff inside IF */
#include <stdio.h>
void helloFromWrapper();
#endif /* WRAPPER_H */
<file_sep>#ifndef MAIN_H_INCLUDED_CHECK
#define MAIN_H_INCLUDED_CHECK
/* Keep stuff inside IF */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#endif
<file_sep>#include "wrapper.h"
void helloFromWrapper(){
printf("Hello from wrapper\n");
}
<file_sep>#ifndef LINKEDLIST_H_INCLUDED_CHECK
#define LINKEDLIST_H_INCLUDED_CHECK
/* Keep stuff inside IF */
#include <stdio.h>
void helloFromLinkedList();
#endif
| 0a6594d329da003aa305a13233189a8b8a1d4dc2 | [
"Markdown",
"C",
"CMake",
"Shell"
] | 9 | C | Swepz/Simple_CMake_Project | 30149c30f7f9498c543e11047d4ce95614ae4242 | 0b6bd89855651c5a4dd419f1028f08ef345558e3 |
refs/heads/master | <repo_name>anuragalakkat/react-PRACTICE<file_sep>/src/CreateBook.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const CreateBook = () => {
const [name, setBookName] = useState('');
const postData = () => {
axios.post('http://localhost:5000/api/books/', {
name,
});
};
return (
<div>
<h1>Add new book names</h1>
<form action="POST">
<input
type="text"
onChange={(e) => setBookName(e.target.value)}
></input>
<button onClick={postData} type="submit">
submit
</button>
</form>
</div>
);
};
export default CreateBook;
<file_sep>/README.md
# react-sfaszo
[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/react-sfaszo) | 25306046f1d3722d91b5167b1a1c1566964404f7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | anuragalakkat/react-PRACTICE | 9e4e4fc4e74e2468631d09c76a29c962612bef17 | fb7ce85642be255dc0b55958cf041a14b229e147 |
refs/heads/master | <file_sep>function EmployeeDetail(props) {
return (
<table className ="table ">
<thead>
<tr>
<th className="col-sm-2">Image</th>
<th className="col-sm-2">Name</th>
<th className="col-sm-2">Phone</th>
<th className="col-sm-2">Email</th>
<th className="col-sm-3">DOB</th>
</tr>
</thead>
<tbody>
<tr>
<th><img alt ="thumbnail" className="img" src={props.image} style={{ margin: "auto"}} /></th>
<td>{props.name}</td>
<td>{props.phone}</td>
<td>{props.email}</td>
<td>{props.dob}</td>
</tr>
</tbody>
</table>
)
}
export default EmployeeDetail;
| a268313494f7bd55c9838b17d00ad0ac3942f465 | [
"JavaScript"
] | 1 | JavaScript | Andrew0502/worker-directory | 45a6cf25966e770dc39ea9f19fdf10e2bed1a9e5 | d8b8ffa33dc97614b711c6397c4447a67575b64e |
refs/heads/master | <file_sep># Machine-Learning-Project
TWIN: Personality-based Intelligent Recommender System
<NAME>, <NAME>, <NAME> {Shetty.poo, Reddy.pra, <EMAIL> INFO7390 ADS Fall 2017, Northeastern University
1. Abstract
To create the recommendation system the trip advisor data set, personality score data set, and reviews given by those users to different hotels data set, was taken into consideration. The data has been clustered based on the personality. After the clustering, the kmean cluster value was added as a column to the reviews dataset. Based on the username and Location input, the model looks at the users with similar personalities and outputs all the hotels which have rating 5.
To validate the given recommendation, the input of the username, and personality test inputs were given to to get the cluster. Then the prediction model is passed the kmean value and the hotel name, and using this the rating of the hotel is predicted. If the hotel is present in the training set then we have the predicted rating similar to the rating in the test dataset. The code was later deployed to google cloud using the flask application
<file_sep>Flask==0.11.1
gunicorn==19.6.0
beautifulsoup4==4.6.0
DateTime==4.2
numpy==1.13.3
pandas==0.20.3
scikit-learn==0.19.1
scipy==0.19.1
virtualenv==15.1.0
requests>=2.9,<3
lxml>=2.2.0
<file_sep>from flask import Flask, render_template, request
import requests
import urllib
import urllib.request
import json
import requests
import os
import zipfile
from urllib.request import urlopen
from bs4 import BeautifulSoup
from zipfile import ZipFile
from io import BytesIO
import shutil
import pandas as pd
import urllib.request
from lxml import html
import gzip
import io
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import csv
import datetime
app = Flask(__name__)
@app.route('/result', methods=['POST'])
def result():
hotels = request.form['hotel']
usernames = request.form['username']
opens = request.form['open']
cons = request.form['cons']
extras = request.form['extra']
neuros = request.form['neuro']
agrees = request.form['agree']
data = {
"Inputs": {
"input1":
[
{
'username': usernames,
'open': opens,
'cons': cons,
'extra': extras,
'agree': agrees,
'neuro': neuros,
}
],
},
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/c2f8dc5126ac4024b08690eda8426a56/services/e61d656160c3434c85e2c75ffed09010/execute?api-version=2.0&format=swagger'
api_key = '<KEY> # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
except urllib.error.HTTPError as error:
result = "error"
result = json.loads(result.decode("utf-8"))
s = result['Results']['output1'][0]['Assignments']
kmean = int(s)
data = {
"Inputs": {
"input1":
[
{
'taObject': hotels,
'kmean': kmean,
}
],
},
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/c2f8dc5126ac4024b08690eda8426a56/services/0efed30347d448769f4235796c8fd62e/execute?api-version=2.0&format=swagger'
api_key = '<KEY> # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
except urllib.error.HTTPError as error:
result = "error"
result = json.loads(result.decode("utf-8"))
s = result['Results']['output1'][0]['Scored Labels']
s = float(s)
if s > 0 and s <6:
return render_template('home.html',delaytime = s)
else:
return render_template('home.html',delaytime = "no data available")
#json_object = response.json
#r = json_object['output1']['ArrDelayMinutes']
@app.route('/')
def index():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True) | 10c163aa5be4982e5d023e320c88f426d9bb55a5 | [
"Markdown",
"Python",
"Text"
] | 3 | Markdown | Reddyprashant/Machine-Learning-Project | c34210143597a74f0c77937307aab6dcb5e19b9e | 43b37eb86a7dfe989302027e47fdbeff5117c028 |
refs/heads/master | <file_sep>package org.richard.coffeeshop.beans;
/**
* Created by 2019-02-16.
*/
public class Event {
private final String id;
public Event(String id) {
this.id = id;
}
public String getId() {
return id;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
'}';
}
}
<file_sep>buildscript {
ext {
springBootVersion = '2.1.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
ext.moduleName = 'org.richard.coffeeshop.cqrs-core'
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter:${springBootVersion}")
implementation("com.google.guava:guava:27.0.1-jre")
implementation("org.apache.commons:commons-lang3:3.8.1")
}
<file_sep>package org.richard.coffeeshop.core.event;
/**
* Created by 2019-02-16.
*/
public interface EventListener {
boolean supportsReplay();
}
<file_sep>package org.richard.coffeeshop.core.event;
import java.util.List;
/**
* Created by 2019-02-16.
*/
public interface EventBus {
void publish(List<Event> events);
void republish(List<Event> events);
<T extends EventListener> T register(T listener);
}
<file_sep>package org.richard.coffeeshop.core.command;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.springframework.context.annotation.Bean;
/**
* Created by 2019-02-16.
*/
public interface CommandBus {
// @Bean
// public EventBus bus() {
// return new EventBus();
// }
void dispatch(Command command);
<T extends CommandHandler> T register(T handler);
}
<file_sep># scalable-coffee-shop
scalable coffee shop using cqrs
<file_sep>package org.richard.coffeeshop.beans;
import com.google.common.eventbus.EventBus;
import org.richard.coffeeshop.core.AggregateRootPostBeanProcessor;
import org.richard.coffeeshop.core.BusConfiguration;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import java.util.UUID;
/**
* Created by 2019-02-15.
*/
@SpringBootApplication
//@ComponentScan(basePackages = {
// "org.richard.coffeeshop.core"
//})
@Import({
AggregateRootPostBeanProcessor.class,
BusConfiguration.class
})
public class BeansApplication {
public static void main(String[] args) {
SpringApplication.run(BeansApplication.class, args);
}
//
// @Bean
// public EventBus eventBus() {
// return new EventBus();
// }
@Bean
public CommandLineRunner commandLineRunner(EventBus commandBus) {
return args -> {
System.out.println("Posting New Command to eventBus");
commandBus.post(new Command(UUID.randomUUID().toString()));
// eventBus.post(new Event(UUID.randomUUID().toString()));
};
}
}
<file_sep>[Guava Event Bus with Spring (2012)](http://pmeade.blogspot.com/2012/06/using-guava-eventbus-with-spring.html)
[Guava Event Bus with Spring (2012)](http://pmeade.blogspot.com/2013/02/using-guava-eventbus-with-spring-part-2.html)<file_sep>package org.richard.coffeeshop.beans;
import com.google.common.eventbus.DeadEvent;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* Created by 2019-02-16.
*/
//@Component
public class DeadEndEventProcessor {
private static final Logger logger = LoggerFactory.getLogger(DeadEndEventProcessor.class);
@Autowired
private EventBus eventBus;
@PostConstruct
public void init() {
eventBus.register(this);
}
@Subscribe
public void processDeadEvent(DeadEvent deadEvent) {
logger.error("DEADEVENT DETECTED: {}", deadEvent);
}
}
| 83bc6264497357e0d6f06664f44808b10085c829 | [
"Markdown",
"Java",
"Gradle"
] | 9 | Java | rnkoaa/deprecated-scalable-coffee-shop | 9e914dcc3d572488488d9b22a1554f4241dada7a | 9e8e6d7de71b24b1d6b0453d8692a45e1da1277c |
refs/heads/master | <file_sep>## Inspired by Spotify Design
Built with the help [card-stack](https://www.react-spring.io/docs/hooks/use-springs) example of react-spring
```
// IDK why I saved these but I dont want to delete it now
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
mouse: {
[theme.breakpoints.down('sm')]: {},
[theme.breakpoints.up('sm')]: {},
[theme.breakpoints.up('md')]: {},
[theme.breakpoints.up('lg')]: {},
[theme.breakpoints.up('xl')]: {},
},
}));
const classes = useStyles()
{
[theme.breakpoints.down('sm')]: {},
[theme.breakpoints.up('sm')]: {},
[theme.breakpoints.up('md')]: {},
[theme.breakpoints.up('lg')]: {},
[theme.breakpoints.up('xl')]: {},
}
```
<file_sep>import React from 'react';
import Navbar from '../components/Navbar';
// import BurgerII from '../components/Sidebar/Sidebar';
import Deck from '../components/Deck';
import Scroll from '../components/Scroll';
import { makeStyles, withStyles, createStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import SkipNextIcon from '@material-ui/icons/SkipNext';
import SkipPreviousIcon from '@material-ui/icons/SkipPrevious';
import Tooltip from '@material-ui/core/Tooltip';
import Zoom from '@material-ui/core/Zoom';
const useStyles = makeStyles((theme) =>
createStyles({
landingRoot: {
position: 'relative',
height: '100vh',
width: '100vw',
overflowX: 'hidden',
},
item: {
width: '',
},
paper: {
padding: theme.spacing(3),
textAlign: 'center',
color: theme.palette.text.secondary,
background: 'transparent',
},
deckBox: {
position: 'relative',
zIndex: '2',
[theme.breakpoints.down('sm')]: { height: '35vh' },
[theme.breakpoints.up('sm')]: { height: '50vh' },
[theme.breakpoints.up('md')]: { height: '70vh' },
[theme.breakpoints.up('lg')]: { height: '70vh' },
[theme.breakpoints.up('xl')]: { height: '70vh' },
},
iconGridContainer: {
[theme.breakpoints.down('md')]: {
flexDirection: 'row',
justify: 'flex-start',
},
[theme.breakpoints.up('md')]: {
flexDirection: 'column',
justify: 'center',
alignItems: 'center',
},
},
footer: {
margin: '0px',
position: 'absolute',
bottom: '0px',
width: '100vw',
'& a': {
color: 'rgb(255, 255, 255, 0.6)',
},
'& span': {
color: 'red',
},
padding: '1rem',
fontSize: '16px',
textAlign: 'center',
backgroundColor: '#3a3939',
color: 'rgb(255, 255, 255, 0.6)',
},
})
);
const LightTooltip = withStyles((theme) => ({
tooltip: {
backgroundColor: theme.palette.common.white,
color: 'rgba(0, 0, 0, 1)',
boxShadow: theme.shadows[2],
fontSize: '14px',
borderRadius: '25px',
},
}))(Tooltip);
const Landing = () => {
const classes = useStyles();
return (
<>
<div className={classes.landingRoot}>
<Scroll />
<Navbar />
<br />
<Box p={2}>
<Grid
container
direction="row-reverse"
spacing={3}
alignItems="center"
justify="center"
>
<Grid item xs={12} md={7}>
<Box className={classes.deckBox}>
{/* <Paper elevation={4} className={classes.deck}>
yo
</Paper> */}
<Deck />
</Box>
</Grid>
<Grid item xs={12} md={4}>
<Paper className={classes.paper}>
<Typography variant="h3">PLACEHOLDER TEXT</Typography>
</Paper>
</Grid>
<Grid
container
item
className={classes.iconGridContainer}
xs={12}
md={1}
alignItems="center"
spacing={2}
>
<Grid item>
<LightTooltip
TransitionComponent={Zoom}
title="Next Post"
placement="right"
>
<IconButton aria-label="next">
<SkipNextIcon style={{ color: 'black' }} />
</IconButton>
</LightTooltip>
</Grid>
<Grid item>
<LightTooltip
TransitionComponent={Zoom}
title="Previous Post"
placement="right"
>
<IconButton aria-label="delete">
<SkipPreviousIcon style={{ color: 'black' }} />
</IconButton>
</LightTooltip>
</Grid>
</Grid>
</Grid>
</Box>
<p className={classes.footer}>
Made with <span> ♥ </span> by <NAME>{' '}•{' '}
<a
href="https://github.com/Rishabh-malhotraa/spotify-design-landing-page"
target="__blank"
>
Github
</a>
</p>
</div>
</>
);
};
export default Landing;
<file_sep>import styled from 'styled-components';
export const StyledMenu = styled.nav`
display: flex;
flex-direction: column;
justify-content: center;
background: black;
transform: ${({ open }) => (open ? 'translateX(0) ' : 'translateX(-100%)')};
height: 100vh;
width: 100vw;
text-align: left;
padding: 2rem;
position: absolute;
top: 0;
left: 0;
transition: transform 0.3s cubic-bezier(0.86, 0.04, 0.45, 0.96);
z-index: 3;
a {
font-size: 2rem;
text-transform: uppercase;
padding: 2rem 0;
font-weight: bold;
letter-spacing: 0.5rem;
color: white;
text-decoration: none;
transition: color 0.3s linear;
}
`;
<file_sep>import React from 'react';
import './Sidebar.css';
import { bubble as Menu } from 'react-burger-menu';
import CssBaseline from '@material-ui/core/CssBaseline';
import HomeIcon from '@material-ui/icons/Home';
import EventIcon from '@material-ui/icons/Event';
import CodeIcon from '@material-ui/icons/Code';
import GroupIcon from '@material-ui/icons/Group';
import BookIcon from '@material-ui/icons/Book';
// import SvgMenuIcon from '@material-ui/icons/SvgMenuIcon';
import ExampleComponent from 'react-rounded-image';
import MyPhoto from './dp-2.jpg';
const Navbar = () => {
return (
<div>
<CssBaseline />
<Menu
right
pageWrapId={'page-wrap'}
width={'280px'}
customBurgerIcon={
<img alt="menu-icon" src={require('../../assets/menu.svg')} />
}
>
<main id="page-wrap"></main>
<div className="img">
<ExampleComponent
image={MyPhoto}
roundedColor=""
imageWidth="180"
imageHeight="180"
roundedSize="1"
/>
</div>
<div className="name"><NAME></div>
<nav class="bm-item-list">
<a id="home" className="bm-item" href="/">
<HomeIcon fontSize={'inherit'} />
<span className="wrap">Home</span>
</a>
<a id="event" className="bm-item" href="/">
<EventIcon fontSize={'inherit'} />
<span className="wrap">Event</span>
</a>
<a id="resources" className="bm-item" href="/">
<BookIcon fontSize={'inherit'} />
<span className="wrap">Resources</span>
</a>
<a id="Project" className="bm-item" href="/">
<CodeIcon fontSize={'inherit'} />
<span className="wrap">Projects</span>
</a>
<a id="team" className="bm-item" href="/">
<GroupIcon fontSize={'inherit'} />
<span className="wrap">Team</span>
</a>
</nav>
</Menu>
</div>
);
};
export default Navbar;
<file_sep>import React from 'react';
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';
import Landing from './pages/Landing.jsx';
const App = () => {
return (
<>
<BrowserRouter>
<Switch>
<Route path="/home" exact component={Landing}></Route>
<Redirect to="/home" />
</Switch>
</BrowserRouter>
</>
);
};
export default App;
| f6bb9df96871594046aae8219cdc9420c754e9d7 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | Rishabh-malhotraa/miniature-octo-spork | 5f916c565350a48cc44e0227d9e84e579d68334a | 21142b527ec7b891711f46d8feb9d3c2b33b79dd |
refs/heads/master | <file_sep>import React, {Component} from 'react';
class Questionair extends Component {
styles = {
margins: {
marginBottom: "3vh"
}
}
render() {
return (
<div style={this.styles.margins}>
<label>I Have Question!</label>
</div>
)
}
}
export default Questionair;<file_sep>import React, {Component} from 'react';
class Title extends Component {
styles = {
margins: {
marginBottom: "3vh"
},
titleFontSize: {
fontSize: "5vw"
}
}
render() {
return (
<div style={this.styles.margins}>
<label style={Object.assign({}, this.styles.titleFontSize)}>For Kris</label>
</div>
);
}
}
export default Title;<file_sep>import React, {Component} from 'react';
import Title from './Title';
import Questionair from './Questionair';
import YesButton from './YesButton';
class Background extends Component {
styles = {
paddings: {
padding: "10px"
},
backgroundBox: {
width: "100%",
height: "100vh",
background: "pink",
textAlign: "center"
},
baeminFontFamily: {
fontFamily: "BMDOHYEON"
}
}
render() {
return (
<div style={Object.assign({}, this.styles.backgroundBox, this.styles.paddings, this.styles.baeminFontFamily)}>
<Title/>
<Questionair/>
<YesButton/>
</div>
)
}
}
export default Background; | daa82264b4f51648cac1114d0b7a72a54c02dd9e | [
"JavaScript"
] | 3 | JavaScript | CheolminConanShin/For_Kris | 5487fabbe309b53c317ea9a4a5cf1983b867baf2 | ae8477a85160d3f32b79f4cfb3d817f196b8c6d7 |
refs/heads/master | <repo_name>mingsong2/frankadmin<file_sep>/src/components/dataEntry/index.js
import React, { Component } from 'react';
import { Input } from "antd";
class DataEntry extends Component {
render() {
return (
<div>
<Input placeholder="请输入内容..."></Input>
</div>
);
}
}
export default DataEntry; | aa8174be4487c23e4934006cf981e55089f82b18 | [
"JavaScript"
] | 1 | JavaScript | mingsong2/frankadmin | 12cfebdcaf1a85b93e02b27bd21b8f09f6720d95 | 64b768ec5e365bdf95b2638d91460c16f272107e |
refs/heads/master | <repo_name>dexit/configurator-app<file_sep>/src/configurator/components/ProductEmailForm.js
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import i18n from 'i18next';
import { withTranslation } from 'react-i18next';
import translations from '../../translations';
import { Button, Form, FormGroup, Label, Input, Spinner } from 'reactstrap';
const validate = values => {
const currentLanguage = i18n.language;
const errors = {};
const emailPatt = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (!emailPatt.test(values.emailSender)) {
errors.emailSender = translations[currentLanguage].translation.error_email;
}
if (!emailPatt.test(values.emailRecipient)) {
errors.emailRecipient =
translations[currentLanguage].translation.error_email;
}
if (!values.title) {
errors.title = translations[currentLanguage].translation.error_title;
}
if (!values.regulation) {
errors.regulation =
translations[currentLanguage].translation.error_regulation;
}
return errors;
};
const input = ({ input, id, label, type, meta: { touched, error } }) => (
<>
<Label htmlFor={id}>{label}</Label>
<Input id={id} {...input} type={type} />
<div className="text-danger">
{touched && (error && <span>{error}</span>)}
</div>
</>
);
const checkbox = ({ input, label, meta: { touched, error } }) => (
<>
<Label check>
<Input {...input} type="checkbox" />
{label}
</Label>
<div className="text-danger">
{touched && (error && <span>{error}</span>)}
</div>
</>
);
const productEmailForm = props => {
const t = props.t;
const { handleSubmit, pristine, submitting } = props;
return (
<Form onSubmit={handleSubmit} noValidate>
<FormGroup>
<Field
name="emailSender"
id="emailSender"
label={t('your_email') + '*'}
component={input}
type="email"
/>
</FormGroup>
<FormGroup>
<Field
name="emailRecipient"
id="emailRecipient"
label={t('recipient_email') + '*'}
component={input}
type="email"
/>
</FormGroup>
<FormGroup>
<Field
name="title"
id="title"
label={t('title') + '*'}
component={input}
type="text"
/>
</FormGroup>
<FormGroup>
<Field
name="message"
id="message"
label={t('message')}
component={input}
type="textarea"
/>
</FormGroup>
<FormGroup check>
<Field
name="regulation"
label={t('agree_regulations') + '*'}
component={checkbox}
/>
</FormGroup>
<p className="mt-4">* {t('required_fields') + '*'}</p>
<Button
color="primary"
className="mt-4"
disabled={pristine || submitting}
>
{props.t('submit')}{' '}
{submitting && <Spinner size="sm" color="danger" className="ml-2" />}
</Button>
</Form>
);
};
export default reduxForm({
form: 'productEmail',
validate
})(withTranslation()(productEmailForm));
<file_sep>/src/store/constants.js
export const CONFIGURATOR_SET_DEFAULT_ACTIVE_ITEMS =
'CONFIGURATOR_SET_DEFAULT_ACTIVE_ITEMS';
export const CONFIGURATOR_SET_ACTIVE_ITEMS = 'CONFIGURATOR_SET_ACTIVE_ITEMS';
export const CONFIGURATOR_SET_ACTIVE_CATEGORY =
'CONFIGURATOR_SET_ACTIVE_CATEGORY';
export const CONFIGURATOR_SAVED_PRODUCTS_TOGGLE =
'CONFIGURATOR_SAVED_PRODUCTS_TOGGLE';
export const CONFIGURATOR_OPEN_SAVED_PRODUCTS =
'CONFIGURATOR_OPEN_SAVED_PRODUCTS';
export const CONFIGURATOR_REMOVE_PRODUCT = 'CONFIGURATOR_REMOVE_PRODUCT';
export const CONFIGURATOR_ADD_PRODUCT = 'CONFIGURATOR_ADD_PRODUCT';
export const CONFIGURATOR_CHECK_PRODUCT_EXIST =
'CONFIGURATOR_CHECK_PRODUCT_EXIST';
export const CONFIGURATOR_CHECK_SAVED_PRODUCTS =
'CONFIGURATOR_CHECK_SAVED_PRODUCTS';
export const CONFIGURATOR_GET_CATEGORIES_START =
'CONFIGURATOR_GET_CATEGORIES_START';
export const CONFIGURATOR_GET_CATEGORIES_SUCCESS =
'CONFIGURATOR_GET_CATEGORIES_SUCCESS';
export const CONFIGURATOR_GET_CATEGORIES_ERROR =
'CONFIGURATOR_GET_CATEGORIES_ERROR';
export const CONFIGURATOR_PRODUCT_EMAIL_MODAL_TOGGLE =
'CONFIGURATOR_PRODUCT_EMAIL_MODAL_TOGGLE';
export const CONFIGURATOR_PRODUCT_EMAIL_MODAL_OPEN =
'CONFIGURATOR_PRODUCT_EMAIL_MODAL_OPEN';
export const CONFIGURATOR_GET_DEFAULT_CATEGORY =
'CONFIGURATOR_GET_DEFAULT_CATEGORY';
export const CONFIGURATOR_SAVE_ROUTE_LNG = 'CONFIGURATOR_SAVE_ROUTE_LNG';
<file_sep>/src/configurator/components/ItemsList.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as configuratorActions from '../configuratorActions';
import styles from './ItemsList.module.scss';
class ItemsList extends Component {
handleClick = (activeCategoryId, itemId) => {
this.props.setActiveItems({ [activeCategoryId]: itemId });
};
list() {
const activeCategory = this.props.configuratorStore.categories.filter(
category => category.active === true
)[0];
let list = [];
if (activeCategory) {
list = activeCategory.items.map(item => {
const activeItemClass = () => item.active && styles.active;
return (
<div
key={item.id}
className="col-md-6 p-4 d-flex justify-content-center align-content-center"
>
<button
className={`${styles.item} ${activeItemClass()}`}
onClick={this.handleClick.bind(this, activeCategory.id, item.id)}
>
<img
src={`${process.env.PUBLIC_URL}/img/simple-model.png`}
alt=""
className={styles.simpleModel}
/>
<img
src={process.env.PUBLIC_URL + item.imgThumb}
alt=""
className={styles.thumb}
/>
{item.name}
</button>
</div>
);
});
}
return list;
}
render() {
return <>{this.list()}</>;
}
}
const mapStateToProps = state => {
return { ...state };
};
const mapDispatchToProps = dispatch => {
return {
setActiveItems: items =>
dispatch(configuratorActions.setActiveItems(items)),
checkProductExist: () => dispatch(configuratorActions.checkProductExist())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ItemsList);
<file_sep>/src/configurator/Configurator.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as configuratorActions from './configuratorActions';
import { Route, Switch, Redirect } from 'react-router-dom';
import { withTranslation } from 'react-i18next';
import i18n from 'i18next';
import styles from './Configurator.module.scss';
import Menu from './components/Menu';
import MenuItems from './components/MenuItems';
import ItemImg from './components/ItemImg';
import Summary from './components/Summary';
import SavedProducts from './components/SavedProducts';
import translations from '../translations';
import { API } from '../app/App';
export const API_PRODUCT_EMAIL = 'https://httpbin.org/post';
class Configurator extends Component {
getApiCategories() {
return API + `categories-${i18n.language}.json`;
}
setDefaultCategory() {
const summaryActive =
this.props.match.path === '/' + this.props.t('routeSummaryName');
const matchCategorySlug = this.props.match.params.category;
const activeCategoryId = this.props.userSettings.activeCategoryId;
let activeCategorySlug;
let activeCategoryIndex;
const matchCategoryIndex = this.props.categories.findIndex(
category => category.slug === matchCategorySlug
);
let matchCategoryId = null;
if (matchCategoryIndex > -1) {
matchCategoryId = this.props.categories[matchCategoryIndex].id;
}
if (activeCategoryId) {
activeCategoryIndex = this.props.categories.findIndex(
category => category.id === activeCategoryId
);
activeCategorySlug = this.props.categories[activeCategoryIndex].slug;
}
let firstCategoryId = '';
let firstCategorySlug = '';
if (this.props.categories.length) {
firstCategoryId = this.props.categories[0].id;
firstCategorySlug = this.props.categories[0].slug;
}
const setCategory = () => {
if (summaryActive) {
this.props.history.replace(
this.props.routeLng + '/' + this.props.t('routeSummaryName')
);
} else if (matchCategorySlug) {
if (matchCategoryIndex > -1) {
this.props.setActiveCategory(matchCategoryId);
} else {
this.props.setActiveCategory(firstCategoryId);
this.props.history.replace(
this.props.routeLng +
'/' +
this.props.t('routeCategoryName') +
'/' +
firstCategorySlug
);
}
} else if (!activeCategoryId) {
this.props.setActiveCategory(firstCategoryId);
this.props.history.replace(
this.props.routeLng +
'/' +
this.props.t('routeCategoryName') +
'/' +
firstCategorySlug
);
} else if (activeCategoryId) {
this.props.setActiveCategory(activeCategoryId);
this.props.history.replace(
this.props.routeLng +
'/' +
this.props.t('routeCategoryName') +
'/' +
activeCategorySlug
);
}
};
setCategory();
}
setDefaultItems() {
const activeItems = this.props.configuratorStore.userSettings.activeItems;
if (activeItems === null) {
this.props.setDefaultActiveItems();
}
this.props.setActiveItems();
}
changeLanguage = lng => {
const { i18n } = this.props;
i18n.changeLanguage(lng);
this.props.saveRouteLng(lng);
};
setRouteLang() {
const routeLng = this.props.match.params.lng;
const { i18n } = this.props;
const { language } = i18n;
if (routeLng && routeLng !== language) {
i18n.changeLanguage(routeLng);
this.props.saveRouteLng(routeLng);
} else {
this.props.saveRouteLng(language);
}
}
componentDidMount() {
this.setRouteLang();
const { language } = this.props.i18n;
this.language = language;
this.props.getCategories(this.getApiCategories()).then(() => {
this.setDefaultItems();
this.setDefaultCategory();
this.props.getDefaultCategory();
});
}
componentDidUpdate() {
const { language } = this.props.i18n;
if (language !== this.language) {
this.props.getCategories(this.getApiCategories()).then(() => {
this.setDefaultItems();
this.setDefaultCategory();
this.props.getDefaultCategory();
});
this.language = language;
}
}
render() {
const { t } = this.props;
const isLoading = this.props.configuratorStore.isLoading;
const defaultCategory = this.props.configuratorStore.defaultCategory;
const spinner = (
<div
className={`d-flex justify-content-center align-items-center ${
styles.loadingSpinner
}`}
>
<div
className={`spinner-border text-danger ${
styles.loadingSpinnerBorder
}`}
role="status"
>
<span className="sr-only">{t('loading')}...</span>
</div>
</div>
);
const Lang = () => {
const { i18n } = this.props;
const lang = [];
for (const key in translations) {
const active = key === i18n.language ? styles.active : undefined;
if (translations.hasOwnProperty(key)) {
lang.push(
<button
key={lang}
onClick={() => this.changeLanguage(key)}
className={`${styles.lang__btn} ${active}`}
>
{key.toUpperCase()}
</button>
);
}
}
return <div className={styles.lang}>{lang}</div>;
};
return (
<>
<div className={`d-flex flex-column ${styles.wrapper}`}>
<header
className={`${styles.header} text-center text-uppercase my-5`}
>
<h1>{t('configurator')}</h1>
<Lang />
</header>
<div className={`row flex-grow-1 ${styles.contentWrapper}`}>
<div className="col-md-2">
<Menu />
</div>
<div className="col-md-3">
<Switch>
<Route
path={
this.props.routeLng +
'/' +
t('routeCategoryName') +
'/:category'
}
component={MenuItems}
/>
<Route
path={this.props.routeLng + '/' + t('routeSummaryName')}
component={Summary}
/>
{defaultCategory ? (
<Redirect
to={
this.props.routeLng +
'/' +
t('routeCategoryName') +
'/' +
defaultCategory
}
/>
) : null}
</Switch>
</div>
<div className="col-md-7">
<ItemImg />
</div>
</div>
</div>
<SavedProducts />
{isLoading ? spinner : null}
</>
);
}
}
const mapStateToProps = state => {
return {
...state,
categories: state.configuratorStore.categories,
userSettings: state.configuratorStore.userSettings,
routeLng: state.configuratorStore.routeLng
};
};
const mapDispatchToProps = dispatch => {
return {
setActiveCategory: categoryId =>
dispatch(configuratorActions.setActiveCategory(categoryId)),
setDefaultActiveItems: () =>
dispatch(configuratorActions.setDefaultActiveItems()),
setActiveItems: () => dispatch(configuratorActions.setActiveItems()),
getCategories: API_CATEGORIES =>
dispatch(configuratorActions.getCategories(API_CATEGORIES)),
getDefaultCategory: () =>
dispatch(configuratorActions.getDefaultCategory()),
saveRouteLng: lng => dispatch(configuratorActions.saveRouteLng(lng))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withTranslation()(Configurator));
<file_sep>/src/utils/createProductPdf.js
import html2pdf from 'html2pdf.js';
export default function createProductPdf() {
const opt = {
margin: 1,
image: { type: 'png' },
html2canvas: {
logging: false
},
jsPDF: { orientation: 'landscape' }
};
return html2pdf()
.set(opt)
.from(document.querySelector('#templatePDF'))
.outputPdf('blob');
}
<file_sep>/src/configurator/components/SavedProducts.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as configuratorActions from '../configuratorActions';
import { withTranslation } from 'react-i18next';
import { Modal, ModalHeader, ModalBody } from 'reactstrap';
import styles from './SavedProducts.module.scss';
import createProductThumb from '../../utils/createProductThumb';
class SavedProducts extends Component {
componentUpdated = false;
handleProductClick = items => {
this.props.setActiveItems(items);
this.props.savedProductsToggle();
};
handleAddProductClick = e => {
if (!this.props.configuratorStore.productExists) {
createProductThumb(this.props.addProduct);
} else {
this.activeItem.style.visibility = 'hidden';
setTimeout(() => {
this.activeItem.style.visibility = 'visible';
}, 200);
}
};
handleRemoveProductClick = index => {
this.props.removeProduct(index);
};
componentDidMount() {
this.props.checkProductExist();
}
componentDidUpdate(prevProps) {
const isCategoriesLoaded = this.props.configuratorStore.isCategoriesLoaded;
if (isCategoriesLoaded !== prevProps.configuratorStore.isCategoriesLoaded) {
if (isCategoriesLoaded) {
this.props.checkSavedProducts();
}
}
if (!this.componentUpdated) {
this.props.checkProductExist();
this.componentUpdated = true;
} else {
this.componentUpdated = false;
}
}
render() {
const t = this.props.t;
const modal = this.props.configuratorStore.savedProductsModal;
const savedProducts = this.props.configuratorStore.userSettings
.savedProducts;
const activeItems = this.props.configuratorStore.userSettings.activeItems;
const savedProductsList = savedProducts.map((item, index) => {
const productsAreEqual =
JSON.stringify(item.productParts) === JSON.stringify(activeItems);
const activeItemClass = productsAreEqual ? styles.active : undefined;
return (
<div
className={styles.itemWrapper}
key={index}
ref={activeItem => productsAreEqual && (this.activeItem = activeItem)}
>
<button
className={styles.btnRemove}
onClick={this.handleRemoveProductClick.bind(this, index)}
>
{t('remove')}
</button>
<button
className={`${styles.btnChange} ${activeItemClass}`}
id={activeItemClass}
onClick={this.handleProductClick.bind(this, item.productParts)}
>
<img src={item.img} alt="" />
</button>
</div>
);
});
return (
<div>
<Modal
isOpen={modal}
toggle={this.props.savedProductsToggle}
className={styles.modal}
centered={true}
>
<ModalHeader toggle={this.props.savedProductsToggle}>
{t('saved_products')}
</ModalHeader>
<ModalBody>
<button onClick={this.handleAddProductClick}>
{t('add_product')}
</button>
{savedProductsList}
</ModalBody>
</Modal>
</div>
);
}
}
const mapStateToProps = state => {
return { ...state };
};
const mapDispatchToProps = dispatch => {
return {
savedProductsToggle: () =>
dispatch(configuratorActions.savedProductsToggle()),
setActiveItems: items =>
dispatch(configuratorActions.setActiveItems(items)),
removeProduct: index => dispatch(configuratorActions.removeProduct(index)),
addProduct: img => dispatch(configuratorActions.addProduct(img)),
checkProductExist: () => dispatch(configuratorActions.checkProductExist()),
checkSavedProducts: () => dispatch(configuratorActions.checkSavedProducts())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withTranslation()(SavedProducts));
<file_sep>/src/configurator/components/SendProductEmail.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as configuratorActions from '../configuratorActions';
import { withTranslation } from 'react-i18next';
import { Modal, ModalHeader, ModalBody } from 'reactstrap';
import ProductEmailForm from './ProductEmailForm';
import createProductPdf from '../../utils/createProductPdf';
import { API_PRODUCT_EMAIL } from '../Configurator';
class SendProductEmail extends Component {
state = {
successMessage: '',
errorMessage: ''
};
handleToggleModal = () => {
this.props.productEmailModalToggle();
};
handleSubmit = values => {
const t = this.props.t;
const data = new FormData();
for (const key in values) {
if (values.hasOwnProperty(key)) {
data.append(key, values[key]);
}
}
return createProductPdf()
.then(pdf => {
data.append('product_pdf', pdf);
})
.then(() => {
return fetch(API_PRODUCT_EMAIL, {
method: 'POST',
body: data
})
.then(resp => {
if (resp.ok) {
this.setState({
submitting: false,
successMessage: t('form_sent'),
errorMessage: ''
});
} else {
this.setState({
submitting: false,
errorMessage: t('form_error')
});
}
return resp;
})
.then(resp => (resp.ok ? resp.json() : resp))
.then(resp => {
console.log(resp);
});
});
};
componentDidUpdate(prevProps) {
if (
this.props.configuratorStore.productEmailModal !==
prevProps.configuratorStore.productEmailModal
) {
setTimeout(() => {
this.setState({
successMessage: ''
});
}, 1000);
}
}
render() {
const t = this.props.t;
const modalProductEmail = this.props.configuratorStore.productEmailModal;
return (
<Modal
isOpen={modalProductEmail}
toggle={this.handleToggleModal}
className={this.props.className}
>
<ModalHeader toggle={this.handleToggleModal}>
{t('send_product_email')}
</ModalHeader>
<ModalBody>
{this.state.successMessage ? null : (
<ProductEmailForm onSubmit={this.handleSubmit} />
)}
<div className="my-4 text-center">
{this.state.successMessage && <h3>{this.state.successMessage}</h3>}
{this.state.errorMessage && <h3>{this.state.errorMessage}</h3>}
</div>
</ModalBody>
</Modal>
);
}
}
const mapStateToProps = state => {
return { ...state };
};
const mapDispatchToProps = dispatch => {
return {
productEmailModalToggle: () =>
dispatch(configuratorActions.productEmailModalToggle())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withTranslation()(SendProductEmail));
<file_sep>/src/configurator/components/MenuItems.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
// import * as configuratorActions from '../configuratorActions';
import styles from './MenuItems.module.scss';
import ItemsList from './ItemsList';
class MenuItems extends Component {
render() {
const activeCategory = this.props.configuratorStore.categories.filter(
category => category.active === true
)[0];
const activeCategoryName = activeCategory && activeCategory.name;
return (
<div className={styles.wrapper}>
{activeCategoryName ? (
<div className="text-center py-4">
<h2>{activeCategoryName}</h2>
</div>
) : null}
<div className="row">
<ItemsList />
</div>
</div>
);
}
}
const mapStateToProps = state => {
return { ...state };
};
const mapDispatchToProps = dispatch => {
return {};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MenuItems);
<file_sep>/src/configurator/components/ItemImg.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as configuratorActions from '../configuratorActions';
import { withTranslation } from 'react-i18next';
import styles from './ItemImg.module.scss';
import createProductThumb from '../../utils/createProductThumb';
class ItemImg extends Component {
handleAddClick = () => {
if (!this.props.configuratorStore.productExists) {
this.props.openSavedProducts();
createProductThumb(this.props.addProduct);
} else {
this.props.openSavedProducts();
}
};
componentDidMount() {
this.props.checkProductExist();
}
componentDidUpdate(prevProps) {
if (
prevProps.configuratorStore.userSettings.activeItems !==
this.props.configuratorStore.userSettings.activeItems
) {
this.props.checkProductExist();
}
}
render() {
const t = this.props.t;
const categories = this.props.configuratorStore.categories;
const images = categories.map(category =>
category.items.map(item => {
if (item.active) {
return (
<img
src={process.env.PUBLIC_URL + item.imgLarge}
alt=""
key={item.id}
className={styles.img}
style={{ zIndex: item.indexCss }}
/>
);
}
return null;
})
);
const productExists = this.props.configuratorStore.productExists;
const btnAddProduct = (
<button
className={`btn btn-primary ${styles.btnAdd} ${
productExists ? styles.active : undefined
}`}
id="btnAdd"
onClick={this.handleAddClick}
>
{!productExists ? (
<span>{t('save_product')}</span>
) : (
<span>{t('saved_product')}</span>
)}
</button>
);
return (
<div
className={styles.bg}
style={{
backgroundImage: `url(${process.env.PUBLIC_URL}/img/product-bg.jpg)`
}}
id="product"
>
<img
src={`${process.env.PUBLIC_URL}/img/transparent-bg.png`}
alt=""
className="img-fluid"
/>
{images}
{categories.length && !this.props.onlyImg ? btnAddProduct : null}
</div>
);
}
}
const mapStateToProps = state => {
return { ...state };
};
const mapDispatchToProps = dispatch => {
return {
openSavedProducts: () => dispatch(configuratorActions.openSavedProducts()),
addProduct: img => dispatch(configuratorActions.addProduct(img)),
checkProductExist: () => dispatch(configuratorActions.checkProductExist())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withTranslation()(ItemImg));
<file_sep>/README.md
# Products Configurator
## Features:
- configure product from many elements
- save products in localstorage
- save product as a picture
- save product description as pdf
- send product description in an e-mail
- support for many languages
## Built with:
- React
- React Router
- React Redux
- Create React App
- Bootstrap 4
- Sass
## Demo:
https://lukkupis.github.io/configurator-app/
<file_sep>/src/utils/imageResize.js
export default function imageResize(image, width, height, format = 'jpeg') {
return new Promise(function(success, reject) {
image.addEventListener('load', () => {
const newCanvas = document.createElement('canvas');
let ctx = newCanvas.getContext('2d');
newCanvas.width = width;
newCanvas.height = height;
ctx.drawImage(image, 0, 0, width, height);
const imageResizedUrl = newCanvas.toDataURL(`image/${format}`);
success(imageResizedUrl);
});
});
}
<file_sep>/src/translations.js
const translations = {
pl: {
translation: {
loading: 'Wczytywanie',
configurator: 'Konfigurator',
routeCategoryName: 'kategoria',
routeSummaryName: 'gotowe',
save_product: 'Zapisz produkt',
saved_product: 'Produkt zapisany',
saved_products: 'Zapisane produkty',
add_product: 'Dodaj produkt',
form_sent:
'Formularz został wysłany. Email nie został dostarczony: testowe API - http://httpbin.org/post. Odpowiedź z serwera w konsoli.',
form_error: 'Wystąpił błąd. Formularz nie został wysłany.',
send_product_email: 'Wyślij opis produktu w wiadomości E-mail',
your_product: 'Twój produkt',
save_product_as_img: 'Zapisz produkt jako obrazek',
save_product_as_pdf: 'Zapisz opis produktu jako PDF',
remove: 'Usuń',
error_email: 'Wpisz poprawny email',
error_title: 'Wpisz tytuł',
enter_message: 'Wpisz wiadomość',
error_regulation: 'Zaakteptuj zgodę',
regulation: 'Zaakceptuj zgodę',
submit: 'Wyślij',
ready: 'Gotowe',
your_email: 'Twój e-mail',
recipient_email: 'E-mail odbiorcy',
agree_regulations: 'Zaakceptuj zgodę',
required_fields: 'Wymagane pola',
title: 'Tytuł',
message: 'Wiadomość'
}
},
en: {
translation: {
loading: 'Loading',
configurator: 'Configurator',
routeCategoryName: 'category',
routeSummaryName: 'ready',
save_product: 'Save product',
saved_product: 'Product saved',
saved_products: 'Saved products',
add_product: 'Add product',
form_sent:
'The form has been sent. Email was not delivered: test API - http://httpbin.org/post. Response from the server in the console.',
form_error: 'An error occured. The form has not been sent.',
send_product_email: 'Send the product description in an E-mail message',
your_product: 'Your product',
save_product_as_img: 'Save the product as a picture',
save_product_as_pdf: 'Save the product description as PDF',
remove: 'Remove',
error_email: 'Enter the correct email',
error_title: 'Enter the title',
enter_message: 'Enter the message',
error_regulation: 'Accept consent',
regulation: 'Accept consent',
submit: 'Submit',
ready: 'Ready',
your_email: 'Your e-mail',
recipient_email: 'E-mail recipient',
agree_regulations: 'Accept consent',
required_fields: 'Required fields',
title: 'Title',
message: 'Message'
}
}
};
export default translations;
<file_sep>/src/store/reducers.js
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import configuratorReducer from '../configurator/configuratorReducer';
const rootReducer = combineReducers({
configuratorStore: configuratorReducer,
form: formReducer
});
export default rootReducer;
| 5e6357e172cbc391bb03bea1315fbfa2a3f0a1b7 | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | dexit/configurator-app | 632cbeba350bfddc46646f84ec732b7101a95f7f | c726dbd1e80a4a86bcaa7243e85ea3e469e86449 |
refs/heads/master | <repo_name>Artemko1/Magic-Maze<file_sep>/Magic Maze/Assets/Scripts/UI/PlayerGoalGui.cs
using Managers;
using UnityEngine;
using UnityEngine.UI;
namespace UI
{
public class PlayerGoalGui : MonoBehaviour
{
#region Variables
public Button GlowButton;
public TurnManager TurnManager;
// public PlayerManager PlayerManager;
public Image image;
#endregion
#region Unity Methods
private void Update()
{
UpdateImage();
}
private void UpdateImage()
{
var texture = TurnManager.CurrentPlayer.ItemsToCollect[0].texture;
if (texture == null) return;
var rect = new Rect(0, 0, texture.width, texture.height);
var sprite = Sprite.Create(texture, rect, Vector2.zero);
image.sprite = sprite;
}
// private void UpdateText()
// {
// ItemText.text = PlayerManager.CurrentPlayer.ItemsToCollect[0].ToString();
// }
#endregion
}
}
<file_sep>/Magic Maze/Assets/Scripts/Tile/Tile.cs
using UnityEngine;
namespace Tile
{
[SelectionBase]
public class Tile : MonoBehaviour
{
#region Variables
protected GameObject upWallObject;
protected GameObject rightWallObject;
protected GameObject downWallObject;
protected GameObject leftWallObject;
[SerializeField]
protected Maze.Maze maze;
[SerializeField]
protected bool isWallUp;
[SerializeField]
protected bool isWallRight;
[SerializeField]
protected bool isWallDown;
[SerializeField]
protected bool isWallLeft;
public bool IsWallUp
{
get => isWallUp;
set
{
isWallUp = value;
upWallObject.SetActive(value);
}
}
public bool IsWallRight
{
get => isWallRight;
set
{
isWallRight = value;
rightWallObject.SetActive(value);
}
}
public bool IsWallDown
{
get => isWallDown;
set
{
isWallDown = value;
downWallObject.SetActive(value);
}
}
public bool IsWallLeft
{
get => isWallLeft;
set
{
isWallLeft = value;
leftWallObject.SetActive(value);
}
}
#endregion
#region Unity Methods
protected void Awake()
{
upWallObject = upWallObject ?? transform.Find("Plate Visual").Find("Wall Up").gameObject;
rightWallObject = rightWallObject ?? transform.Find("Plate Visual").Find("Wall Right").gameObject;
downWallObject = downWallObject ?? transform.Find("Plate Visual").Find("Wall Down").gameObject;
leftWallObject = leftWallObject ?? transform.Find("Plate Visual").Find("Wall Left").gameObject;
maze = transform.parent.GetComponent<Maze.Maze>();
}
private void OnValidate()
{
upWallObject = upWallObject ?? transform.Find("Plate Visual").Find("Wall Up").gameObject;
rightWallObject = rightWallObject ?? transform.Find("Plate Visual").Find("Wall Right").gameObject;
downWallObject = downWallObject ?? transform.Find("Plate Visual").Find("Wall Down").gameObject;
leftWallObject = leftWallObject ?? transform.Find("Plate Visual").Find("Wall Left").gameObject;
upWallObject.SetActive(isWallUp);
rightWallObject.SetActive(IsWallRight);
downWallObject.SetActive(isWallDown);
leftWallObject.SetActive(isWallLeft);
}
#endregion
}
}
<file_sep>/Magic Maze/Assets/Scripts/Managers/PlayerManager.cs
using System.Collections.Generic;
using Item;
using UnityEngine;
namespace Managers
{
public class PlayerManager : MonoBehaviour
{
#region Variables
public List<Player.Player> players = new List<Player.Player>();
private ItemManager itemManager;
#endregion
#region Unity Methods
private void Awake()
{
itemManager = GetComponent<ItemManager>();
}
#endregion
public void AssignItemsToCollect()
{
foreach (var player in players)
{
for (var i = 0; i < itemManager.itemsPerPlayer; i++)
{
player.ItemsToCollect.Add(itemManager.UnassignedItems[0]);
itemManager.UnassignedItems.RemoveAt(0);
}
}
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Tile/ExcessTile/ExcessTile.cs
using System;
using Managers;
using UI;
using UnityEngine;
namespace Tile.ExcessTile
{
public class ExcessTile : Tile
{
#region Variables
public int ExtraPosId
{
get => extraPosId;
set
{
if (value < 0)
{
extraPosId = maze.MovableRows + (value % maze.MovableRows);
}
else
{
extraPosId = value % maze.MovableRows;
}
}
}
public Direction CurrentDirection
{
get
{
switch ((ExtraPosId / maze.MovableRowsPerSide))
{
case 0:
return Direction.Down;
case 1:
return Direction.Right;
case 2:
return Direction.Up;
case 3:
return Direction.Left;
default:
throw new System.ArgumentException("Parameter can only be 0-3, " +
$"but it's {ExtraPosId / maze.MovableRowsPerSide}");
}
}
}
[SerializeField]
private int extraPosId;
private Buttons buttons;
public Actions actions;
#endregion
#region Unity Methods
private void OnEnable()
{
buttons = maze.GetComponent<Buttons>();
buttons.moveExcessTileForward?.onClick.AddListener(MoveForward);
buttons.moveExcessTileBackward?.onClick.AddListener(MoveBackward);
buttons.RotateExcessTile?.onClick.AddListener(RotateClockwise);
actions = new Actions();
actions.ExcessTileMap.MoveForward.performed += ctx => MoveForward();
actions.ExcessTileMap.MoveBackward.performed += ctx => MoveBackward();
actions.ExcessTileMap.RotateClockwise.performed += ctx => RotateClockwise();
actions.ExcessTileMap.RotateCounterclockwise.performed += ctx => RotateCounterclockwise();
actions.ExcessTileMap.MoveColumn.performed += ctx => maze.MoveColumn();
}
private void OnDisable()
{
buttons.moveExcessTileForward?.onClick.RemoveListener(MoveForward);
buttons.moveExcessTileBackward?.onClick.RemoveListener(MoveBackward);
buttons.RotateExcessTile?.onClick.RemoveListener(RotateClockwise);
actions.ExcessTileMap.MoveForward.performed -= ctx => MoveForward();
actions.ExcessTileMap.MoveBackward.performed -= ctx => MoveBackward();
actions.ExcessTileMap.RotateClockwise.performed -= ctx => RotateClockwise();
actions.ExcessTileMap.RotateCounterclockwise.performed -= ctx => RotateCounterclockwise();
actions.ExcessTileMap.MoveColumn.performed -= ctx => maze.MoveColumn();
actions.ExcessTileMap.Disable();
}
#endregion
/// <summary>
/// Возвращает координату z или x лабиринта, где сейчас находится ExcessTile
/// </summary>
/// <returns></returns>
public int GetRowNumber()
{
switch (CurrentDirection)
{
case Direction.Down:
return ExtraPosId * 2 + 1;
case Direction.Right:
return maze.BoardSize - 1 - ((ExtraPosId - maze.MovableRowsPerSide) * 2 + 1);
case Direction.Up:
return maze.BoardSize - 1 - ((ExtraPosId - 2 * maze.MovableRowsPerSide) * 2 + 1);
case Direction.Left:
return (ExtraPosId - 3 * maze.MovableRowsPerSide) * 2 + 1;
default:
throw new System.ArgumentException("Wrong direction in CurrentDirection");
}
}
/// <summary>
/// Поворачивает клетку на 90* против часовой стрелки.
/// Вызывается при движении клетки против часовой стрелки вокруг лабиринта.
/// </summary>
public void RotateCounterclockwise()
{
var wasWallUp = IsWallUp;
IsWallUp = IsWallRight;
IsWallRight = IsWallDown;
IsWallDown = IsWallLeft;
IsWallLeft = wasWallUp;
}
public void RotateClockwise()
{
var wasWallUp = IsWallUp;
IsWallUp = IsWallLeft;
IsWallLeft = IsWallDown;
IsWallDown = IsWallRight;
IsWallRight = wasWallUp;
}
/// <summary>
/// Двигает клетку на следующую позицию
/// </summary>
public void MoveForward()
{
ExtraPosId++;
var nextPosition = maze.extraPositions[ExtraPosId];
transform.position = nextPosition;
if (ExtraPosId % maze.MovableRowsPerSide == 0)
{
RotateCounterclockwise();
}
}
/// <summary>
/// Двигает клетку на предыдущую позицию
/// </summary>
public void MoveBackward()
{
if ((ExtraPosId % maze.MovableRowsPerSide) == 0)
{
RotateClockwise();
}
ExtraPosId--;
var nextPosition = maze.extraPositions[ExtraPosId];
transform.position = nextPosition;
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Item/ItemGenerator.cs
using System.Collections.Generic;
using Managers;
using Tile.MazeTile;
using UnityEngine;
namespace Item
{
[RequireComponent(typeof(Maze.Maze))]
public class ItemGenerator : MonoBehaviour
{
#region Variables
public GameObject[] ItemPrefabs;
private Maze.Maze maze;
private ItemManager itemManager;
#endregion
#region Unity Methods
private void Awake()
{
maze = GetComponent<Maze.Maze>();
itemManager = GetComponent<ItemManager>();
}
#endregion
public void GenerateItems()
{
if (itemManager.itemsPerPlayer == 0)
{
return;
}
// Кортеж координат (0,0), (0,1), (0,2) и т.д.
var tileList = new List<(int, int)>();
for (var i = 0; i < maze.BoardSize; i++)
{
for (var j = 0; j < maze.BoardSize; j++)
{
tileList.Add((i, j));
}
}
var numberOfItems = itemManager.itemsPerPlayer * maze.NumberOfPlayers;
for (var i = 0; i < numberOfItems; i++)
{
var index = Random.Range(0, tileList.Count);
var tile = maze.GetTile(tileList[index]);
if (tile.currentItem != null || tile.currentPlayer != null)
{
i--;
}
else
{
CreateItem(tile, i);
}
tileList.RemoveAt(index);
if (tileList.Count == 0)
{
break;
}
}
}
private void CreateItem(MazeTile tile, int itemId)
{
var itemObj = Instantiate(
ItemPrefabs[itemId],
tile.transform.position,
Quaternion.identity,
maze.transform);
var item = itemObj.GetComponent<Item>();
tile.currentItem = item;
item.CurrentTile = tile;
itemManager.UnassignedItems.Add(item);
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Tile/TileGenerator.cs
using UnityEngine;
namespace Tile
{
public static class TileGenerator
{
public static void GenerateCornerWalls(Tile tile, Direction upDownDirection, Direction leftRightDirection)
{
ActivateWalls(tile, upDownDirection == Direction.Up, leftRightDirection == Direction.Right,
upDownDirection == Direction.Down, leftRightDirection == Direction.Left);
}
public static void GenerateNoWalls(Tile tile)
{
ActivateWalls(tile, false, false, false, false);
}
public static void GenerateOneWall(Tile tile)
{
if (Random.value <= 0.25)
{
ActivateWalls(tile, true, false, false, false);
}
else if (Random.value <= 0.5)
{
ActivateWalls(tile, false, true, false, false);
}
else if (Random.value <= 0.75)
{
ActivateWalls(tile, false, false, true, false);
}
else
{
ActivateWalls(tile, false, false, false, true);
}
}
/// <summary>
/// Случайно генерирует стены для переданной клетки.
/// </summary>
/// <param name="tile"></param>
public static void GenerateRandomWalls(Tile tile)
{
if (Random.value <= 0.6)
{
GenerateOppositeWalls(tile);
}
else
{
GenerateCornerWalls(tile);
}
}
private static void GenerateOppositeWalls(Tile tile)
{
if (Random.value <= 0.5)
{
// Верхнюю и нижнюю
ActivateWalls(tile, true, false, true, false);
}
else
{
// Правую и левую
ActivateWalls(tile, false, true, false, true);
}
}
private static void GenerateCornerWalls(Tile tile)
{
if (Random.value <= 0.25)
{
// Верхнюю и правую
ActivateWalls(tile, true, true, false, false);
}
else if (Random.value <= 0.5)
{
// Правую и нижнюю
ActivateWalls(tile, false, true, true, false);
}
else if (Random.value <= 0.75)
{
// Нижнюю и левую
ActivateWalls(tile, false, false, true, true);
}
else
{
// Левую и верхнюю
ActivateWalls(tile, true, false, false, true);
}
}
private static void ActivateWalls(Tile tile, bool up, bool right, bool down, bool left)
{
tile.IsWallUp = up;
tile.IsWallRight = right;
tile.IsWallDown = down;
tile.IsWallLeft = left;
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Item/Item.cs
using Managers;
using Tile.MazeTile;
using UnityEngine;
namespace Item
{
[SelectionBase]
public class Item : MonoBehaviour
{
#region Variables
public Texture2D texture;
public MazeTile CurrentTile
{
get => currentTile;
set
{
if (currentTile != null)
{
currentTile.currentItem = null;
}
currentTile = value;
currentTile.currentItem = this;
}
}
[SerializeField] private MazeTile currentTile;
private ItemManager itemManager;
#endregion
#region Unity Methods
private void Awake()
{
var board = transform.parent;
itemManager = board.GetComponent<ItemManager>();
}
#endregion
}
}
<file_sep>/Magic Maze/Assets/Scripts/Managers/ItemManager.cs
using System.Collections.Generic;
using UnityEngine;
namespace Managers
{
public class ItemManager : MonoBehaviour
{
#region Variables
[SerializeField][Range(0, 9)] public int itemsPerPlayer;
[HideInInspector] public List<Item.Item> UnassignedItems = new List<Item.Item>();
public bool loadAssetPreviews;
#endregion
#region Unity Methods
#endregion
}
}
<file_sep>/Magic Maze/Assets/Scripts/Player/PlayerGenerator.cs
using Managers;
using UnityEngine;
namespace Player
{
[RequireComponent(typeof(Maze.Maze))]
public class PlayerGenerator : MonoBehaviour
{
#region Variables
public GameObject playerPrefab;
public GameObject[] playerPrefabs;
private Maze.Maze maze;
private PlayerManager playerManager;
private readonly (int, int)[] spawnPositions = new (int, int)[4];
#endregion
#region Unity Methods
private void Awake()
{
maze = GetComponent<Maze.Maze>();
playerManager = GetComponent<PlayerManager>();
spawnPositions[0] = (0, 0);
spawnPositions[1] = (0, maze.BoardSize - 1);
spawnPositions[2] = (maze.BoardSize - 1, 0);
spawnPositions[3] = (maze.BoardSize - 1, maze.BoardSize - 1);
}
#endregion
/// <summary>
/// Создает всех игроков.
/// </summary>
/// <param name="numberOfPlayers"></param>
public void GeneratePlayers(int numberOfPlayers)
{
for (int i = 0; i < numberOfPlayers; i++)
{
if (i == spawnPositions.Length)
{
break;
}
CreatePlayer(spawnPositions[i], playerPrefabs[i], "Player "+i);
}
}
private void CreatePlayer((int,int) p, GameObject prefab, string playerName = "Player")
{
var (z, x) = p;
var tile = maze.GetTile(z, x);
var playerObj = Instantiate(
prefab,
tile.transform.position,
Quaternion.identity,
transform);
playerObj.name = playerName;
playerObj.transform.SetAsFirstSibling();
var player = playerObj.GetComponent<Player>();
tile.currentPlayer = player;
player.CurrentTile = tile;
playerManager.players.Add(player);
player.isIgnoringWalls = false;
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Managers/TurnManager.cs
using System;
using UnityEngine;
namespace Managers
{
public class TurnManager : MonoBehaviour
{
#region Variables
public TurnPhase CurrentPhase;
public Player.Player CurrentPlayer => playerManager.players[playerIndex];
private int playerIndex;
private Maze.Maze maze;
private PlayerManager playerManager;
#endregion
#region Unity Methods
private void Awake()
{
var board = GameObject.FindWithTag("Board");
playerManager = board.GetComponent<PlayerManager>();
maze = board.GetComponent<Maze.Maze>();
}
#endregion
public void SwitchTurn()
{
switch (CurrentPhase)
{
case TurnPhase.PlayerMove:
ToColumnMove();
break;
case TurnPhase.ColumnMove:
ToPlayerMove();
break;
default:
throw new Exception("Turn phase not assigned");
}
}
private void ToColumnMove()
{
CurrentPlayer.actions.PlayerMap.Disable();
maze.ExcessTile.actions.ExcessTileMap.Enable();
playerIndex++;
if (playerIndex == playerManager.players.Count)
{
playerIndex = 0;
}
CurrentPhase = TurnPhase.ColumnMove;
print("Column turn");
}
private void ToPlayerMove()
{
maze.ExcessTile.actions.ExcessTileMap.Disable();
CurrentPlayer.actions.PlayerMap.Enable();
CurrentPhase = TurnPhase.PlayerMove;
print("Player turn");
}
public void InitializeFirstTurn()
{
maze.ExcessTile.actions.Enable();
}
}
public enum TurnPhase
{
ColumnMove,
PlayerMove
}
}
<file_sep>/Magic Maze/Assets/Scripts/Maze/Maze.cs
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Item;
using Managers;
using Player;
using Tile;
using Tile.ExcessTile;
using Tile.MazeTile;
using UI;
using UnityEngine;
namespace Maze
{
[RequireComponent(typeof(Buttons))]
[SuppressMessage("ReSharper", "Unity.NoNullPropagation")]
public class Maze : MonoBehaviour
{
#region Variables
public int BoardSize { get; } = 9;
public float Spacing { get; } = 2f;
/// <summary>
/// Количество excess позиций вдоль одной стороны лабиринта.
/// </summary>
public int MovableRowsPerSide => (BoardSize - 1) / 2;
/// <summary>
/// Количество возможных позиций для ExcessTile.
/// </summary>
public int MovableRows => (BoardSize - 1) * 2;
public Vector3[] extraPositions;
public ExcessTile ExcessTile => excessTile;
public int NumberOfPlayers;
public Actions actions;
private MazeGenerator mazeGenerator;
private PlayerGenerator playerGenerator;
private ItemGenerator itemGenerator;
private PlayerManager playerManager;
private TurnManager turnManager;
[SerializeField] private MazeTile[] tileArray;
[SerializeField] private ExcessTile excessTile;
#endregion
#region Unity Methods
private void Awake()
{
mazeGenerator = GetComponent<MazeGenerator>();
playerGenerator = GetComponent<PlayerGenerator>();
itemGenerator = GetComponent<ItemGenerator>();
playerManager = GetComponent<PlayerManager>();
var managers = GameObject.FindWithTag("Managers");
turnManager = managers.GetComponent<TurnManager>();
var buttons = GetComponent<Buttons>();
buttons.moveColumn?.onClick.AddListener(MoveColumn);
actions = new Actions();
}
private void Start()
{
tileArray = new MazeTile[BoardSize * BoardSize];
mazeGenerator?.GenerateTiles(tileArray);
mazeGenerator?.GenerateExcessPositions();
excessTile.transform.position = extraPositions[0];
TileGenerator.GenerateRandomWalls(excessTile);
playerGenerator?.GeneratePlayers(NumberOfPlayers);
itemGenerator?.GenerateItems();
playerManager.AssignItemsToCollect();
turnManager.InitializeFirstTurn();
}
#endregion
/// <summary>
/// Присваивает переданный tile в массив объекта.
/// </summary>
/// <param name="z">Номер строки клетки.</param>
/// <param name="x">Номер столбца клетки.</param>
/// <param name="mazeTile"></param>
public void SetTile(int z, int x, MazeTile mazeTile)
{
// 2D representation stored in row-major order.
tileArray[z * BoardSize + x] = mazeTile;
}
/// <summary>
/// Возвращает клетку из лабиринта по её координатам.
/// </summary>
/// <param name="z">Номер строки клетки.</param>
/// <param name="x">Номер столбца клетки.</param>
/// <returns></returns>
public MazeTile GetTile(int z, int x)
{
return tileArray[z * BoardSize + x];
}
public MazeTile GetTile((int, int) p)
{
var (z, x) = p;
return tileArray[z * BoardSize + x];
}
/// <summary>
/// Смещает ряд клеток.
/// ExcessTile оказывается с противоположной стороны
/// </summary>
public void MoveColumn()
{
if (turnManager.CurrentPhase != TurnPhase.ColumnMove)
{
Debug.LogError("Column move should not be called in not it's turn.'");
return;
}
switch (excessTile.CurrentDirection)
{
case Direction.Down:
MoveColumnUp();
break;
case Direction.Right:
MoveColumnLeft();
break;
case Direction.Up:
MoveColumnDown();
break;
case Direction.Left:
MoveColumnRight();
break;
}
turnManager.SwitchTurn();
}
private void MoveColumnUp()
{
var x = excessTile.GetRowNumber();
var oldExtraPosId = excessTile.ExtraPosId;
// Первый тайл становится эксесс
var toBecomeExcessTile = GetTile(0, x);
var newExcessTile = toBecomeExcessTile.gameObject.AddComponent<ExcessTile>();
var newTile = excessTile.gameObject.AddComponent<MazeTile>();
CopyTileWalls(toBecomeExcessTile, newExcessTile);
toBecomeExcessTile.MoveUp();
Destroy(toBecomeExcessTile);
for (var z = 1; z < BoardSize; z++) // От второй до последней, против направления движения ряда
{
var currentTile = GetTile(z, x);
currentTile.zIndex--;
SetTile(z - 1, x, currentTile);
currentTile.MoveUp();
}
// Последний тайл становится обычным вместо эксесс
var toBeReplacedByExcessTile = GetTile(BoardSize - 1, x);
CopyTileWalls(excessTile, newTile);
Destroy(excessTile);
// Индекс уменьшался, чтобы перезаписать тайл в другую клетку.
// Теперь возвращается обратно, т.к. конкретно эта клетка не перезаписывается.
// Аналогично в других функциях смещения ряда.
newTile.zIndex = toBeReplacedByExcessTile.zIndex;
newTile.zIndex++;
newTile.xIndex = toBeReplacedByExcessTile.xIndex;
newTile.MoveUp();
AlsoMovePlayerAndItem(toBecomeExcessTile, newTile);
SetTile(BoardSize - 1, x, newTile);
excessTile = newExcessTile;
excessTile.ExtraPosId = 3 * MovableRowsPerSide - oldExtraPosId - 1;
}
private void MoveColumnRight()
{
var z = excessTile.GetRowNumber();
var oldExtraPosId = excessTile.ExtraPosId;
// Последний тайл становится эксесс
var toBecomeExcessTile = GetTile(z, BoardSize - 1);
var newExcessTile = toBecomeExcessTile.gameObject.AddComponent<ExcessTile>();
var newTile = excessTile.gameObject.AddComponent<MazeTile>();
CopyTileWalls(toBecomeExcessTile, newExcessTile);
toBecomeExcessTile.MoveRight();
Destroy(toBecomeExcessTile);
for (var x = BoardSize - 2; x >= 0; x--) // От предпоследней до первой, против направления движения ряда
{
var currentTile = GetTile(z, x);
currentTile.xIndex++;
SetTile(z, x + 1, currentTile);
currentTile.MoveRight();
}
// Первый тайл становится обычным вместо эксесс
var toBeReplacedByExcessTile = GetTile(z, 0);
CopyTileWalls(excessTile, newTile);
Destroy(excessTile);
newTile.zIndex = toBeReplacedByExcessTile.zIndex;
newTile.xIndex = toBeReplacedByExcessTile.xIndex;
newTile.xIndex--;
newTile.MoveRight();
AlsoMovePlayerAndItem(toBecomeExcessTile, newTile);
SetTile(z, 0, newTile);
excessTile = newExcessTile;
excessTile.ExtraPosId = 5 * MovableRowsPerSide - oldExtraPosId - 1;
}
private void MoveColumnDown()
{
var x = excessTile.GetRowNumber();
var oldExtraPosId = excessTile.ExtraPosId;
// Последний тайл становится эксесс
var toBecomeExcessTile = GetTile(BoardSize - 1, x);
var newExcessTile = toBecomeExcessTile.gameObject.AddComponent<ExcessTile>();
var newTile = excessTile.gameObject.AddComponent<MazeTile>();
CopyTileWalls(toBecomeExcessTile, newExcessTile);
toBecomeExcessTile.MoveDown();
Destroy(toBecomeExcessTile);
for (var z = BoardSize - 2; z >= 0; z--) // От предпоследней до первой, против направления движения ряда
{
var currentTile = GetTile(z, x);
currentTile.zIndex++;
SetTile(z + 1, x, currentTile);
currentTile.MoveDown();
}
// Первый тайл становится обычным вместо эксесс
var toBeReplacedByExcessTile = GetTile(0, x);
CopyTileWalls(excessTile, newTile);
Destroy(excessTile);
newTile.zIndex = toBeReplacedByExcessTile.zIndex;
newTile.zIndex--;
newTile.xIndex = toBeReplacedByExcessTile.xIndex;
newTile.MoveDown();
AlsoMovePlayerAndItem(toBecomeExcessTile, newTile);
SetTile(0, x, newTile);
excessTile = newExcessTile;
excessTile.ExtraPosId = 3 * MovableRowsPerSide - oldExtraPosId - 1;
}
private void MoveColumnLeft()
{
var z = excessTile.GetRowNumber();
var oldExtraPosId = excessTile.ExtraPosId;
// Первый тайл становится эксесс
var toBecomeExcessTile = GetTile(z, 0);
var newExcessTile = toBecomeExcessTile.gameObject.AddComponent<ExcessTile>();
var newTile = excessTile.gameObject.AddComponent<MazeTile>();
CopyTileWalls(toBecomeExcessTile, newExcessTile);
toBecomeExcessTile.MoveLeft();
Destroy(toBecomeExcessTile);
for (var x = 1; x < BoardSize; x++) // От второй до последней, против направления движения ряда
{
var currentTile = GetTile(z, x);
currentTile.xIndex--;
SetTile(z, x - 1, currentTile);
currentTile.MoveLeft();
}
// Последний тайл становится обычным вместо эксесс
var toBeReplacedByExcessTile = GetTile(z, BoardSize - 1);
CopyTileWalls(excessTile, newTile);
Destroy(excessTile);
newTile.xIndex = toBeReplacedByExcessTile.xIndex;
newTile.xIndex++;
newTile.zIndex = toBeReplacedByExcessTile.zIndex;
newTile.MoveLeft();
AlsoMovePlayerAndItem(toBecomeExcessTile, newTile);
SetTile(z, BoardSize - 1, newTile);
excessTile = newExcessTile;
excessTile.ExtraPosId = 5 * MovableRowsPerSide - oldExtraPosId - 1;
}
/// <summary>
/// Для перемещения когда mazeTile выдвигается из лабиринта.
/// </summary>
/// <param name="fromTile"></param>
/// <param name="toTile"></param>
private static void AlsoMovePlayerAndItem(MazeTile fromTile, MazeTile toTile)
{
if (fromTile.currentPlayer != null)
{
fromTile.currentPlayer.CurrentTile = toTile;
toTile.currentPlayer.transform.position = toTile.transform.position;
}
if (fromTile.currentItem != null)
{
fromTile.currentItem.CurrentTile = toTile;
toTile.currentItem.transform.position = toTile.transform.position;
}
}
private static void CopyTileWalls(Tile.Tile oldTile, Tile.Tile newTile)
{
newTile.IsWallUp = oldTile.IsWallUp;
newTile.IsWallRight = oldTile.IsWallRight;
newTile.IsWallDown = oldTile.IsWallDown;
newTile.IsWallLeft = oldTile.IsWallLeft;
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/UI/Buttons.cs
using System;
using UnityEngine;
using UnityEngine.UI;
namespace UI
{
public class Buttons : MonoBehaviour
{
public Button moveExcessTileForward;
public Button moveExcessTileBackward;
public Button RotateExcessTile;
public Button moveColumn;
public Button movePlayerUpButton;
public Button movePlayerRightButton;
public Button movePlayerDownButton;
public Button movePlayerLeftButton;
public Button switchTurnButton;
}
}
<file_sep>/Magic Maze/Assets/Scripts/Player/Player.cs
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Managers;
using Tile.MazeTile;
using UI;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Player
{
[SelectionBase]
public class Player : MonoBehaviour
{
#region Variables
public bool isIgnoringWalls;
public List<Item.Item> ItemsToCollect = new List<Item.Item>();
public Actions actions;
public MazeTile CurrentTile
{
private get => currentTile;
set
{
if (currentTile != null)
{
currentTile.currentPlayer = null;
}
currentTile = value;
currentTile.currentPlayer = this;
}
}
private Maze.Maze maze;
private PlayerManager playerManager;
private TurnManager turnManager;
private Buttons buttons;
private MazeTile currentTile;
#endregion
#region Unity Methods
private void Awake()
{
var board = transform.parent;
maze = board.GetComponent<Maze.Maze>();
playerManager = board.GetComponent<PlayerManager>();
var managers = GameObject.FindWithTag("Managers");
turnManager = managers.GetComponent<TurnManager>();
actions = new Actions();
actions.PlayerMap.MoveUp.performed += ctx => Move(Direction.Up);
actions.PlayerMap.MoveRight.performed += ctx => Move(Direction.Right);
actions.PlayerMap.MoveDown.performed += ctx => Move(Direction.Down);
actions.PlayerMap.MoveLeft.performed += ctx => Move(Direction.Left);
actions.PlayerMap.EndPlayerTurn.performed += ctx => turnManager.SwitchTurn();
}
[SuppressMessage("ReSharper", "Unity.NoNullPropagation")]
private void OnEnable()
{
buttons = maze.GetComponent<Buttons>();
buttons.movePlayerUpButton?.onClick.AddListener(() => Move(Direction.Up));
buttons.movePlayerRightButton?.onClick.AddListener(() => Move(Direction.Right));
buttons.movePlayerDownButton?.onClick.AddListener(() => Move(Direction.Down));
buttons.movePlayerLeftButton?.onClick.AddListener(() => Move(Direction.Left));
}
[SuppressMessage("ReSharper", "Unity.NoNullPropagation")]
private void OnDisable()
{
buttons.movePlayerUpButton?.onClick.RemoveListener(() => Move(Direction.Up));
buttons.movePlayerRightButton?.onClick.RemoveListener(() => Move(Direction.Right));
buttons.movePlayerDownButton?.onClick.RemoveListener(() => Move(Direction.Down));
buttons.movePlayerLeftButton?.onClick.RemoveListener(() => Move(Direction.Left));
}
#endregion
private void Move(Direction direction)
{
MazeTile nextTile = null;
switch (direction)
{
case Direction.Up:
//Debug.Log(this + " Moving Up");
if (CurrentTile.zIndex == 0)
{
Debug.Log(this + " reached board boundary.");
return;
}
nextTile = maze.GetTile(CurrentTile.zIndex - 1, CurrentTile.xIndex);
if (!isIgnoringWalls && (CurrentTile.IsWallUp || nextTile.IsWallDown))
{
Debug.Log(this + " reached wall up.");
return;
}
break;
case Direction.Right:
//Debug.Log(this + " Moving Right");
if (CurrentTile.xIndex + 1 == maze.BoardSize)
{
Debug.Log(this + "reached board boundary.");
return;
}
nextTile = maze.GetTile(CurrentTile.zIndex, CurrentTile.xIndex + 1);
if (!isIgnoringWalls && (CurrentTile.IsWallRight || nextTile.IsWallLeft))
{
Debug.Log(this + " reached wall right.");
return;
}
break;
case Direction.Down:
//Debug.Log(this + " Moving Down");
if (CurrentTile.zIndex + 1 == maze.BoardSize)
{
Debug.Log(this + "reached board boundary.");
return;
}
nextTile = maze.GetTile(CurrentTile.zIndex + 1, CurrentTile.xIndex);
if (!isIgnoringWalls && (CurrentTile.IsWallDown || nextTile.IsWallUp))
{
Debug.Log(this + " reached wall down.");
return;
}
break;
case Direction.Left:
//Debug.Log(this + " Moving Left");
if (CurrentTile.xIndex == 0)
{
Debug.Log(this + "reached board boundary.");
return;
}
nextTile = maze.GetTile(CurrentTile.zIndex, CurrentTile.xIndex - 1);
if (!isIgnoringWalls && (CurrentTile.IsWallLeft || nextTile.IsWallRight))
{
Debug.Log(this + " reached wall left.");
return;
}
break;
default:
Debug.LogError("Wrong move direction;");
break;
}
CurrentTile = nextTile;
transform.position = CurrentTile.transform.position;
TryCollectItem();
}
private void TryCollectItem()
{
var item = currentTile.currentItem;
if (item != null && item == ItemsToCollect[0])
{
item.gameObject.SetActive(false);
ItemsToCollect.RemoveAt(0);
}
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Tile/MazeTile/MazeTile.cs
using UnityEngine;
namespace Tile.MazeTile
{
public class MazeTile : Tile
{
#region Variables
public byte zIndex;
public byte xIndex;
public Player.Player currentPlayer;
public Item.Item currentItem;
#endregion
/// <summary>
/// Смещение вверх на расстояние одной клетки
/// </summary>
public void MoveUp()
{
transform.Translate(new Vector3(0, 0, 1) * maze.Spacing, Space.World);
PlayerAndItemToTilePos();
}
/// <summary>
/// Смещение вправо на расстояние одной клетки
/// </summary>
public void MoveRight()
{
transform.Translate(new Vector3(1, 0, 0) * maze.Spacing, Space.World);
PlayerAndItemToTilePos();
}
/// <summary>
/// Смещение вниз на расстояние одной клетки
/// </summary>
public void MoveDown()
{
transform.Translate(new Vector3(0, 0, -1) * maze.Spacing, Space.World);
PlayerAndItemToTilePos();
}
/// <summary>
/// Смещение влево на расстояние одной клетки
/// </summary>
public void MoveLeft()
{
transform.Translate(new Vector3(-1, 0, 0) * maze.Spacing, Space.World);
PlayerAndItemToTilePos();
}
private void PlayerAndItemToTilePos()
{
if (currentPlayer != null)
{
currentPlayer.transform.position = transform.position;
}
if (currentItem != null)
{
currentItem.transform.position = transform.position;
}
}
}
}
<file_sep>/Magic Maze/Assets/Scripts/Maze/MazeGenerator.cs
using Tile;
using Tile.MazeTile;
using UnityEngine;
namespace Maze
{
[RequireComponent(typeof(Maze))]
public class MazeGenerator : MonoBehaviour
{
#region Variables
public GameObject tilePrefab;
private Maze maze;
#endregion
#region Unity Methods
private void Awake()
{
maze = GetComponent<Maze>();
}
#endregion
public void GenerateTiles(MazeTile[] tileArray)
{
for (byte z = 0; z < maze.BoardSize; z++)
{
for (byte x = 0; x < maze.BoardSize; x++)
{
var tile = CreateTile(z, x);
if (IsCorner(z, x, out var upDownDirection, out var leftRightDirection))
{
TileGenerator.GenerateCornerWalls(tile, upDownDirection, leftRightDirection);
}
else if (!IsMovable(z, x))
{
TileGenerator.GenerateNoWalls(tile);
}
else
{
TileGenerator.GenerateRandomWalls(tile);
}
maze.SetTile(z, x, tile);
tile.zIndex = z;
tile.xIndex = x;
}
}
}
public void GenerateNewTiles() // Генерирует новые стенки всем клеткам лабиринта
{
for (byte z = 0; z < maze.BoardSize; z++)
{
for (byte x = 0; x < maze.BoardSize; x++)
{
TileGenerator.GenerateRandomWalls(maze.GetTile(z, x));
}
}
}
public void GenerateExcessPositions()
{
maze.extraPositions = new Vector3[maze.MovableRows];
byte n = 0;
byte z, x;
x = 1;
while (x < maze.BoardSize - 1)
{
SetExtraPosition((byte)(maze.BoardSize - 1), x, n, Direction.Down);
x += 2;
n++;
}
z = (byte)(maze.BoardSize - 2);
while (z > 0 && z < maze.BoardSize)
{
SetExtraPosition(z, (byte)(maze.BoardSize - 1), n, Direction.Right);
z -= 2;
n++;
}
x = (byte)(maze.BoardSize - 2);
while (x > 0 && x < maze.BoardSize)
{
SetExtraPosition(0, x, n, Direction.Up);
x -= 2;
n++;
}
z = 1;
while (z < maze.BoardSize - 1)
{
SetExtraPosition(z, 0, n, Direction.Left);
z += 2;
n++;
}
}
private bool IsCorner(byte z, byte x, out Direction upDownDirection, out Direction leftRightDirection)
{
if (z == 0 && x == 0)
{
upDownDirection = Direction.Up;
leftRightDirection = Direction.Left;
}
else if (z == 0 && x == maze.BoardSize - 1)
{
upDownDirection = Direction.Up;
leftRightDirection = Direction.Right;
}
else if (z == maze.BoardSize - 1 && x == 0)
{
upDownDirection = Direction.Down;
leftRightDirection = Direction.Left;
}
else if (z == maze.BoardSize - 1 && x == maze.BoardSize - 1)
{
upDownDirection = Direction.Down;
leftRightDirection = Direction.Right;
}
else
{
upDownDirection = (Direction)5;
leftRightDirection = (Direction)5;
}
return (z == 0 || z == maze.BoardSize - 1) && (x == 0 || x == maze.BoardSize - 1);
}
private bool IsMovable(byte z, byte x)
{
if (z % 2 != 0 || x % 2 != 0)
{
return true;
}
else
{
return false;
}
}
private MazeTile CreateTile(byte z, byte x)
{
var pos = new Vector3(x, 0, -z) * maze.Spacing;
var tileObj = Instantiate(
tilePrefab,
maze.transform.position + pos,
Quaternion.identity,
maze.transform);
tileObj.name = $"MazeTile {z} {x}";
var tile = tileObj.GetComponent<MazeTile>();
return tile;
}
private void SetExtraPosition(byte z, byte x, byte n, Direction direction) // direction - направление смещения позиций.
{
switch (direction)
{
//Up
case Direction.Up:
maze.extraPositions[n] = maze.GetTile(z, x).transform.position + new Vector3(0, 0, 1) * maze.Spacing;
break;
//Right
case Direction.Right:
maze.extraPositions[n] = maze.GetTile(z, x).transform.position + new Vector3(1, 0, 0) * maze.Spacing;
break;
//Down
case Direction.Down:
maze.extraPositions[n] = maze.GetTile(z, x).transform.position + new Vector3(0, 0, -1) * maze.Spacing;
break;
//Left
case Direction.Left:
maze.extraPositions[n] = maze.GetTile(z, x).transform.position + new Vector3(-1, 0, 0) * maze.Spacing;
break;
}
}
}
}<file_sep>/README.md
# Maze-Project
Игра-головоломка на 4 игроков с текущим названием Magic Maze, где каждому игроку необходимо собрать определенное число предметов, случайно разбросанных по лабиринту.
# Особенности игры
Стены в лабиринте генерируются случайно каждый раз при запуске игры.
Предметы так же распологаются случайно.
Каждый игрок может двигать стены лабиринта, тем самым открывая новые проходы в нём.
# Как играть
Игра пошаговая. Каждый ход состоит из двух частей - управление лабиринтом и управление игроком.
В первой фазе необходимо выбрать ряд клуток и сдвинуть его, все клетки в этом ряду сместятся на одну, с другой стороны лабиринта выйдет лишняя клетка.
На второй фазе управление переключается на игрока. Когда игрок оказывается на одной клетке с предметом, происходит его сбор.
При сборе всех выделенных игроку предметов он выигрывает. Текущий необходимый для сбора предмет указан в верхнем левом углу.
# Управление
На данный момент управление нельзя изменить.
## Во время управления лабиринтом
W,S - вращение внешней клетки.
A,D - перемещение внешней клетки вокруг лабиринта.
Space - сдвиг ряда и переход к следующей фазе.
## Во время управления игроком
WASD - переход игрока на соседнюю клетку, если между клетками нет стен.
Space - передача хода следующему игроку.
# Развитие проекта
На данный момент проект находится в альфе.
Ближайшие планы - добавить подсвечивание текущего предмета, добавить экран победы, скорректировать генерацию стен, добавить предпросмотр лабиринта после возможного смещения ряда.
| 5e11683836acd9b96020bedeb03d2253b11cee55 | [
"Markdown",
"C#"
] | 16 | C# | Artemko1/Magic-Maze | d04cdc10749db33d47012895486b5feda07988f7 | 159778d7d00ffa9a7ab07bb5f502d6bb38ef8f3c |
refs/heads/master | <repo_name>mmorehea/callielaunch<file_sep>/WVULaunchPad/other/src/parser/ThreeDObject.java
package parser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class ThreeDObject {
private String name;
private ArrayList <double []> vertexes;
private ArrayList <int []> faces;
ThreeDObject(String name){
this.name = name;
vertexes = new ArrayList<double[]>();
faces = new ArrayList<int[]>();
}
void addVertex (double x,double y, double z){
vertexes.add(new double[]{x,y,z});
}
void addFace (int one, int two, int three){
faces.add(new int[]{one,two,three});
}
void lastVert(){
for(Double d: vertexes.get(vertexes.size()))
System.out.print(d.toString()+", ");
System.out.println();
}
void lastFace(){
for(Integer f: faces.get(faces.size()))
System.out.print(f.toString()+", ");
System.out.println();
}
void write(File Directory){
try {
PrintWriter output = new PrintWriter(new File(Directory,name+".obj"));
output.write("#Wavefront .obj model generated by Quinn Jones FileParser\n\n");
output.write("g " + name+"\n\n");
for(double[] vert: vertexes){
output.write("v ");
for(Double d: vert)
output.write(d.toString()+' ');
output.write('\n');
}
output.write('\n');
for(int[] face : faces){
output.write("f ");
for(Integer i : face)
output.write(i.toString()+' ');
output.write('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
<file_sep>/WVULaunchPad/src/cells/CellManager.java
package cells;
import java.util.HashMap;
public class CellManager {
private HashMap<String, Cell> cellBank;
public CellManager(){
cellBank = new HashMap<String, Cell>();
}
}
<file_sep>/WVULaunchPad/src/cells/parts/Axon.java
package cells.parts;
public class Axon extends Part{
public Axon(String filePath){
super.setFilePath(filePath);
super.setType("axon");
}
@Override
public Axon clone(){
return new Axon(super.getFilePath());
}
}
<file_sep>/WVULaunchPad/src/cells/Cell.java
package cells;
import java.util.ArrayList;
import java.util.HashMap;
import cells.parts.Axon;
import cells.parts.Body;
import cells.parts.Dendrite;
import cells.parts.Input;
import cells.parts.Nucleus;
import cells.parts.Part;
public class Cell{
private String name;
private HashMap<String, Part> parts = new HashMap<String, Part>();
private ArrayList<Input> inputs = new ArrayList<Input>();
public Cell(String givenName){
this.name = givenName;
}
//Setters
public void setName(String newName){
this.name = newName;
}
public void setAxon(String filePath){
parts.put("axon", new Axon(filePath));
}
public void setBody(String filePath){
parts.put("body", new Body(filePath));
}
public void setDendrite(String filePath){
parts.put("dendrite", new Dendrite(filePath));
}
public void setNucleus(String filePath){
parts.put("nucleus", new Nucleus(filePath));
}
public void setInputs(String[] filePaths){
inputs = new ArrayList<Input>();
for (String filePath : filePaths){
inputs.add(new Input(filePath));
}
}
public void removeAxon(){
parts.remove("axon");
}
public void removeBody(){
parts.remove("body");
}
public void removeDendrite(){
parts.remove("dendrite");
}
public void removeNucleus(){
parts.remove("nucleus");
}
//Getters
public String getName(){
return name;
}
public String getAxonPath(){
return (parts.get("axon").getFilePath());
}
public String getBodyPath(){
return (parts.get("body").getFilePath());
}
public String getDendritePath(){
return (parts.get("dendrite").getFilePath());
}
public String getNucleusPath(){
return (parts.get("nucleus").getFilePath());
}
public Cell clone(){
Cell clonedCell = new Cell(this.name);
clonedCell.setAxon(parts.get("axon").getFilePath());
clonedCell.setBody(parts.get("body").getFilePath());
clonedCell.setDendrite(parts.get("dendrite").getFilePath());
clonedCell.setNucleus(parts.get("nucleus").getFilePath());
String[] clonedInputPaths = new String[inputs.size()];
for (int i = 0; i < inputs.size(); i++){
clonedInputPaths[i] = inputs.get(i).getFilePath();
}
clonedCell.setInputs(clonedInputPaths);
return null;
}
public String toString(){
String id = name + ":\n\t";
return id;
}
public String toXML(){
return null;
}
}<file_sep>/WVULaunchPad/other/src/parser/WrlParser.java
package parser;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WrlParser implements FileParser {
File filein;
Pattern defPattern;
public WrlParser(String fileName) {
filein = new File(fileName);
defPattern = Pattern.compile("DEF\\s(.+)\\sTransform.*");
}
@Override
public void parse() throws FileNotFoundException {
Scanner input = new Scanner(filein);
ArrayList<ThreeDObject> objects = new ArrayList<ThreeDObject>();
ThreeDObject cObject = null;
boolean first = true;
boolean point = false;
boolean face = false;
while(input.hasNext()){
if(point){
if(input.findInLine("]") == null){
if(input.hasNextDouble())
cObject.addVertex(input.nextDouble(), input.nextDouble(), input.nextDouble());
cObject.lastVert();
}
else
point = false;
}
else if(face){
if(input.findInLine("]")== null){
if(input.hasNextInt())
cObject.addFace(input.nextInt(), input.nextInt(), input.nextInt());
cObject.lastFace();
}
else
face =false;
}
else{
String line = input.nextLine();
System.out.println(line);
Matcher m;
if((m = defPattern.matcher(line)).matches()){
if(!first){
if (cObject != null)
objects.add(cObject);
cObject = new ThreeDObject(m.group(1));
}
else
first = false;
}
else if(line.matches("\\s*point.*")){
point = true;
}
else if(line.matches("\\s*coordIndex.*")){
face = true;
}
}
}
}
}
<file_sep>/WVULaunchPad/src/sets/Set.java
package sets;
import java.util.HashMap;
import cells.Cell;
import cells.CellException;
public class Set {
private String name;
private HashMap<String, Cell> cells = new HashMap<String, Cell>();
public Set(String givenName){
this.name = givenName;
}
public void setName(String newName){
this.name = newName;
}
public String getName(){
return name;
}
public void addCell(String cellName, Cell cell) throws CellException{
if (cells.containsKey(cellName)){
throw new CellException("This set already contains a cell with that name.");
}
else cells.put(cellName, cell.clone());
}
public Cell getCell(String cellName) throws CellException{
if (cells.containsKey(cellName)){
return cells.get(cellName);
}
else throw new CellException("Cannot find the cell: " + cellName);
}
public void removeCell(String cellName) throws CellException{
if (cells.containsKey(cellName)){
cells.remove(cellName);
}
}
}
<file_sep>/WVULaunchPad/src/sets/SetManager.java
package sets;
public class SetManager {
}
| 561c0db4cc587b8ddfc06aa1ee0de9731014bda8 | [
"Java"
] | 7 | Java | mmorehea/callielaunch | f7d2640cc4e8b1508033b75a5452bbb6017ca7a2 | fb6f217ff7b2bc869e78c3792894370c18bc9178 |
refs/heads/master | <file_sep>
let app = {};
app.value = 5;
app.firstFunction = function () {
console.log(app.value);
};
app.secondFunction = function () {
console.log("hellow universe");
}
app.firstFunction();
app.secondFunction(); | 99f30371b3250e730b1e4d3fa6fd5e8e2674095d | [
"JavaScript"
] | 1 | JavaScript | vkyadav998/demo001 | b0c8c3d024add39fa2a8ae38efb28bdc95983fcd | fe0d731111f23ec9122045cbb064c613b3444f17 |
refs/heads/master | <repo_name>davidkatanik/castle-wars<file_sep>/app/src/main/java/davidkatanik/vsb/cz/gameCard/Ability.java
package davidkatanik.vsb.cz.gameCard;
import davidkatanik.vsb.cz.gameUtils.CardTargetTypes;
/**
* Created by <NAME> on 07.11.2015.
*
*/
public class Ability {
private CardTargetTypes targetType;
private int power;
public Ability(CardTargetTypes targetType, int power) {
this.targetType = targetType;
this.power = power;
}
public CardTargetTypes getTargetType() {
return targetType;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
}
<file_sep>/app/src/main/java/davidkatanik/vsb/cz/gameCard/CardMapper.java
package davidkatanik.vsb.cz.gameCard;
import java.util.LinkedList;
import java.util.List;
import davidkatanik.vsb.cz.gameUtils.CardTargetTypes;
import davidkatanik.vsb.cz.gameUtils.CardTypes;
/**
* Created by David on 07.11.2015.
*
*/
public class CardMapper implements ICardMapper {
@Override
public Card mapCard(CardTypes type) {
Card card = null;
switch (type) {
case PLATOON: {
card = mapPlatoon();
card.setType(CardTypes.PLATOON);
break;
}
case RIDER: {
card = mapRider();
card.setType(CardTypes.RIDER);
break;
}
case BANSHEE: {
card = mapBanshee();
card.setType(CardTypes.BANSHEE);
break;
}
case ARCHER: {
card = mapArcher();
card.setType(CardTypes.ARCHER);
break;
}
case SWAT: {
card = mapSwat();
card.setType(CardTypes.SWAT);
break;
}
case CATAPULT: {
card = mapCatapult();
card.setType(CardTypes.CATAPULT);
break;
}
case DRAGON: {
card = mapDragon();
card.setType(CardTypes.DRAGON);
break;
}
case SABOTEUR: {
card = mapSaboteur();
card.setType(CardTypes.SABOTEUR);
break;
}
case CRUSH_BRICKS: {
card = mapCrushBricks();
card.setType(CardTypes.CRUSH_BRICKS);
break;
}
case CRUSH_CRYSTALS: {
card = mapCrushCrystals();
card.setType(CardTypes.CRUSH_CRYSTALS);
break;
}
case CRUSH_WEAPONS: {
card = mapCrushWeapons();
card.setType(CardTypes.CRUSH_WEAPONS);
break;
}
case THIEF: {
card = mapThief();
card.setType(CardTypes.THIEF);
break;
}
case CURSE: {
card = maCurse();
card.setType(CardTypes.CURSE);
break;
}
case WAIN: {
card = mapWain();
card.setType(CardTypes.WAIN);
break;
}
case CONJURE_BRICKS: {
card = mapConjureBrick();
card.setType(CardTypes.CONJURE_BRICKS);
break;
}
case CONJURE_CRYSTALS: {
card = mapConjureCrystals();
card.setType(CardTypes.CONJURE_CRYSTALS);
break;
}
case CONJURE_WEAPONS: {
card = mapConjureWeapons();
card.setType(CardTypes.CONJURE_WEAPONS);
break;
}
case RECRUIT: {
card = mapRecruit();
card.setType(CardTypes.RECRUIT);
break;
}
case SCHOOL: {
card = mapSchool();
card.setType(CardTypes.SCHOOL);
break;
}
case SORCERER: {
card = mapSorcerer();
card.setType(CardTypes.SORCERER);
break;
}
case PIXIES: {
card = mapPixies();
card.setType(CardTypes.PIXIES);
break;
}
case BABYLON: {
card = mapBabylon();
card.setType(CardTypes.BABYLON);
break;
}
case FENCE: {
card = mapFence();
card.setType(CardTypes.FENCE);
break;
}
case DEFENCE: {
card = mapDefence();
card.setType(CardTypes.DEFENCE);
break;
}
case FORT: {
card = mapFort();
card.setType(CardTypes.FORT);
break;
}
case TOWER: {
card = mapTower();
card.setType(CardTypes.TOWER);
break;
}
case BASE: {
card = mapBase();
card.setType(CardTypes.BASE);
break;
}
case WALL: {
card = mapWall();
card.setType(CardTypes.WALL);
break;
}
case RESERVE: {
card = mapReserve();
card.setType(CardTypes.RESERVE);
break;
}
}
return card;
}
private Card mapAttack(CardTargetTypes target, int power, CardTargetTypes resource, int stock) {
Card card = new Card();
Ability ability = new Ability(target, power);
card.getAbilities().add(ability);
card.setAffectHome(false);
card.setTransactional(false);
Ability resources = new Ability(resource, stock);
card.setNeededResources(resources);
return card;
}
private Card mapResources(CardTargetTypes target, int power, CardTargetTypes resource, int stock) {
Card card = new Card();
Ability ability = new Ability(target, power);
card.getAbilities().add(ability);
card.setAffectHome(true);
card.setTransactional(false);
Ability resources = new Ability(resource, stock);
card.setNeededResources(resources);
return card;
}
private Card mapPlatoon() {
return mapAttack(CardTargetTypes.CASTLE, 6, CardTargetTypes.WEAPONS, 4);
}
private Card mapRider() {
return mapAttack(CardTargetTypes.CASTLE, 4, CardTargetTypes.WEAPONS, 2);
}
private Card mapBanshee() {
return mapAttack(CardTargetTypes.CASTLE, 32, CardTargetTypes.WEAPONS, 28);
}
private Card mapArcher() {
return mapAttack(CardTargetTypes.CASTLE, 2, CardTargetTypes.WEAPONS, 1);
}
private Card mapSwat() {
return mapAttack(CardTargetTypes.CASTLE, 10, CardTargetTypes.WEAPONS, 18);
}
private Card mapCatapult() {
return mapAttack(CardTargetTypes.CASTLE, 12, CardTargetTypes.WEAPONS, 10);
}
private Card mapDragon() {
return mapAttack(CardTargetTypes.CASTLE, 25, CardTargetTypes.WEAPONS, 21);
}
private Card mapCrushBricks() {
return mapAttack(CardTargetTypes.BRICKS, 8, CardTargetTypes.CRYSTALS, 4);
}
private Card mapCrushCrystals() {
return mapAttack(CardTargetTypes.CRYSTALS, 8, CardTargetTypes.CRYSTALS, 4);
}
private Card mapCrushWeapons() {
return mapAttack(CardTargetTypes.WEAPONS, 8, CardTargetTypes.CRYSTALS, 4);
}
private Card mapSaboteur() {
Card card = new Card();
Ability ability = new Ability(CardTargetTypes.CRYSTALS, 4);
Ability ability2 = new Ability(CardTargetTypes.WEAPONS, 4);
Ability ability3 = new Ability(CardTargetTypes.BRICKS, 4);
card.getAbilities().add(ability);
card.getAbilities().add(ability2);
card.getAbilities().add(ability3);
card.setAffectHome(false);
card.setTransactional(false);
Ability resources = new Ability(CardTargetTypes.WEAPONS, 12);
card.setNeededResources(resources);
return card;
}
private Card mapThief() {
Card card = new Card();
Ability ability = new Ability(CardTargetTypes.CRYSTALS, 5);
Ability ability2 = new Ability(CardTargetTypes.WEAPONS, 5);
Ability ability3 = new Ability(CardTargetTypes.BRICKS, 5);
card.getAbilities().add(ability);
card.getAbilities().add(ability2);
card.getAbilities().add(ability3);
card.setAffectHome(false);
card.setTransactional(true);
Ability resources = new Ability(CardTargetTypes.WEAPONS, 15);
card.setNeededResources(resources);
return card;
}
private Card maCurse() {
Card card = new Card();
List<Ability> abilities = new LinkedList<>();
abilities.add(new Ability(CardTargetTypes.BUILDERS, 1));
abilities.add(new Ability(CardTargetTypes.BRICKS, 1));
abilities.add(new Ability(CardTargetTypes.SOLDIERS, 1));
abilities.add(new Ability(CardTargetTypes.WEAPONS, 1));
abilities.add(new Ability(CardTargetTypes.MAGI, 1));
abilities.add(new Ability(CardTargetTypes.CRYSTALS, 1));
abilities.add(new Ability(CardTargetTypes.CASTLE, 100));
abilities.add(new Ability(CardTargetTypes.FENCE, 1));
card.getAbilities().addAll(abilities);
card.setAffectHome(false);
card.setTransactional(true);
Ability resources = new Ability(CardTargetTypes.CRYSTALS, 25);
card.setNeededResources(resources);
return card;
}
private Card mapWain() {
Card card = new Card();
Ability ability = new Ability(CardTargetTypes.CASTLE, 40);
card.getAbilities().add(ability);
card.setAffectHome(false);
card.setTransactional(true);
Ability resources = new Ability(CardTargetTypes.BRICKS, 10);
card.setNeededResources(resources);
return card;
}
private Card mapConjureBrick() {
return mapResources(CardTargetTypes.BRICKS, 8, CardTargetTypes.CRYSTALS, 4);
}
private Card mapConjureCrystals() {
return mapResources(CardTargetTypes.CRYSTALS, 8, CardTargetTypes.CRYSTALS, 4);
}
private Card mapConjureWeapons() {
return mapResources(CardTargetTypes.WEAPONS, 8, CardTargetTypes.CRYSTALS, 4);
}
private Card mapRecruit() {
return mapResources(CardTargetTypes.SOLDIERS, 1, CardTargetTypes.WEAPONS, 8);
}
private Card mapSchool() {
return mapResources(CardTargetTypes.BUILDERS, 1, CardTargetTypes.BRICKS, 8);
}
private Card mapSorcerer() {
return mapResources(CardTargetTypes.MAGI, 1, CardTargetTypes.CRYSTALS, 8);
}
private Card mapPixies() {
return mapResources(CardTargetTypes.CASTLE, 22, CardTargetTypes.CRYSTALS, 22);
}
private Card mapBabylon() {
return mapResources(CardTargetTypes.CASTLE, 32, CardTargetTypes.BRICKS, 39);
}
private Card mapFence() {
return mapResources(CardTargetTypes.FENCE, 22, CardTargetTypes.BRICKS, 12);
}
private Card mapDefence() {
return mapResources(CardTargetTypes.FENCE, 6, CardTargetTypes.BRICKS, 3);
}
private Card mapFort() {
return mapResources(CardTargetTypes.CASTLE, 20, CardTargetTypes.BRICKS, 18);
}
private Card mapTower() {
return mapResources(CardTargetTypes.CASTLE, 5, CardTargetTypes.BRICKS, 5);
}
private Card mapBase() {
return mapResources(CardTargetTypes.CASTLE, 2, CardTargetTypes.BRICKS, 1);
}
private Card mapWall() {
return mapResources(CardTargetTypes.FENCE, 3, CardTargetTypes.BRICKS, 1);
}
private Card mapReserve() {
Card card = new Card();
Ability ability = new Ability(CardTargetTypes.FENCE, 4);
Ability ability2 = new Ability(CardTargetTypes.CASTLE, 8);
card.getAbilities().add(ability);
card.getAbilities().add(ability2);
card.setAffectHome(true);
card.setTransactional(false);
Ability resources = new Ability(CardTargetTypes.BRICKS, 3);
card.setNeededResources(resources);
return card;
}
}
<file_sep>/app/src/main/java/davidkatanik/vsb/cz/dbStatistics/StatisticsUnit.java
package davidkatanik.vsb.cz.dbStatistics;
/**
* Created by David on 12.12.2015.
*/
public class StatisticsUnit {
Integer id;
String homePlayer;
String awayPlayer;
String date;
String homeScore;
String awayScore;
Integer rounds;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHomePlayer() {
return homePlayer;
}
public void setHomePlayer(String homePlayer) {
this.homePlayer = homePlayer;
}
public String getAwayPlayer() {
return awayPlayer;
}
public void setAwayPlayer(String awayPlayer) {
this.awayPlayer = awayPlayer;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getHomeScore() {
return homeScore;
}
public void setHomeScore(String homeScore) {
this.homeScore = homeScore;
}
public String getAwayScore() {
return awayScore;
}
public void setAwayScore(String awayScore) {
this.awayScore = awayScore;
}
public Integer getRounds() {
return rounds;
}
public void setRounds(Integer rounds) {
this.rounds = rounds;
}
}
<file_sep>/README.md
# castle-wars
Nice strategic android game in Czech langage
<file_sep>/app/src/main/java/davidkatanik/vsb/cz/dbStatistics/StatisticsAdapter.java
package davidkatanik.vsb.cz.dbStatistics;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import davidkatanik.vsb.cz.castlewars2.R;
/**
* Created by David on 12.12.2015.
*/
public class StatisticsAdapter extends ArrayAdapter<StatisticsUnit> {
private final Context context;
private final List<StatisticsUnit> values;
public StatisticsAdapter(Context context, List<StatisticsUnit> values) {
super(context, R.layout.activity_statistics_unit, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_statistics_unit, parent, false);
StatisticsUnit su = values.get(position);
((TextView) rowView.findViewById(R.id.tvHomePlayerStat)).setText(su.getHomePlayer());
((TextView) rowView.findViewById(R.id.tvAwayPlayerStat)).setText(su.getAwayPlayer());
((TextView) rowView.findViewById(R.id.tvHomeScoreStat)).setText(su.getHomeScore());
((TextView) rowView.findViewById(R.id.tvAwayScoreStat)).setText(su.getAwayScore());
((TextView) rowView.findViewById(R.id.tvDateStat)).setText(su.getDate());
((TextView) rowView.findViewById(R.id.tvRoundsStat)).setText(su.getRounds().toString());
return rowView;
}
}
<file_sep>/app/src/main/java/davidkatanik/vsb/cz/castlewarsActivities/MultiplayerActivity.java
package davidkatanik.vsb.cz.castlewarsActivities;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import davidkatanik.vsb.cz.gameUtils.CardTypes;
import davidkatanik.vsb.cz.gameCard.Card;
import davidkatanik.vsb.cz.castlewars2.R;
import davidkatanik.vsb.cz.fragments.CardFragment;
import davidkatanik.vsb.cz.fragments.PlayerProperties.OnFragmentInteractionListener;
import davidkatanik.vsb.cz.dbStatistics.Statistics;
import davidkatanik.vsb.cz.dialogs.SettingsDialog;
import davidkatanik.vsb.cz.dialogs.StatisticsDialog;
import davidkatanik.vsb.cz.game.Game;
import davidkatanik.vsb.cz.game.Player;
public class MultiplayerActivity extends Activity implements OnFragmentInteractionListener, CardFragment.OnFragmentInteractionListener, SettingsDialog.OnFragmentInteractionListener, StatisticsDialog.OnFragmentInteractionListener {
private final float INITIAL_VOLUME = (float) 0.5;
private Game game;
private List<ImageButton> cards;
private View frRed;
private View frBlue;
private View frCards;
private DialogFragment soundDialog;
private MediaPlayer mpMusic = null;
private MediaPlayer mpCards = null;
private SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
private void loadPlayerIndicator(Player actualPlayer) {
if (game.isPlayerHome(actualPlayer)) {
(findViewById(R.id.ivActualPlayerColor)).setBackgroundColor(Color.RED);
} else {
(findViewById(R.id.ivActualPlayerColor)).setBackgroundColor(Color.BLUE);
}
}
private void loadPlayersProperties() {
loadPlayerProperties(frRed, game.getRed());
loadPlayerProperties(frBlue, game.getBlue());
}
private void loadPlayerProperties(View view, Player player) {
((TextView) view.findViewById(R.id.tvBuilders)).setText(player.getBuilders() + "");
((TextView) view.findViewById(R.id.tvBricks)).setText(player.getBricks() + "");
((TextView) view.findViewById(R.id.tvSoldiers)).setText(player.getSoldiers() + "");
((TextView) view.findViewById(R.id.tvWeapons)).setText(player.getWeapons() + "");
((TextView) view.findViewById(R.id.tvMagi)).setText(player.getMagi() + "");
((TextView) view.findViewById(R.id.tvCrystals)).setText(player.getCrystals() + "");
((TextView) view.findViewById(R.id.tvCastle)).setText(player.getCastle() + "");
((TextView) view.findViewById(R.id.tvFence)).setText(player.getFence() + "");
}
private void loadPlayerCards(Player player) {
for (int i = 0; i < player.getCards().size(); i++) {
Card c = player.getCards().get(i);
String s;
if (game.checkIsAvailable(c)) {
s = c.getType().toString().toLowerCase();
} else {
s = c.getType().toString().toLowerCase() + "x";
}
int resID = getResources().getIdentifier(s, "drawable", getPackageName());
try {
cards.get(i).setImageDrawable(this.getDrawable(resID));
} catch (Resources.NotFoundException e) {
Log.e("Error in card loading:", resID + "");
}
}
}
private void loadPlayersCastleAndWall() {
ImageView hCastle = (ImageView) findViewById(R.id.ivHCastle);
ImageView hFence = (ImageView) findViewById(R.id.ivHFence);
ImageView eCastle = (ImageView) findViewById(R.id.ivECastle);
ImageView eFence = (ImageView) findViewById(R.id.ivEFence);
Player red = game.getRed();
Player blue = game.getBlue();
float scale = getResources().getDisplayMetrics().density;
int paddingPixel = (int) (380 - 2.5 * red.getCastle());
int paddingDp = (int) (paddingPixel * scale);
hCastle.setPadding(0, paddingDp, 0, 0);
paddingPixel = 400 - 3 * red.getFence();
paddingDp = (int) (paddingPixel * scale);
hFence.setPadding(0, paddingDp, 0, 0);
paddingPixel = (int) (380 - 2.5 * blue.getCastle());
paddingDp = (int) (paddingPixel * scale);
eCastle.setPadding(0, paddingDp, 0, 0);
paddingPixel = 400 - 3 * blue.getFence();
paddingDp = (int) (paddingPixel * scale);
eFence.setPadding(0, paddingDp, 0, 0);
}
private void loadUsedCard(Card card) {
try {
((ImageView) findViewById(R.id.ivLastCard)).setImageDrawable(this.getDrawable(getResources().getIdentifier(card.getType().toString().toLowerCase(), "drawable", getPackageName())));
} catch (Resources.NotFoundException e) {
Log.e("Error in loading:", "Used card loading");
}
}
private void initCardsButtons() {
cards = new ArrayList<>();
cards.add((ImageButton) frCards.findViewById(R.id.ibC1));
cards.add((ImageButton) frCards.findViewById(R.id.ibC2));
cards.add((ImageButton) frCards.findViewById(R.id.ibC3));
cards.add((ImageButton) frCards.findViewById(R.id.ibC4));
cards.add((ImageButton) frCards.findViewById(R.id.ibC5));
cards.add((ImageButton) frCards.findViewById(R.id.ibC6));
}
private void makeWinnerSound() {
MediaPlayer mp = MediaPlayer.create(this, R.raw.aplaus);
float x = sharedPreferences.getFloat("sound", INITIAL_VOLUME);
mp.setVolume(x, x);
mp.start();
}
private void makeSound(Card card) {
CardTypes type = card.getType();
if (mpCards != null)
mpCards.release();
if (type == CardTypes.PLATOON || type == CardTypes.RIDER || type == CardTypes.DRAGON || type == CardTypes.ARCHER || type == CardTypes.CATAPULT || type == CardTypes.BANSHEE || type == CardTypes.WAIN) {
mpCards = MediaPlayer.create(this, (game.getActualPlayer().getFence() >= card.getAbilities().get(0).getPower()) ? R.raw.low_fence : R.raw.low_castle);
} else if (type == CardTypes.RECRUIT || type == CardTypes.SCHOOL || type == CardTypes.SORCERER) {
mpCards = MediaPlayer.create(this, R.raw.high_strenght);
} else if (type == CardTypes.SABOTEUR || type == CardTypes.CRUSH_BRICKS || type == CardTypes.CRUSH_CRYSTALS || type == CardTypes.CRUSH_WEAPONS) {
mpCards = MediaPlayer.create(this, R.raw.low_stock);
} else if (type == CardTypes.BASE || type == CardTypes.BABYLON || type == CardTypes.PIXIES || type == CardTypes.FORT || type == CardTypes.RESERVE || type == CardTypes.TOWER) {
mpCards = MediaPlayer.create(this, R.raw.high_castle);
} else if (type == CardTypes.FENCE || type == CardTypes.WALL || type == CardTypes.DEFENCE) {
mpCards = MediaPlayer.create(this, R.raw.high_fence);
} else if (type == CardTypes.THIEF || type == CardTypes.CONJURE_BRICKS || type == CardTypes.CONJURE_CRYSTALS || type == CardTypes.CONJURE_WEAPONS) {
mpCards = MediaPlayer.create(this, R.raw.high_stock);
} else if (type == CardTypes.CURSE) {
mpCards = MediaPlayer.create(this, R.raw.course);
} else if (type == CardTypes.SWAT) {
mpCards = MediaPlayer.create(this, R.raw.low_castle);
} else {
return;
}
float x = sharedPreferences.getFloat("sound",INITIAL_VOLUME);
mpCards.setVolume(x, x);
mpCards.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multi_player);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
frRed = findViewById(R.id.frRedPlayer);
frBlue = findViewById(R.id.frBluePlayer);
frCards = findViewById(R.id.frCards);
initCardsButtons();
initGame();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
soundDialog = new SettingsDialog();
mpMusic = MediaPlayer.create(this, R.raw.adrian_von_ziegler_android);
float x = sharedPreferences.getFloat("music",INITIAL_VOLUME);
mpMusic.setVolume(x, x);
mpMusic.start();
}
private void initGame() {
game = new Game("", "");
loadPlayerIndicator(game.getActualPlayer());
loadPlayerCards(game.getActualPlayer());
loadPlayersProperties();
loadPlayersCastleAndWall();
}
public void onCardClick(View v) {
if (game.checkWinner() != null) {
return;
}
int cardPosition = 0;
if (v.getId() == R.id.ibC1) {
cardPosition = 0;
} else if (v.getId() == R.id.ibC2) {
cardPosition = 1;
} else if (v.getId() == R.id.ibC3) {
cardPosition = 2;
} else if (v.getId() == R.id.ibC4) {
cardPosition = 3;
} else if (v.getId() == R.id.ibC5) {
cardPosition = 4;
} else if (v.getId() == R.id.ibC6) {
cardPosition = 5;
}
Card card = game.getActualPlayer().getCards().get(cardPosition);
boolean avilible = false;
if (game.checkIsAvailable(card)) {
makeSound(game.getActualPlayer().getCards().get(cardPosition));
makeVibration();
avilible = true;
}
game.nextMove(card);
if (avilible)
loadUsedCard(card);
loadPlayersProperties();
loadPlayersCastleAndWall();
if (game.checkWinner() != null) {
makeWinnerSound();
StatisticsDialog statisticsDialog = new StatisticsDialog();
statisticsDialog.show(getFragmentManager(), "statistics");
return;
}
loadPlayerIndicator(game.getActualPlayer());
loadPlayerCards(game.getActualPlayer());
}
private void makeVibration() {
boolean vibrations = sharedPreferences.getBoolean("vibrations", false);
if (vibrations) {
Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
}
}
public void onClickPause(View v) {
soundDialog.show(getFragmentManager(), "sound settings");
}
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public void onMusicProgressChanged(float progress) {
mpMusic.setVolume(progress,progress);
edit = sharedPreferences.edit();
edit.putFloat("music", progress);
edit.apply();
}
@Override
public void onSoundProgressChanged(float progress) {
if (mpCards != null){
mpCards.setVolume(progress,progress);
}
edit = sharedPreferences.edit();
edit.putFloat("sound", progress);
edit.apply();
}
@Override
public void onVibrationsCheckChanged(boolean isChecked) {
edit = sharedPreferences.edit();
edit.putBoolean("vibrations", isChecked);
edit.apply();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mpCards != null)
mpCards.release();
if (mpMusic != null)
mpMusic.release();
}
@Override
protected void onPause() {
super.onPause();
if (mpMusic != null)
mpMusic.pause();
}
@Override
protected void onResume() {
super.onResume();
if (mpMusic != null)
mpMusic.start();
}
@Override
public void onStatisticsSet(String redPlayer, String bluePlayer) {
Statistics statistics = new Statistics(this);
statistics.insertStatistics(redPlayer, bluePlayer, game.getRed().getCastle(), game.getBlue().getCastle(), game.getRound());
Intent i = new Intent(this, MainMenuActivity.class);
startActivity(i);
}
}
<file_sep>/app/src/main/java/davidkatanik/vsb/cz/castlewarsActivities/MainMenuActivity.java
package davidkatanik.vsb.cz.castlewarsActivities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.Multiplayer;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.turnbased.OnTurnBasedMatchUpdateReceivedListener;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatch;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig;
import java.util.ArrayList;
import davidkatanik.vsb.cz.castlewars2.R;
import davidkatanik.vsb.cz.dbStatistics.Statistics;
import davidkatanik.vsb.cz.game.Game;
public class MainMenuActivity extends Activity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean("vibrations", true);
edit.apply();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnMultiplayer) {
Intent intent = new Intent(this, MultiplayerActivity.class);
startActivity(intent);
}
if (v.getId() == R.id.btnSettings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
if (v.getId() == R.id.btnAbout) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://homel.vsb.cz/~kat0013/tamz2/"));
startActivity(intent);
}
if (v.getId() == R.id.btnStatistics) {
Intent intent = new Intent(this, StatisticsActivity.class);
startActivity(intent);
}
}
}
| ff3304dd03cc9a93680da93e30d745705d8d6f39 | [
"Markdown",
"Java"
] | 7 | Java | davidkatanik/castle-wars | a4f26c4d677a0e9a6c936a16475ff071831f141c | 542543d114eb9ddf62c7880404cd0bc3ec415c30 |
refs/heads/master | <repo_name>TaniaLucero/t1tlgr<file_sep>/app/src/main/java/mx/edu/tesoem/isc/tlgr/t1tlgr/SumaActivity.java
package mx.edu.tesoem.isc.tlgr.t1tlgr;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class SumaActivity extends AppCompatActivity {
EditText valor1, valor2;
TextView res;
float num1,num2,num3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suma);
valor1=(EditText)findViewById(R.id.valor1s);
valor2=(EditText)findViewById(R.id.valor2s);
}
public void suma (View view)
{
if((valor1.getText().toString().equals(""))&&(valor2.getText().toString().equals("")))
{
res=(TextView) findViewById(R.id.txtres);
valor1.setText("0.0");
valor2.setText("0.0");
res.setText("Resultado: 0");
}
else if((valor1.getText().toString().equals(""))&&(!valor2.getText().toString().equals("")))
{
num2=Float.parseFloat(valor2.getText().toString());
valor1.setText("0.0");
res=(TextView) findViewById(R.id.txtres);
res.setText("Resultado: "+num2);
}
else if((valor2.getText().toString().equals(""))&&(!valor1.getText().toString().equals("")))
{
num1=Float.parseFloat(valor1.getText().toString());
valor2.setText("0.0");
res=(TextView) findViewById(R.id.txtres);
res.setText("Resultado: "+num1);
}
else
{
num1=Float.parseFloat(valor1.getText().toString());
num2=Float.parseFloat(valor2.getText().toString());
num3=num1+num2;
res=(TextView) findViewById(R.id.txtres);
res.setText("Resultado: "+num3);
}
}
}
| 82e108d61b7fda2234aa4c443c2bd2e5db6713d8 | [
"Java"
] | 1 | Java | TaniaLucero/t1tlgr | a1d03996495dbf39e801ae9db98849a3c895db71 | f2cf93980a5c2afb4157f04830038e0eebb50bb8 |
refs/heads/master | <file_sep>#!/usr/bin/env python
"""
Author: <NAME> (<ryan ATSIGN ryanrat.com>)
check_jsrx_session.py
Last-Modified: 2016-12-12
Version 0.1.1
get_session.py was originally intended to pull a specific session from the Juniper SRX Firewall
via PYEZ from a Nagios host. The script relies upon version 2.7 of Python, although earlier
versions may also work.
Example:
python check_jsrx_session.py myfirewall.corp.com
Will return all sessions in the firewall in a pretty print format.
python check_jsrx_session.py myfirewall.corp.com --src_address x.x.x.x --dst_address y.y.y.y
--dst_port 80 --protocol tcp
Will return all sessions that match specified criteria.
python check_jsrx_session.py myfirewall.corp.com --src_address x.x.x.x --dst_address y.y.y.y
--dst_port 80 --protocol tcp --nagios_bytes
Will return all sessions that match specified criteria, but evaluate
only the first match in a Nagios output format.
Output Example:
SESSION OK - Session ID 31432 | bytes_in=17515 bytes_out=4786 configured_timeout=43200
timeout=43094
python check_jsrx_session.py --username XXXXXX --password <PASSWORD>
Will return all sessions, but leverage a username and password in lieu of SSH keys.
python check_jsrx_session.py myfirewall.corp.com --src_address x.x.x.x --dst_address y.y.y.y
--dst_port 80 --protocol tcp --nagios_bytes --debug
Will return all sessions that match the specified critera, and also show the facts and
session parameters sent to the SRX.
Output Exmaple:
{ '2RE': True,
'HOME': '/cf/var/home/user',
'RE0': { 'last_reboot_reason': '0x1:power cycle/failure',
'model': 'RE-SRX210HE2',
'status': 'OK',
'up_time': '12 days, 19 hours, 35 minutes, 44 seconds'},
'RE1': { 'last_reboot_reason': '0x1:power cycle/failure',
'model': 'RE-SRX210HE2',
'status': 'OK',
'up_time': '12 days, 19 hours, 18 minutes, 48 seconds'},
'RE_hw_mi': True,
...
...
{ 'destination_port': '80',
'destination_prefix': 'x.x.x.x',
'protocol': 'tcp',
'source_prefix': 'y.y.y.y'}
OK - Session ID 31539 | bytes_in=3884785;bytes_out=3843606;;"""
import sys
import argparse
import xml.etree.ElementTree as ET
import pprint
from lxml import etree
from jnpr.junos import Device
from jnpr.junos.exception import ConnectError
# Since the SRX returns XML data, we parse the XML using etree, and place the corresponding data
# session elements inside a dictionary. We then also parse each flow or wing element of the
# session and add it to the dictionary. In order to distinguish between 'in' and 'out' wings, we
# prepend the dictionary with the 'direction' element of the wing, thus giving us a unique key for
# the flow.
def get_session(source_ip, destination_ip, destination_port, protocol, device,
username, password, debug):
"""
get_session returns a list of dictionary items that contain Juniper SRX session data based upon
the input criteria given. device is the only mandatory field for this, as if no other options are
specified, all sessions will be returned. if the SRX is clustered, Backup sessions from the
passive device are not included in the list. Netconf must be enabled on the firewall.
"""
if (username and password) != None:
dev = Device(host=device, user=username, password=<PASSWORD>)
else:
dev = Device(host=device)
try:
dev.open()
if debug:
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(dev.facts)
except ConnectError as err:
print "Cannot connect to device: {0}".format(err)
sys.exit(1)
flow_args = {}
if source_ip != None:
flow_args['source_prefix'] = source_ip
if destination_ip != None:
flow_args['destination_prefix'] = destination_ip
if destination_port != None:
flow_args['destination_port'] = destination_port
if protocol != None:
flow_args['protocol'] = protocol
flow_request = dev.rpc.get_flow_session_information(**flow_args)
if debug:
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(flow_args)
dev.close()
root = ET.fromstring(etree.tostring(flow_request))
session_list = []
for session in root.findall('./multi-routing-engine-item/\
flow-session-information/flow-session'):
session_state = session.find('session-state')
session_identifier = session.find('session-identifier')
policy = session.find('policy')
configured_timeout = session.find('configured-timeout')
timeout = session.find('timeout')
start_time = session.find('start-time')
duration = session.find('duration')
session_dict = {'session-id' : session_identifier.text,\
'session-state' : session_state.text, 'policy' : policy.text, 'timeout' : timeout.text,\
'start-time' : start_time.text, 'duration' : duration.text,
'configured-timeout' : configured_timeout.text}
for flow in session.findall('./flow-information'):
direction = flow.find('direction')
source_address = flow.find('source-address')
destination_address = flow.find('destination-address')
source_port = flow.find('source-port')
destination_port = flow.find('destination-port')
protocol = flow.find('protocol')
byte_count = flow.find('byte-cnt')
session_dict.update({direction.text + ':source-address' :\
source_address.text, direction.text + ':destination-address' :\
destination_address.text, direction.text + ':source_port' :\
source_port.text, direction.text + ':destination-port' :\
destination_port.text, direction.text + ':protocol' :\
protocol.text, direction.text + ':byte-count' : byte_count.text})
if session_state.text == 'Active':
session_list.append(session_dict.copy())
return session_list
def main(argv):
"""
Main declares a standard parser and passes the arguments to get_session. Once
the output is returned back to main, we evaluate if args.nagios is being used,
and if so, it returns output that will allow Nagios to evaluate the health of
the service, and also pass perf data after the '|' (pipe) delimiter. If Nagios
is not specified, the main function returns a pretty printed version of the
session data.
"""
parser = argparse.ArgumentParser()
nagiosGroup = parser.add_mutually_exclusive_group()
parser.add_argument("device", help="Specify the hostname or IP address of your Juniper SRX")
parser.add_argument("--src_address", help="Source address or prefix of desired session(s)")
parser.add_argument("--dst_address", help="Destination address or prefix of desired session(s)"\
)
parser.add_argument("--dst_port", help="Destination port of desired session(s)")
parser.add_argument("--protocol", help="TCP or UDP, or any supported SRX protocol")
nagiosGroup.add_argument("--nagios_bytes", dest="nagios_bytes", action="store_true",\
help="Nagios formatted output to return byte counts")
nagiosGroup.add_argument("--nagios_timeouts", dest="nagios_timeouts", action="store_true",\
help="Nagios formatted output to return session timeouts")
parser.add_argument("--username", help="Username to firewall, in the event ssh-keys are not\
available")
parser.add_argument("--password", help="<PASSWORD> to firewall, in the event ssh-keys are not\
available")
parser.add_argument("--debug", dest="debug", action="store_true", help="Debug connection and\
flow information")
args = parser.parse_args()
session = get_session(args.src_address, args.dst_address, args.dst_port, args.protocol,\
args.device, args.username, args.password, args.debug)
if args.nagios_bytes:
if len(session) == 0:
print 'CRITICAL - No session found'
sys.exit(2)
print 'OK - Session ID ' + session[0].get('session-id') + ' | bytes_in=' + session[0].get\
('In:byte-count') + ';bytes_out=' + session[0].get('Out:byte-count')+ ';;'
print 'Policy=' + session[0].get('policy') + ' Source=' + session[0].get\
('In:source-address') + ' Destination=' + session[0].get('In:destination-address') + \
' DestinationPort=' + session[0].get('In:destination-port')
(sys.exit(0))
elif args.nagios_timeouts:
if len(session) == 0:
print 'CRITICAL - No session found'
sys.exit(2)
print 'OK - Session ID ' + session[0].get('session-id') + ' | configured_timeout=' +\
session[0].get('configured-timeout') + ';timeout=' + session[0].get('timeout') + ';;'
print 'Policy=' + session[0].get('policy') + ' Source=' + session[0].get\
('In:source-address') + ' Destination=' + session[0].get('In:destination-address') + \
' DestinationPort=' + session[0].get('In:destination-port')
(sys.exit(0))
else:
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(session)
if __name__ == "__main__":
main(sys.argv[1:])
| bd879ca45c0eb78f1fb9feda296fffe85b0a9549 | [
"Python"
] | 1 | Python | rratkiewicz/check_jsrx_session.py | 58d05a1561917ceedf07de04361e2369a6d86dd7 | f72c4e012145a01abb3c8b01855742a7209d1479 |
refs/heads/master | <repo_name>sophieannebourgine/project2-aida-sa<file_sep>/public/scripts/cart inspire.js
// const btnBasket = document.getElementById("fa-shopping-cart");
// const addToCart = document.getElementById("btn_add_cart");
// const elementQty = document.getElementById("product-qty");
// const cartBtn = document.getElementById("checkout");
// addToCart.onclick = evt => {
// // const elementQty = document.getElementById ("product-qty");
// var currentCart = {
// nbItems: 0,
// totalPrice: 0,
// productsInKart: []
// };
// evt.preventDefault();
// const elementRef = document.getElementById("product-ref");
// const elementPrice = document.getElementById("product-price");
// const productSize = document.getElementById("main-size");
// const productId = document.getElementById("one-product");
// const productName = document.getElementById("product-name");
// const productImg = document.getElementById("product-img");
// currentCart.nbItems += 1;
// currentCart.totalPrice += Number(elementPrice.innerHTML.replace(" €", ""));
// };
// const cartBtn = document.getElementById("checkout");
// const cartDetails = document.getElementById("cart-details");
// const recapCart = document.getElementById("cart-small-summary");
// // evt.preventDefault();
// // console.log("recap cart");
// // console.log(recapCart)
// if (localStorage.getItem("currentCart")){
// var checkedOutCart = JSON.parse(localStorage.getItem("currentCart"));
// var cartProducts = checkedOutCart.productsInKart;
// recapCart.innerHTML = [nb items : ${checkedOutCart.nbItems} | ${checkedOutCart.totalPrice} €]
// cartDetails.innerHTML = "";
// cartProducts.forEach(food => {
// cartDetails.innerHTML +=`
// <div class="one-product-cart">
// <div class="product-img">
// <img src="${food.image}" alt="what a nice pair of kicks">
// </div>
// <div>
// <p class="product-name">${food.name}</p>
// <p class="product-size">Size: ${food.ref}</p>
// <label for="product-qty">Quantity</label>
// <div class ="product-qty" id = "product-qty">
// <input type="number" value="${food.stock}">
// </div>
// <p class="product-price">Total: ${Number(food.price)*Number(food.stock)} €</p>
// </div>
// </div>`
// });
// }
<file_sep>/public/scripts/cart.js
// const foodModel = require("../models/food");
// const cartModel = require("../models/Cart");
const ironCart = (function() {
"use strict";
function updateCart() {
console.log("clicked");
// nombre d'article dans le panier
const cartCount = Number(
document.getElementById("quantity-total").textContent
);
// sélection de la qantité d'un produit
const valToAdd = Number(document.getElementById("main_qty").value);
//addition de la quantité ajouté et de celle présente dans le panier
const newQty = cartCount + valToAdd;
const prodId = document.getElementById("prod_id").value;
document.getElementById("quantity-total").textContent = newQty;
updateDatabase(prodId, valToAdd);
}
// function totalPrice() {
// var priceElement = document.getElementsByClassName("price_cart");
// var totalQtyElement = document.getElementsByClassName("qty_cart");
// var priceValue = Number(priceElement.textContent.split("")[1]);
// var qtyValue = totalQtyElement.textContent.split("");
// console.log(priceValue);
// console.log(qtyValue[qtyValue.length - 1]);
// var total = priceValue * Number(qtyValue[qtyValue.length - 1]);
// console.log("total", total);
// return total;
// }
// console.log(totalPrice);
// totalPrice();
function updateDatabase(prodId, qty) {
axios
.patch("/cart", { prodId, qty })
.then(APIRes => {
console.log(APIRes);
})
.catch(APIErr => {
console.error(APIErr);
});
}
function start() {
console.log(document.getElementById("btn_add_cart"));
document.getElementById("btn_add_cart").onclick = updateCart;
}
return { start };
})();
window.addEventListener("DOMContentLoaded", ironCart.start);
// .populate
<file_sep>/bin/seed.js
const foodModel = require("../models/food");
const products = require("./products.json");
console.log(products);
function insertProducts() {
foodModel
.insertMany(products)
.then(dbRes => console.log(dbRes))
.catch(dbErr => console.log(dbErr));
}
function deleteAllProducts() {
foodModel
.remove()
.then(dbRes => console.log(dbRes))
.catch(dbErr => console.log(dbErr));
}
// run this file ONCE with : node bin/seed.js
insertProducts(products); // add all products
// deleteAllProducts(); // remove all products
<file_sep>/routes/auth.js
const express = require("express");
const router = new express.Router();
const bcrypt = require("bcrypt");
const bcryptSalt = 10;
const User = require("../models/User");
const Cart = require("../models/Cart");
//------ SIGN UP
router.get("/signup", (req, res, next) => {
res.render("signup");
});
router.post("/signup", (req, res, next) => {
const firstname = req.body.firstname;
const lastname = req.body.lastname;
const email = req.body.email;
const password = req.body.password;
// console.log(req.body);
// if (firstname === "" || password === "") {
// res.render("signup", { msg: { text: "This email adress is already use" } });
// return;
// }
// User.findOne({ email: email }).then(user => {
// if (!user) {
// res.render("signup", {
// msg: { text: "The user already exists. PLease sign in" }
// });
// return;
// }
// });
const salt = bcrypt.genSaltSync(bcryptSalt);
console.log("----->", password);
const hashPass = bcrypt.hashSync(password, salt);
User.create({
firstname,
lastname,
email,
password: <PASSWORD>Pass
})
.then(newUser => {
console.log(newUser);
console.log("newUser");
console.log("----------");
Cart.create({ user_id: newUser._id })
.then(newCart => {
console.log("newCart");
console.log(newCart);
res.redirect("/auth/signin");
})
.catch(cartErr => {
console.log(cartErr);
});
})
.catch(error => {
console.log(error);
});
});
//------ SIGN IN
router.get("/signin", (req, res, next) => {
res.render("signin");
});
router.post("/signin", (req, res, next) => {
const theEmail = req.body.email;
const thePassword = req.body.password;
if (theEmail === "" || thePassword === "") {
res.render("signin", {
msg: { text: "Please enter both, username and password to sign in" }
});
return;
}
User.findOne({ email: theEmail })
.then(user => {
if (!user) {
res.render("signin", {
msg: "The username doesn't exist."
});
return;
}
if (bcrypt.compareSync(thePassword, user.password)) {
// Save the login in the session!
req.session.currentUser = user;
res.redirect("/");
} else {
res.render("signin", { msg: { text: "Incorrect email or password" } });
}
Cart.findOneAndUpdate(
{ user_id: user._id },
{ content: [] },
{ new: true }
)
.then(cart => console.log("cart"))
.catch(cartErr => console.log(cartErr));
})
.catch(error => {
next(error);
});
});
//----- LOG OUT
router.get("/logout", (req, res, next) => {
req.session.destroy(err => {
// can't access session here
res.redirect("/auth/signin");
});
});
router.post("/cartInfos", (req, res, next) => {
if (req.session.currentUser) {
let UserId = req.session.currentUser._id;
Cart.findOne({ user_id: UserId })
.then(cart => {
// console.log("************");
// console.log(cart);
res.send(cart);
})
.catch(Err => console.log(Err));
}
});
module.exports = router;
<file_sep>/public/scripts/cartOnly.js
// const foodModel = require("../models/food");
// const cartModel = require("../models/Cart");
function getCartInfoFromDB() {
axios
.post("/auth/cartInfos")
.then(serverResp => {
console.log(serverResp);
let qty = 0;
for (let i = 0; i < serverResp.data.content.length; i++) {
qty += serverResp.data.content[i].qty;
}
document.getElementById("quantity-total").textContent = qty;
})
.then(Err => console.log(Err));
}
getCartInfoFromDB();
// window.addEventListener("DOMContentLoaded", ironCart.start);
<file_sep>/routes/dashboard_food.js
const express = require("express"); // import express in this module
const router = new express.Router(); // create an app sub-module (router)
const foodModel = require("../models/food");
const cloudinary = require("./../config/cloudinary");
//AFFICHER TOUS LES PRODUITS ET SELON CATEGORIES
router.get("/prod-add", (req, res) => {
res.render("products_add");
});
router.get("/:cat", (req, res) => {
if (req.params.cat == "all") {
foodModel
.find()
.then(dbRes => {
res.render("products", { food: dbRes });
})
.catch(dbErr => console.log(dbErr));
} else {
foodModel
.find({ category: req.params.cat })
.then(dbRes => {
res.render("products", { food: dbRes });
})
.then(dbErr => console.log(dbErr));
}
});
//--------- PRODUCTS "ADD TO COLLECTION"
router.post("/prod-add", cloudinary.single("image"), (req, res) => {
const name = req.body.name;
const ref = req.body.ref;
const description = req.body.description;
const price = req.body.price;
const category = req.body.category;
if (!name || !ref || !price) {
res.render("products_add", {
errorMessage: "Name, Ref. and Price are required !"
});
return;
}
const newItem = {
name,
ref,
description,
price,
category
};
if (req.file) newItem.image = req.file.secure_url;
foodModel
.create(newItem)
.then(() => {
return res.redirect("/products/all");
})
.catch(error => {
console.log(error);
res.render("products_add", {
errorMessage: "Duplicate ref, please update form !"
});
});
});
module.exports = router;
<file_sep>/public/scripts/client.js
const burger = document.querySelector(".icon.mobile");
const navMobile = document.getElementById("sidebar_main");
console.log(navMobile);
function toggleMobileNav(evt) {
console.log("click");
navMobile.classList.toggle("is-active");
}
burger.addEventListener("click", toggleMobileNav);
| b1df7e633c808022e48f2620dcbafb97366f9c98 | [
"JavaScript"
] | 7 | JavaScript | sophieannebourgine/project2-aida-sa | 849679ab91ac82efa0a6202bbd2d9349eb4da454 | 2d6c13beb2c6b6f50c498874513d1112a31192f7 |
refs/heads/master | <file_sep>/* Binary to Decimal/Decimal to Binary
Programmer: <NAME>
Date: September 2016
DecimalBinaryConverter.java */
import java.util.Scanner;
public class DecimalBinaryConverter {
public static void main(String[] args) {
// Variables:
Scanner input = new Scanner(System.in);
String binaryDecimal;
String binary;
String decimal;
System.out.println("Please enter 'Binary' or 'Decimal' for which you would like to convert: ");
binaryDecimal = input.nextLine();
if (binaryDecimal.equals("Binary") || binaryDecimal.equals("binary")) {
System.out.println("Please enter the binary you'd like to convert to decimal: ");
binary = input.nextLine();
System.out.println(Integer.parseInt(binary, 2));
} else {
System.out.println("Please enter the decimal you'd like to convert to binary: ");
decimal = input.nextLine();
int newDecimal = Integer.parseInt(decimal);
System.out.println(Integer.toBinaryString(newDecimal));
}
}
}
<file_sep># Binary-to-Decimal-and-Back-Converter
Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent.
I will be completing this exercise in the following languages:
* Java
* C++
* Python
* C#
| 1679710a55ee9688a7372b3a5b86420f5bdf7f34 | [
"Markdown",
"Java"
] | 2 | Java | VictoriaBrown/Binary-to-Decimal-and-Back-Converter | 617127240dccbe37ac52bac56c112950a4abe3d4 | c642f59646bae68dbf1953be3ab01e48212957d5 |
refs/heads/master | <repo_name>bijilap/Conjourn<file_sep>/README.md
HackSC
======
Making apps to change the owrld
<file_sep>/EasyTravel/mysql/conjourn.sql
-- MySQL dump 10.13 Distrib 5.6.16, for Linux (i686)
--
-- Host: localhost Database: CONJOURN
-- ------------------------------------------------------
-- Server version 5.6.16
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `accounts`
--
DROP TABLE IF EXISTS `accounts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accounts` (
`email` varchar(100) NOT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `accounts`
--
LOCK TABLES `accounts` WRITE;
/*!40000 ALTER TABLE `accounts` DISABLE KEYS */;
/*!40000 ALTER TABLE `accounts` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `api_keys`
--
DROP TABLE IF EXISTS `api_keys`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `api_keys` (
`email` varchar(100) DEFAULT NULL,
`accountid` varchar(40) DEFAULT NULL,
`authtoken` varchar(40) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `api_keys`
--
LOCK TABLES `api_keys` WRITE;
/*!40000 ALTER TABLE `api_keys` DISABLE KEYS */;
INSERT INTO `api_keys` VALUES ('<EMAIL>','AC039eede063a62ee1210452cfd115329b','2a707b93848e765a57cecafaff99e3ab'),('<EMAIL>','AC76bb6d1d2ab5ce21018ec74522e418be','516ea02dd2fe75d17f7f00fd7840a69c');
/*!40000 ALTER TABLE `api_keys` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `contacts`
--
DROP TABLE IF EXISTS `contacts`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `contacts` (
`emailid` varchar(100) DEFAULT NULL,
`contact_list` mediumtext
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `contacts`
--
LOCK TABLES `contacts` WRITE;
/*!40000 ALTER TABLE `contacts` DISABLE KEYS */;
INSERT INTO `contacts` VALUES ('<EMAIL>','(\'<EMAIL>\',\'<EMAIL>\',\'<EMAIL>\',\'<EMAIL>\',\'<EMAIL>\',\'connect<EMAIL>\')'),('<EMAIL>','(\'<EMAIL>\',\'<EMAIL>\',\'<EMAIL>\')'),('<EMAIL>','(\'<EMAIL>\',\'<EMAIL>\',\'<EMAIL>\')');
/*!40000 ALTER TABLE `contacts` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `gmailids_list`
--
DROP TABLE IF EXISTS `gmailids_list`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gmailids_list` (
`user` varchar(100) DEFAULT NULL,
`friend` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `gmailids_list`
--
LOCK TABLES `gmailids_list` WRITE;
/*!40000 ALTER TABLE `gmailids_list` DISABLE KEYS */;
/*!40000 ALTER TABLE `gmailids_list` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `profiles`
--
DROP TABLE IF EXISTS `profiles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profiles` (
`email` varchar(100) NOT NULL,
`twiliono` varchar(13) DEFAULT NULL,
`phno` varchar(13) DEFAULT NULL,
`location` varchar(100) DEFAULT NULL,
`loclat` decimal(8,4) DEFAULT NULL,
`loclong` decimal(8,4) DEFAULT NULL,
`ploclat` decimal(8,4) DEFAULT NULL,
`ploclong` decimal(8,4) DEFAULT NULL,
`dispname` varchar(100) DEFAULT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `profiles`
--
LOCK TABLES `profiles` WRITE;
/*!40000 ALTER TABLE `profiles` DISABLE KEYS */;
INSERT INTO `profiles` VALUES ('<EMAIL>','+1 424-279-49','+12132550684',NULL,34.0214,-118.2845,34.0214,-118.2845,'<NAME>'),('<EMAIL>','+919035297135','+918886782108',NULL,12.9667,77.5667,12.9667,77.5667,'<NAME>'),('<EMAIL>','+1 4242856484','+1 2132559124',NULL,34.0215,-118.2845,34.0215,-118.2845,'<NAME>'),('<EMAIL>','+1 5103715969','2132842648',NULL,34.0215,-118.2845,34.0215,-118.2845,'Vineet G H');
/*!40000 ALTER TABLE `profiles` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2014-03-09 4:21:37
<file_sep>/EasyTravel/sendmessage.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>Cover Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.1.1/dist/css/bootstrap.min.css<?php echo '?'.mt_rand(); ?>" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="bootstrap-3.1.1/dist/css/cover.css<?php echo '?'.mt_rand(); ?>" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="text/javascript">
/**
* Global variables to hold the profile and email data.
*/
var profile, email;
/*
* Triggered when the user accepts the sign in, cancels, or closes the
* authorization dialog.
*/
function loginFinishedCallback(authResult) {
if (authResult) {
if (authResult['error'] == undefined){
toggleElement('signin-button'); // Hide the sign-in button after successfully signing in the user.
gapi.client.load('plus','v1', loadProfile); // Trigger request to get the email address.
} else {
console.log('An error occurred');
}
} else {
console.log('Empty authResult'); // Something went wrong
}
}
/**
* Uses the JavaScript API to request the user's profile, which includes
* their basic information. When the plus.profile.emails.read scope is
* requested, the response will also include the user's primary email address
* and any other email addresses that the user made public.
*/
function loadProfile(){
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(loadProfileCallback);
}
/**
* Callback for the asynchronous request to the people.get method. The profile
* and email are set to global variables. Triggers the user's basic profile
* to display when called.
*/
function loadProfileCallback(obj) {
profile = obj;
// Filter the emails object to find the user's primary account, which might
// not always be the first in the array. The filter() method supports IE9+.
email = obj['emails'].filter(function(v) {
return v.type === 'account'; // Filter out the primary email
})[0].value; // get the email from the filtered results, should always be defined.
displayProfile(profile);
}
/**
* Display the user's basic profile information from the profile object.
*/
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function displayProfile(profile){
document.getElementById('name').innerHTML = profile['displayName'];
document.getElementById('pic').innerHTML = '<img src="' + profile['image']['url'] + '" />';
document.getElementById('email').innerHTML = email;
document.cookie="email="+email;
toggleElement('profile');
}
/**
* Utility function to show or hide elements by their IDs.
*/
function toggleElement(id) {
var el = document.getElementById(id);
if (el.getAttribute('class') == 'hide') {
el.setAttribute('class', 'show');
} else {
el.setAttribute('class', 'hide');
}
}
</script>
</head>
<body>
<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<h3 class="masthead-brand">Con-Journ</h3>
<ul class="nav masthead-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="search_request1.html">Locale</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
<div class="inner cover">
<h1 class="cover-heading">Con-Journ</h1>
<?php
require "twilio-php-latest/Services/Twilio.php";
$AccountSid = "AC039eede063a62ee1210452cfd115329b";
$AuthToken = "2a707b93848e765a57cecafaff99e3ab";
$client = new Services_Twilio($AccountSid, $AuthToken);
$from = '5103715969';
$to = $_POST['phno'];
$name = $_POST['name'];
//echo "messageform.value";
$body = $_POST['message'];
$client->account->sms_messages->create($from, $to, $body);
echo "Sent message to $name";
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js<?php echo '?'.mt_rand(); ?>"></script>
<script src="bootstrap-3.1.1/dist/js/bootstrap.min.js<?php echo '?'.mt_rand(); ?>"></script>
<script src="bootstrap-3.1.1/assets/js/docs.min.js"></script>
</body>
</html>
<file_sep>/EasyTravel/search_response.php
<?php
// Make sure search terms were sent
$file = fopen("tweet.txt","w");
// Strip any dangerous text out of the search
$search_terms = htmlspecialchars($_GET['q']);
$lat = htmlspecialchars($_GET['lat']);
$long = htmlspecialchars($_GET['long']);
//echo $_GET['q'];
//echo $_GET['lat'];
//echo $_GET['long'];
// Create an OAuth connection
require 'app_tokens.php';
require 'tmhOAuth.php';
$connection = new tmhOAuth(array(
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'user_token' => $user_token,
'user_secret' => $user_secret
));
// Run the search with the Twitter API
$http_code = $connection->request('GET',$connection->url('1.1/search/tweets'),
array('q' => $search_terms,
'count' => '510',
'geocode' => $lat.','.$long.',25mi',
'lang' => 'en'
));
//print $http_code;
// Search was successful
if ($http_code == 200) {
// Extract the tweets from the API response
$response = json_decode($connection->response['response'],true);
$tweet_data = $response['statuses'];
//print $response['screen_name'];
// Accumulate tweets from search results
$tweet_stream = '';
foreach($tweet_data as $tweet) {
// Ignore retweets
if (isset($tweet['retweeted_status'])) {
continue;
}
// Add this tweet's text to the results
//$tweet_stream .= $tweet['text'] ." - ".$tweet['user']['screen_name'] .'<br/><br/>';
$tmp = preg_replace("/http.*/", " ",$tweet['text']);
$tmp=$tmp.PHP_EOL;
fwrite($file,$tmp);
//$tweet_stream .= $tweet['text'] .'<br/><br/>';
$tweet_stream .= $tmp .'.';
}
// Send the result tweets back to the Ajax request
//Call to Bijil's Sentiment Analyser
//print $tweet_stream;
fclose($file);
$output = array();
//$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
exec("python cgi-bin/percepclassify.py cgi-bin/senti.model < tweet.txt |grep POS|wc -l", $poscnt);
//var_dump( $output);
//print $poscnt[0];
exec("python cgi-bin/percepclassify.py cgi-bin/senti.model < tweet.txt |grep NEG|wc -l", $negcnt);
/* print "<br>";
print $negcnt[0];
print "<br>";
if (abs($poscnt[0]-$negcnt[0]) <5)
{
print "<h>Normal</h>";
}
else if($poscnt[0]>$negcnt[0])
{
print "<h>Positive</h>";
}
else
{
print "<h>Negative</h>";
}*/
$response = file_get_contents("http://api.wunderground.com/api/85d4e790fba476fd/conditions/current/alert/q/".$lat.",".$long.".json");
$response = json_decode($response,true);
//print $response;
//print $item['current_observation']->temp_f;
$temp=0;
$icon=0;
$hum=0;
foreach ($response as $item)
{
$temp=$item['temp_f'];
$icon=$item['icon_url'];
$hum=$item['relative_humidity'];
}
$dl=$response['current_observation']['display_location'];
$city=$dl['city'];
//print_r($response);
//print $city;
$city=preg_replace("/[\s-]+/", "", $city);
//print $city;
$RSSURL="http://news.google.com/news?q='".$city."'&output=rss";
//$URL5 = "http://feeds.finance.yahoo.com/rss/2.0/headline?s=";
//$URL6="®ion=US&lang=en-US";
//$RSSURL = $URL5.urlencode($_POST['company']).$URL6;
$headers1 = get_headers($RSSURL);
$errors1 = substr($headers1[0], 9, 3);
if($errors1 != "404"){
$xmlStr1 = file_get_contents($RSSURL);
if ($xmlStr1 === false)
{
die('Request failed');
}
$xmlData1 = simplexml_load_string($xmlStr1);
if ($xmlData1 === false)
{
die('Parsing failed');
}
//echo $xmlData1->channel->item->link[0];
//var_dump($xmlData1);
//echo $xmlData1->channel->title;
if($xmlData1->channel->title == "Yahoo! Finance: RSS feed not found")
{
//echo '<div style="text-align:center;"><h2>Financial Company News is not available.</h2></div>';
}
else
{
$i=0;
$linksarray = array();
foreach($xmlData1->channel->item as $child)
{
//echo $child->link."<br/>;";
//echo $child->title."<br/>;";
$linksarray[$i][0]= $child->title;
$linksarray[$i][1]= $child->link;
//echo "Here is the stored".$linksarray[$i][0]."<br/>;";
//echo "Here is the stored".$linksarray[$i][1]."<br/>;";
$i++;
}
//echo $i;
$count = $i;
// echo '<div style="text-align:left;"><font face="Times New Roman" size="+2"><strong>News Headlines</strong></font></div>';
//echo '<hr style="height:1px;border:2px solid;color:#333;background-color:#333;">';
//echo '<ul>';
$file1 = fopen("news.txt","w");
$json_arr="[";
for($i = 0; $i < $count-1; $i++)
{
$json_arr=$json_arr.'{"headline":"'.$linksarray[$i][0].'"},';
$tmp1=$linksarray[$i][0].PHP_EOL;
fwrite($file1,$tmp1);
//echo '<li><a href="'.$linksarray[$i][1].'"</a>'.$linksarray[$i][0].'</li>';
}
$json_arr=$json_arr.'{"headline":"'.$linksarray[0][0].'"}]}';
//echo '</ul>';
fclose($file1);
}
}
exec("python cgi-bin/percepclassify.py cgi-bin/senti.model < news.txt |grep POS|wc -l", $poscnt_n);
exec("python cgi-bin/percepclassify.py cgi-bin/senti.model < news.txt |grep NEG|wc -l", $negcnt_n);
$good=$poscnt_n[0]*3+$poscnt[0];
$bad=$negcnt_n[0]*3+$negcnt[0];
$json='{"Happy":'.$good.',"Sad":'.$bad.',"Weather":'.$temp.',"humid":"'.$hum.'","icon":"'.$icon.'","news":';
$json=$json.$json_arr;
//$json='{"Happy":'.$poscnt[0].',"Sad":'.$negcnt[0].',"Weather":'.$temp.',"humid":"'.$hum.'","icon":"'.$icon.'"}';
print $json;
// Handle errors from API request
} else {
if ($http_code == 429) {
print 'Error: Twitter API rate limit reached';
} else {
print 'Error: Twitter was not able to process that search';
}
}
?>
<file_sep>/EasyTravel/NearbyContacts.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<?php
//Create connection
global $con;
$con=mysqli_connect("localhost","root","","CONJOURN");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function getFriends($con, $emailList, $lat, $long, $email)
{
$result1 = mysqli_query($con,"SELECT accountid, authtoken from api_keys where email='$email'");
$row1 = mysqli_fetch_array($result1);
$result = mysqli_query($con,"SELECT a.dispname, a.phno, a.ploclat, a.ploclong FROM profiles a where email in $emailList");
while($row = mysqli_fetch_array($result))
{
$val=getDistance($lat, $long, $row['ploclat'], $row['ploclong']);
//echo $val.'<br>';
if($val<160)
{
echo "<li align=\"center\"><table><tr><td> <a href=\"new\">".$row['dispname']."</a></td><td><a href=\"messagetext.php?dispname=".$row['dispname']."&phno=".$row['phno']."&accountid=".$row1['accountid']."&authtoken=".$row1['authtoken']."\" data-role=\"button\" data-icon=\"delete\">MSG</a></td></tr></table></li>";
}
}
}
function getDistance( $lat1, $long1, $lat2, $long2)
{
//echo $lat1.' '.$long1.' '.$lat2.' '.$long2.'<br>';
$R = 6371; // Earth's Radius
$dLat = ($lat2-$lat1) * (3.142/180);
$dLon = ($long2-$long1) * (3.142/180);
$a = (sin($dLat/2) * sin($dLat/2)) +
cos(($lat1)* (3.142/180)) * cos(($lat2)* (3.142/180)) *
sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$d = $R * $c;
return $d;
}
?>
<div data-role="page">
<div data-role="header">
<a href="index.html" rel="external" data-role="button" data-icon="home">Home</a></td>
<h1>Nearby Contacts</h1>
</div>
<div data-role="content">
<ul id="contacts" data-role="listview" data-inset="false" align="center">
<?php
//$email=$_GET['email'];
$email='<EMAIL>';
$longitude=$_GET['longitude'];
$latitude=$_GET['latitude'];
//$result = mysqli_query($con,"SELECT contact_list FROM contacts where emailid=$email");
$result = mysqli_query($con,"SELECT contact_list FROM contacts where emailid='$email'");
while($row = mysqli_fetch_array($result))
{
//echo $row['contact_list'];
echo getFriends($con, $row['contact_list'], $latitude, $longitude, $email);
}
?>
</ul>
</div>
<?php
mysqli_close($con)
?>
<div data-role="footer" data-position="fixed">
<h3><EMAIL></h3>
</div>
</body>
</html>
<file_sep>/sendmessage.php
<html>
<head>
</head>
<body>
<form name="messageform" class="form-inline">
<p><textarea name="message"class="form-control" rows="4" cols="40"></textarea></p>
</form>
<?php
require "twilio-php-latest/Services/Twilio.php";
$AccountSid = "AC039eede063a62ee1210452cfd115329b";
$AuthToken = "2a707b93848e765a57cecafaff99e3ab";
$client = new Services_Twilio($AccountSid, $AuthToken);
$from = '5103715969';
$to = $_GET['phno'];
$name = $_GET['dispname'];
//echo "messageform.value";
$body = $_GET['message'];
$client->account->sms_messages->create($from, $to, $body);
echo "Sent message to $name";
?>
</body>
</html>
<file_sep>/EasyTravel_old/PhpDB.php
<!DOCTYPE html>
<html>
<body>
<h1>Test</h1>
<?php
echo "Testing1";
?>
<?php
// Create connection
$con=mysqli_connect("localhost","root","","easytravel");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM login_twilio");
while($row = mysqli_fetch_array($result))
{
echo $row['gmailId'] . " " . $row['twilioPhoneNo'];
echo "<br>";
}
class Contact
{
var $fName;
var $mName;
var $lName;
var $location;
var $phone;
function Contact($fName,$mName,$lName,$location,$phone)
{
$this->fName=$fName;
$this->mName=$mName;
$this->lName=$lName;
$this->location=$location;
$this->phone=$phone;
}
function retFName()
{
return $this->fName;
}
function retMName()
{
return $this->mName;
}
function retLName()
{
return $this->lName;
}
function retLocation()
{
return $this->location;
}
function retPhone()
{
return $this->Phone;
}
}
function storeNewUser( $gmailId, $twilioPhoneNo)
{
mysqli_query($con,"INSERT INTO login_twilio (gmailId, twilioPhoneNo)
VALUES ('$gmailId','$twilioPhoneNo')");
mysqli_close($con);
}
function storeLocation( $gmailId, $contact )
{
mysqli_query($con,"INSERT INTO contact_details (gmailId, fname, mname, lname, location, phone) VALUES ('$gmailId','$contact->retFName()', '$contact->retMName()', '$contact->retLName()', '$contact->retLocation()', '$contact->retPhone()'");
mysqli_close($con);
}
?>
</body>
</html><file_sep>/search_response.php
<?php
// Make sure search terms were sent
$file = fopen("tweet.txt","w");
// Strip any dangerous text out of the search
$search_terms = htmlspecialchars($_GET['q']);
$lat = htmlspecialchars($_GET['lat']);
$long = htmlspecialchars($_GET['long']);
echo $_GET['q'];
echo $_GET['lat'];
echo $_GET['long'];
// Create an OAuth connection
require 'app_tokens.php';
require 'tmhOAuth.php';
$connection = new tmhOAuth(array(
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'user_token' => $user_token,
'user_secret' => $user_secret
));
// Run the search with the Twitter API
$http_code = $connection->request('GET',$connection->url('1.1/search/tweets'),
array('q' => $search_terms,
'count' => '100',
'geocode' => $lat.','.$long.',10mi',
'lang' => 'en'
));
//print $http_code;
// Search was successful
if ($http_code == 200) {
// Extract the tweets from the API response
$response = json_decode($connection->response['response'],true);
$tweet_data = $response['statuses'];
//print $response['screen_name'];
// Accumulate tweets from search results
$tweet_stream = '';
foreach($tweet_data as $tweet) {
// Ignore retweets
if (isset($tweet['retweeted_status'])) {
continue;
}
// Add this tweet's text to the results
//$tweet_stream .= $tweet['text'] ." - ".$tweet['user']['screen_name'] .'<br/><br/>';
$tmp = preg_replace("/http.*/", " ",$tweet['text']);
$tmp=$tmp.PHP_EOL;
fwrite($file,$tmp);
//$tweet_stream .= $tweet['text'] .'<br/><br/>';
$tweet_stream .= $tmp .'.';
}
// Send the result tweets back to the Ajax request
//Call to Bijil's Sentiment Analyser
print $tweet_stream;
fclose($file);
// Handle errors from API request
} else {
if ($http_code == 429) {
print 'Error: Twitter API rate limit reached';
} else {
print 'Error: Twitter was not able to process that search';
}
}
?>
<file_sep>/EasyTravel/app_tokens.php
<?php
// OAuth tokens for single-user programming
// After you create an app you MUST copy
// the tokens and paste them into the following lines
$consumer_key = 'Tc2Pm4mwTlv4mDkWGf2hA';
$consumer_secret = '<KEY>';
$user_token = '<KEY>';
$user_secret = '<KEY>';
?><file_sep>/EasyTravel/twilio-php-latest/makecall.php
<?php
require "Services/Twilio.php";
/* Set our AccountSid and AuthToken */
$AccountSid = "AC039eede063a62ee1210452cfd115329b";
$AuthToken = "2<PASSWORD>";
/* Your Twilio Number or an Outgoing Caller ID you have previously validated
with Twilio */
$from= '5103715969';
/* Number you wish to call */
$to= '2132842648';
/* Directory location for callback.php file (for use in REST URL)*/
$url = 'http://www.example.com/clicktocall/';
/* Instantiate a new Twilio Rest Client */
$client = new Services_Twilio($AccountSid, $AuthToken);
if (!isset($_REQUEST['called']) || strlen($_REQUEST['called']) == 0) {
$err = urlencode("Must specify your phone number");
header("Location: index.php?msg=$err");
die;
}
/* make Twilio REST request to initiate outgoing call */
$call = $client->account->calls->create($from, $_REQUEST['called'], $url . 'callback.php?number=' . $_REQUEST['called']);
/* redirect back to the main page with CallSid */
$msg = urlencode("Connecting... ".$call->sid);
header("Location: index.php?msg=$msg");
?>
<file_sep>/EasyTravel/messagetext.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>Cover Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.1.1/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="bootstrap-3.1.1/dist/css/cover.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<h3 class="masthead-brand">Con-Journ</h3>
<ul class="nav masthead-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
<div class="inner cover">
<form name="messageform" class="form-inline" method="POST" action="sendmessage.php">
<input type="hidden" name="phno" value="<?php
echo $_GET['phno'];
?>"/>
<input type="hidden" name="name" value="<?php
echo $_GET['dispname'];
?>"/>
<p><textarea name="message"class="form-control" rows="4" cols="40"></textarea></p>
<p><button class="btn btn-lg btn-default" type="submit">Text Now</button></p>
</form>
</div>
<div class="mastfoot">
<div class="inner">
<p>Cover template for <a href="http://getbootstrap.com">Bootstrap</a>, by <a href="https://twitter.com/mdo">@mdo</a>.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="bootstrap-3.1.1/dist/js/bootstrap.min.js"></script>
<script src="bootstrap-3.1.1/assets/js/docs.min.js"></script>
</body>
</html>
<file_sep>/EasyTravel/signup.php
<?
//the example of inserting data with variable from HTML form
//input.php
mysql_connect("localhost","root","");//database connection
mysql_select_db("CONJOURN");
//inserting data order
$order = "INSERT INTO profiles
(email, twiliono,phno,location,loclat,loclong,ploclat,ploclong,dispname)
VALUES
('$_POST[gmailid]',
'$_POST[tno]',
'$_POST[phno]', null,
$_POST[latitude],
$_POST[longitude],
$_POST[latitude],
$_POST[longitude],
'$_POST[dpname]')";
echo $order;
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo("<br>Account creation succeed");
header( 'Location: index.html' ) ;
} else{
echo("<br>Input data is fail");
}
?>
| 08cbb60bea80e9048ba57459ae6919425c4c9f1c | [
"Markdown",
"SQL",
"PHP"
] | 12 | Markdown | bijilap/Conjourn | 21abc67e7db58d40761aa545af05e931d399bde4 | 4081c12b44dbeaf882432c04d1ba4af3d6913d0e |
refs/heads/master | <repo_name>sobobe01/project1<file_sep>/README.md
#project1
first start This project consists of coding pratice for algorithim design and techniques the main focus would be on testing for bettter coding implementation and tries for different practice examples with possible test bench cases for the code
progressing through the assignment, testing testing<file_sep>/Max.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <iostream>
#include <vector>
#include <stdint.h>
#include <stdlib.h>
#include <bits/stdc++.h>
using std::vector;
using std::cin;
using std::cout;
using std::max;
using namespace std;
int64_t MaxPairwiseProduct(const vector<int>& numbers) {
//int64_t product = 0;
int index1 = 1;
int index2;
int n = numbers.size();
for (int i = 1; i < n; ++i) {
if (numbers[i] > numbers[index1]){
index1 = i;
//index1 = numbers[i];
}
}
// std::
swap(numbers[index1],numbers[n]);
//if (index1 == 1){
//int index2 = 2;
//}
// else{
//int index2 = 1;
//}
int index1 = 1;
for (int j = 1; j < n-1; ++j){
if(( numbers[j] > numbers[index1])) {
//if ((numbers[j] != numbers[index1]) && (numbers[j] > numbers[index2])) {
index2 = j;
}
}
int64_t product = (int64_t)numbers[index1] * numbers[index2];
return product;
//return numbers[index1] * numbers[index2];
}
int main() {
int n;
cin >> n;
vector<int> numbers(n);
//for (int i = 1; i <= k; ++i) {
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
numbers[i];
}
int64_t product = MaxPairwiseProduct(numbers);
cout << product << "\n";
return 0;
}
| 12be3719b49488f121e38290c64aeee52f7bbae6 | [
"Markdown",
"C++"
] | 2 | Markdown | sobobe01/project1 | ac3fe3d4f86aeeb210260160a5000a9496188fa4 | 6d87d72cb9f5e7fa323e8893f8614e25cbf3449f |
refs/heads/main | <repo_name>LS-T/mongoFitness<file_sep>/README.md
# mongoFitness

# Description
This fitness tracker allows a user to keep track of their workouts and add or remove exercises as they wish. When a workout is completed, a user sees aggregated data representing totals from the exercises they completed during their workout. If a user were to click the dashboard, they would be presented with graphs showing their workout history from the last 7 days.
# User Story
AS a user I want to be able to track my workouts
I want to be able to log individual exercises to my workouts
I want to be able to see a weekly report of my workouts on the dashboard
SO that I can accurately keep track of my exercises by weight, reps, set, resistance/cardio.
# Deployed
https://polar-woodland-49819.herokuapp.com/
<file_sep>/routes/apiRoutes.js
const router = require("express").Router();
const { reverse } = require("methods");
const { Workout } = require("../models");
const db = require("../models");
// get workouts
router.get('/api/workouts', (req,res) => {
Workout.aggregate ([
{
// add new field totalDuration to workout collection, equate it to the sum of exercise.duration
$addFields: {
totalDuration: { $sum: '$exercises.duration'},
},
}
])
.then((workoutDuration) => {
res.json(workoutDuration);
})
.catch((err) => res.json(err));
});
// Post a workout
router.post('/api/workouts', ({ body }, res) => {
db.Workout.create(body)
.then((newWorkout) => {
res.json(newWorkout);
})
.catch((err) => res.json(err));
});
router.put('/api/workouts/:id', ({ body, params}, res) => {
db.Workout.findByIdAndUpdate(
params.id,
// push into exercises array in the workout collection
{$push: { exercises: body }},
// Set new to true to return modified document rather than the original
{new: true }
)
.then((updatedWorkout) => {
res.json(updatedWorkout)
})
.catch((err) => res.json(err));
});
// Get total duration of workouts from last 7 days
router.get(`/api/workouts/range`, (req, res) => {
Workout.aggregate([
{
$addFields: {
totalDuration: {$sum: '$exercises.duration' },
}
}
])
// sort from descending id_ , and limit it to 7 workouts
.sort({_id: -1})
.limit(7)
.then((workout) => {
mostRecent = workout.reverse();
res.json(mostRecent);
})
.catch((err) => res.json(err))
});
module.exports = router; | 4916bae4107b063d8da3ae030e9e5f51bd656e88 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | LS-T/mongoFitness | ea7c80073a5b537385fb91f2a45e2e64f3db0330 | d4681b3a67726362075ec83bc2748f0f254560da |
refs/heads/master | <repo_name>Canardlaquay/RemoteControl<file_sep>/RemoteControlServer/Main.cs
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.Xml;
//using iTunesLib;
namespace RemoteControlServer
{
public class serv
{
public static void Main(string[] arg)
{
List<string> nomCmd = new List<string>();
List<string> typCmd = new List<string>();
List<string> tgtCmd = new List<string>();
List<string> ipList = new List<string>();
//iTunesControl itunes = new iTunesControl();
string operatingSystem = "";
string LocalIPv6 = "";
string LocalIPv4 = "";
string InternetIPv4 = "";
try
{
if (!File.Exists("config.xml"))
{
Console.WriteLine("No configuration file found, creating one.");
XmlCreate("config.xml");
XmlRead(ref nomCmd, ref typCmd, ref tgtCmd, ref operatingSystem, ref LocalIPv6, ref LocalIPv4, ref InternetIPv4);
Console.WriteLine("New and fresh config file created !");
}
else
{
Console.WriteLine("Configuration file found, reading it !");
XmlRead(ref nomCmd, ref typCmd, ref tgtCmd, ref operatingSystem, ref LocalIPv6, ref LocalIPv4, ref InternetIPv4);
Console.WriteLine("Reading finished !");
}
string ans = "";
while (ans == "")
{
Console.WriteLine("Which IP Adress do you want to choose as the host ?");
Console.WriteLine("1) Your local IPv6 which is: {0}", LocalIPv6);
Console.WriteLine("2) Your local IPv4 which is: {0}", LocalIPv4);
Console.WriteLine("3) Your public IPv4 which is: {0}", InternetIPv4);
Console.Write("Write the number of the choice you decided: ");
ans = Console.ReadLine();
if (Convert.ToInt32(ans) != 1 && Convert.ToInt32(ans) != 2 && Convert.ToInt32(ans) != 3)
{
Console.WriteLine("Wrong number entered, please try again.");
ans = "";
}
else
{
break;
}
}
ipList.Add(LocalIPv6);
ipList.Add(LocalIPv4);
ipList.Add(InternetIPv4);
IPAddress ipAd = IPAddress.Parse(ipList[Convert.ToInt32(ans) - 1]);
TcpListener myList = new TcpListener(ipAd, 8001);
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
while (true)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
string reponse = "";
for (int i = 0; i < k; i++)
reponse += Convert.ToChar(b[i]);
Console.WriteLine(reponse);
if (CheckCommand(reponse, ref nomCmd))
{
ProcessCommand(reponse, ref nomCmd, ref typCmd, ref tgtCmd, ref operatingSystem, ref s);
}
else
{
Console.WriteLine("No command to execute found ! Skipping...");
}
s.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.WriteLine("Press any key to Exi...");
Console.ReadLine();
Environment.Exit(0);
}
}
public static bool CheckCommand(string rep, ref List<string> nomCmd)
{
for (int i = 0; i < nomCmd.Count; i++)
{
if (rep == nomCmd[i].ToString())
return true;
}
return false;
}
public static void XmlRead(ref List<string> nomCmd, ref List<string> typCmd, ref List<string> tgtCmd, ref string operatingSystem, ref string LocalIPv6, ref string LocalIPv4, ref string InternetIPv4)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("config.xml");
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
string ipLocalv6 = "";
string ipLocalv4 = "";
WebClient webClient = new WebClient();
string ipIntv4 = webClient.DownloadString("http://myip.ozymo.com/");
foreach (IPAddress ipp in ip.AddressList)
{
if (ipp.IsIPv6LinkLocal == true)
{
ipLocalv6 = ipp.ToString();
}
if (ipp.ToString().StartsWith("192.") || ipp.ToString().StartsWith("172.") || ipp.ToString().StartsWith("10."))
{
ipLocalv4 = ipp.ToString();
}
}
XmlNode node0 = xmlDoc.SelectSingleNode("GlobalInfo/OS");
node0.InnerText = Environment.OSVersion.ToString();
XmlNode node = xmlDoc.SelectSingleNode("GlobalInfo/LocalIPv6");
node.InnerText = ipLocalv6;
XmlNode node1 = xmlDoc.SelectSingleNode("GlobalInfo/LocalIPv4");
node1.InnerText = ipLocalv4;
XmlNode node2 = xmlDoc.SelectSingleNode("GlobalInfo/InternetIPv4");
node2.InnerText = ipIntv4;
xmlDoc.Save("config.xml");
XmlTextReader reader = new XmlTextReader("config.xml");
while (reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{
string nameElem = reader.Name;
while (reader.MoveToNextAttribute())
{// Read the attributes.
nomCmd.Add(nameElem);
typCmd.Add(reader.Name);
tgtCmd.Add(reader.Value);
}
}
}
XmlDocument xml = new XmlDocument();
xml.Load("config.xml");
XmlNodeList xnList = xml.SelectNodes("/GlobalInfo");
foreach (XmlNode xn in xnList)
{
operatingSystem = xn["OS"].InnerText;
LocalIPv6 = xn["LocalIPv6"].InnerText;
LocalIPv4 = xn["LocalIPv4"].InnerText;
InternetIPv4 = xn["InternetIPv4"].InnerText;
}
}
public static void XmlCreate(string path)
{
XmlTextWriter myXmlTextWriter = new XmlTextWriter("config.xml", null);
myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteComment("This is the configuration file for commands that are listened by the server. You can put your owns there.");
myXmlTextWriter.WriteComment("You can easily add commands by adding an other node with the target attribute next to it.");
myXmlTextWriter.WriteComment("example: <nameofthecommand target=\"command to execute in console\" />");
myXmlTextWriter.WriteComment("Do not modify any information in the GlobalInfo node except under Windows/Unix nodes.");
myXmlTextWriter.WriteStartElement("GlobalInfo");
myXmlTextWriter.WriteElementString("OS", Environment.OSVersion.ToString());
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
string ipLocalv6 = "";
string ipLocalv4 = "";
WebClient webClient = new WebClient();
string ipIntv4 = webClient.DownloadString("http://myip.ozymo.com/");
foreach (IPAddress ipp in ip.AddressList)
{
if (ipp.IsIPv6LinkLocal == true)
{
ipLocalv6 = ipp.ToString();
}
if (ipp.ToString().StartsWith("192.") || ipp.ToString().StartsWith("172.") || ipp.ToString().StartsWith("10."))
{
ipLocalv4 = ipp.ToString();
}
}
myXmlTextWriter.WriteElementString("LocalIPv6", ipLocalv6);
myXmlTextWriter.WriteElementString("LocalIPv4", ipLocalv4);
myXmlTextWriter.WriteElementString("InternetIPv4", ipIntv4);
myXmlTextWriter.WriteElementString("Version", "1000");
myXmlTextWriter.WriteStartElement("Unix");
myXmlTextWriter.WriteStartElement("writesomething");
myXmlTextWriter.WriteAttributeString("exec", "echo this was written in the console");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("exit");
myXmlTextWriter.WriteAttributeString("exec", "exit");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("screen");
myXmlTextWriter.WriteAttributeString("exec", "screen");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("Windows");
myXmlTextWriter.WriteComment("Use the exec parameter with an argument to execute files easily");
myXmlTextWriter.WriteStartElement("calculator");
myXmlTextWriter.WriteAttributeString("exec", "calc");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteComment("Just specify the correct path for the app !");
myXmlTextWriter.WriteStartElement("calculator");
myXmlTextWriter.WriteAttributeString("exec", "C:\\Windows\\notepad.exe");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteComment("Here, it's remotely controlling iTunes (via a proper library).");
myXmlTextWriter.WriteComment("All the commands will be listed in the README at https://github.com/Canardlaquay/RemoteControl");
myXmlTextWriter.WriteStartElement("itunesPause");
myXmlTextWriter.WriteAttributeString("itunes", "pause");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("itunesNextTrack");
myXmlTextWriter.WriteAttributeString("itunes", "playNextTrack");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("itunesPlay");
myXmlTextWriter.WriteAttributeString("itunes", "play");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("itunesPreviousTrack");
myXmlTextWriter.WriteAttributeString("itunes", "playPreviousTrack");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("itunesIncreaseVolume");
myXmlTextWriter.WriteAttributeString("itunes", "volIncrease");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteStartElement("itunesDecreaseVolume");
myXmlTextWriter.WriteAttributeString("itunes", "volDecrease");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.Flush();
myXmlTextWriter.Close();
}
public static void ProcessCommand(string rep, ref List<string> nomCmd, ref List<string> typCmd, ref List<string> tgtCmd, ref string operatingSystem, ref Socket s)
{
for(int i = 0; i < nomCmd.Count; i++)
{
if (rep == nomCmd[i])
{
if (operatingSystem.Contains("Windows"))
{
switch (typCmd[i])
{
//console commands only, mainly for executing apps.
case "exec":
Process.Start(tgtCmd[i]);
break;
case "execReturn":
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("Not yet included on windows..."));
break;
case "exit":
Console.WriteLine("Exiting...");
Environment.Exit(0);
break;
//itunes Part !
case "killApp":
Process[] proc = Process.GetProcessesByName(tgtCmd[i]);
foreach (Process pr in proc)
{
if (pr.ToString() == tgtCmd[i])
{
pr.Kill();
}
}
break;
case "shutdown":
Console.WriteLine("Shutting down computer, byebye !");
Process.Start("shutdown", "/s /t 0");
break;
case "itunes":
iTunesControl it = new iTunesControl();
switch (tgtCmd[i])
{
case "play":
it.playMusic();
break;
case "stop":
it.stopMusic();
break;
case "pause":
it.pauseMusic();
break;
case "volIncrease":
it.volume += 10;
break;
case "volDecrease":
it.volume -= 10;
break;
case "playNextTrack":
it.playNextTrack();
break;
case "playPreviousTrack":
it.playPreviousTrack();
break;
default:
break;
}
break;
default:
break;
}
}
if (operatingSystem.Contains("Unix"))
{
switch (typCmd[i])
{
case "exec":
Process.Start("/bin/" + tgtCmd[i], "-l");
break;
case "exit":
Console.WriteLine("Exiting...");
Environment.Exit(0);
break;
case "execReturn":
string progPath = Directory.GetCurrentDirectory() + "\\rcsDump";
File.WriteAllText(progPath, tgtCmd[i] + " >> rcsDump");
Process.Start("/bin/sh", progPath);
string answer = File.ReadAllText(progPath);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("Here's the answer:" + answer));
break;
default:
break;
}
}
}
}
}
//public void XmlUpdateInfo(
}
}
<file_sep>/RemoteControlServer/iTunesControl.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesLib;
namespace RemoteControlServer
{
public class iTunesControl
{
iTunesApp itunes = new iTunesApp();
public iTunesControl()
{
}
public IITTrack getCurrentTrack
{
get { return itunes.CurrentTrack; }
set { }
}
public void stopMusic()
{
itunes.Stop();
}
public void playMusic()
{
itunes.Play();
itunes.Resume();
}
public void playFileMusic(string file)
{
itunes.PlayFile(file);
}
public void pauseMusic()
{
itunes.Pause();
}
public void playNextTrack()
{
itunes.NextTrack();
}
public void playPreviousTrack()
{
itunes.PreviousTrack();
}
public int volume
{
get { return itunes.SoundVolume; }
set { itunes.SoundVolume += value; }
}
}
}
<file_sep>/README.txt
Hello fellow visitor !
I present you my project, a Remote Control Server, which works by sending
very simple strings, whose does simple commands.
It can easily be used by any language (programming, heh.), because it's
using sockets.
For a concrete example, in python, I send the string like this:
Remote_Socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
Remote_Socket.connect((ipAdressofRemoteHost,portOfRemoteHost))
Remote_Socket.send("query")
I'd try to make some different connectors in different languages, to help
the use of the program.
After that, on the server, we handle the query. You have a XML config file, created
at the start of the process, it reads it, update the information needed, and reads
commands there. Let me explain the system: If the server receives a "magic string", like
"writesomething" in the example config.xml, sent from a client (obviously), it does what
the command is meant. E.G, if the command is "exec", it'll execute the file that is passed
in argument, we'll take here "C:\notepad.exe". I focus to get a lot of commands, but I'll try,
for the moment, to get the server the most stable possible.
Anyway, for the commands, you can check a basic config.xml at the root of the repo.
You can easily add commands there, but I'll explain which are working,
and how, of course.
For the moment, I only focus Windows, because nearly everything can be
done by commands on Unix systems. It is already included for basic shell
commands like ls, date, etc... They DOES return something, it's sended to
the client after the query was successful. There's much more things that can
be done easily on unix via commands, so now I focus on windows to get the
more commands possible, including external librairies.
For example, I already included iTunes remote control, i'll use the library at the fullest later.
If any information/help needed, contact me @ Mathysleleu[at]gmail(dot)com !
TODO:
- MOAR librairies !
- MOAR COMMANDS !
| bf153d5b364298f0c2335facc1bad974d6032b69 | [
"C#",
"Text"
] | 3 | C# | Canardlaquay/RemoteControl | d2bbb2bce3b17c848b0eb606400b55a5847ff2e5 | 6f23ea76a4e899811a9ce467ba6784c2dd012ad3 |
refs/heads/master | <file_sep>import unittest
import requests
addDataURL = 'http://127.0.0.1:5000/post_location'
baseURL ='http://127.0.0.1:5000/'
class testFlask(unittest.TestCase):
def setUp(self):
pass
def test_existing_pincode(self):
data = {
'pincode':'IN/110001',
'place_name':'Connaught Place',
'admin_name1':'New Delhi',
'longitude':77.2167,
'latitude':28.6333,
'accuracy':4
}
result = requests.post(addDataURL, data=data)
string = result.text
self.assertIn('This Pincode Already Exists!',string)
def test_proximity_points(self):
data={
'pincode':'IN/99999',
'place_name':'test_place',
'admin_name1':'test_location',
'longitude':77.2160,
'latitude':28.6330,
'accuracy':99
}
result = requests.post(addDataURL, data=data)
string = result.text
self.assertIn('A location already exists within',string)
def test_key_null(self):
data={
'pincode':'IN/99999',
'place_name':'test_place',
'admin_name1':'test_location',
'longitude':77.2160,
'latitude':28.6330,
'accuracy':99
}
data['pincode']='NULL'
result = requests.post(addDataURL,data=data)
string = result.text
self.assertIn('You must supply a pincode',string)
def test_place_name_null(self):
data={
'pincode':'IN/99999',
'place_name':'test_place',
'admin_name1':'test_location',
'longitude':77.2160,
'latitude':28.6330,
'accuracy':99
}
data['place_name']='NULL'
result = requests.post(addDataURL,data=data)
string = result.text
self.assertIn('You must supply a place name',string)
def test_get_using_self(self):
result = requests.get(baseURL+'get_using_self?longitude=77.216&latitude=28.633')
string = result.text
self.assertIn('Pincodes within 5Kms of given cordinates:',string)
def test_get_using_postgres(self):
result = requests.get(baseURL+'get_using_postgres?longitude=77.216&latitude=28.633')
string = result.text
self.assertIn('Pincodes within 5Kms of given cordinates:',string)
def test_compare_get(self):
result = requests.get(baseURL+'get_using_self?longitude=77.216&latitude=28.633')
string = result.text
get_self = string.split(':')
result = requests.get(baseURL+'get_using_postgres?longitude=77.216&latitude=28.633')
string = result.text
get_postgres = string.split(':')
self.assertTrue(set(get_self[1])==set(get_postgres[1]))
def test_get_incomplete(self):
result = requests.get(baseURL+'get_using_self')
string = result.text
self.assertIn('You must supply valid arguments!',string)
def test_get_place(self):
result = requests.get(baseURL+'get_place?longitude=77.216&latitude=28.633')
string = result.text
self.assertIn('The Point falls under:',string)
def test_get_place_incomplete(self):
result = requests.get(baseURL+'get_place')
string = result.text
self.assertIn('You must supply valid arguments!',string)
def test_get_place_out_of_bound(self):
result = requests.get(baseURL+'get_place?longitude=0&latitude=0')
string = result.text
self.assertIn("Given point doesn't fall under any known location!",string)
if __name__=='__main__':
unittest.main()<file_sep>from flask import Flask, request
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import func
import math
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:***password***@localhost:5432/apitest'
db = SQLAlchemy(app)
distanceLimit = 2 #distance in Kms
class pincodes(db.Model):
__tablename__='pincodes'
key = db.Column(db.String, primary_key=True)
place_name = db.Column(db.String)
admin_name1 = db.Column(db.String)
latitude = db.Column(db.Float)
longitude = db.Column(db.Float)
accuracy = db.Column(db.Integer)
def __repr__(self):
'''
data={
'key':str(self.key),
'place_name':str(self.place_name),
'admin_name1':str(self.admin_name1),
'latitude':self.latitude,
'longitude':self.longitude,
'accuracy':self.accuracy
}
'''
return "%r%r%r%r'%r'%r" % (self.key,self.place_name,self.admin_name1,self.latitude,self.longitude,self.accuracy)
#return data
class geolocation(db.Model):
__tablename__='geolocation'
key = db.Column(db.Integer, primary_key=True)
geometry = db.Column(db.Binary)
name = db.Column(db.String)
category = db.Column(db.String)
parent = db.Column(db.String)
def __repr__(self):
return "%r%r%r" % (self.name,self.category,self.parent)
@app.route('/')
def hello_world():
#data = db.session.query(pincodes).first()
data = pincodes.query.get('IN/110001')
msg = getFormatedRow(data)
return msg
@app.route('/post_location',methods=['POST'])
def post_location():
if request.method == 'POST':
key = request.form['pincode']
place_name = request.form['place_name']
admin_name1 = request.form['admin_name1']
latitude = request.form['latitude']
longitude = request.form['longitude']
accuracy = request.form['accuracy']
#return pincode
data=db.session.query(pincodes).filter_by(key=key).scalar()
if data is not None:
msg = 'This Pincode Already Exists!\n'
msg += str(getFormatedRow(data))
return msg
else:
#data = db.session.query(pincodes).filter_by(place_name=place_name).order_by('ABS(latitude - %f)' % float(latitude))
#data = pincodes.query.order_by('ABS(latitude - %f)' % float(latitude)).limit(10).all()
msg = ''
if(not dataExists(key)):
return 'You must supply a pincode!'
if(not dataExists(place_name)):
return 'You must supply a place name!'
data = pincodes.query.order_by('(( 3959 * acos( cos( radians(%f) ) * cos( radians( pincodes.latitude ) ) * cos( radians( pincodes.longitude ) - radians(%f) ) + sin( radians(%f) ) * sin( radians( pincodes.latitude ) ) ) )*1.60934)' % (float(latitude),float(longitude),float(latitude))).limit(1).all()
row = getFormatedRow(data)
distance = ( 3959 * math.acos( math.cos( math.radians(float(latitude)) ) * math.cos( math.radians( float(row['latitude']) ) ) * math.cos( math.radians( float(row['longitude']) ) - math.radians(float(longitude)) ) + math.sin( math.radians(float(latitude)) ) * math.sin( math.radians( float(row['latitude']) ) ) ) )*1.60934
if distance < distanceLimit:
msg += 'A location already exists within '+str(distanceLimit)+'Kms of given coorinates.\n'
msg += str(row)
addAllowed=False
else:
addAllowed = True
if(addAllowed):
newRow = pincodes(
key=key,
place_name=place_name,
admin_name1=formDataFormat(admin_name1),
latitude=formDataFormat(latitude),
longitude=formDataFormat(longitude),
accuracy=formDataFormat(accuracy)
)
db.session.add(newRow)
db.session.commit()
data = pincodes.query.get(key)
msg += 'New Data Added\n'
msg += str(getFormatedRow(data))
return msg
@app.route('/get_using_self',methods=['GET'])
def get_using_sef():
try:
latitude=float(request.args.get('latitude'))
longitude=float(request.args.get('longitude'))
except:
return 'You must supply valid arguments!'
data = pincodes.query.order_by('(( 3959 * acos( cos( radians(%f) ) * cos( radians( pincodes.latitude ) ) * cos( radians( pincodes.longitude ) - radians(%f) ) + sin( radians(%f) ) * sin( radians( pincodes.latitude ) ) ) )*1.60934)' % (float(latitude),float(longitude),float(latitude))).all()
data = sort_by_distance(data,latitude,longitude)
msg = 'Pincodes within 5Kms of given cordinates:\n'
msg+=str(data)
return msg
@app.route('/get_using_postgres',methods=['GET'])
def get_using_postgres():
try:
latitude=float(request.args.get('latitude'))
longitude=float(request.args.get('longitude'))
except:
return 'You must supply valid arguments!'
data = pincodes.query.filter('((point(77.216,28.633)<@>point(pincodes.longitude,pincodes.latitude))*1.60934::double precision)<5').order_by('((point(77.216,28.633)<@>point(pincodes.longitude,pincodes.latitude))*1.60934::double precision)').all()
newList=[]
for i in data:
row = getFormatedRow(i)
newList.append(row['key'])
msg = 'Pincodes within 5Kms of given cordinates:\n'
msg += str(newList)
return msg
@app.route('/get_place',methods=['GET'])
def get_place():
try:
latitude=float(request.args.get('latitude'))
longitude=float(request.args.get('longitude'))
except:
return 'You must supply valid arguments!'
loc='point('+str(longitude)+' '+str(latitude)+')'
data = geolocation.query.filter(func.st_contains(geolocation.geometry,func.st_geometryfromtext(loc,4326))).all()
if str(data)=='[]':
return "Given point doesn't fall under any known location!"
#data = geolocation.query.limit(1).all()
row = getFormatedPlace(data)
msg='The Point falls under:\n'
msg+=str(row)
return msg
def sort_by_distance(data,latitude,longitude):
#recursionAllowed=True
newList=[]
for i in data:
#while(recursionAllowed):
row=getFormatedRow(i)
distance = distance = ( 3959 * math.acos( math.cos( math.radians(float(latitude)) ) * math.cos( math.radians( float(row['latitude']) ) ) * math.cos( math.radians( float(row['longitude']) ) - math.radians(float(longitude)) ) + math.sin( math.radians(float(latitude)) ) * math.sin( math.radians( float(row['latitude']) ) ) ) )*1.60934
if distance < 5:
newList.append(row['key'])
else:
#recursionAllowed=False
break
return newList
def getFormatedPlace(data):
data=str(data)
data=data.split("'")
row={
'name':data[1],
'category':data[3],
'parent':data[5]
}
return row
def getFormatedRow(data):
data = str(data)
data = data.split("'")
row = {'key':data[1],
'place_name':data[3],
'admin_name1':data[5],
'latitude':data[6],
'longitude':data[7],
'accuracy':data[8],
}
return row
def formDataFormat(data):
if data=='NULL':
return None
else:
return data
def dataExists(data):
if data=='NULL' or data=='':
return False
else:
return True
if __name__ == '__main__':
app.run()<file_sep># APITEST
The main flask app is titled app.py
Testing is done by unit test framework of python.
Testing file is named test_API.py
Run the test file with command `python test_API.py -v`
In app.py replace `***password***` with your own password
| 048799a47885a9fc255c42ddda40133822478f77 | [
"Markdown",
"Python"
] | 3 | Python | LiveSparks/apitest | c6eb204f834c03fe52aa8c4c3ee980ec3220141f | 813bfead5dbe11574c65e591367ff319fdfcf36b |
refs/heads/main | <file_sep># Chromotherapy IoT
IoT Project with Raspberry Pi, Arduino and windows IoT
Proyecto experimental de IoT para proyecto inicial basado en cromoterapia con el uso de Raspberry Pi, Arduino y uso de WindowsIoT
Bibliografía:
• Windows IoT: https://developer.microsoft.com/es-es/windows/iot
• Windows IoT download: https://developer.microsoft.com/en-us/windows/iot/Downloads
• Samples with Windows IoT: https://www.hackster.io/microsoft/products/windows-10-iot-core?sort=trending
• Temperature Sample : https://www.hackster.io/Alirezap/windows-10-iot-temperature-smt172-6cdabe
• Chromotherapy Sample: https://www.hackster.io/lentzlive/chromotherapy-with-raspberry-and-arduino-69d11e
• Google Home + Raspberri Pi: http://www.instructables.com/id/Google-Home-Raspberry-Pi-Power-Strip/
• Weather Station: https://www.hackster.io/windows-iot/weather-station-67e40d
• Windows IoT Remote Control: Store de Windows 10
• Programa diseño diagramas eléctricos: http://fritzing.org/
• Programa online para testear código y circuito de Arduino: https://www.tinkercad.com/learn/
<file_sep>#include <SoftwareSerial.h>
//Variables
const byte rxPin = 11;
const byte txPin = 10;
const int GREEN_pin = 3;
const int BLUE_pin = 5;
const int RED_pin = 6;
String RGBColor = "";
String RGBColor_previous = "255.255.255"; // inicializacion a blanco
boolean RGBRead_Completed = false;
long bps = 9600; //bytes por seg
SoftwareSerial myConnect(txPin, rxPin); // RX, TX recordar que se cruzan
void setup()
{
pinMode(GREEN_pin, OUTPUT);
pinMode(BLUE_pin, OUTPUT);
pinMode(RED_pin, OUTPUT);
Serial.begin(bps);
myConnect.begin(bps);
}
void loop()
{
while(myConnect.available())
{
char ReadChar = (char)myConnect.read();
if(ReadChar == ')')
{
RGBRead_Completed = true;
}
else
{
RGBColor += ReadChar;
}
}
if(RGBRead_Completed)
{
if(RGBColor == "ON")
{
RGBColor = RGBColor_previous;
Control_RGB_StripLed();
}
else if(RGBColor == "OFF")
{
RGBColor = "0.0.0";
Control_RGB_StripLed();
}
else
{
Control_RGB_StripLed();
RGBColor_previous = RGBColor;
}
RGBColor = "";
RGBRead_Completed = false;
}
}
void Control_RGB_StripLed() {
// get finish position of colors
int position1RGBColor = RGBColor.indexOf(' ');
int position2RGBColor = RGBColor.indexOf(' ', position1RGBColor + 1);
int position3RGBColor = RGBColor.indexOf(' ', position2RGBColor + 1);
// get colors from string RGBColor with previous positions
String RedColor = RGBColor.substring(0, position1RGBColor);
String GreenColor = RGBColor.substring(position1RGBColor + 1, position2RGBColor);
String BlueColor = RGBColor.substring(position2RGBColor + 1, position3RGBColor);
//Pass string colors to int and get color variety between 0 - 255
analogWrite(GREEN_pin, (GreenColor.toInt()));// you can use de analogWrite if you use this arduino's conections
analogWrite(BLUE_pin, (BlueColor.toInt()));
analogWrite(RED_pin, (RedColor.toInt()));
// If you need to invert colors, you could change GreenColor.toInt() by (255 - GreenColor.toInt())
}
| b74cd9b35bcaf0851b91d437efea1e6d7ecf5b61 | [
"Markdown",
"C++"
] | 2 | Markdown | jmrp81/CromoterapiaIoT | 0d851eff4c63a7cf69b9ba9762b0146beefc76ad | 11d0bf039c04ad11be11f0af4b48309d93e1edf1 |
refs/heads/master | <repo_name>Henkeboi/hk<file_sep>/curses/editor.cpp
#include "editor.hpp"
#include "curses.h"
editor::editor(std::string filename)
: _filename(filename), _text_window(text_window{filename}), _mode(normal), _window(text), _mode_switch_timer(std::chrono::system_clock::now()), _repeat_timer(std::chrono::system_clock::now()), _repeat_string("-1"), _exit(false)
{}
bool editor::open_file(std::string filename)
{
if (_text_window.open_file(filename)) {
_text_window.display();
_text_window.resize();
_filename = filename;
return true;
}
return false;
}
bool editor::save_file(std::string filename)
{
if (_text_window.save_file(filename)) return true;
return false;
}
void editor::edit()
{
_text_window.display();
bool j_symbol_not_inserted = false;
while (!_exit) {
mode next_mode = _mode;
window next_window = _window;
std::wstring command_string = L"";
wint_t user_input = _get_input();
if (user_input == KEY_RESIZE) {
_text_window.resize();
} else if (_window == text) {
if (_mode == normal) {
// repeat commands
if (user_input == int('0') && _repeat_string == "-1") {
_text_window.curser_start_line();
_text_window.display();
} else if (user_input == int('0')) {
_append_to_repeat_string('0');
} else if (user_input == int('1')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('2')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('3')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('4')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('5')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('6')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('7')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('8')) {
_append_to_repeat_string(user_input);
} else if (user_input == int('9')) {
_append_to_repeat_string(user_input);
// move curser
} else if (user_input == int('j')) {
_text_window.curser_down(_get_repeat_number());
_text_window.display();
} else if (user_input == 4) { // CTRL + d
_text_window.curser_down(_get_repeat_number() * ((LINES - 2) / 2));
_text_window.display();
} else if (user_input == int('j')) {
_text_window.curser_down(_get_repeat_number());
_text_window.display();
} else if (user_input == int('k')) {
_text_window.curser_up(_get_repeat_number());
_text_window.display();
} else if (user_input == 21) { // CTRL + u
_text_window.curser_up(_get_repeat_number() * 28);
_text_window.display();
} else if (user_input == int('h')) {
_text_window.curser_left(_get_repeat_number());
_text_window.display();
} else if (user_input == int('l')) {
_text_window.curser_right(_get_repeat_number());
_text_window.display();
} else if (user_input == int('e')) {
_text_window.curser_next_word(_get_repeat_number());
_text_window.display();
} else if (user_input == int('b')) {
_text_window.curser_prev_word(_get_repeat_number());
_text_window.display();
} else if (user_input == int('$')) {
_text_window.curser_end_line();
_repeat_string = "-1";
_text_window.display();
// move dispay
} else if (user_input == int('x')) {
_text_window.display_center();
} else if (user_input == int('z')) {
_text_window.display_up(_get_repeat_number());
} else if (user_input == int('c')) {
_text_window.display_down(_get_repeat_number());
// change to insert
} else if (user_input == int('i')) {
next_mode = insert;
} else if (user_input == int('o')) {
next_mode = insert;
_text_window.curser_end_line();
_text_window.insert_newline();
_text_window.auto_indent();
_repeat_string = "-1";
_text_window.display();
} else if (user_input == int('O')) {
next_mode = insert;
_text_window.curser_start_line();
_text_window.insert_newline();
_text_window.curser_up(1);
_text_window.auto_indent();
_repeat_string = "-1";
_text_window.display();
// visual operations
} else if (user_input == int('v')) {
_text_window.toggle_select();
} else if (user_input == int('d')) {
_text_window.delete_selection();
_text_window.display();
// change to command
} else if (user_input == int(':')) {
next_window = command;
next_mode = insert;
_command_window.insert(':');
_command_window.display();
} else if (user_input == 0) { // CTRL + c
_command_window.print_abort_message();
}
} else if (_mode == insert) {
// change to normal
auto now = std::chrono::system_clock::now();
auto time_span = std::chrono::duration_cast<std::chrono::duration<double> >(now - _mode_switch_timer);
if (j_symbol_not_inserted && user_input != int('k')) {
_text_window.insert('j');
j_symbol_not_inserted = false;
}
if (user_input == int('j')) {
_mode_switch_timer = std::chrono::system_clock::now();
j_symbol_not_inserted = true;
} else if (user_input == int('k')) {
if (time_span.count() < _timer_constant && j_symbol_not_inserted == true) {
next_mode = normal;
} else {
if (j_symbol_not_inserted) _text_window.insert('j');
_text_window.insert('k');
}
j_symbol_not_inserted = false;
}
if (user_input == 9) { // tab
std::wstring tab = L" ";
_text_window.insert_symbols(tab);
_text_window.display();
} else if (user_input == 127) { // delete
_text_window.delete_symbol();
_text_window.display();
} else if (user_input == 10) { // newline
_text_window.insert_newline();
_text_window.auto_indent();
_text_window.display();
} else if (user_input == 0) { // CTRL + c
_command_window.print_abort_message();
} else if (user_input != int('j') && user_input != int('k')) { // normal insert
_text_window.insert(user_input);
_text_window.display();
}
}
} else if (_window == command) {
if (_mode == insert) {
if (user_input == 10) { // newline
command_string = _command_window.execute();
next_window = text;
next_mode = normal;
_text_window.display();
} else {
_command_window.insert(user_input);
_command_window.display();
}
}
}
if (command_string != L"") {
_execute(command_string);
command_string = L"";
}
_mode = next_mode;
_window = next_window;
}
}
void editor::_append_to_repeat_string(char number)
{
auto now = std::chrono::system_clock::now();
auto time_span = std::chrono::duration_cast<std::chrono::duration<double> >(now - _repeat_timer);
if (time_span.count() < _timer_constant) {
if (_repeat_string == "-1" && number != 0) {
_repeat_string = number;
} else {
_repeat_string += number;
}
} else {
_repeat_string = "-1";
}
_repeat_timer = std::chrono::system_clock::now();
}
int editor::_get_repeat_number()
{
int number = 1;
auto now = std::chrono::system_clock::now();
auto time_span = std::chrono::duration_cast<std::chrono::duration<double> >(now - _repeat_timer);
if (time_span.count() < _timer_constant) {
number = std::stoi(_repeat_string);
if (number == -1) {
number = 1;
}
}
_repeat_string = "-1";
_repeat_timer = std::chrono::system_clock::now();
return number;
}
void editor::_execute(std::wstring command)
{
if (command == L"q") {
_exit = true;
} else if (command == L"w") {
_text_window.save_file(_filename);
} else if (command == L"wq") {
_text_window.save_file(_filename);
_exit = true;
}
}
wint_t editor::_get_input()
{
wint_t input_symbol;
get_wch(&input_symbol);
return input_symbol;
}
<file_sep>/curses/text_window.hpp
#ifndef __TEXT__WINDOW__HPP__
#define __TEXT__WINDOW__HPP__
#include "file.hpp"
#include <memory>
#include <string>
class text_window {
public:
text_window() = delete;
text_window(std::string filename);
bool open_file(std::string filename);
bool save_file(std::string filename);
void display();
void insert_symbols(std::wstring symbols);
void insert(wint_t symbol);
void insert_newline();
void delete_symbol();
void auto_indent();
void curser_down(int jump);
void curser_left(int jump);
void curser_right(int jump);
void curser_up(int jump);
void curser_next_word(int word_count);
void curser_prev_word(int word_count);
void curser_start_line();
void curser_end_line();
void toggle_select();
void delete_selection();
void copy_selection();
void display_center();
void display_up(int jump);
void display_down(int jump);
void resize();
private:
void display(int buffer_start);
void buffer_up(int jump);
void buffer_down(int jump);
bool _use_select_color(int current_x, int current_y);
file _file;
int _left_margin;
int _right_margin;
int _max_line_size;
int _x_curser;
int _y_curser;
int _buffer_start;
int _scrolling_buffer_start;
std::tuple<int, int> _select_start;
bool _select_in_progress;
};
#endif // __TEXT__WINDOW__HPP__
<file_sep>/curses/Makefile
CXXFLAG= -std=c++1z -Wall -Wextra -g -Wunused -vv
LIBS=-lncursesw
ed: ed.cpp editor.o command_window.o text_buffer.o file.o text_window.o
g++ $(CXXFLAGS) ed.cpp editor.o command_window.o text_buffer.o text_window.o file.o $(LIBS) -o ed
editor.o: editor.cpp editor.hpp
g++ $(CXXFLAGS) -c editor.cpp $(LIBS)
command_window.o: command_window.cpp command_window.hpp
g++ $(CXXFLAGS) -c command_window.cpp $(LIBS)
text_buffer.o: text_buffer.cpp text_buffer.hpp
g++ $(CXXFLAGS) -c text_buffer.cpp $(LIBS)
file.o: file.cpp file.hpp
g++ $(CXXFLAGS) -c file.cpp $(LIBS)
text_window.o: text_window.cpp text_window.hpp
g++ $(CXXFLAGS) -c text_window.cpp $(LIBS)
clean:
rm *.o *~ ed
install:
make
chmod 755 ed
sudo cp ed /usr/local/bin/
<file_sep>/curses/text_window.cpp
#include "text_window.hpp"
#include "cassert"
#include "curses.h"
#define SELECT_COLOR 1
text_window::text_window(std::string filename)
: _file(filename), _left_margin(_file.get_left_margin()), _right_margin(1), _max_line_size(COLS - _left_margin - _right_margin),_x_curser(_left_margin), _y_curser(0), _buffer_start(0), _scrolling_buffer_start(0), _select_start(std::make_tuple(-1, -1)), _select_in_progress(false)
{
resize();
}
bool text_window::open_file(std::string filename)
{
return _file.open(filename);
}
bool text_window::save_file(std::string filename)
{
return _file.save(filename);
}
void text_window::display()
{
clear();
int end_line = _buffer_start + LINES - 2;
if (end_line >= _file.get_number_of_lines()) {
end_line = _file.get_number_of_lines() - 1;
}
auto display_line_number = [this](int current_line) {
std::string current_line_symbols = std::to_string(current_line);
attroff(COLOR_PAIR(SELECT_COLOR));
use_default_colors();
for (int x_printer = 0; x_printer < _left_margin; ++x_printer) {
if (x_printer < current_line_symbols.size()) {
addch(current_line_symbols.at(x_printer));
} else {
addch(char(32)); // whitespace
}
}
};
auto display_relative_line_number = [this](int current_line) {
if (current_line < _y_curser + _buffer_start) {
current_line = _y_curser + _buffer_start - current_line;
} else if (current_line > _y_curser + _buffer_start) {
current_line -= _y_curser + _buffer_start;
}
std::string current_line_symbols = std::to_string(current_line);
attroff(COLOR_PAIR(SELECT_COLOR));
use_default_colors();
for (int x_printer = 0; x_printer < _left_margin; ++x_printer) {
if (x_printer < current_line_symbols.size()) {
addch(current_line_symbols.at(x_printer));
} else {
addch(char(32)); // whitespace
}
}
};
auto display_text = [this](int current_line) {
std::wstring current_line_symbols{_file.get_line(current_line)};
for (int x_printer = 0; x_printer < current_line_symbols.size(); ++x_printer) {
if (_use_select_color(x_printer, current_line)) {
attron(COLOR_PAIR(SELECT_COLOR));
} else {
attroff(COLOR_PAIR(SELECT_COLOR));
use_default_colors();
}
std::wstring s;
wint_t symbol = current_line_symbols.at(x_printer);
s += symbol;
wchar_t wide_char[] = { s.at(0), 0x00 };
addwstr(wide_char);
}
};
int y_curser = 0;
if (_buffer_start < 0) {
y_curser -= _buffer_start;
}
if (_y_curser < LINES - 1) {
if (_buffer_start < 0) {
for (int line_number = 0; line_number <= end_line; ++line_number) {
move(y_curser, 0);
//display_line_number(line_number);
display_relative_line_number(line_number);
display_text(line_number);
++y_curser;
}
} else {
for (int line_number = _buffer_start; line_number <= end_line; ++line_number) {
move(y_curser, 0);
//display_line_number(line_number);
display_relative_line_number(line_number);
display_text(line_number);
++y_curser;
}
}
}
move(_y_curser, _x_curser);
_scrolling_buffer_start = _buffer_start;
}
void text_window::display(int buffer_start)
{
if (_scrolling_buffer_start < -((LINES - 2)/ 2)) {
_scrolling_buffer_start += (LINES - 2) / 4;
}
int old_scrolling_buffer_start = _scrolling_buffer_start;
int old_buffer_start = _buffer_start;
_buffer_start = _scrolling_buffer_start;
display();
_scrolling_buffer_start = old_scrolling_buffer_start;
_buffer_start = old_buffer_start;
}
void text_window::insert_symbols(std::wstring symbols)
{
if (_y_curser + _buffer_start >= _file.get_number_of_lines()) return;
_file.insert_symbols(_x_curser, _y_curser + _buffer_start, symbols);
int old_y = _y_curser;
curser_right(symbols.size());
if (old_y != _y_curser) curser_right(1);
}
void text_window::insert(wint_t symbol)
{
if (_y_curser + _buffer_start >= _file.get_number_of_lines()) return;
_file.insert_symbol(_x_curser, _y_curser + _buffer_start, symbol);
int old_y = _y_curser;
curser_right(1);
if (old_y != _y_curser) curser_right(1);
}
void text_window::insert_newline()
{
if (_y_curser + _buffer_start >= _file.get_number_of_lines()) return;
_file.insert_newline(_x_curser, _y_curser + _buffer_start);
curser_right(1);
}
void text_window::delete_symbol()
{
if (_x_curser == _left_margin) {
int old_x = _x_curser;
if (_file.get_number_of_lines() > 1 && _y_curser + _buffer_start != 0) {
curser_left(1);
_file.delete_symbol(old_x, _y_curser + _buffer_start + 1);
}
} else {
_file.delete_symbol(_x_curser, _y_curser + _buffer_start);
curser_left(1);
}
}
void text_window::auto_indent()
{
if (_y_curser == 0 && _buffer_start == 0 || _y_curser + _buffer_start > _file.get_number_of_lines()) return;
auto space_count = [this](int line_number) {
std::wstring line = _file.get_line(line_number);
if (line.size() == 0) return 0;
int counter = 0;
while (counter < line.size()) {
if (line.at(counter) == ' ' || line.at(counter) == '\n') {
++counter;
} else {
return counter;
}
}
return counter;
}(_y_curser + _buffer_start - 1);
if (space_count != 0) {
std::wstring indent = std::wstring(space_count, ' ');
insert_symbols(indent);
}
}
void text_window::curser_down(int jump)
{
curs_set(1);
_y_curser += jump;
int buffer_jump = 0;
if (_y_curser > LINES - 2) {
buffer_jump = _y_curser - LINES + 2;
_y_curser = LINES - 2;
}
buffer_down(buffer_jump);
if (_y_curser + _buffer_start >= 0) {
if (_y_curser + _buffer_start >= _file.get_number_of_lines()) {
_y_curser = _file.get_number_of_lines() - _buffer_start - 1;
}
if (_x_curser >= _file.get_line(_y_curser + _buffer_start).size() + _left_margin) {
_x_curser = _file.get_line(_y_curser + _buffer_start).size() + _left_margin;
}
}
}
void text_window::curser_up(int jump)
{
curs_set(1);
if (_y_curser + _buffer_start < jump) {
jump = _y_curser + _buffer_start;
}
_y_curser -= jump;
int buffer_jump = 0;
if (_y_curser < 0) {
buffer_jump = -_y_curser;
_y_curser = 0;
}
buffer_up(buffer_jump);
if (_y_curser + _buffer_start >= 0) {
if (_y_curser + _buffer_start < _file.get_number_of_lines()) {
if (_x_curser >= _file.get_line(_y_curser + _buffer_start).size() + _left_margin) {
_x_curser = _file.get_line(_y_curser + _buffer_start).size() + _left_margin;
}
}
}
}
void text_window::curser_left(int jump)
{
curs_set(1);
if (_x_curser == _left_margin && _y_curser == 0 && _buffer_start == 0) {
return;
} else if (_y_curser + _buffer_start >= _file.get_number_of_lines()) {
curser_up(1);
} else {
_x_curser -= jump;
while (_x_curser < _left_margin) {
curser_up(1);
if (_file.get_line(_buffer_start + _y_curser).size()== 0) {
_x_curser += 1;
}
else {
_x_curser += _file.get_line(_buffer_start + _y_curser).size() + 1;
}
}
}
}
void text_window::curser_right(int jump)
{
curs_set(1);
if (_y_curser + _buffer_start == _file.get_number_of_lines() - 1 && _x_curser == _file.get_line(_y_curser + _buffer_start).size() + _left_margin) {
return;
} else if (_y_curser + _buffer_start >= _file.get_number_of_lines()) {
curser_down(1);
} else {
_x_curser += jump;
while (_x_curser >= _file.get_line(_y_curser + _buffer_start).size() + _left_margin + 1) {
_x_curser -= _file.get_line(_y_curser + _buffer_start).size() + 1;
curser_down(1);
}
}
}
void text_window::buffer_down(int jump)
{
_buffer_start += jump;
if (_buffer_start >= _file.get_number_of_lines()) {
_buffer_start = _file.get_number_of_lines();
}
}
void text_window::buffer_up(int jump)
{
_buffer_start -= jump;
}
void text_window::curser_next_word(int word_count)
{
if (_y_curser + _buffer_start >= _file.get_number_of_lines()) return;
int line_index = _x_curser - _left_margin;
int distance = _file.next_word_index(line_index, _y_curser + _buffer_start, word_count) - line_index;
if (_file.get_line(_y_curser + _buffer_start).size() - _x_curser + _left_margin <= distance) {
_x_curser = _file.get_line(_y_curser + _buffer_start).size() + _left_margin;
if (_file.get_line(_y_curser + _buffer_start).size() != 0) _x_curser -= 1;
} else {
curser_right(distance);
}
}
void text_window::curser_prev_word(int word_count)
{
if (_y_curser + _buffer_start >= _file.get_number_of_lines()) return;
int line_index = _x_curser - _left_margin;
int distance = line_index - _file.prev_word_index(line_index, _y_curser + _buffer_start, word_count);
if (_x_curser - _left_margin < distance) {
_x_curser = _left_margin;
} else {
curser_left(distance);
}
}
void text_window::curser_start_line()
{
_x_curser = _left_margin;
}
void text_window::curser_end_line()
{
_x_curser = _file.get_line(_y_curser + _buffer_start).size() + _left_margin;
}
void text_window::toggle_select()
{
if (!_select_in_progress) {
std::get<0>(_select_start) = _x_curser - _left_margin;
std::get<1>(_select_start) = _y_curser + _buffer_start;
_select_in_progress = true;
} else {
_select_in_progress = false;
display();
}
}
void text_window::delete_selection()
{
if (!_select_in_progress) return;
int x_start = std::get<0>(_select_start);
int y_start = std::get<1>(_select_start);
int x_end = _x_curser - _left_margin;
int y_end = _y_curser + _buffer_start;
if (y_start == y_end) {
if (x_start > x_end) {
int temp = x_start;
x_start = x_end;
x_end = temp;
}
} else if (y_start > y_end) {
int temp_x = x_start;
int temp_y = y_start;
x_start = x_end;
x_end = temp_x;
y_start = y_end;
y_end = temp_y;
}
_file.delete_symbols(x_start, y_start, x_end, y_end);
toggle_select();
}
bool text_window::_use_select_color(int x_printer, int current_line)
{
if (_select_in_progress) {
auto y_in_selection_range = [current_line](int select_start, int y_curser) {
if (y_curser >= select_start) {
if (current_line <= y_curser && current_line >= select_start) {
return true;
}
} else {
if (current_line >= y_curser && current_line <= select_start) {
return true;
}
}
return false;
}(std::get<1>(_select_start), _y_curser + _buffer_start);
auto x_in_selection_range = [this, x_printer](int select_start, int x_curser) {
if (select_start <= x_curser) {
if (x_printer <= x_curser && x_printer >= select_start) return true;
}
if (select_start >= x_curser) {
if (x_printer >= x_curser && x_printer <= select_start) return true;
}
return false;
}(std::get<0>(_select_start) - _left_margin, _x_curser - _left_margin);
if (current_line == std::get<1>(_select_start)) {
if (_y_curser + _buffer_start > current_line) {
if (x_printer >= std::get<0>(_select_start) - _left_margin) return true;
} else if (_y_curser + _buffer_start < current_line) {
if (x_printer <= std::get<0>(_select_start) - _left_margin) return true;
} else if (x_in_selection_range) return true;
} else if (_y_curser + _buffer_start == current_line) {
if (_y_curser + _buffer_start > std::get<1>(_select_start)) {
if (x_printer < _x_curser - _left_margin) return true;
} else if (_y_curser + _buffer_start < std::get<1>(_select_start)) {
if (x_printer > _x_curser - _left_margin) return true;
}
} else if (y_in_selection_range) return true;
}
return false;
}
void text_window::display_center()
{
int old_y = _y_curser;
int jump_distance = _y_curser - ((LINES - 2) / 2);
if (jump_distance < 0) {
_y_curser = old_y - jump_distance;
buffer_up(-jump_distance);
} else {
buffer_down(jump_distance);
_y_curser = old_y - jump_distance;
}
display();
curs_set(1);
}
void text_window::display_up(int jump)
{
if (_scrolling_buffer_start == _buffer_start && _y_curser <= 3 * (LINES - 2) / 4) {
_buffer_start -= (LINES - 2) / 4;
_y_curser += (LINES - 2) / 4;
display();
curs_set(1);
} else {
_scrolling_buffer_start -= (LINES - 2) / 4;
display(_scrolling_buffer_start);
curs_set(0);
}
if (_scrolling_buffer_start == _buffer_start) curs_set(1);
}
void text_window::display_down(int jump)
{
if (_scrolling_buffer_start == _buffer_start && _y_curser >= (LINES - 2) / 4) {
_buffer_start += (LINES - 2) / 4;
_y_curser -= (LINES - 2) / 4;
display();
curs_set(1);
} else {
_scrolling_buffer_start += (LINES - 2) / 4;
display(_scrolling_buffer_start);
curs_set(0);
}
if (_scrolling_buffer_start == _buffer_start) curs_set(1);
}
void text_window::resize()
{
auto new_line_number = _file.resize(_y_curser + _buffer_start);
_buffer_start -= new_line_number - _y_curser - _buffer_start;
display();
}
<file_sep>/curses/editor.hpp
#ifndef __EDITOR__HPP__
#define __EDITOR__HPP__
#include <chrono>
#include <string>
#include "text_window.hpp"
#include "command_window.hpp"
class editor {
public:
editor() = delete;
editor(std::string filename);
void edit();
bool open_file(std::string filename);
bool save_file(std::string filename);
private:
void _append_to_repeat_string(char number);
int _get_repeat_number();
text_window _text_window;
command_window _command_window;
enum mode { normal=0, insert=1 } _mode;
enum window { text=0, command=1 } _window;
bool _exit;
std::chrono::system_clock::time_point _mode_switch_timer;
std::chrono::system_clock::time_point _repeat_timer;
std::string _repeat_string;
std::string _filename;
const double _timer_constant = 2;
void _execute(std::wstring command);
wint_t _get_input();
};
#endif // __EDITOR__HPP__
<file_sep>/curses/text_buffer.cpp
#include "text_buffer.hpp"
std::vector<std::tuple<std::wstring, bool> >& buffer::get_lines()
{
return _lines;
}
std::wstring buffer::get_line(int line_number)
{
return std::get<0>(_lines.at(line_number));
}
int buffer::get_number_of_lines()
{
return _lines.size();
}
void buffer::clear_text()
{
_lines.clear();
}
<file_sep>/curses/text_buffer.hpp
#ifndef __TEXT__BUFFER__HPP__
#define __TEXT__BUFFER__HPP__
#include <vector>
#include <string>
#include <tuple>
class buffer {
public:
std::vector<std::tuple<std::wstring, bool> >& get_lines();
int get_number_of_lines();
std::wstring get_line(int line_number);
void clear_text();
private:
std::vector<std::tuple<std::wstring, bool> > _lines = std::vector<std::tuple<std::wstring, bool> >{};
};
#endif // __TEXT__BUFFER__HPP__
<file_sep>/curses/ed.cpp
#include <iostream>
#include <fstream>
#include <locale>
#include <string>
#include <sstream>
#include <cstdlib>
#include "signal.h"
#include "unistd.h"
#include "curses.h"
#include "editor.hpp"
void abort_handler(int s) {}
int main(int argc, char* argv[])
{
initscr();
cbreak();
noecho();
start_color();
use_default_colors();
init_pair(1, COLOR_BLACK, COLOR_WHITE);
struct sigaction sig_handler;
sig_handler.sa_handler = abort_handler;
sigemptyset(&sig_handler.sa_mask);
sig_handler.sa_flags = 0;
sigaction(SIGINT, &sig_handler, NULL);
try {
if (!setlocale(LC_ALL, "")) {
std::cout << "Couldnt set locale" << "\n";
}
editor ed = editor(argv[1]);
ed.edit();
std::system("stty sane");
} catch (...) {
std::system("stty sane");
}
endwin();
return 0;
}
<file_sep>/curses/command_window.hpp
#ifndef __COMMAND__WINDOW__HPP__
#define __COMMAND__WINDOW__HPP__
#include <vector>
#include <string>
class command_window {
public:
command_window();
void display();
void insert(wint_t symbol);
void delete_symbol();
std::wstring execute();
void print_abort_message();
private:
std::wstring _command_string;
int _x_curser;
};
#endif // __COMMAND__WINDOW__HPP__
<file_sep>/curses/command_window.cpp
#include "command_window.hpp"
#include "cassert"
#include "curses.h"
command_window::command_window()
: _command_string(L""), _x_curser(0)
{}
void command_window::display()
{
move(LINES - 1, 0);
for (int x_printer = 0; x_printer < _command_string.size(); ++x_printer) {
std::wstring s;
wint_t symbol = _command_string.at(x_printer);
s += symbol;
wchar_t wide_char[] = { s.at(0), 0x00 };
addwstr(wide_char);
}
}
void command_window::insert(wint_t symbol)
{
_command_string += symbol;
}
std::wstring command_window::execute()
{
auto command = _command_string.substr(1);
_command_string = L"";
return command;
}
void command_window::print_abort_message()
{
move(LINES - 1, 0);
addstr(":q to exit");
}
<file_sep>/curses/mapping.cpp
#include <fstream>
#include "curses.h"
#include "cstdlib"
#include <iostream>
#include <locale>
#include "signal.h"
void abort_handler(int s) {
printf("%d\n", s);
}
int main()
{
try {
if (!setlocale(LC_ALL, "")) {
std::cout << "Couldnt set locale" << "\n";
}
initscr();
cbreak();
noecho();
struct sigaction sig_handler;
sig_handler.sa_handler = abort_handler;
sigemptyset(&sig_handler.sa_mask);
sig_handler.sa_flags = 0;
sigaction(SIGINT, &sig_handler, NULL);
// Mappings
nl();
wint_t a;
get_wch(&a);
std::ofstream file;
file.open("mappings", std::wios::out | std::wios::in);
file << a << '\n';
file.close();
endwin();
std::system("stty sane");
} catch (...) {
std::system("stty sane");
}
return 0;
}
<file_sep>/curses/file.cpp
#include "file.hpp"
#include <fstream>
#include <sstream>
#include "curses.h"
#include "cassert"
#include <codecvt>
file::file(std::string filename)
: _tab_size(4)
{
open(filename);
_left_margin = std::to_string(_buffer.get_number_of_lines()).size() + 1;
_max_line_size = COLS - _left_margin - 1;
}
bool file::open(std::string filename)
{
try {
// read unicode from file
std::wifstream wif(filename);
wif.imbue(std::locale(std::locale(""), new std::codecvt_utf8<wchar_t>));
std::wstringstream file;
file << wif.rdbuf();
std::wstring line;
while (std::getline(file, line)) {
_buffer.get_lines().push_back(std::make_tuple(std::wstring{}, true));
int x_curser = 0;
for (int i = 0; i < line.size(); ++i) {
if (x_curser == _max_line_size) {
std::get<1>(_buffer.get_lines().back()) = false;
_buffer.get_lines().push_back(std::make_tuple(std::wstring{}, true));
x_curser = 0;
}
std::wstring s;
s += line.at(i);
wchar_t wide_char[] = { s.at(0), 0x00 };
std::get<0>(_buffer.get_lines().back()) += wide_char;
++x_curser;
}
}
// init _buffer.get_lines() if file is empty
if (_buffer.get_number_of_lines() == 0) {
_buffer.get_lines().push_back(std::make_tuple(std::wstring{}, true));
}
return true;
} catch (...) {
}
return false;
}
int file::get_left_margin()
{
return _left_margin;
}
bool file::save(std::string filename)
{
auto string_to_write = [this]() {
std::wstring new_file_string;
for (auto line_info : _buffer.get_lines()) {
for (auto symbol : std::get<0>(line_info)) {
new_file_string += symbol;
}
if (std::get<1>(line_info) == true) {
wchar_t wide_char[] = { 10, 0x00 };
new_file_string += wide_char;
}
}
return new_file_string;
}();
std::wofstream wof(filename);
wof.imbue(std::locale(std::locale(), new std::codecvt_utf8<wchar_t>()));
wof << string_to_write;
return true;
}
void file::insert_symbols(int x_curser, int line_number, std::wstring symbols)
{
if (x_curser - _left_margin >= get_line(line_number).size()) std::get<0>(_buffer.get_lines().at(line_number)) += symbols;
else std::get<0>(_buffer.get_lines().at(line_number)).insert(x_curser - _left_margin, symbols);
if (get_line(line_number).size() > _max_line_size) {
if (is_end_line(line_number) == true) {
std::get<1>(_buffer.get_lines().at(line_number)) = false;
auto next_line_iter = _buffer.get_lines().begin() + line_number + 1;
_buffer.get_lines().insert(next_line_iter, std::make_tuple(std::wstring{}, true));
}
auto next_line = std::get<0>(_buffer.get_lines().at(line_number)).substr(_max_line_size);
std::get<0>(_buffer.get_lines().at(line_number)) = std::get<0>(_buffer.get_lines().at(line_number)).substr(0, _max_line_size);
insert_symbols(_left_margin, line_number + 1, next_line);
}
}
void file::insert_symbol(int x_curser, int line_number, wint_t symbol)
{
assert(line_number < _buffer.get_number_of_lines());
auto simple_insert_symbol = [this](int x_curser, int line_number, wint_t symbol) {
std::wstring s;
wint_t c = symbol;
s += c;
wchar_t wide_char[] = {s.at(0), 0x00};
std::get<0>(_buffer.get_lines().at(line_number)).insert(x_curser - _left_margin, wide_char);
};
if (is_end_line(line_number) == true) {
simple_insert_symbol(x_curser, line_number, symbol);
if (std::get<0>(_buffer.get_lines().at(line_number)).size() > _max_line_size) {
auto next_line_symbol = std::get<0>(_buffer.get_lines().at(line_number)).back();
auto next_line_tuple = std::make_tuple(std::wstring{next_line_symbol}, true);
auto next_line_iter = _buffer.get_lines().begin() + line_number + 1;
_buffer.get_lines().insert(next_line_iter, next_line_tuple);
std::get<1>(_buffer.get_lines().at(line_number)) = false;
std::get<0>(_buffer.get_lines().at(line_number)).pop_back();
}
} else {
simple_insert_symbol(x_curser, line_number, symbol);
auto next_line_symbol = std::get<0>(_buffer.get_lines().at(line_number)).back();
std::get<0>(_buffer.get_lines().at(line_number)).pop_back();
insert_symbol(_left_margin, line_number + 1, next_line_symbol);
}
}
void file::insert_newline(int x_curser, int line_number)
{
assert(line_number < _buffer.get_lines().size());
auto current_line = std::get<0>(_buffer.get_lines().at(line_number));
std::wstring next_line = L"";
auto next_line_iter = _buffer.get_lines().begin() + line_number + 1;
next_line += current_line.substr(x_curser - _left_margin, current_line.size());
_buffer.get_lines().insert(next_line_iter, std::make_tuple(next_line, true));
auto prev_line = current_line.substr(0, x_curser - _left_margin);
_buffer.get_lines().at(line_number) = std::make_tuple(prev_line, true);
}
void file::delete_symbol(int x_curser, int line_number)
{
assert(line_number < _buffer.get_lines().size());
if (x_curser - _left_margin == 0) {
if (line_number == 0) return;
if (!(get_line(line_number - 1).size() == _max_line_size)) {
if (is_end_line(line_number) && (line_number != _buffer.get_lines().size() - 1)) {
if (get_line(line_number + 1).size() + get_line(line_number).size() <= _max_line_size) {
std::get<1>(_buffer.get_lines().at(line_number - 1)) = true;
}
}
auto line = std::get<0>(_buffer.get_lines().at(line_number));
_buffer.get_lines().erase(_buffer.get_lines().begin() + line_number);
insert_symbols(get_line(line_number - 1).size() + _left_margin, line_number - 1, line);
}
} else {
auto erase_iter = std::get<0>(_buffer.get_lines().at(line_number)).begin() + x_curser - _left_margin - 1;
std::get<0>(_buffer.get_lines().at(line_number)).erase(erase_iter);
if (is_end_line(line_number) == false) { // append the first letter of next line
auto next_line_symbol = std::get<0>(_buffer.get_lines().at(line_number + 1)).front();
std::get<0>(_buffer.get_lines().at(line_number)) += next_line_symbol;
delete_symbol(_left_margin + 1, line_number + 1);
if (get_line(line_number + 1).size() == 0) {
_buffer.get_lines().erase(_buffer.get_lines().begin() + line_number + 1);
std::get<1>(_buffer.get_lines().at(line_number)) = true;
}
}
}
}
void file::delete_symbols(int x_start, int y_start, int x_end, int y_end)
{
if (y_end - y_start > 1) {
auto erase_start = _buffer.get_lines().begin() + y_start + 1;
auto erase_end = _buffer.get_lines().begin() + y_end;
_buffer.get_lines().erase(erase_start, erase_end);
}
auto delete_substring = [this](int start_x, int end_x, int line_number) {
auto& line = std::get<0>(_buffer.get_lines().at(line_number));
line.erase(line.begin() + start_x, line.begin() + end_x);
if (!is_end_line(line_number)) {
std::get<1>(_buffer.get_lines().at(line_number)) = true;
delete_symbol(_left_margin, line_number + 1);
}
};
if (y_start == y_end) {
if (x_start == 0 && x_end == std::get<0>(_buffer.get_lines().at(y_start)).size()) {
auto erase_start = _buffer.get_lines().begin() + y_start;
_buffer.get_lines().erase(erase_start);
} else delete_substring(x_start, x_end, y_start);
} else {
delete_substring(x_start, std::get<0>(_buffer.get_lines().at(y_start)).size(), y_start);
auto erase_start = _buffer.get_lines().begin() + y_start + 1;
_buffer.get_lines().erase(erase_start);
}
}
std::wstring file::get_line(int line_number)
{
assert(line_number <= _buffer.get_lines().size());
return _buffer.get_line(line_number);
}
bool file::is_end_line(int line_number)
{
assert(line_number <= _buffer.get_lines().size());
return std::get<1>(_buffer.get_lines().at(line_number));
}
int file::get_number_of_lines()
{
return _buffer.get_lines().size();
}
int file::next_word_index(int x_index, int line_number, int word_count)
{
auto line = get_line(line_number);
if (x_index >= line.size() || line.size() == 0) return 0;
for (; x_index < line.size(); ++x_index) {
if (word_count == 0) return x_index;
if (int(line.at(x_index)) == 160 || int(line.at(x_index)) == 95) --word_count;
if (int(line.at(x_index)) == 32) {
if (x_index < line.size() - 1) {
if (int(line.at(x_index + 1)) != 32) --word_count;
} else {
--word_count;
}
}
}
return x_index;
}
int file::prev_word_index(int x_index, int line_number, int word_count)
{
auto line = get_line(line_number);
if (line.size() == 0) return 0;
if (x_index == line.size()) return --x_index;
for (; x_index >= 0; --x_index) {
if (word_count == 0) return x_index;
if (int(line.at(x_index)) == 160 || int(line.at(x_index)) == 95) --word_count;
if (int(line.at(x_index)) == 32) {
if (x_index > 0) {
if (int(line.at(x_index - 1)) != 32) --word_count;
} else {
--word_count;
}
}
}
return x_index;
}
int file::resize(int current_line_number)
{
auto find_empty_bottom_lines = [this]() {
int empty_bottom_lines = 0;
for (auto _ = _buffer.get_lines().end(); std::get<0>(*_).size() != 0; --_) {
++empty_bottom_lines;
}
return empty_bottom_lines;
};
int empty_bottom_lines = find_empty_bottom_lines();
_max_line_size = COLS - _left_margin - 1;
auto lines = std::vector<std::tuple<std::wstring, bool> >{};
lines.push_back(std::make_tuple(std::wstring{}, true));
lines.reserve(_buffer.get_lines().size());
int x_index = 0;
for (auto line : _buffer.get_lines()) {
for (int i = 0; i < std::get<0>(line).size(); ++i) {
if (x_index == _max_line_size) {
std::get<1>(lines.back()) = false;
lines.push_back(std::make_tuple(std::wstring{}, true));
x_index = 0;
}
std::wstring s;
s += std::get<0>(line).at(i);
wchar_t wide_char[] = { s.at(0), 0x00 };
std::get<0>(lines.back()) += wide_char;
++x_index;
}
if (std::get<1>(line) == true) {
std::get<1>(lines.back()) = true;
lines.push_back(std::make_tuple(std::wstring{}, true));
x_index = 0;
}
}
int empty_bottom_lines_diff = find_empty_bottom_lines() - empty_bottom_lines;
lines.erase(lines.end() - 1 - empty_bottom_lines_diff, lines.end());
_buffer.get_lines() = lines;
return current_line_number;
}
<file_sep>/curses/file.hpp
#ifndef __FILE__HPP__
#define __FILE__HPP__
#include "text_buffer.hpp"
class file {
public:
file() = delete;
file(std::string filename);
bool open(std::string filename);
int get_left_margin();
bool save(std::string filename);
void insert_symbols(int x_curser, int line_number, std::wstring symbols);
void insert_symbol(int x_curser, int line_number, wint_t symbol);
void insert_newline(int x_curser, int line_number);
void delete_symbol(int x_curser, int line_number);
void delete_symbols(int x_start, int y_start, int x_end, int y_end);
std::wstring get_line(int line_number);
bool is_end_line(int line_number);
int get_number_of_lines();
int next_word_index(int x_index, int line_number, int word_count);
int prev_word_index(int x_index, int line_number, int word_count);
int resize(int current_line_number);
private:
int _tab_size;
int _left_margin;
int _max_line_size;
buffer _buffer;
};
#endif // __FILE__HPP__
| 9bae26c70819f03b89962361ec5d220521ea2241 | [
"Makefile",
"C++"
] | 13 | C++ | Henkeboi/hk | 71a5cbcabbcfd44ef66b705cd0e45b44e4332107 | 8cd17691efb1e7995f804bde78a66ee49528b2a2 |
refs/heads/master | <repo_name>AngusPasc/ActaNet-Control<file_sep>/README.md
# ActaNet-Control
ActaNet Control HTML 5 version
<file_sep>/ActaNet.Control/ActaNet.Control.REST/Controllers/LoginController.cs
using ActaNet.Control.REST.Models;
using Swashbuckle.Swagger.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ActaNet.Control.REST.Controllers
{
public class LoginController : ApiController
{
[SwaggerOperation("Login")]
[SwaggerResponse(HttpStatusCode.OK)]
[SwaggerResponse(HttpStatusCode.BadRequest)]
public IHttpActionResult Post(LoginModel loginModel) => BadRequest("Invalid username or password");
//// GET api/<controller>/5
//public string Get(int id)
//{
// return "value";
//}
//// POST api/<controller>
//public void Post([FromBody]string value)
//{
//}
//// PUT api/<controller>/5
//public void Put(int id, [FromBody]string value)
//{
//}
//// DELETE api/<controller>/5
//public void Delete(int id)
//{
//}
}
} | c825fbafb22b21bcf3f34437c1851d34e23acbdf | [
"Markdown",
"C#"
] | 2 | Markdown | AngusPasc/ActaNet-Control | da6592b8a04a2f94159b987f99472ef29494c271 | bc670944550165ad1c8dae7331a830ce27720ba3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.