php boolean retrieval with binary operation - php

I have a piece source code to search with Boolean retrieval
<?php
$path = "Korpus";
foreach(glob("$path/*.txt") as $file) {
foreach(file($file) as $line) {
echo $line."<br>";
}
}
$file = "";
$conv = "";
for($i = 1; $i < 4; $i++){
$file[$i] = file_get_contents("$path/Doc".$i.".txt");
$conv[$i] = explode(" ", strtolower($file[$i]));
echo "<br>";
print_r ($conv[$i]);
}echo "<br><br>";
?>
This is my Query
One AND Two AND NOT Three
I want the result like this
Term Doc1 Doc2 Doc3
One 1 0 0
Two 0 1 1
Three 0 1 0
Result : Doc1, Doc3
can someone help me to solve this problem ?

Related

This if condition is false when comparing array to string in PHP

I have a FOR loop and an IF statement that checks each line for a certain word in a txt document. However when the loop gets to a line that holds the value 'header' the IF statement does not think it is true.
txt file
header
bods
#4f4f4f
30
100
1
text
this is content for the page
#efefef
10
300
2
img
file/here/image.png
300
500
filler
3
header
this is header text
#4f4f4f
30
100
4
php file
$order = array();
$e = 0;
$h = 0;
$headerCount = 0;
$textCount = 0;
$imgCount = 0;
//Open file putting each line into an array
$textFile = fopen("test.txt","r+");
$inTextFile = fread($textFile, filesize("test.txt"));
$arrayFile = explode("\n", $inTextFile);
$arrayFileSize = sizeof($arrayFile);
$elementCount = $arrayFileSize / 6;
for ($x = 0; $x < $arrayFileSize; $x++) {
if ($arrayFile[$x] == "header") {
echo $x;
echo " Yes : ".$arrayFile[$x] . "<br>";
$headerCount++;
}
else {
echo $x;
echo " No : " . $arrayFile[$x] . "<br>";
}
}
Welcome to Stack Overflow Billy. There are two solutions you can try: using the trim() function of strpos().
Using trim() will remove any leading or trailing spaces from a string:
if (trim($arrayFile[$x]) == "header") {...}
Using strpos() can help you check if word "header" exists anywhere in a string. If the given word does not exists than it will return false:
if (strpos($arrayFile[$x], "header") !== false) {...}

Insert fails while loop in pdo (pdo/php 5.6)

I've wrote a script in PHP for an university big data project.
The following code should support following function:
Read amount of data from a table
read a subset of the same table und extend it with 2 columns which calculate 2 values.
generate f.e. 1000 inserts and commit them to an other table
do this for the whole dataset of point 1
My problem:
0-1000:
my solution inserts in the first try 1000 datalines
1000-2000:
in this step it inserts 2000 datalines, so after the 2nd step it seems to insert 0-2000 datalines of the origin dataset. In sum 3000 datalines.
I'm a little bit out of ideas... I don't see my failure.
<?php
$user = 'root';
$pass = '';
$kill = 0;
echo 'Connecting to DB:';
try {
$db1 = new PDO('mysql:host=localhost;dbname=itt2_joined;charset=utf8',$user,$pass);
$db1->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "OK \nGOING2COPY!\n";
}
catch(PDOException $ex) {
echo " Failed - Process stopped!\n";
$kill = 1;
}
if(!$kill) {
$stmt = 'SELECT
`id_transaction`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0';
$setSize = $db1->query($stmt)->rowCount();
echo "No. Of Datasets: " . $setSize . "\n";
$stepSize = 1000;
echo "Start Copy $stepSize Datasets per Query! \n";
$copy = 1;
$lower = 0;
$upper = 0;
echo "[";
while($copy) {
$lower = $upper;
$upper += $stepSize;
$upper = ($upper > $setSize ? $setSize : $upper);
$data = $db1->query("SELECT
`id_transaction`,
`id_order_line`,
`relative_transaction_date`,
`relative_requested_date`,
`new_requested_qty`, `new_requested_price`,
`relative_suggested_date`,
`new_suggested_qty`,
`delivery_qty`,
`relative_delivery_date`,
`received_qty`,
`relative_received_date`,
`id_order_header`,
`delivery_counter`,
`relative_issued_date`,
`relative_xcurrent_date`,
`issued_quantity`,
`current_quantity`,
`product_code`,
`destination`,
`relative_issuing_date`,
`delivery_location`,
`issuer`,
`id_supplier`,
`currency`,
`shipment`,
`issued_price4unit`,
`current_price4unit`,
`total_delivered`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0
LIMIT $lower OFFSET $stepSize")->fetchAll();
$db1->beginTransaction();
foreach($data as $row) {
$sql = "";
$sql = "INSERT INTO `refactored_data` (`id_transaction`, `id_order_line`, `relative_transaction_date`,
`relative_requested_date`, `new_requested_qty`, `new_requested_price`, `relative_suggested_date`,
`new_suggested_qty`, `delivery_qty`, `relative_delivery_date`, `received_qty`,
`relative_received_date`, `id_order_header`, `delivery_counter`, `relative_issued_date`,
`relative_xcurrent_date`, `issued_quantity`, `current_quantity`, `product_code`, `destination`,
`relative_issuing_date`, `delivery_location`, `issuer`, `id_supplier`, `currency`, `shipment`,
`issued_price4unit`, `current_price4unit`, `total_delivered`, `shipment_delay`, `sending_delayed`) VALUES ";
$sql .= "(";
for($i = 0; $i<sizeof($row)/2; $i++) {
$sql .= "'".$row[$i] . "', ";
}
$sql .= $row['relative_received_date'] - $row['relative_delivery_date'] . ',';
$sql .= ($row['relative_received_date'] <= $row['relative_issued_date'] ? 1 : 0) .')';
$db1->prepare($sql)->execute();
}
$db1->commit();
// Statusbar
//echo "\n$lower - $upper\n";
$perc = ceil(($upper/$setSize) *40);
$bar = "\r[". str_repeat("=", $perc - 1). ">";
$bar .= str_repeat(" ", 40 - $perc) . "] - " . number_format($upper / $setSize * 100, 3) ."% ";
echo "\033$bar"; // Note the \033. Put the cursor at the beginning of the line
//While_Exit
$copy = ($upper == $setSize ? 0 : 1);
//$copy = 0;
}
echo "\nall done, BYE! \n";
}
?>
You're using the stepsize as the offset each time:
LIMIT $lower OFFSET $stepSize
Should be:
LIMIT $stepSize OFFSET $lower
Oh thank you! I haven't seen the failure.
Now the code works, nearly completely, my last problem is the following:
in the first Select query i get from '->rowCount();' the number of rows of the select query.
But with my insertion copys a bit more data. But in the second Select i have the same Where clause likewise the first Select query.
I get from the CLI-Print : No. of Rows: 655056
and it writes in the Database 658597
so how do i get the 3541 rows?
or is maybe a failure inside the Insert?
Greetings

Save results form rand() to new files?

I'm trying to figure out how to save results from the rand() function to 10 different files.
Here's my code:
<?php
for($i = 0; $i < 10; $i++)
{
$rand_valuec = rand(0,16);
echo "<b>Your Lucky Number is</b>: " . $rand_valuec . " <br />";
$fp = fopen("results.php", "w");
fwrite($fp, $rand_valuec);
fclose($fp);
}
Sample output:
Your Lucky Number is: 6
Your Lucky Number is: 16
Your Lucky Number is: 16
Your Lucky Number is: 8
Your Lucky Number is: 6
Your Lucky Number is: 10
Your Lucky Number is: 13
Your Lucky Number is: 5
Your Lucky Number is: 6
Your Lucky Number is: 5
results.php contains:
5
I need to save each result to a new file; e.g. 1result.php, 2result.php, 3result.php, 4result.php, ..., 10result.php. Any ideas? :-) Thanks!
You could just change your file open to read:
$fp = fopen($i."result.php", "w");
<?php
for($i=0; $i < 10; $i++)
{
$rand_valuec = rand(0,16);
echo "<b>Your Lucky Number is</b>: ".$rand_valuec." <br />";
$fp = fopen($i."results.php", "w");
fwrite($fp, $rand_valuec);
fclose($fp);
}
?>
try it:
<?php
$numberOfFiles = 10;
$numberOfLinesPerFile = 10;
$path = "/home/your-user/your-path/";
for ($fileIndex = 1; $fileIndex <= $numberOfFiles; $fileIndex++) {
$contentFile = "";
for ($i = 0; $i < $numberOfLinesPerFile; $i++) {
$rand_valuec = rand(0,16);
$content = "<b>Your Lucky Number is</b>: ".$rand_valuec." <br />";
}
file_put_contents($path . $fileIndex . "result.php", $content);
}

maximum gap between two 1s in a binary equivalent of a decimal number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to write a program to find the maximum gap between two 1s in a binary equivalent of a decimal number. For example for 100101: the gap is 2 and for 10101: the gap is 1.
<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);
$status = false;
$count = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
var_dump($binaryForm[$i]);
if($binaryForm[$i] == 1)
{
$status = false;
$count = 0;
}
else
{
$status = true;
$count += 1;
}
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>
but i was not successfull..
First use regex to find "0" groups, then sort by length, descending—take the first one in the list, and get it's length:
$numberGiven = 37;
$binaryForm = decbin($numberGiven);
// get all groups of "0", put list in $matches
preg_match_all('/(0+)/', $binaryForm, $matches_all);
$matches = $matches_all[0];
// sort descending
rsort($matches, SORT_STRING);
// get first `$matches[0]` and print string length
echo 'count = ' . strlen($matches[0]) . '<br>';
echo $binaryForm;
UPDATED: based on Mark Baker's comments below.
UPDATE #2: As brought up by afeijo in the comments below, the above does not exclude ending zeros. Here's a solution for that:
preg_match_all('/(0+)1/', $binaryForm, $matches_all);
$matches = $matches_all[1];
I would use the binary right-shift operator >> and iteratively shift by 1 bit and check if the current rightmost bit is a 1 until I've checked all the bits. If a 1 was found, the gap between the previous 1 is calculated:
foreach(array(5,17,25,1223243) as $number) {
$lastpos = -1;
$gap = -1; // means there are zero or excatly one '1's
// PHP_INT_SIZE contains the number of bytes an integer
// will consume on your system. The value * 8 is the number of bits.
for($pos=0; $pos < PHP_INT_SIZE * 8; $pos++) {
if(($number >> $pos) & 1) {
if($lastpos !== -1) {
$gap = max($gap, $pos - $lastpos -1);
}
$lastpos = $pos;
}
}
echo "$number " . decbin($number) . " ";
echo "max gap: {$gap}\n";
}
Output:
5 101 max gap: 1
17 10001 max gap: 3
25 11001 max gap: 2
1223243 100101010101001001011 max gap: 2
What you currently are doing is reseting the count each time you find a 1.
You need to keep track of the current max value:
$count = 0;
$maxCount = 0;
and where you set $count = 0 you should also do
if ($count > $maxCount)
$maxCount = $count;
$count = 0;
then
echo "count = " . $maxCount . "<br>";
In all:
<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);
$status = false;
$count = 0;
$maxCount = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
// Don't count leading zeroes.
if ($status == false && $binaryForm[$i] == 0) continue;
$status = true;
var_dump($binaryForm[$i]);
// We've found a 1. Remember the count.
if($binaryForm[$i] == 1)
{
if ($count > $maxCount)
$maxCount = $count;
$count = 0;
}
// We found a 0. Add one to count.
else
{
$count += 1;
}
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>
Disclaimer: Code not tested

PHP - Convert single byte to Integer (PCX Graphic Format)

I'm working on a project that involves talking directly with Zebra printers. Currently, I am trying to convert images to the GRF format using something called "ztools". ZTools appears to be ancient and doesn't always convert the graphic correctly.
I've began digging up information on the PCX file format it is converting from and now find myself in byte land. This is my reference at this time: PCX Technical Reference
So, I have a basic PCX file I saved from photoshop that is 2x2 and would look like this:
10
01
This is where I am stuck, however. I've never worked with bytes and am attempting to read the pcx file with PHP using fopen("file", "rb"); and fread. However, it seems no matter what I do, I get a bunch of zeros. Anyone know what I need to do to convert the bytes to there numeric equivalents?
This is my weak attempt:
<?php
$file = "test.pcx";
// Open the file for binary reading (b flag)
$handle = fopen($file, "rb");
while (!feof($handle)) {
$contents = fread($handle, 1);
$contents = $contents >> 8;
echo $contents >> 8;
$content .= $contents;
}
fclose($handle);
I was able to get the header information accurately with this:
<?php
$file = "test.pcx";
function intToBits($int) {
$return = "00000000";
if ($int <= 255 && $int >= 0) {
$check = 128;
$x = 0;
while ($int > 0) {
if ($int > $check) {
$return[$x] = "1";
}
$int -= $check;
$check /= 2;
$x++;
}
}
return $return;
}
// Open the file for binary reading (b flag)
$handle = fopen($file, "rb");
$PCX_MAP = array();
$PCX_MAP['Manufacturer'][0] = 1; // Manufacturer
$PCX_MAP['Version'] = 1; // Version Info
$PCX_MAP['Encoding'] = 1; // Encoding
$PCX_MAP['BitsPerPixel'] = 1; // BitsPerPixel
$PCX_MAP['Xmin'] = 2; // Window Xmin
$PCX_MAP['Ymin'] = 2; // Window Ymin
$PCX_MAP['Xmax'] = 2; // Window Xmax
$PCX_MAP['Ymax'] = 2; // Window Ymax
$PCX_MAP['HDpi'] = 2; // HDpi (Resolution)
$PCX_MAP['VDpi'] = 2; // VDpi (Resolution)
$PCX_MAP['colormap'] = 48; // Colormap
$PCX_MAP['Reserved'] = 1; // Reserved = 0
$PCX_MAP['NumberColorPlanes'] = 1; // Number of color planes
$PCX_MAP['BytesPerLine'] = 2; // Bytes Per Line
$PCX_MAP['PalleteInfo'] = 2; // Palette Info
$PCX_MAP['HorizontalScreenSize'] = 2; // H Screen Size
$PCX_MAP['VerticalScreenSize'] = 2; // V Screen Size
$PCX_MAP['Filler'] = 54; // Filler
$length = reset($PCX_MAP);
while (!feof($handle)) {
if ($length !== false) {
$contents = fread($handle, $length);
$contents = ord($contents);
echo key($PCX_MAP) . " : {$contents}\n";
$content .= $contents;
$length = next($PCX_MAP);
}
else {
// Get the rest 1 By 1
$contents = fread($handle, 1);
$contents = ord($contents);
$contents = intToBits($contents);
echo $contents ."\n";
}
}
fclose($handle);
/*
$data = file_get_contents($file);
for($i = 0; $i < strlen($data); ++$i) {
$char = ord($data[$i]);
echo "Byte $i: $char\n";
}*/
However, I am still attempting to parse the image data.
This currently returns this:
Manufacturer : 10
Version : 5
Encoding : 1
BitsPerPixel : 1
Xmin : 0
Ymin : 0
Xmax : 3
Ymax : 1
HDpi : 200
VDpi : 200
colormap : 15
Reserved : 0
NumberColorPlanes : 1
BytesPerLine : 2
PalleteInfo : 1
HorizontalScreenSize : 0
VerticalScreenSize : 0
Filler : 0
10000000
11000000
11111110
00000000
11000000
11111110
00000000
The header information is correct, but I'm not sure about the data after filler.
The graphic ran in this instance is a 4 x 2 - 0 means white, 1 means black
0101
1010
Try this:
while (!feof($handle)) {
$contents = fread($handle, 1);
$contents = $contents && 0xFF;
echo $contents;
$content .= $contents;
}

Categories