本文整理汇总了PHP中writeToFile函数的典型用法代码示例。如果您正苦于以下问题:PHP writeToFile函数的具体用法?PHP writeToFile怎么用?PHP writeToFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了writeToFile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: sendMessage
function sendMessage($sentMsg, $senderChatId, $senderEmail, $groupId)
{
global $conn;
writeToFile("msg: {$sentMsg}, chat_id: {$senderChatId}, email: {$senderEmail}, group_id: {$groupId}");
//get the current timestamp
$timeStamp = date("Y-m-d H:i:s");
if ($groupId) {
//insert the sent msg to DB
$sql = "INSERT INTO CHATLINETABLE" . "(id, chat_id, user_email, text_line, time_stamp, group_id)" . "VALUES (NULL, {$senderChatId}, '{$senderEmail}', '{$sentMsg}', '{$timeStamp}', {$groupId})";
} else {
//insert the sent msg to DB
$sql = "INSERT INTO CHATLINETABLE" . "(id, chat_id, user_email, text_line, time_stamp, group_id)" . "VALUES (NULL, {$senderChatId}, '{$senderEmail}', '{$sentMsg}', '{$timeStamp}',NULL)";
}
try {
$result = $conn->query($sql);
if ($result) {
if (isset($_COOKIE['groupId'])) {
getGroupData($_COOKIE['groupId']);
} else {
if (isset($_COOKIE['sender']) && isset($_COOKIE['receiver'])) {
getMessages($_COOKIE['sender'], $_COOKIE['receiver'], $_COOKIE['recName']);
}
}
} else {
echo "Error while inserting data to chat table";
}
} catch (Exception $e) {
echo 'Exception in sendMessage() :' . $e->getMessage();
}
}
开发者ID:TalentSourcing,项目名称:web-dev,代码行数:30,代码来源:chat1.php
示例2: setConfig
public function setConfig($key, $val)
{
if (!is_string($key) || !is_string($val)) {
//记录日志
logMsg(SL_ERROR, "参数错误!");
return FALSE;
}
$this->arrConfig[$key] = $val;
$content = json_encode($this->arrConfig);
writeToFile(CONFIG_FILE, $content);
return TRUE;
}
开发者ID:ethanshancn,项目名称:zhSpider,代码行数:12,代码来源:config.php
示例3: createFile
function createFile($dir)
{
$file = "index.php";
if (file_exists($dir . "/" . $file)) {
echo $dir . "/" . $file . ' already exists!';
} else {
if (fopen($dir . "/" . $file, 'w+')) {
echo $dir . "/" . $file . ' was created!<br />';
writeToFile($dir . "/" . $file);
} else {
echo "ERROR: " . $php_errormsg . "<br />";
}
}
}
开发者ID:kcoltharp,项目名称:InternetProgramming,代码行数:14,代码来源:listDir.php
示例4: getCacheData
function getCacheData($key, $sql)
{
global $webRootPath, $_pvar;
$filePath = $webRootPath . "cache/datacache/{$key}.php";
$dir = dirname($filePath);
if (!file_exists($dir)) {
mkdir($dir);
}
if (!file_exists($filePath)) {
$array = getData($sql);
writeToFile($filePath, "<?php\n \$_pvar=" . var_export($array, true) . " \n?>");
}
include $filePath;
return $_pvar;
}
开发者ID:qichangjun,项目名称:HTMLLearn,代码行数:15,代码来源:database.php
示例5: fetch_wikihow
function fetch_wikihow($url)
{
echo "<h2>FROM WIKIHOW</h2>";
global $current_file;
global $machine_id;
global $source_machine;
global $spell_checked;
global $source_id, $oldSource_id;
global $fetchFromOutside, $oldSource, $lastResult, $newResult;
$title = substr($url, 23);
$query = "select * from data_how where title = '" . mysql_real_escape_string($title) . "'";
$result = mysql_query($query) or trigger_error(mysql_error() . " in {$query}", E_USER_ERROR);
if (mysql_num_rows($result) && !$fetchFromOutside) {
$row = mysql_fetch_array($result);
$source_id = $row['id'];
$source_machine = $row['machine'];
$current_file = "/hownew/{$source_id}";
$how_return = get_file_contents($current_file, $source_machine);
} else {
require_once 'class.WikiHow.php';
$mywiki = new WikiHow($url);
$how_return = $mywiki->start_search();
if ($how_return) {
if (mysql_num_rows($result)) {
$source_machine = $row['machine'];
$source_id = $row['id'];
$current_file = "/hownew/" . $row['id'];
$str = substr($result, 0, 500);
$newResult = str2hex($str);
if ($newResult != $lastResult || $oldSource != "how") {
writeToFile($source_machine, DATA_PATH . $current_file, $how_return);
}
} else {
$query = "insert into data_how(title,machine) values('" . mysql_real_escape_string($title) . "',{$machine_id})";
mysql_query($query) or trigger_error(mysql_error() . " in {$query}", E_USER_ERROR);
$source_id = mysql_insert_id();
file_put_contents(DATA_PATH . "/hownew/{$source_id}", $how_return);
$source_machine = $machine_id;
$current_file = "/hownew/{$source_id}";
}
}
}
echo "HOW RETURN : " . $how_return;
return $how_return;
}
开发者ID:superego546,项目名称:SMSGyan,代码行数:45,代码来源:fix_fetch_functions.php
示例6: start
function start()
{
// Server IP address
$address = '10.9.20.205';
// Port to listen
$port = 27005;
$mysock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($mysock, $address, $port) or die('Could not bind to address');
socket_listen($mysock, 5);
$client = socket_accept($mysock);
// read 1024 bytes from client
$input = socket_read($client, 1024);
// write received data to the file
writeToFile('abc.txt', $input);
socket_close($client);
socket_close($mysock);
return $input;
}
开发者ID:Tachyon,项目名称:Counter-Strike-Server-FInder,代码行数:18,代码来源:listen.class.php
示例7: filebuild
function filebuild($typefilename = 'mysql', $arrval = array(), $contenthtml = '', $file_name = '')
{
if ($typefilename == 'mysql') {
$contenthtml = str_replace("{mysql_hostname}", $arrval["mysql_hostname"], $contenthtml);
$contenthtml = str_replace("{mysql_username}", $arrval["mysql_username"], $contenthtml);
$contenthtml = str_replace("{mysql_password}", $arrval["mysql_password"], $contenthtml);
$contenthtml = str_replace("{mysql_database}", $arrval["mysql_database"], $contenthtml);
$contenthtml = str_replace("{mysql_prefix}", $arrval["mysql_prefix"], $contenthtml);
$contenthtml = str_replace("{domain_name}", $arrval["domain_name"], $contenthtml);
$contenthtml = str_replace("{base_weburl}", $arrval["base_weburl"], $contenthtml);
$contenthtml = str_replace("{document_dir}", $arrval["document_dir"], $contenthtml);
$contenthtml = str_replace("{url_time}", $arrval["url_time"], $contenthtml);
$contenthtml = str_replace("{user_name}", $arrval["user_name"], $contenthtml);
} else {
$contenthtml = md5("gvphp.org") . "" . $contenthtml;
}
writeToFile($file_name, $contenthtml, $method = "w+");
}
开发者ID:rttg125,项目名称:website,代码行数:18,代码来源:index.php
示例8: createNewWiki
function createNewWiki($newWrapper, $newSource, $dirShift, $baseDir)
{
global $data, $templatename, $wikiframe;
$wrapperpath = $dirShift . $newWrapper;
$sourcepath = $dirShift . $newSource;
if (file_exists($wrapperpath)) {
$data .= "error:true, message:\"A wrapper file of the name '{$newWrapper}' already exists\",";
} else {
if (file_exists($sourcepath)) {
$data .= "error:true, message:\"A source file of the name '{$newSource}' already exists\",";
} else {
// COPY TEMPLATE // Copy the template wiki
$source = file_get_contents($templatename);
$source = preg_replace('/SiteUrl: ".*"/i', "SiteUrl: \"{$baseDir}{$newWrapper}\"", $source);
writeToFile($sourcepath, $source);
// CREATE WRAPPER // Open the wikiframe, put in the new filename and go.
$output = file_get_contents($wikiframe);
$output = preg_replace('/"WIKIPATH"/i', "\"{$newSource}\"", $output);
writeToFile($wrapperpath, $output);
}
}
}
开发者ID:pohly,项目名称:mts,代码行数:22,代码来源:Functions.php
示例9: done
function done($msg, $template = "ERROR\n%s")
{
printf($template, $msg);
global $localaddr;
if ($_SERVER['REMOTE_ADDR'] != $localaddr) {
$result = sprintf(str_replace("\n", ", ", $template), $msg);
writeToFile("result: " . $result);
// only if it's a bad pass, text me
if (strpos($msg, 'assword') === FALSE) {
exit;
}
$to = "YOUR_EMAIL_ADDRESS_IF_REQUIRED";
$subject = "auth alert";
$message .= $result . "\n";
$message .= $_SERVER['REMOTE_ADDR'] . " user: " . $_REQUEST['user'] . ", field: " . $_REQUEST['field'] . ", pass length: " . strlen($_REQUEST['pass']);
$from = "EMAIL_TO_SEND_FROM";
$headers = "From: {$from}";
$sendmail_params = "-f {$from} -r {$from}";
writeToFile("mail sent: " . (mail($to, $subject, $message, $headers, $sendmail_params) ? 'true' : 'false'));
}
exit;
}
开发者ID:hayashi1110,项目名称:xAuth,代码行数:22,代码来源:smf_auth.php
示例10: template
function template($path)
{
global $developmode;
$file = "cache/template/" . $path;
$dir = dirname($file);
if (!file_exists($dir)) {
/*
$dirParts = explode("/",$dir);
for($i=0;$i<count($dirParts);$i++){
$dirForCreate="";
for($j=0;$j<=$i;$j++){
$dirForCreate.=$dirParts[$j]."/";
}
if(!file_exists($dirForCreate)){
mkdir($dirForCreate,0777,true);
}
}
*/
mkdir($dir, 0777, true);
}
if (!file_exists($file) || file_exists($file) && filectime($path) > filectime($file)) {
$fp = fopen($path, 'r');
$fz = filesize($path);
if ($fz) {
$theData = fread($fp, filesize($path));
$rSlot = " *([^}]+)";
$patterns = array("/\\{include:{$rSlot}\\}/", "/\\{for:{$rSlot} *;{$rSlot} *;{$rSlot}\\}/", "/\\{\\/for\\}/", "/\\{echo:{$rSlot}\\}/", "/\\{if:{$rSlot}\\}/", "/\\{\\/if\\}/", "/\\{elseif:{$rSlot}\\}/", "/\\{else\\}/", "/\\{([\$][^}]+)\\}/", "/\\{css:{$rSlot}\\}/", "/\\{loopsql:{$rSlot} cachekey:{$rSlot}\\}/", "/\\{loopsql:{$rSlot}\\}/", "/\\{\\/loopsql\\}/", "/\\{\\[{$rSlot}\\]\\}/", "/\\{{$rSlot}\\(\\[{$rSlot}\\]\\)}/", "/\\{langtext:{$rSlot}\\|{$rSlot}\\}/", "/\\{\\{{$rSlot}\\}\\}/", "/\\{hasdata:\\[{$rSlot}\\]\\}/", "/\\{hasdata:{$rSlot}\\}/", "/\\{\\/hasdata}/", "/include(_once)* +[\"'](..\\/)*include\\/template.php[\"'] *;/", "/\\{foreach:{$rSlot} +counter:{$rSlot}\\}/", "/\\{foreach:{$rSlot}\\}/", "/\\{\\/foreach}/");
$replacements = array("<?php include(template(\"\\1\"));?>", "<?php for(\\1;\\2;\\3){ ?>", "<?php }?>", "<?php echo \\1; ?>", "<?php if(\\1){?>", "<?php }?>", "<?php }elseif(\\1){ ?>", "<?php }else{ ?>", "<?php echo \\1;?>", "<?php cssTemplate('\\1'); ?>", "<?php \$_data_rs=getCacheData(\\2,\\1);foreach(\$_data_rs as \$_d){ ?>", "<?php \$_data_rs=query(\\1);while(\$_d=mysqli_fetch_array(\$_data_rs)){ ?>", "<?php }?>", "<?php echo \$_d[\\1]; ?>", "<?php echo \\1(\$_d[\\2]); ?>", "<?php langText(array('\\1','\\2')) ?>", "<?php echo nl2br(\$_d[\\1]); ?>", "<?php if(\$_d[\\1]){?>", "<?php if(\\1){?>", "<?php }?>", "", "<?php \\2=-1;foreach(\\1){\\2++?>", "<?php foreach(\\1){?>", "<?php }?>");
$theData = preg_replace($patterns, $replacements, $theData);
} else {
$theData = "";
}
fclose($fp);
writeToFile($file, $theData);
//chmod($file, 0777);
}
return $file;
}
开发者ID:qichangjun,项目名称:HTMLLearn,代码行数:38,代码来源:template.php
示例11: generateMVC
function generateMVC($debug_on)
{
$debug = "Debug Info:<br>";
$files = glob('../objects/*.{json}', GLOB_BRACE);
$sql_all = '';
foreach ($files as $file) {
$filename = basename($file, '.json');
if ($filename == 'DEFAULT') {
continue;
}
$debug .= '<h3>' . $filename . '</h3>';
$myfile = fopen("../objects/DEFAULT.json", "r") or die("UNABLE TO OPEN FILE!");
$default_json = fread($myfile, filesize("../objects/DEFAULT.json"));
fclose($myfile);
$myfile = fopen($file, "r") or die("UNABLE TO OPEN FILE!");
$json = fread($myfile, filesize($file));
fclose($myfile);
$default_obj = json_decode($default_json, true);
$obj = json_decode($json, true);
$data = getData($obj, $default_obj, $filename);
$sql = writeFullSQL($data['sql'], $filename);
$model = writeFullModel($data['model'], $filename);
$controller = writeFullController($filename);
$debug .= '<br>------ SQL ---------------------<br><br>' . $sql . '<br><br>';
$debug .= '<br>------ MODEL ---------------------<br><br>' . convertToHTML($model) . '<br><br>';
$debug .= '<br>------ CONTROLLER ---------------------<br><br>' . convertToHTML($controller) . '<br><br>';
$model = convertToFileText($model);
$sql_all .= "\n" . $sql;
writeToFile($model, '../../model/', $filename, '.php');
$controller = convertToFileText($controller);
writeToFile($controller, '../../controller/', $filename . 'Controller', '.php');
}
writeToFile($sql_all, '../sql/', 'create_tables', '.sql');
if ($debug_on) {
echo '<hr><div class="debug-info">' . $debug . '</div>';
}
return array('success' => 1, 'sql' => $sql_all, 'debug' => $debug);
}
开发者ID:jocodev1,项目名称:colliermvc,代码行数:38,代码来源:build.php
示例12: Copyright
<?php
/*/////////////////////////////////////////////////////////////////////////////
MiniTiddlyServer: A mini-server for TiddlyWikis
Copyright (C) 2007 Sean Clark Hess and Saq Imtiaz
MiniTiddlyServer is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
////////////////////////////////////////////////////////////////////////////////*/
// UPDATE FILE MOD TIME //
$newfiletime = filemtime($clientRequest->sourceFile);
// Create the new access file and update the reference //
$actualfile = $module->name . "/access/{$newfiletime}.txt";
$recentChangesFile = $serverInfo->ModulesDirectory . $actualfile;
writeToFile($recentChangesFile, "");
$serverResponse->setString("conflictmodtime", $newfiletime);
开发者ID:pohly,项目名称:mts,代码行数:29,代码来源:ConflictsPostSave.php
示例13: writeToFile
}
if (isset($_POST['substringLength']) && !empty($_POST['substringLength'])) {
$substringLength = $_POST['substringLength'];
}
if (isset($_POST['alertName']) && !empty($_POST['alertName'])) {
$alertName = $_POST['alertName'];
}
if (isset($_POST['snortFile']) && !empty($_POST['snortFile'])) {
$snortFile = $_POST['snortFile'];
if (!file_exists($snortFile)) {
//if the snort output file doesn't already exist, write out the header information
$header = "#\n#---------------------------\n# Data Loss Prevention rules\n#---------------------------\n";
writeToFile($snortFile, $header);
}
}
echo "<h2>Selected substring:</h2>";
$substring = selectSubstring($useRepository, $repositoryLocations, genHistogram($inputText), $inputText, $substringLength);
echo "\"{$substring}\"";
echo "<h2>Regex:</h2>";
echo createRegex($substring);
echo "<h2>Snort rule:</h2>";
$rule = createSnortRule(getNextsid($snortFile), $alertName, $substring);
echo "{$rule}<br><br>";
if ($snortFile != "") {
//if snortFile was passed, write the rule out to the snort file
writeToFile($snortFile, $rule);
echo "Snort rule written to {$snortFile}<br><br>";
}
?>
</body>
</html>
开发者ID:bill-lonely,项目名称:snortdlp,代码行数:31,代码来源:launcher.php
示例14: var_export
<?php
include_once 'moduledata.php';
include_once '../../include/lib.php';
for ($i = 0; $i < count($ModuleData); $i++) {
$item = $ModuleData[$i];
for ($j = 0; $j < count($item["Modules"]); $j++) {
$item1 = $item["Modules"][$j];
if ($item1["Type"] == "Chart") {
for ($k = 0; $k < count($item1["Column"]); $k++) {
$item2 = $item1["Column"][$k];
if (key_exists("StatisticIsFromOtherTable", $item2)) {
$item2["StatisticReferenceCondition"] = "";
}
$item1["Column"][$k] = $item2;
}
}
$item["Modules"][$j] = $item1;
}
$ModuleData[$i] = $item;
}
$output = var_export($ModuleData, true);
$header = "<?php \n \$ModuleData = ";
writeToFile("moduledata.php", $header . $output . ";");
开发者ID:qichangjun,项目名称:HTMLLearn,代码行数:24,代码来源:modify.php
示例15: foreach
}
if ($isConflict) {
// REDIRECT CHANGES //
$file = $clientRequest->sourceName . "/conflict_" . $sessionManager->user . "_" . $localtime . ".html";
$redirectedFile = $serverInfo->BackupDirectory . $file;
$savingMachine->saveFile = $redirectedFile;
$moduleManager->killEvent();
// don't allow low-priority MainSaveEvent scripts to run.
// SEND MESSAGE //
$serverResponse->setBoolean("conflict", true);
$serverResponse->setString("conflictfile", $file);
foreach ($newchangesarr as $tiddler) {
if ($tiddler != "") {
$serverResponse->setArrayString("tiddlers", $tiddler);
}
}
} else {
// ON A GOOD SAVE, WRITE THE TIDDLERS TO ALL ACCESS FILES //
$tiddlers = join(" ", $newchangesarr);
if (is_dir($accessdir)) {
$files = scandir($accessdir);
foreach ($files as $file) {
if (strpos($file, ".txt") != false) {
writeToFile($accessdir . $file, $tiddlers);
}
}
$serverResponse->setString("conflictaccess", $module->name);
} else {
$serverResponse->throwError("The access directory was not found: {$accessdir}");
}
}
开发者ID:pohly,项目名称:mts,代码行数:31,代码来源:ConflictsSave.php
示例16: array
}
// fields to be included (from fields in image table)
$fieldMain = array('Title' => 'img_name', 'Partner' => 'img_minor_mime');
// fields to be included (come from img_metadata)
$fieldMeta = array('Description' => 'description', 'Keywords' => 'keywords');
$header = array_merge(array_keys($fieldMain), array_keys($fieldMeta));
writeToFile($header);
$limit = 1000;
$total = 1;
$lastTitle = '';
$db = wfGetDB(DB_SLAVE);
do {
$result = $db->select(array('image'), array('*'), array('img_media_type' => 'VIDEO', 'img_minor_mime' => $provider, 'img_name > ' . $db->addQuotes($lastTitle)), __METHOD__, array('LIMIT' => $limit));
$cnt = 1;
$subTotal = $result->numRows();
while ($row = $db->fetchRow($result)) {
echo "\n[Total: {$total} ({$cnt} of {$subTotal})] Video: {$row['img_name']}\n";
$videoMain = addDataToVideo($row, $fieldMain);
$metaData = unserialize($row['img_metadata']);
$video = addDataToVideo($metaData, $fieldMeta, $videoMain);
writeToFile($video);
$lastTitle = $row['img_name'];
$cnt++;
$total++;
}
} while ($subTotal);
$db->freeResult($result);
if ($export) {
fclose($fp);
}
echo "\nWiki: {$wgCityId}, Provider: {$provider}, Total Videos: " . ($total - 1) . ".\n\n";
开发者ID:Tjorriemorrie,项目名称:app,代码行数:31,代码来源:getVideoMetadata.php
示例17: switch
$action = 'select';
}
switch ($action) {
case 'update':
// die("esto es update");
if ($_POST) {
} else {
$arrayUser = readUser($_GET['id']);
echo "<pre>";
print_r($arrayUser);
echo "</pre>";
}
case 'insert':
if ($_POST) {
$imageName = uploadImage($_FILES);
writeToFile($imageName);
header("Location: users.php?action=select");
exit;
} else {
// definir arrayUser
include "../application/views/formulario.php";
}
break;
case 'delete':
break;
case 'select':
$arrayUsers = readUsersFromFile();
include "../application/views/select.php";
default:
break;
}
开发者ID:jonathansky,项目名称:formulario,代码行数:31,代码来源:users.php
示例18: exec
default:
$res = "123";
$fname = "default";
}
//On gere un cache si ADE plante
$fname .= ".ics";
exec($ADE2ICS . " -s " . $FAC . " -l " . $LOGIN . " -p '" . $PWD . "' -n " . $res, $output);
/*
En cas d'erreur (contenu vide), on renvoie les infos contenues dans le cache.
*/
$calContent = "";
for ($i = 0; $i < sizeof($output); $i++) {
$calContent .= $output[$i];
}
//A virer pour livraison, permet de tester le bon fonctionnement du cache
#$calContent="";
if (isCompleteVCalendar($calContent)) {
createFolder($CACHE_DIR);
writeToFile($CACHE_DIR . "/" . $fname, $calContent);
} else {
//!\\
//Ici, si le cache n'a pas été crée un erreur sera levée.
//Ne devrais jamais se produire si le déploiement prévois de créer les fichiers cache.
$calContent = readFromFile($CACHE_DIR . "/" . $fname);
}
//On pose le mime type
header('Content-type: text/calendar; charset=utf-8');
echo $calContent;
} else {
echo "No ressource setted !\n";
}
开发者ID:jcsaaddupuy,项目名称:scripts,代码行数:31,代码来源:index.php
示例19: writeToFile
//*********************************************
//Write results to files
writeToFile($blekkoResults, "metrics/blekkoResults", $query);
writeToFile($bingResults, "metrics/bingResults", $query);
writeToFile($googleResults, "metrics/googleResults", $query);
//AGGREGATE the Results using Borda-Fuse
//NOTE THAT THE ORDER THE ARRAYS ARE SENT IN TO BE AGGREGATED MATTERS
//FOR ANY RESULTS THAT HAVE THE SAME COMBINED SCORE/RANK
aggregateResults($googleResults, $bingResults, $blekkoResults, $aggregatedResults);
//*********************************************
//Write results to file
writeToFile($aggregatedResults, "metrics/aggregatedResults", $query);
//initialize variables to rank search engines
$wsumGoogle = $wsumBing = $wsumBlekko = 0.0;
//CALCULATE THE WEIGHT FOR EACH SEARCH ENGINE
calcWeight($googleResults, $bingResults, $blekkoResults, $wsumGoogle, $wsumBing, $wsumBlekko);
//APPLY THE WEIGHT TO EACH OF THE SEARCH ENGINES RESULTS
applyWeight($googleResults, $wsumGoogle);
applyWeight($bingResults, $wsumBing);
applyWeight($blekkoResults, $wsumBlekko);
//AGGREGATE the Results using Borda-Fuse
$aggregatedResults = array();
aggregateResults($googleResults, $bingResults, $blekkoResults, $aggregatedResults);
$weights = array($query => array("google" => $wsumGoogle, "bing" => $wsumBing, "blekko" => $wsumBlekko));
writeToFile($weights, "metrics/weightedResults", $query . " weights");
//*********************************************
//Write results to file
writeToFile($aggregatedResults, "metrics/weightedResults", $query);
sleep(5);
//pause between queries
}
开发者ID:soitun,项目名称:php_software_engineering_project,代码行数:31,代码来源:getResults.php
示例20: generateArrivalsDepartures
/**
* Loops through date_serviceIdsArray and generates ordered list of arrivals and departures of trips per day.
* The arrivals and departures are written away to corresponding JSON file each time.
*
* @param array $date_serviceIdsArray Array of dates with serviceIds on corresponding date.
* @param mixed $entityManager Entity manager of Doctrine.
*/
function generateArrivalsDepartures($date_serviceIdsArray, $entityManager)
{
global $arrivalsFilename, $departuresFilename;
global $arrivalNr, $departureNr;
$prevTripRouteIdPair = [];
$firstLoop = true;
// First date is previous date that we need to retrieve stoptimes after midnight
// Loop through all dates
foreach ($date_serviceIdsArray as $date => $serviceIds) {
$serviceMatches = [];
for ($j = 0; $j < count($serviceIds); $j++) {
$serviceMatches[] = "'" . $serviceIds[$j] . "'";
}
$serviceMatches = join(' , ', $serviceMatches);
$sql = "\n SELECT *\n FROM trips\n WHERE serviceId IN ( {$serviceMatches} )\n ";
$stmt = $entityManager->getConnection()->prepare($sql);
$stmt->execute();
$trips = $stmt->fetchAll();
$tripRouteIdPair = $prevTripRouteIdPair;
$tripMatches = [];
for ($j = 0; $j < count($trips); $j++) {
$tripMatches[] = "'" . $trips[$j]['tripId'] . "'";
$tripRouteIdPair[] = [$trips[$j]['tripId'], $trips[$j]['routeId']];
$prevTripRouteIdPair[] = [$trips[$j]['tripId'], $trips[$j]['routeId']];
}
$tripMatches = join(' , ', $tripMatches);
if ($firstLoop) {
$prevDayTripMatches = $tripMatches;
$firstLoop = false;
continue;
}
// Smaller timespans for big datasets
$hourEvery = 1;
// Query every x hour
$minEvery = 1;
// Query every x minutes
for ($startHour = 0; $startHour < 24; $startHour += $hourEvery) {
$endH = $startHour + $hourEvery;
// Loop all hours between start and end
for ($endHour = $startHour; $endHour < $endH; $endHour++) {
for ($startMin = 0; $startMin <= 60; $startMin += $minEvery) {
$endMin = $startMin + $minEvery;
// ARRIVALS
$arrivalsArray = queryArrivals($entityManager, $tripMatches, $startHour, $startMin, $endHour, $endMin);
// Search arrivals that happen after midnight of previous day
$arrivalsAfterMidnight = queryArrivalsAfterMidnight($entityManager, $prevDayTripMatches, $startHour, $startMin, $endHour, $endMin);
// Merge sort
$i = 0;
$j = 0;
while ($i < count($arrivalsArray) && $j < count($arrivalsAfterMidnight)) {
if ($arrivalsArray[$i]['arrivalTime'] < $arrivalsAfterMidnight[$j]['arrivalTime']) {
$arrivalData = $arrivalsArray[$i++];
} else {
$arrivalData = $arrivalsAfterMidnight[$j++];
}
writeToFile($arrivalsFilename, generateArrival($arrivalData, $date, $tripRouteIdPair, $arrivalNr));
$arrivalNr++;
}
while ($i < count($arrivalsArray)) {
$arrivalData = $arrivalsArray[$i++];
writeToFile($arrivalsFilename, generateArrival($arrivalData, $date, $tripRouteIdPair, $arrivalNr));
$arrivalNr++;
}
while ($j < count($arrivalsAfterMidnight)) {
$arrivalData = $arrivalsAfterMidnight[$j++];
writeToFile($arrivalsFilename, generateArrival($arrivalData, $date, $tripRouteIdPair, $arrivalNr));
$arrivalNr++;
}
unset($arrivalsArray);
// free memory
// DEPARTURES
$departuresArray = queryDepartures($entityManager, $tripMatches, $startHour, $startMin, $endHour, $endMin);
// Search departures that happen after midnight of previous day
$departuresAfterMidnight = queryDeparturesAfterMidnight($entityManager, $prevDayTripMatches, $startHour, $startMin, $endHour, $endMin);
// Merge sort
$i = 0;
$j = 0;
while ($i < count($departuresArray) && $j < count($departuresAfterMidnight)) {
if ($departuresArray[$i]['departureTime'] < $departuresAfterMidnight[$j]['departureTime']) {
$departureData = $departuresArray[$i++];
} else {
$departureData = $departuresAfterMidnight[$j++];
}
writeToFile($departuresFilename, generateDeparture($departureData, $date, $tripRouteIdPair, $departureNr));
$departureNr++;
}
while ($i < count($departuresArray)) {
$departureData = $departuresArray[$i++];
writeToFile($departuresFilename, generateDeparture($departureData, $date, $tripRouteIdPair, $departureNr));
$departureNr++;
}
while ($j < count($departuresAfterMidnight)) {
$departureData = $arrivalsAfterMidnight[$j++];
//.........这里部分代码省略.........
开发者ID:brechtvdv,项目名称:gtfs2arrdep,代码行数:101,代码来源:create_arrivals_and_departures.php
注:本文中的writeToFile函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论