lundi 29 juin 2015

Implementing Jquery Pagination to Opencart Admin page

I am trying to add jquery pagination plugin to opencart Admin page(Catalog > Options > Option value)( /admin/view/template/catalog/option_form.tpl ).

When you click on edit option it loads option values. I have lots of those that is why I am trying to implement paging.

I tried many jquery plugins but to no avail as the plugins have no effect.

Is there any way I can implement paging using jquery or is there any other method i can use?

Thanks.

[Edit]

Whatever i know i tried in php and it is not working.

  EDIT:

I tried one more thing: in admin/controller/catalog/product/option.php

in the method: public function edit() {

I added this code:

<code>

    $pagination = new Pagination();
    $pagination->total = $option_value_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('catalog/option/edit', 'token='     . $this->session->data['token'] . $url . '&page={page}', 'SSL');

    $data['pagination'] = $pagination->render();

    $data['results'] = sprintf($this->language->get('text_pagination'), ($option_value_total) ? (($page - 1) 
                        * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) 
                        * $this->config->get('config_limit_admin')) > ($option_total - $this->config->get('config_limit_admin'))) ? $option_value_total : ((($page - 1) 
                        * $this->config->get('config_limit_admin')) 
                        + $this->config->get('config_limit_admin')), $option_value_total, ceil($option_value_total / $this->config->get('config_limit_admin')));

</code>
In Option_form.tpl
<code> 

    <div class="row">
        <div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
        <div class="col-sm-6 text-right"><?php echo $results; ?></div>
    </div>

</code>
In admin/model option.php

in <code>public function getOptionValues($option_id) {</code> I added 
<code> 

    if (isset($data['start']) || isset($data['limit'])) {
        if ($data['start'] < 0) {
        $data['start'] = 0;
        }

        if ($data['limit'] < 1) {
        $data['limit'] = 20;
        }

        $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }

        $query = $this->db->query($sql);

        return $query->rows;

</code>

Escaping input for WMI Query

I'm creating a PHP package for querying WMI objects, and I'm wondering if there's a need to escape strings inserted into WMI queries?

If so, how do I parametrize and escape strings in the query since I can't use things like PDO as it required a PDO connection?

For an example query:

$value = 'PC';

$query = sprintf('SELECT * FROM Win32_LogicalDisk WHERE SystemName = "%s"', $value);

$connection->ExecQuery($query);

Why is Laravel 5 removing REMOTE_ADDR from Server object?

I hope someone has seen this before, I've been searching Google and getting nowhere.

I'm trying to do something very simple, retrieve REMOTE_ADDR from $_SERVER object but it simply equates to true (1).

I am convinced this is a config issue related to laravel but have no idea where to start digging.

The contents of $_SERVER are as follows (obviously I've removed potentially sensitive paths etc.)

USER = '[REMOVED]'
HOME = '[REMOVED]'
FCGI_ROLE = 'RESPONDER'
REDIRECT_HANDLER = 'php5-fcgi'
REDIRECT_STATUS = '200'
HTTP_HOST = '[REMOVED]'
HTTP_CONNECTION = 'keep-alive'
HTTP_ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
HTTP_USER_AGENT = 'Mozilla/5.0 (Linux; Android 5.0.1; GT-I9505 Build/LRX22C) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36'
HTTP_REFERER = '[REMOVED]'
HTTP_ACCEPT_ENCODING = 'gzip, deflate, sdch'
HTTP_ACCEPT_LANGUAGE = 'en-GB,en-US;q=0.8,en;q=0.6'
PATH = '/usr/local/bin:/usr/bin:/bin'
SERVER_SIGNATURE = 'Apache/2.2.22 (Ubuntu) Server at [REMOVED] Port 80'
SERVER_SOFTWARE = 'Apache/2.2.22 (Ubuntu)'
SERVER_NAME = '[REMOVED]'
SERVER_ADDR = '[REMOVED]'
SERVER_PORT = '80'
REMOTE_ADDR = '1'
DOCUMENT_ROOT = '[REMOVED]'
SERVER_ADMIN = '[REMOVED]'
SCRIPT_FILENAME = '[REMOVED]'
REMOTE_PORT = '48650'
REDIRECT_QUERY_STRING = '[REMOVED]'
REDIRECT_URL = '/index.php'
GATEWAY_INTERFACE = 'CGI/1.1'
SERVER_PROTOCOL = 'HTTP/1.1'
REQUEST_METHOD = 'GET'
QUERY_STRING = '[REMOVED]'
REQUEST_URI = '[REMOVED]'
SCRIPT_NAME = '/index.php'
ORIG_SCRIPT_FILENAME = '[REMOVED]'
ORIG_PATH_INFO = '/index.php'
ORIG_PATH_TRANSLATED = '[REMOVED]'
ORIG_SCRIPT_NAME = '/php5-fcgi'
PHP_SELF = '/index.php'
REQUEST_TIME = '1435331181'

Note the REMOTE_ADDR = '1'

What is going on there?

I have tried simply creating a test.php file in a /var/www/myapp/public/ as follows

<?php
print_r($_SERVER)

and it gives me the REMOTE_ADDR correctly, which is what leads me to believe it is a laravel issue.

If anyone can suggest why this is happening and what I can do about it, it would be greatly appreciated.

Relevant version numbers:

OS: Debian 7

nginx: 1.2.1

php: 5.4.39

Laravel 5

how to make a joomla plugin?

I am trying to make a joomla plugin, but I have few questions that I haven't found any answer.

What the plugin has to do: add a new field in register form(let's say Cell Number), and on form submit insert that cell number in database.

My documentation is this tutorial.

Questions:

  • How do you add a new field in register form? xml file is done, but I am not sure how to write the php code...(please help)

  • How do I get the cell number variable from that form? $jinput = JFactory::getApplication()->input; ?

Pleas help me with few tips. Thanks!

Get basic information of instagram page

I have number of instagram pages/urls of different users like http://ift.tt/1HtGUL2 etc etc etc. I want to get following information of that page

name, number of followers, description, bio,

I have searched and all showing using access token. But I am confused if I will take access token from my account, how can I get information of other pages?

Please guide me how can I do that?

Make SQL Query from button via PHP

I have my SQL query working fine in PHPMyAdmin but can't get it work with PHP. Let's say I have this query:

SELECT Login, Firstname, Lastname, Company INTO OUTFILE 'c:\\users.txt' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'  
FROM `Users` WHERE Company = 'SID';

I would like to call my query from a web page with a click. I did 2 files fonction.php and form.php as follow. For fonction.php

<?php
function connectMaBase(){
    $base = mysql_connect ('localhost', 'root', '');  
    mysql_select_db ('CCPayment', $base) ;
}
?>

And for form.php I have this

<?php
include("fonction.php");
?>
<html>
    <head><title>Pages de requetes SQL </title></head>
    <body>
        <h1> Requete SQL </h1>
       <form name="sqlquery" method="post" action="form.php">        
        <input type="submit" name="valider" value="Go"/>
       </form>
 <?php 
    if (isset ($_POST['valider'])){
        connectMaBase();
        $sql = "SELECT Login, Firstname, Lastname, Company  INTO OUTFILE \'c:\\\\Users.txt\' FIELDS TERMINATED BY \',\' LINES TERMINATED BY \'\\r\\n\' \n"
     . "FROM `OptiOutput` WHERE Company = \'SID\'";

        mysql_query ($sql) or die ('Erreur SQL !'.$sql.'<br />'.mysql_error()); 
        mysql_close();
    }
?>
    </body>
</html>

I'm a beginner and could not find what is wrong in the code.

Thanks for your help.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data on my Image Uploader

Im new here and did not find out my Solution by using Google or StackOverflow.
My Problem is that i have a Multiple Image Uploader that works with JSON, AJAX and PHP... But while I am programming, i get this Message on the Firefox Console:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Witch is related to this line:

ajax = function (data) {
    var xml = new XMLHttpRequest(), uploaded;
    xml.addEventListener("readystatechange", function() {
        if(this.readyState === 4) {
            if(this.status === 200) {
                uploaded = JSON.parse(this.response); //THIS IS THE ERROR LINE
                if(typeof o.options.finished === "function") {
                    o.options.finished(uploaded);
                }
            }else {
                if(typeof o.options.error === "function") {
                    o.options.error();
                }
            }
        }
    });

I think its because the Array in the Variable "Uploaded" is empty... But it shouldve be filled so far.. Well, here is the PHP Code:

header("Content-Type: application/json");

$uploaded = [];
$allowed = ["mp4", "jpg", "png", "jpeg", "doc", "avi"];

$files = $_FILES["file"];

$succedeed = [];
$failed = [];

if (!empty($files)) {
    foreach($files["name"] as $key => $name) {
        if($files["error"][$key] === 0) {

            $temp = $files["tmp_name"][$key];

            $ext = explode(".", $name);
            $ext = strtolower(end($ext));

            $file = $files["tmp_name"][$key] . $ext;


            if(in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
                $succedeed[] = array(
                    "Original Name" => $name,
                    "MD5 Name" => $file
                );
            }else {
                $failed[] = array(
                    "Original Name" => $name
                );

            }   
        }
    }

    if(!empty($_POST["ajax"])) {
        echo json_encode(array(
            "Erfolgreich hochgeladen" => $succedeed,
            "Nicht erfolgreich hochgeladen" => $failed
        ));
    }


}

Im very Desperated because of this... :D Hope someone can Help me... ^^

Niggo

PHP Sum of mysql results calculated in real time dynamically

EDIT No working answer ...

I have a table with product price model cost stock etc, to make it easier I calculate the total customer pay for for each product like this

<?php echo number_format($show['quantity'] * $show['product_price'],0,',','.'); ?>

But now I need to show the total sum of this calculation but as you can see they are calculared in PHP real time. Is there a way to do it?

Here is the complete code

<?php
$result=mysqli_query($database,"SELECT * FROM `products` order by `category` ASC");
$rows=mysqli_num_rows($result);
if(mysqli_num_rows($result)>0){
?>

<table class="sales">

<tr>
<td>Quantity</td>
<td>Product Cost</td>
<td>Customer Pays</td>
</tr>        

<?php if($rows){$i=0;while($show=mysqli_fetch_assoc($result)){?>

<tr>
<td><?php echo number_format($show['quantity'],0,',','.'); ?></td>
<td><?php echo number_format($show['product_cost'],0,',','.'); ?></td>
<td><?php echo number_format($show['quantity'] * $show['product_cost'],0,',','.'); ?></td>
</tr>

<?php }}?>
</table>

TOTAL CUSTOMER PAY FOR ALL PRODUCTS = EXAMPLE $10.234

<?php }else{?> 

No products to show

<?php }?>

Online javascript editor like inDesign

For a project we're currently trying to create an online WYSIWYG editor which should have the same basic functionality as Adobe's InDesign:

  • Adding text frames, and linking text frames together
  • Master Pages (with baseline, margins, columns and gutter)
  • Basic formatting (font size and styles, alignment)

We're trying to enable users to create simple documents using articles on their news-website as a source. Trough a drag'n'drop interface they should be able to quickly build a simple news-paper-like document. The user's creation should get converted to PDF (trough FPDF library). Therefore the editor should create some sort of html with data-attributes containing properties like width, height, etc. so this data can be converted to a json object to be extracted in PHP and loaded into FDPF. The progress in simple steps:

  1. Html WYSIWYG generates preview + html attributes with measurements;
  2. Post html attributes trough ajax to server sided;
  3. PHP server side extracts json and converts it to FPDF object;
  4. User is offered PDF file for download.

I've tried looking at iCloud's Pages, which uses SproutCore (or Ember?) as far as I can see, but I think it would be overkill to use that framework, possibly it won't even have the basic functionality I'm looking for.

Has anybody got any idea's how to get started? What JavaScript framework to use (I've used Prototype, Mootools and jQuery in the past) and where to look for possible examples / similar projects?

Mamp/PHP: how to disable PHP warnings messages about deprecated functions

In my web app my boss wants me to use msql_* php functions but I can't even login because of PHP messages about these deprecated functions. How can I disable them in MAMP? Looking in this forum I've found the following rules to write inside php.ini

error_reporting  = E_ALL & ~E_DEPRECATED
display_errors = On
disable_functions = "list of mysqli_* functions"

but this doesn't work. I've written this to all file php.ini of each php version contained in MAMP. The only thing that works is to put

display_errors = Off

but I can't use it like that otherwisw I won't even be able to see my programming/syntax error of other problems.

Here is my php.ini of php 5.6.10 inside /Applications/MAMP/bin/php/php5.6.10/conf/

Do you have any ideas? I know I should use new functions and not deprecated ones but it's not up to me and I can't disable all error messages...

Angular does not updated loop due to implementation $mdDialog (Material Design)

Based on my previous post: Angular loop is not updating, i updated the code slightly to add a dialog box to the button a a user.

the only change in my app.js file is the directive to add a $mdDialog box. so the complete code for my app.js file is:

var app = angular.module('AddUser', ['ngMaterial']);

app.controller('AppCtrl', function($scope, $http, $mdDialog){
$scope.userInfo =  [];

/** function to add details for a user in mysql referecing php **/
$scope.save_user = function() {
    $http.post('db.php?action=add_user', 
        {
            'user_name'  : $scope.user_name, 
            'user_email' : $scope.user_email
        }
    )

    .success(function (data, status, headers, config) {
        $scope.userInfo.push(data);
        $scope.get_user(); //this will fetch latest record from DB
        console.log("The user has been added successfully to the DB");
        console.log(data);
    })

    .error(function(data, status, headers, config) {
        console.log("Failed to add the user to DB");
    });
}

/** function to get info of user added in mysql referencing php **/
$scope.get_user = function() {
    $http.get('db.php?action=get_user').success(function(data)
    { 
        $scope.userInfo = data;   
        console.log("You were succesfull in showing user info"); 
        //$scope.get_user(); //this will fetch latest record from DB
    })
}

/** function to delete a user from list referencing php **/
$scope.delete_user = function(index) {  
    $http.post('db.php?action=delete_user', 
        {
            'user_index' : index
        }
    )      
    .success(function (data, status, headers, config) {    
        $scope.get_user();//this will fetch latest record from DB
        console.log('Deletion was succesfull');
    })

    .error(function(data, status, headers, config) {
       console.log("You were NOT succesfull in deleting a user"); 
    });
}

$scope.showPopUp= function(ev) {
    $mdDialog.show({
      controller: DialogController,
      templateUrl: 'popup.tmpl.html',
      parent: angular.element(document.body),
      targetEvent: ev,
    })
};

function DialogController($scope, $mdDialog) {
    $scope.closeDialog = function() {
      $mdDialog.hide();
    }

    $scope.save_user = function() {
        $mdDialog.hide();
    }
}

});

i had to comment out the following code in the get_user function ($scope.get_user();) otherwise i could not preform a delete but then on the other hand the loop did not update. so either i comment out $scope.get_user() in de get_user function and then i can delete a user or i don't comment it out and the loop will update when i add a new user but then the delete function does not work ...

my html code is:

<body ng-controller="AppCtrl">
  <div>
    <ul ng-init="get_user()">
      <li ng-repeat="user in userInfo ">{{user.user_name}}<a href="#" ng- 
      click="delete_user(user.id)"> --> Delete</a></li>
    </ul>
  </div>

 <md-button class="md-primary md-raised" ng-click="showPopUp($event)" flex 
 flex-md="100">Add a user</md-button>
</body>

and the code for the dialog box (popup.tmpl.html) is the following:

<md-dialog aria-label="Add or invite a user" ng-app="AddUser">
<form ng-controller="AppCtrl">
      <md-toolbar>
       <div class="md-toolbar-tools">
         <h2>Add or invite a user</h2>
         <span flex></span>
         <md-button class="md-icon-button" ng-click="closeDialog()">
              <md-icon md-svg-src="images/ic_close_24px.svg" aria-label="Close 
              dialog"></md-icon>
         </md-button>
       </div>
      </md-toolbar>
      <md-dialog-content>
        <div>
          <div layout="" layout-sm="column">
            <md-input-container flex="">
            <label>Enter a name</label>
            <input name="user_email" ng-model="user_name">
            </md-input-container>
        </div>
        <div layout="" layout-sm="column">
          <md-input-container flex="">
          <label>Enter an e-mail</label>
          <input name="user_name" ng-model="user_email">
          </md-input-container>
       </div>
      </div>
     </md-dial
     <div class="md-actions" layout="row">
       <md-button ng-click="closeDialog()" class="md-primary">Cancel</md-     
        button>
       <md-button ng-click="save_user()" name="add_user" class="md-
       primary">Add</md-button>
     </div>
    </form>
   </md-dialog>

TYPO3: Backend login redirects to index.php

Recently I have been having some problems with my typo3 installation on my webhosting. One of those problems is, that whenever I login to backend I get redirected to index.php and not the backend. The admin panel is shown on the index.php indicating that the it logs in successfully but then why can't I go to the backend interface.

I have tried several things, like clearing the be_sessions table in the database, clearing the browser cookies, deleting the cache, testing on other web browsers etc. but still no luck.

I am using TYPO3 4.6. Any help will be highly appreciated. Thanks :)

CAKEPHP SELECT OPTION CLASS

Does someone know how to add class to a select option in a view file ?

I have at the moment:

echo $this->Form->input(
                'shelf_id',
                array(
                    'options' => $Shelves,
                    'label'=> 'Etagère :',
                    'default' => $Place['Place']['shelf_id'],
                    'class'=>'form-control')
            );

All my options element are like this :

<option value="1">Element</option>

But I want them to be like this :

<option value="1" class="myClass">Etagere 1</option>

Tks

How do you scrape .asp or .php pages?

Can you explain a bit of the intuition behind it?

I'm using mechanize in python and I only get the server script, etc , where I believe the server script was supposed to put the table with the data I want in it.

I just want to load the page like I see it on the browser and save it to a text file.

show only parent class properties in child class using $this in parent class

I have the following two classes. Class BMW extends class Car.

class Car{

    public $doors;
    public $wheels;
    public $color;
    public $size;

    public function print_this(){
        print_r($this);
    }

}

class BMW extends Car{
    public $company;
    public $modal;

    public function __construct(){
        print_r(parent::print_this());
    }
}

$bmw = new BMW();
$bmw->print_this();

In above code when I access parent class method from constructor using parent::print_this() and inside print_this() method I have print_r($this) which prints all properties(parent and child class properties) Now what I want print_r(parent::print_this()); should output only parent class properties in child class? Can anyone help me on this?

How to log out a banned user in Symfony?

Symfony provides a simple way of preventing users from logging in using the isEnabled property if the user class implements AdvancedUserInterface.

However, if the user is logged in nothing will prevent them from accessing the website until their session expires.

The idea would be to check the isEnabled property upon getting the user entity ($this->get('security.token_storage')->getToken()->getUser()) and to invalidate the session then. What is the preferred way of doing so?

Or is there a better way to achieve this goal?

Neo4j PHP returning results at the same order as the where

I have nodes with the label "Campaign". I'm getting them each time in a different order.

So after I query to the DB, I have an array with Campaigns objects.

After that, I'm sending them into another function in the db.

MATCH (campaign:Campaign)
                 where campaign.id="1433855846340" or campaign.id="1433855948013" or campaign.id="1433856017523" or campaign.id="1433856146618" or campaign.id="1433856170282" or campaign.id="1433856364138" or campaign.id="1433856901298" or campaign.id="1433857169469" or campaign.id="1433857216853" or campaign.id="1433873093289" or campaign.id="1433873178949" or campaign.id="1433926766014"
                with campaign optional match campaign<-[:TAKEN_IN]-(picture:Picture) with campaign, collect(picture) as pictures
                with pictures[toInt(rand()*size(pictures))] as picture,campaign
                optional match picture-[:UPLOADED_TO]->(facebookPicture:FacebookPicture)
                RETURN picture.source as coverPicture,campaign.id

Basically all I need, is to return the results at the same order as the where clause. How can I do that without knowing if the campaigns were got from the DB, in

DESC

, for example/

What means prefix "preg" in php PCRE functions? [duplicate]

This question already has an answer here:

I know that PCRE is for Perl-Compatible Regular Expressions. But what means PREG? Php REGex? Perl REGex?

Check if the index exists or not Elasticsearch

I want to check in elasticsearch if the index exists or not. If it not exists it should create the index and do other functionality. I try to find out a solution for that, but did not find any perfect solution for that. Can anyone have any solution to solve this problem.

I am using Elasticsearch library.

**$client = new Elasticsearch\Client();**

post multideminsional array in multideminsional array

We need to post products here.

The product will have more than one color, while each color have different image.

I have created a form. in this form when user click add more color, it will create them a block div to pick up multiple images for that color, and so on for the next color.

Here is the sketch or input that I will create dynamically with js

<input type="text" name="color[red]" value="red" /> 
    <input name="color[red][image1]" /> 
    <input name="color[red][image2]" /> 
    <input name="color[red][image3]" /> 
    <input name="color[red][image4]" /> 

<input type="text" name="color[blue]" value="blue" />
    <input name="color[blue][image1]" /> 
    <input name="color[blue][image2]" /> 
    <input name="color[blue][image3]" /> 
    <input name="color[blue][image4]" /> 


    And so on...

I need a help how to post the inputs above with php, so that the output array would be like this:

array
    (
        [0] => array
                (
                    name => one
                    id => 1
                    color => array
                                (
                                    [0] => array 
                                                (
                                                    name =>red
                                                    image => array 
                                                                (
                                                                    [0] =>oneRed1.jpg
                                                                    [1] =>oneRed2.jpg
                                                                    [2] =>oneRed3.jpg
                                                                )   
                                                )   
                                    [1] => array 
                                                (
                                                    name =>blue
                                                    image => array 
                                                                (
                                                                    [0] =>oneBlue1.jpg
                                                                    [1] =>oneBlue2.jpg
                                                                    [2] =>oneBlue3.jpg
                                                                )   
                                                )   
                                    [2] => array 
                                                (
                                                    name =>purple
                                                    image => array 
                                                                (
                                                                    [0] =>onePurple1.jpg
                                                                    [1] =>onePurple2.jpg
                                                                    [2] =>onePurple3.jpg
                                                                )   
                                                )   
                                )
                )
        [1] => array
                (
                    name => two
                    id => 2
                    color => array
                                (
                                    [0] => array 
                                                (
                                                    name =>red
                                                    image => array 
                                                                (
                                                                    [0] =>twoRed1.jpg
                                                                    [1] =>twoRed2.jpg
                                                                    [2] =>twoRed3.jpg
                                                                )   
                                                )   
                                    [1] => array 
                                                (
                                                    name =>blue
                                                    image => array 
                                                                (
                                                                    [0] =>twoBlue1.jpg
                                                                    [1] =>twoBlue2.jpg
                                                                    [2] =>twoBlue3.jpg
                                                                )   
                                                )   
                                    [2] => array 
                                                (
                                                    name =>purple
                                                    image => array 
                                                                (
                                                                    [0] =>twoPurple1.jpg
                                                                    [1] =>twoPurple2.jpg
                                                                    [2] =>twoPurple3.jpg
                                                                )   
                                                )   
                                )
                )
    )

Thank you very much in advance for any help.

php tags with regex preg_replace

I have a url let's say : http://ift.tt/1HqMoVf and images tags and here is my regex code for preg_replace: $regex = "-(src\s*=\s*['\"])(((?!'|\"|http://|https://).)*)(['\"])-i"; so if I use this code in the tags above the output will be : but what I want is /example2 and example3 get replaced too but for /example2 it gets only http://ift.tt/gbk8l4 and for example3 it gets http://ift.tt/1GLmpDZ ps : I know how to get domain using parse_url. and f= is src ^^

How do use go lang as a web server

I have recently look into go lang and decided that it would be the best option to further improve the speed of the my website and handle more request. As php is not very efficient. In go lang i can write a script which runs multiple go lang webpage (it will host multiple page in a website). However all the page detial and code has to be in the one file.

My current code:

    package main

import (
    "fmt"
    "net/http"
    "strings"
    "log"
    "os"
    "strconv"
    "io"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()  // parse arguments, you have to call this by yourself
    fmt.Println(r.Form)  // print form information in server side
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello User!") // send data to client side
}
func main() {
    http.HandleFunc("/hello", sayhelloName) // set router    
err := http.ListenAndServe(":900", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

As you can see this script will host the page which is myip:900/hello and it will print hello. If i type myip:/hello/person it will say hello person ect.

However my script from the hello world page, (at the moment) has to also be in the same script as this.

Basically, i would like to have a go lang script which handles the request and send them to another script which will be run and provide a the page - if possible can you demonstrate exemplar code for both pages. Additionally is it possible for go to host some php page passing the url to the php manger fastcgi. So that I can switch over my server to go lang fast server - whilst i convert my php code into go lang code - however this is not vital (just useful).

Also would it be better to program a website in java or go lang. If java can you show an example code please.

Include config for subdirectory in Nginx

For example, I have a webserver for testing.

Now I put Drupal 8 in a Subdirectory.

The server config in Nginx is OK for plain php files, but Drupal needs another config because of URL scheme.

My goal is something like this:

normal.cfg

server {
   listen 80;
   server_name _;

   location (phpfiles) {
      pass to PHPFPM;
   }
}

drupal_test.cfg

server {
   listen 80;
   server_name _;

   location /drupal/(phpfiles) {
      do_some_magic
      pass to PHPFPM;
   }
}

But then Nginx complains about ignoring duplicated server_name.

So, how can I include a specific (separated file) configuration for a given subdirectory of a given server_name that I can later delete without much problems? This is because I don't want to mess up the main config.

PayPal donation button form inside on submit form

I have a need to submit form with specific values by clicking submit button. When clicking submit button I want to be redirected to PayPal where asked for donation. After submitting donation I need to redirect customer back to my website where form with values are submitted and shown to customer. But right now I`m stuck. If I press submit button after paying or canceling donation nothing happens with entered values in my primary form with title and website. My Code looks like this:


    <form action="adding.php" method="post" enctype='multipart/form-data'>
        <table>
        <tr>
            <td class="abc">
                <p id="insert">Title:*</p><br>
                <input type="text" name="title" class="abcd"  value="<?php echo $title; ?>" />
            </td>
            <td class="abc">
                <p id="insert">Website:*</p><br>
                <input type="text" name="website" class="abcd" value="<?php echo $website; ?>" />
            </td>
        </tr>
        </table>
        <input type="submit" value="Submit" id="submit" name="submit" />
    </form>


    <form action="http://ift.tt/rDmnwQ" method="post" target="_top">
        <input type="hidden" name="cmd" value="_s-xclick">
        <input type="hidden" name="hosted_button_id" value="EJJ5RT9MEEJSC">
        <input type="image" src="http://localhost/www/images/submit.png" id="submit" name="submit" border="0" alt="PayPal - The safer, easier way to pay online!">
        <img alt="" border="0" src="http://ift.tt/rpOo6s" width="1" height="1">
    </form>


    <?php
        $sql2 = "INSERT INTO `www` (title, website)
        VALUES ('$title', '$website')";
    ?>
    <?php 
        if (isset($_POST['submit'])) {

            $con = mysql_connect("localhost","root","");
            if (!$con){
            exit("Can not connect: " . mysql_error());
        }
        mysql_select_db("www",$con);            
    ?>
    <?php           
    if ((strlen($title) < 3) or (strlen($title) > 15)) {
        echo "<h1 id='top'>Title must be between 3 and 15 characters long!</h1>";
    } else if (filter_var($website, FILTER_VALIDATE_URL) === false) {
        echo("<h1 id='top'>Website: Please enter a valid website to your wish.</h1>");
    }
    else
    {   
        mysql_query($sql2,$con);
        mysql_close($con);

        header("Location:index.php");           
    }
    ?>

how to go back to login page if given wrong php GET credentials?

so im given 3 variables on my login page from an outside source, if one of those do not belong in the database I want it to just go to the normal login.php page. as of right now it stays on that page and does not change the url even though the vars are not in the db. i give it localhost/john/login.php?uniqueID=BmWDLlkcyU&compID=2&tempID=22 , but tempID 22 does not exist so i want it to revert to login.php

     $uniqueID = $_GET['uniqueID'];
     $compid =  $_GET['compID'];
     $tempID = $_GET['tempID'];

     $checkUnique = mysqli_query($conn, "SELECT unique_id from answers WHERE unique_id = '$uniqueID' and template_id = '$tempID'");
     $checkComp = mysqli_query($conn, "SELECT company_id from t_list WHERE company_id = '$compid'");


 if(!$checkUnique)
{

   header("Location: login.php"); 
  exit;
 }
else if(!$checkComp)
  {
    header("Location: login.php"); 
   exit;
   }

Avoid HTML file cache in HTML5 manifest (appcache)

I made a little script in PHP that create a file manifest for my website scanning the directories which I give it but without include in the manifest the HTML pages and the manifest file it cache them anyway. The problem is that many part of HTML pages are dynamical written by PHP and now don't change, they remain static but the more strange things is that when I change language and the website is reloaded the page is correctly translated and the text are also written by PHP. I've seen in a guide for the manifest usage to include in .htaccess this:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/cache-manifest "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds" 
</IfModule>

The mod_expires is active and I seen website HTML index headers:

HTTP/1.1 200 OK => 
Date => Mon, 29 Jun 2015 19:13:02 GMT
Server => Apache/2.4.12 (Ubuntu)
X-Powered-By => PHP/5.6.10-1+deb.sury.org~trusty+1
Vary => Accept-Encoding
Cache-Control => max-age=1
Expires => Mon, 29 Jun 2015 19:13:03 GMT
X-Frame-Options => DENY
Connection => close
Content-Type => text/html; charset=UTF-8

So I think that the .htaccess directive is working but browser ignores it, I've tested on Chrome and Safari and also on Safari for iOS 8 but no changes. With manifest I can get a website that loads in few seconds but now ever works offline. How can I disable HTML and manifest cache? Here there is the website (beta): http://ift.tt/1CF9sdk Here there is the manifest: http://ift.tt/1C2CTLu

Validating Information....error with query...No connection could be made because the target machine actively refused it

I have created php connect with php database. I checked locally its working well. I have moved server Its showing error. changed the database config details. It is showing, but this code connect xampp locally that time working well. I get this error:

Validating Information....error with query: SELECT ID,fname,lname,email,userlevel,user_group,orgID FROM students WHERE username='test' AND password='123456' No connection could be made because the target machine actively refused it.

Get Thread information from Single Database

I am trying to learn how to create a simple forum and i stuck in here;

My Database is something like this; (post table)

ThreadID |  PostID  | Author |  Title   |  Content |    Date    |    Time
--------------------------------------------------------------
   1     |     1    |  Jack  | Thread 1 |    ...   | 14/12/2015 |   20:21
   1     |     2    |  Arn   |          |    ...   | 15/12/2015 |   19:28
   1     |     3    |  Hank  |          |    ...   | 15/12/2015 |   20:24
   2     |     1    |  Tom   | Thread 2 |    ...   | 15/12/2015 |   22:41
   2     |     2    |  Frank |          |    ...   | 16/12/2015 |   13:06

Post table contains both replies and threads And i would like to get some information from database on category segment

and this is what i want;

Title      |   Author   |   Replies   | Views |               Last Poster
-------------------------------------------------------------------------
Thread 1   |    Jack    |      2      |   -   |   Hank - 20:24 15/12/2015
Thread 2   |    Tom     |      1      |   -   |  Frank - 20:24 15/12/2015

and finally my code is;

$get_threads = "SELECT threadid, title, author, postid, date, time FROM post WHERE categoryid = '" . $category . "'";   
$threads = mysqli_query($conn, $get_threads); if (mysqli_num_rows($threads) > 0) {while($row = mysqli_fetch_assoc($threads)) {
$get_reply = "SELECT (MAX(postid)-1) rn, (max(postid)) lp FROM post WHERE threadid = '".$row["threadid"]."'";
$reply = mysqli_query($conn, $get_reply); if (mysqli_num_rows($reply) > 0) {while($rod = mysqli_fetch_assoc($reply)) {
$get_lp = "SELECT op.author, op.date, op.time FROM post op INNER JOIN (SELECT author, date, time FROM post WHERE POSTID = '".$rod["lp"]."' GROUP BY threadid) lp ON op.author = lp.author AND op.date = lp.date AND op.time = lp.time WHERE threadid = '".$row['threadid']."'";
$lp = mysqli_query($conn, $get_lp); if (mysqli_num_rows($lp) > 0) {while($roc = mysqli_fetch_assoc($lp)) {

echo "<div class='thread'><div class='threadbox'>";
echo "<a href='forum.php?post=".$row["threadid"]."'class='ttitle'>".$row["title"]."</a>";
echo "<div class='tauthor'>".$row["author"]."</div>";
echo "<div class='treplies'>".$rod["rn"]."</div>";
echo "<div class='tviews'>".$row["date"]."</div>";
echo "<div class='tlastposter'>".$roc['author']." - ".$roc["time"]." ".$roc["date"]."</div>";
echo "</div></div><div class='threaddiv'></div>";

}}}}}} else {echo "<center>Content Not Found</center>";}

Well it may be the worst code ever written but its my first, i apologize for that anyway its duplicating some results i couldnt figure out.

  1. Please help me about how i can handle it?
  2. If you improove and shorten this code i would be glad ^^

Thanks in Advance

PHP Session: Preset login details only working locally

I am working on a website and I decided to make my own CMS for it. It doesn't need amazing security but I do have a login page for it that directs to the CMS page if the login information is correctly filled out.

It's only possible to login with 1 account (admin). And its login name and password are set within the login page PHP file. When submitting the form it checks if the right information is filled out, and if so, it puts the username within a SESSION[user] variable.

Aslong as that session exists the loginpage should always autodirect you to the CMS page, but this only seems to work locally. When i put it online, and fill out the right information and submit the form on the loginpage, it just stays on the same page instead of going to the CMS page. When i manually type in the URL of the cms page I can access it without being directed to the loginpage. And in my PHP i do check whether $_SESSION['user'] == admin.

Any of you guys have an idea why this only works locally, and what I need to change to make it work online too?

Here is the relevant code:

//LOGIN PHP PAGE

<?php
session_start();
    //login info
    $xinlognaam = 'admin';
    $xwachtwoord = 'PASSWORD HERE';

    //als je al ingelogd bent, wordt je direct naar cms pagina gestuurd
    if(!empty($_SESSION['user'])){
        if($_SESSION['user'] == $xinlognaam){
            header("Location: ../php/cms.php");
        }
    }
?>

    <div id="inlogsectie">
        <form id="inlogform" method="POST" action="#">

            Accountnaam:<br><br>
            <input type="text" name="accountnaam" id="accountnaam" maxlength="100"/><br><br><br>

            Wachtwoord:<br><br>
            <input type="text" name="wachtwoord" id="wachtwoord" maxlength="100"/><br><br><br>

            <input type="submit" name="inlogknop" id="inlogknop" value="inloggen"/>
        </form>

        <div id="inlogmelding">
            <?php
                //als op de knop gedrukt wordt
                if(isset($_POST['inlogknop'])){
                    //als velden niet leeg zijn
                    if(!empty($_POST['accountnaam']) && !empty($_POST['wachtwoord'])) {
                        //als de gegevens correct zijn
                        if(($xinlognaam == $_POST['accountnaam']) && ($xwachtwoord == $_POST['wachtwoord'])){
                            $_SESSION['user'] = $xinlognaam;
                            header("Location: ../php/cms.php");
                        //als de gegevens incorrect zijn
                        }else{
                            echo"De ingevulde login informatie is incorrect.";
                        }
                    } else{ //als velden leeg zijn
                        echo"De ingevulde login informatie is incorrect.";
                    }
                }
            ?>
        </div>
    </div>

//CMS PAGE

 <?php
  session_start();

 if($_SESSION['user'] != 'admin'){
        header('Location: ../admin/index.php');
    }

 if(isset($_POST['uitlogknop'])){
        include_once('uitloggen.php');
    }
   ?>

//LOG OUT PHP FILE

<?php
session_destroy();

header("Location: ../admin/index.php");

?>

Unable to find slug [slug] as mapped property in entity Gedmo Doctrine Extensions

I am implementing the Gedmo Sluggable annotations in Symfony 2 and cannot get the slugs to generate at all and it throws a 500 error everytime I try to save the object.

I've tried creating a new object as well as updating an existing object that has a slug already defined.

// config.yml
stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            timestampable: true
            uploadable: true
            sluggable: true

Object class

// Journal.php
<?php
namespace Example\JournalBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Example\UserBundle\Entity\User;
use \DateTime;


/**
 * Class Journal
 * @package Example\JournalBundle\Entity
 *
 * @ORM\Entity(repositoryClass="Example\JournalBundle\Entity\JournalRepository")
 * @ORM\Table(name="journal", indexes={
 *     @ORM\Index(name="idx_created", columns={"created"}),
 *     @ORM\Index(name="idx_status", columns={"status"})
 * })
 */
class Journal
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer", options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=100)
     */
    protected $title;

    /**
     * @Gedmo\Slug(fields={"title", "id"})
     * @ORM\Column(length=128, unique=true)
     */
    protected $slug;

    /**
     * @return mixed
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * @param mixed $slug
     * @return $this
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;
        return $this;
    }


}

controller

<?php
namespace Example\JournalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Example\JournalBundle\Entity\Journal;

/**
 * Class JournalController
 * @package Example\JournalBundle\Controller
 *
 * @Route("/journals")
 */
class JournalController extends Controller
{
    /**
     * @Route("/slugify")
     * @Security("is_granted('IS_AUTHENTICATED_ANONYMOUSLY')")
     * @Template("ExampleJournalBundle::test.html.twig")
     */
    public function slugifyAction()
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();

        $journal = new Journal();
        $journal->setBody('this is the body');
        $journal->setTitle('this is the title');
        $journal->setPrivacy(1);
        $journal->setStatus(1);
        $journal->setType(1);
        $journal->setUser($user);
        $em->persist($journal);
        $em->flush();
    }
}

It throws the following error: Sluggable error Any ideas why sluggable is not working?

Prepopulate a Gravity Forms field with the country name shortcode of Geolify

I'm trying to get the visitors country into the list when the user signs up, seems like I got the [geolifycountryname] code to work everywhere on wordpress except the Gravity Forms "Allow field to be populated dynamically" section - this is not working and leaves the Country field blank.

I know that Graviy Forms doesn't allow custom plugins short codes so I was wondering if there is a snippet I could write and to somehow retrieve the data from Geolify into my Gravity Forms table after user signs up.

Any advices?

PHP Oauth2 Grant_type cases based on custom data

I have a requirement which needs to generate a token code, and using this token, access to any kind of resources, however, I cannot find a oauth2 workflow to this specific case.

Let's some third party app will send me a request like

 grant_type="I DONT KNOW"&client_id=myapp&client_secret=mypass&phone=1234567

Based on this, I need to return some information regarding to the phone number, given the fact I've never used oauth, I was thinking about using User Credentials, but checking the sources, it only allows user and password.

Can anyone pls point me in the right direction?

Best Regards.

MySQL subtract two columns and compare them to number in WHERE clause

I have a table which looks like this:

id | some | irrelevant | data | time | waste_time | logged_in
--------------------------------------------------------------
1  |      |            |      | 0    | 246        | 0
2  |      |            |      | 0    | 360        | 0
3  |      |            |      | 116  | 116        | 0
4  |      |            |      | 291  | 199        | 0
5  |      |            |      | 3997 | 520        | 0
6  |      |            |      | 0    | 175        | 0
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

I am trying to have multiple tables, based on the result of time-waste_time I tought I had it work, but I was wrong. If the result is negative number, the compare to 0 (time-waste_time > 0) just gets ignored.

Those are my queries:

SELECT * FROM players WHERE time-waste_time>0 OR logged_in=1 ORDER BY logged_in DESC, login DESC

SELECT * FROM players WHERE time-waste_time>0 AND login<$time_limit ORDER BY login DESC

SELECT * FROM players WHERE time-waste_time<=0 AND logged_in=0 ORDER BY login DESC

The first query will show player that has time 0 and waste_time 150, even tho 0-150 = -150 and -150 < 0 and the third query will not show such player. Re required result is, that such player will not be shown with first and second query, but will be shown with third one.

I already found this anwer: Using 'Greater than' operator with a negative number but its not helping.

Any ideas why its acting like this and how can I make it work?

Thanks.

PHP - How can I tell in which domain a script will look for cookies?

I'm trying to fix a really elusive bug where I lose my session upon redirect. In my local setup, there is no problem; it only manifests itself on the live site. I discovered that my local version was creating two identical cookies: one for .mydomain.com and one for www.mydomain.com. However, the live site only creates a cookie for .mydomain.com. It seems as though my script is looking for the 'www.mydomain.com' cookie, which is why there's no apparent problem on the local server.

How do I determine to which domain a given script will look for its cookies? (or if this sounds like a different problem, please let me know)

Thoughts on building repositories into composer package to reuse in multiple apps

I am facing a new personal challenge at my work. We had just redesigned a legacy database to a much more normalized, organized schema and we need to port many apps to it. I'd suggested that one way we can do it is by creating a composer package with repositories and models bundled in it and then use the package on every single app. This way we can make changes to the package and update all apps the easy way.

Now, I want to use Eloquent models for such a package, since I found them really nice for building a simple database layer and with the repositories pattern. Problem is I never did this before and I'm kind of clueless about good practices on this.

Are there anyone who has went through something like this? Mind you left any thoughts?

Echo result of sql query in php

I have this sql query and I am trying to print / get the result.

$sql2="SELECT COUNT(*) FROM zones where routeID='15'";

The result is 3. How can I get this on my screen??

PHP variable ['url'] pushing wrong variable

I am not understanding why my variable $linkedin is not working properly. When I click the text, "linkedin" it will not redirect me to www.yahoo.com but instead add to the site.url + "/$linkedin". After I added the variable $linkedin into the if statements it will no longer appear and I believe it is because the variable is not identifying itself as a url. Causing it to fail if statements. Lastly, this is on WordPress + Advanced Custom Fields Plugin.

Added into the code a var_dump to hopefully show what my issue is.

Code:

function member_contact() {

    $vcard = get_field('vcard');
    $bio   = get_field('bio_pdf');
    $linkedin = get_field('linkedin');
    $phone = get_field('phone');
    $fax   = get_field('fax');
    $email = get_field('email');

    $post_info = '';

    if (isset($vcard['url'])) {
        $img = get_stylesheet_directory_uri() . "/images/mail-icon.png";
        $post_info .= '<a class="vcard" href="'.$vcard['url'].'"><img src="'.$img.'" /> Download Contact</a>';
    }

    if (isset($bio['url']) && isset($vcard['url'])) {
        $post_info .= ' | ';
    }

    if (isset($bio['url'])) {
        $post_info .= '<a class="bio-pdf" href="'.$bio['url'].'">Download Bio</a>';
    }

    if (isset($linkedin['url']) && isset($vcard['url']) || isset($bio['url'])) {
        $post_info .= ' | ';
    }

    if (isset($linkedin['url'])) {
        $post_info .= '<a href="'.$linkedin['url'].'"><i class="fa fa-linkedin" style="color:blue"></i> Linkedin</a>';
    }


    $post_info .= '<ul class="member-contact">';
    $post_info .= "<li>$email</li>";
    $post_info .= "<li>p: $phone</li>";
    $post_info .= "<li>f: $fax</li>";
    $post_info .= "</ul>";
    var_dump($linkedin);

Images:

HTML Front-End

enter image description here

HTML Back-End

enter image description here

Custom Field Plugin enter image description here

Anyone familiar with a press87.php file – is this a hack?

I just noticed a strange file on the Joomla install on my server named "press87.php" that isn't associated with anything in particular. It seems to be encrypted and, doing a search on the interweb, it seems to show up in a number of directories – including WP installs – but in seemingly random places. Is this a hack? Does anyone know anything about this?

The original code contained in the file can be viewed at http://ift.tt/1U1nJvP

Cheers!

Magento search results in wrong order

I'm working on a Magento 1.9.1.0 project and the search results aren't being displayed in the correct order. I've modified a function to fetch the results in order of position (which almost works), but it appears to be looping through each category first, listing the products from that category in order of position and name and then moving on to the next category - for example, if I search "a":

Anti-Slip Bath Mat, Bath Safety Strips, Square Shower Mat, Walking Frame, (here the order breaks, because it's entered a new category) Alarm Clock, Amplified Phone.

I'd have liked it to have returned:

Alarm Clock, Amplified Phone, Bath Safety Strips, Square Shower Mat, Walking Frame, Anti-Slip Bath Mat

(Anti-Slip Bath Mat would be last, because the position of everything else is 0 where as this product has a position of 10).

Is there a way I can amend this search just display all products without ordering them in category order? The function I'd written to achieve what I have so far is:

public function setListOrders()
{
    $category = Mage::getSingleton('catalog/layer')
        ->getCurrentCategory();
    /* @var $category Mage_Catalog_Model_Category */
    $availableOrders = $category->getAvailableSortByOptions();
    unset($availableOrders['position']);
    $availableOrders = array_merge(array(
        'relevance' => $this->__('Relevance'),
        'name' => $this->__('Name'),
        'position' => $this->__('Position')
    ), $availableOrders);

    $this->getListBlock()
        ->setAvailableOrders($availableOrders)
        ->setDefaultDirection('asc')
        ->setSortBy('position');
    return $this;

}

and...

protected function _getProductCollection()
{
    if (is_null($this->_productCollection)) {
        $this->_productCollection = $this->getListBlock()->getLoadedProductCollection();
    }

return $this->_productCollection->addAttributeToSort('position')->addAttributeToSort('name');

}

Script unresponsive to signals when its infinite while loop is doing nothing

I'm experimenting with creating a reusable generic cli server, that I can control (start/pause/resume/stop) from a terminal session.

My approach, so far, is that I have one script independently acting as both the console (parent loop) and the server (child loop), not by pcntl_fork()-ing, but by proc_open()-ing itself as the child process, so to speak.

The console loop then acts on the server loop by signaling it with posix_kill().

Disregarding, for now, whether this is a sensible approach, I stumbled upon something strange — namely, that when the console loop pauses the server loop with the SIGTSTP signal, the server loop will not respond to the SIGCONT signal, unless its while-loop is actually doing something useful.

What could be going on here?


edit:

As per request in the comments, I've simplified my code example. However, as I kind of feared already, this code works just fine.

Perhaps I'm overlooking something in the code with the classes, but I just don't see how both examples differ in their routine — to me it looks like both examples follow the same routine.

And as an important side note: in my more complex example I've tried constantly writing to a file in loop(), which actually works, even when paused. So, this tells me the loop continues to run properly. The Server simply just doesn't want to respond to signals anymore, after I've paused it.

Anyway, here's the simplified version of my earlier example that I've shown below:

$lockPath = '.lock';
if( file_exists( $lockPath ) ) {
  echo 'Process already running; exiting...' . PHP_EOL;
  exit( 1 );
}
else if( $argc == 2 && 'child' == $argv[ 1 ] ) {
  /* child process */

  if( false === ( $lock = fopen( $lockPath, 'x' ) ) ) {
    echo 'Unable to acquire lock; exiting...' . PHP_EOL;
    exit( 1 );
  }
  else if( false !== flock( $lock, LOCK_EX ) ) {
    echo 'Process started...' . PHP_EOL;

    $state = 1;

    declare( ticks = 1 );
    pcntl_signal( SIGTSTP, function( $signo ) use ( &$state ) {
      echo 'pcntl_signal SIGTSTP' . PHP_EOL;
      $state = 0;
    } );
    pcntl_signal( SIGCONT, function( $signo ) use ( &$state ) {
      echo 'pcntl_signal SIGCONT' . PHP_EOL;
      $state = 1;
    } );
    pcntl_signal( SIGTERM, function( $signo ) use ( &$state ) {
      echo 'pcntl_signal SIGTERM' . PHP_EOL;
      $state = -1;
    } );

    while( $state !== -1 ) {
      /**
       * It doesn't matter whether I leave the first echo out
       * and/or whether I put either echo's in functions,
       * Any combination simply works as expected here
       */
      echo 'Server state: ' . $state . PHP_EOL;
      if( $state !== 0 ) {
        echo 'Server tick.' . PHP_EOL;
      }
      usleep( 1000000 );
    }

    flock( $lock, LOCK_UN ) && fclose( $lock ) && unlink( $lockPath );
    echo 'Process ended; unlocked, closed and deleted lock file; exiting...' . PHP_EOL;
    exit( 0 );
  }
}
else {
  /* parent process */

  function consoleRead() {
    $fd = STDIN;
    $read = array( $fd );
    $write = array();
    $except = array();

    $result = stream_select( $read, $write, $except, 0 );
    if( $result === false ) {
      throw new RuntimeException( 'stream_select() failed' );
    }
    if( $result === 0 ) {
      return false;
    }

    return stream_get_line( $fd, 1024, PHP_EOL );
  }

  $decriptors = array(
    0 => STDIN,
    1 => STDOUT,
    2 => STDERR
  );
  $childProcess = proc_open( sprintf( 'exec %s child', __FILE__ ), $decriptors, $pipes );

  while( 1 ) {

    $childStatus = proc_get_status( $childProcess );
    $childPid    = $childStatus[ 'pid' ];
    if( false !== ( $command = consoleRead() ) ) {
      switch( $command ) {
        case 'status':
          var_export( $childStatus );
        break;
        case 'run':
        case 'start':
          // nothing?
        break;
        case 'pause':
        case 'suspend':
          // SIGTSTP
          if( false !== $childPid ) {
            posix_kill( $childPid, SIGTSTP );
          }
        break;
        case 'resume':
        case 'continue':
          // SIGCONT
          if( false !== $childPid ) {
            posix_kill( $childPid, SIGCONT );
          }
        break;
        case 'halt':
        case 'quit':
        case 'stop':
          // SIGTERM
          if( false !== $childPid ) {
            posix_kill( $childPid, SIGTERM );
          }
        break;
      }
    }
    usleep( 1000000 );
  }

  exit( 0 );
}

When you run either example (above and below) in the console, enter pause<enter> and then resume<enter>. The expected behavior is that, after resuming, you'll see (amongst other things) this stream again:

Server tick.
Server tick.
Server tick.

/edit


Here's what I use:

Both the console and server are instances of my abstract LoopedProcess class:

abstract class LoopedProcess
{

  const STOPPED = -1;
  const PAUSED  =  0;
  const RUNNING =  1;

  private $state    = self::STOPPED;
  private $throttle = 50;

  final protected function getState() {
    return $this->state;
  }

  final public function isStopped() {
    return self::STOPPED === $this->getState();
  }

  final public function isPaused() {
    return self::PAUSED === $this->getState();
  }

  final public function isRunning() {
    return self::RUNNING === $this->getState();
  }

  protected function onBeforeRun() {}

  protected function onRun() {}

  final public function run() {
    if( $this->isStopped() && false !== $this->onBeforeRun() ) {
      $this->state = self::RUNNING;
      $this->onRun();
      $this->loop();
    }
  }

  protected function onBeforePause() {}

  protected function onPause() {}

  final public function pause() {
    if( $this->isRunning() && false !== $this->onBeforePause() ) {
      $this->state = self::PAUSED;
      $this->onPause();
    }
  }

  protected function onBeforeResume() {}

  protected function onResume() {}

  final public function resume() {
    if( $this->isPaused() && false !== $this->onBeforeResume() ) {
      $this->state = self::RUNNING;
      $this->onResume();
    }
  }

  protected function onBeforeStop() {}

  protected function onStop() {}

  final public function stop() {
    if( !$this->isStopped() && false !== $this->onBeforeStop() ) {
      $this->state = self::STOPPED;
      $this->onStop();
    }
  }

  final protected function setThrottle( $throttle ) {
    $this->throttle = (int) $throttle;
  }

  protected function onLoopStart() {}

  protected function onLoopEnd() {}

  final private function loop() {
    while( !$this->isStopped() ) {
      $this->onLoopStart();
      if( !$this->isPaused() ) {
        $this->tick();
      }
      $this->onLoopEnd();
      usleep( $this->throttle );
    }
  }

  abstract protected function tick();
}

Here's a very rudimentary abstract console class, based on LoopedProcess:

abstract class Console
  extends LoopedProcess
{

  public function __construct() {
    $this->setThrottle( 1000000 ); // 1 sec
  }

  public function consoleRead() {
    $fd = STDIN;
    $read = array( $fd );
    $write = array();
    $except = array();

    $result = stream_select( $read, $write, $except, 0 );
    if( $result === false ) {
      throw new RuntimeException( 'stream_select() failed' );
    }
    if( $result === 0 ) {
      return false;
    }

    return stream_get_line( $fd, 1024, PHP_EOL );
  }

  public function consoleWrite( $data ) {
    echo "\r$data\n";
  }
}

The following actual server console extends the above abstract console class. Inside ServerConsole::tick() you'll find that it responds to commands, typed in from the terminal, and sends the signals to the child process (the actual server).

class ServerConsole
  extends Console
{

  private $childProcess;
  private $childProcessId;

  public function __construct() {
    declare( ticks = 1 );
    $self = $this;
    pcntl_signal( SIGINT, function( $signo ) use ( $self ) {
      $self->consoleWrite( 'Console received SIGINT' );
      $self->stop();
    } );
    parent::__construct();
  }

  protected function onBeforeRun() {
    $decriptors = array( /*
      0 => STDIN,
      1 => STDOUT,
      2 => STDERR
    */ );
    $this->childProcess = proc_open( sprintf( 'exec %s child', __FILE__ ), $decriptors, $pipes );

    if( !is_resource( $this->childProcess ) ) {
      $this->consoleWrite( 'Unable to create child process; exiting...' );
      return false;
    }
    else {
      $this->consoleWrite( 'Child process created...' );
    }
  }

  protected function onStop() {
    $this->consoleWrite( 'Parent process ended; exiting...' );
    $childPid = proc_get_status( $this->childProcess )[ 'pid' ];
    if( false !== $childPid ) {
      posix_kill( $childPid, SIGTERM );
    }
  }

  protected function tick() {    
    $childStatus = proc_get_status( $this->childProcess );
    $childPid = $childStatus[ 'pid' ];
    if( false !== ( $command = $this->consoleRead() ) ) {
      var_dump( $childPid, $command );
      switch( $command ) {
        case 'run':
        case 'start':
          // nothing, for now
        break;
        case 'pause':
        case 'suspend':
          // SIGTSTP
          if( false !== $childPid ) {
            posix_kill( $childPid, SIGTSTP );
          }
        break;
        case 'resume':
        case 'continue':
          // SIGCONT
          if( false !== $childPid ) {
            posix_kill( $childPid, SIGCONT );
          }
        break;
        case 'halt':
        case 'quit':
        case 'stop':
          // SIGTERM
          if( false !== $childPid ) {
            posix_kill( $childPid, SIGTERM );
          }
        break;
      }
    }
  }
}

And here is the server implementation. This is where the strange behavior occurs. If don't override the LoopedProcess::onLoopStart() hook, it will not respond to signals anymore, once it has paused. So, if I remove the hook, LoopedProcess::loop() effectively is doing nothing of importance anymore.

class Server
  extends LoopedProcess
{

  public function __construct() {
    declare( ticks = 1 );
    $self = $this;

    // install the signal handlers
    pcntl_signal( SIGTSTP, function( $signo ) use ( $self ) {
      echo 'pcntl_signal SIGTSTP' . PHP_EOL;
      $self->pause();
    } );
    pcntl_signal( SIGCONT, function( $signo ) use ( $self ) {
      echo 'pcntl_signal SIGCONT' . PHP_EOL;
      $self->resume();
    } );
    pcntl_signal( SIGTERM, function( $signo ) use ( $self ) {
      echo 'pcntl_signal SIGTERM' . PHP_EOL;
      $self->stop();
    } );
    $this->setThrottle( 2000000 ); // 2 sec
  }

  protected function tick() {
    echo 'Server tick.' . PHP_EOL;
  }

  protected function onBeforePause() {
    echo 'Server pausing.' . PHP_EOL;
  }

  protected function onPause() {
    echo 'Server paused.' . PHP_EOL;
  }

  protected function onBeforeResume() {
    echo 'Server resuming.' . PHP_EOL;
  }

  protected function onResume() {
    echo 'Server resumed.' . PHP_EOL;
  }

  /**
   * if I remove this hook, Server becomes unresponsive
   * to signals, after it has been paused
   */
  protected function onLoopStart() {
    echo 'Server state: ' . ( $this->getState() ) . PHP_EOL;
  }
}

And here's the script that ties it all together:

$lockPath = '.lock';
if( file_exists( $lockPath ) ) {
  echo 'Process already running; exiting...' . PHP_EOL;
  exit( 1 );
}
else if( $argc == 2 && 'child' == $argv[ 1 ] ) {
  /* child process */

  if( false === ( $lock = fopen( $lockPath, 'x' ) ) ) {
    echo 'Unable to acquire lock; exiting...' . PHP_EOL;
    exit( 1 );
  }
  else if( false !== flock( $lock, LOCK_EX ) ) {
    echo 'Process started...' . PHP_EOL;
    $server = new Server();
    $server->run();
    flock( $lock, LOCK_UN ) && fclose( $lock ) && unlink( $lockPath );
    echo 'Process ended; unlocked, closed and deleted lock file; exiting...' . PHP_EOL;
    exit( 0 );
  }
}
else {
  /* parent process */

  $console = new ServerConsole();
  $console->run();
  exit( 0 );
}


So, to summarize:

When Server is paused and is effectively doing nothing of importance inside loop() because I have no hook implemented that outputs anything, it becomes unresponsive to new signals. However, when a hook is implemented, it responds to the signals as expected.

What could be going on here?

Php script not working in Safari only (online only - it works locally for testing)

This script works in all browsers but not Apple Mac or Windows Safari. It works on same machines in Chrome. It works in other browsers. iOS no problem. It works in localhost too with Safari - just not on line! - Mac Safari: login happens and the user stays briefly (milliseconds) on index.php but immediately gets sent back to login page...

login_do.php below...

<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
    {
        require ('includes/connect_db.php');
        require ('login_tools.php');
        list ($check,$data)=validate($con,$_POST['username'],$_POST['pass']);
        if ($check)
            {session_start();
                $_SESSION['user_id']=$data['user_id'];
                $_SESSION['username']=$data['username'];
                $_SESSION['admin']=$data['admin'];
                load ('index.php');
            }
        else {$errors=$data;}
        mysqli_close($con);
    }
include ('login.php');
?>

Why?

This is the login.php that POSTs to the above script.

<?php
$page_title='Login';
include ('includes/header.html');?>
<link rel="stylesheet" type="text/css" href="handover.css">
<?php 
if (isset($errors) && !empty($errors))
{
echo'<p id="err_msg">Oops! There was a problem:<br>';
foreach ($errors as $msg)
{
echo "- $msg<br>";
}
echo 'Please try again or <a href="help.php">Ask for help</a></p>';
}
?>
<div id="middler">
<h2>
<form action="login_do.php" method="POST">
<p>
User name: <input type="text" name="username"></p>
<p>
Password: <input type="password" name="pass"></p>
<p>
<input type="submit" name="Login"value="Login"></p>
</form>

</div>
<?php 
include ('includes/logoutfooter.html')?>

The index.php that the login lands on briefly...

<?php 
session_start();
if (isset($_SESSION['username']))
{
    $screenname=$_SESSION['username'];
}
if (isset($_SESSION['admin']))
{
    $admincheck=$_SESSION['admin'];
}

else {$url = 'login.php';
    echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';}
?>

And finally: login_tools.php

<?php
function load ($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url=rtrim($url,'/\\');
$url.='/'.$page;
header("Location: $url");
exit();
}
function validate($con,$email='' , $pwd = '')
{
$errors=array();
if (empty($email))
{$errors[]='Enter your user name.';}
else
{$e=mysqli_real_escape_string($con,trim($email));}
if (empty($pwd))
{$errors[]='Enter your password.';}
else
{$p = mysqli_real_escape_string($con,trim($pwd));}

if (empty($errors))
{
$q="SELECT user_id, username, admin
FROM DPLA.users
WHERE username='$e'
AND password='$p'";
$r=mysqli_query($con, $q);
if (@mysqli_num_rows($r)==1)
{$row=mysqli_fetch_array($r,MYSQLI_ASSOC);
return array(true,$row);
}
else
{$errors[]='username and password not found.';}
}
return array(false, $errors);
}

Sending form with POST method and Polymer iron-form?

i use Polymer starter kit 1.0.2 and i'm trying to use iron-form based on (little) documentation i found.

My method form is "post" and contain only one input.

My form "action" is a PHP script (add.php) showing content of $_GET and $_POST:

print_r($_POST);
print_r($_GET);

My form component (form_eclp.html) is:

<dom-module id="my-form">
    <template>
        <div class="horizontal center-center layout">
            <div>
                <div class="horizontal-section">
                    <form is="iron-form" id="formGet" method="post" action="add.php">
                        <paper-input name="name" label="Name" required></paper-input>
                        <br><br><br>
                        <paper-button raised onclick="clickHandler(event)">Submit</paper-button>
                    </form>
                </div>
            </div>
        </div>
    </template>
    <script>

        function clickHandler(event) {
            Polymer.dom(event).localTarget.parentElement.submit();
        }

        Polymer({
            is: 'my-form',
            listeners: {
                'iron-form-response': 'formResponse'
            },
            formResponse: function(e) {
                // ?????????
            }
        });
    </script>
</dom-module>

I call if from:

<link rel="import" href="form_eclp.html">
<my-form></my-form>

When i click the submit button after entering the text 'test' in name input, i can see in the network tab of the browser developper tools that it's a POST request, ok, but the url is add.php?name=test, and in the response tab i have:

Array
(
)
Array
(
    [name] => test
)

According to my form action (add.php script), first array is for $_POST and the second $_GET.

I can see, despite form method="post", it's a "get" request because only $_GET is populated, there is nothing in $_POST.

I don't understand, is it a bug ?

php preg_match exclude negative number

preg_match_all('/(\b[0-9]+)/',"This is -44 55433 example",$amatches);

This will grab all numbers, however how would I exclude anything with a minus in front of it like -44.

Thanks

Unserialize() offset error when using CodeIgniter 2.2 Sessions with Objects

I'm trying to debug some old code from CodeIgniter 2.2. When running some data thru Session, I noticed an unserialize error, Message: unserialize(): Error at offset 160 of 163 bytes. After doing some debugging and research, I found out it's a common backslash issue when unserializing data from Sessions.

The serialized data I'm using has objects of data with backslashes in them, which causes the errors to occur. I'm in need of a replacement that can handle standard class objects as well.

Could someone recommend a quick replacement for codeigniter's Session _serialize() and _unserialize() methods?

public function data_test() {

    $input = array(
        (object)array('name' => 'test2', 'desc' => 'bla bla ob/gyn'),
        (object)array('name' => 'test2', 'desc' => 'bla bla ob\\gyn'),
    );
    var_dump($input);

    $data = $this->_serialize($input);
    var_dump($data);

    $result = $this->_unserialize($data);
    var_dump($result);


}



// --------------------------------------------------------------------

/**
 * Serialize an array
 *
 * This function first converts any slashes found in the array to a temporary
 * marker, so when it gets unserialized the slashes will be preserved
 *
 * @access  private
 * @param   array
 * @return  string
 */
function _serialize($data) {
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            if (is_string($val)) {
                $data[$key] = str_replace('\\', '{{slash}}', $val);
            }
        }
    } else {
        if (is_string($data)) {
            $data = str_replace('\\', '{{slash}}', $data);
        }
    }

    return serialize($data);
}

// --------------------------------------------------------------------

/**
 * Unserialize
 *
 * This function unserializes a data string, then converts any
 * temporary slash markers back to actual slashes
 *
 * @access  private
 * @param   array
 * @return  string
 */
function _unserialize($data) {

    $data = unserialize(strip_slashes($data));

    if (is_array($data)) {
        foreach ($data as $key => $val) {
            if (is_string($val)) {
                $data[$key] = str_replace('{{slash}}', '\\', $val);
            }
        }

        return $data;
    }

    return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
}

How to add an optional toppings option to Woocommerce products?

i want to add an optional topping feature to my Woocommerce wordpress food joint site. I have a pizza category and every pizza has three different sizes. Though I can add the toppings with fixed price, but I want to let the users add as many toppings they want and the price for the toppings changes with the size of the pizza. It has been done on several sites and here are two example sites I could found.

Image one

image two

I am using the composite product woocommerce extension but don't know how to use it to get this. Have tried several things, but it doesn't seem to work exactly how I would want to it to, i.e. different topping prices for different sizes. I have about 20 toppings to offer.

Please help.

Do i save time when requesting page via ajax and excluding non ajax parts?

I am implementing page loading through ajax() and I would like to know if I can save some time when requesting a page through the jQuery function .get()

When running the .get() function I pass a parameter that will indicate to my PHP page that it is being requested by AJAX and that it should return only those parts that are marked as such.

For example, all my PHP pages have header and footer functions, so when these pages are called by my AJAX function, the header and footer functions will be skipped.

Will this save my any time and bandwidth in my .get() request and thus delivering the page faster? If not, is there any other way to accomplish this?

How to store values in a data attribute and pass the value with php

I'm trying to figure out how I can store a user_id value in my drag and drop table and pass the value along when dropping the item in a new column.

For instance with my code. I start all the users in the 'Owes' column. When someone pays I want to move them to the appropriate column with my drag and drop table. I am outputting all this information from my database, so when I move someone from 'Owes' to 'Paid' I will need to update the record in the db so it saves in the drag and drop table.

My table is like this..

 <table class="paymentTable" id="dragTable">
        <tr>
            <th class="thPayment">Paid</th>
            <th class="thPayment">Partially Paid</th>
            <th class="thPayment">Owes</th>
        </tr>
        <tr>
            <td class="tdPayment" id="paid">
                            <div>
            <?php
                if ($paid_name == true) {
                    echo $paid_name;
                } else {
                    echo "No one has paid";
                }
            ?>
                            </div>
            </td>
            <td class="tdPayment" id="partially_paid">
            <div>
            <?php 
                if ($partially_paid__name == true) {
                    echo $partially_paid__name . " - " . $partially_paid_amount;
                } else {
                    echo "No one has made a partial payment";
                }
            ?>  
            </div>
            </td>
            <td class="tdPayment" id="owes">
            <div>
            <?php
                if ($owes_name == true) {
                    echo $owes_name;
                } else {
                    echo "Everyone has paid something";
                }
            ?>  
            </div>
            </td>
        </tr>
    </table>

I drag and drop the table cells like this..

 $(function() {
        $( "#paid, #partially_paid, #owes" ).sortable({
          connectWith: ".tdPayment",
          remove: function(e, ui) {
            var $this = $(this);
            var childs = $this.find('div');
            if (childs.length === 0) {
               $this.text("Nothing");
            }
          },
          receive: function(e, ui) {
            $(this).contents().filter(function() {
                return this.nodeType == 3; //Node.TEXT_NODE
             }).remove();
          },
        }).disableSelection();
      });

My php to output the values is like this. I am going to consolidate the php so it is only one db table rather than three, but this conveys what I am trying to do...

<?php
    //Payment Section

        $con = mysqli_connect("localhost", "root", "", "db");
        $paid_run = mysqli_query($con,"SELECT * FROM paid ORDER BY id DESC");
        $partially_paid_run = mysqli_query($con,"SELECT * FROM partial_payment ORDER BY id DESC");
        $owes_run = mysqli_query($con,"SELECT * FROM owes ORDER BY id DESC");
        $paid_numrows = mysqli_num_rows($paid_run);
        $partially_paid_numrows = mysqli_num_rows($partially_paid_run);
        $owes_numrows = mysqli_num_rows($owes_run);

            if($paid_numrows > 0){
                while($row = mysqli_fetch_assoc($paid_run)){
                    $paid_id = $row['user_id'];
                    $paid_name = $row['name'];
                }
            }

        if($partially_paid_numrows > 0){
                while($row = mysqli_fetch_assoc($partially_paid_run)){
                    $partially_paid_id = $row['user_id'];
                    $partially_paid_name = $row['name'];
                    $partially_paid_amount = $row['payment'];
                }
            }

        if($owes_numrows > 0){
                while($row = mysqli_fetch_assoc($owes_run)){
                    $owes_id = $row['user_id'];
                    $owes_name = $row['name'];
                }
            }
    ?>  

How can I store the user_id, so that I can update the db with php in this drag and drop table?

CORS header not set - can I request an image url and then serve it back to myself?

I am attempting to populate a WebGL Earth with meshes that are compiled from images. These images are cross-domain, and hosted on a server where setting the appropriate headers isn't an option. Can I XMLHttpRequest the image urls, and then serve them back to myself via PHP to bypass CORS errors?

Or, more specifically, can I use my own webserver as a proxy to serve img urls back to myself (to get around CORS) in a WebGL context?

EDIT: The real question here is if I can use my own webserver as a proxy to pass the urls, or if I'll have to actually download each image to the server to then use it.

Using FFMpeg av_read_frame in PHP?

I'm hoping to incorporate FFMpeg in a PHP script. My understanding is that the two best solutions are to use the command line via exec() and extract results or use PHP-FFMpeg (http://ift.tt/1cuzO85).

What I want to do is walk through a video frame-by-frame, and I think I need to use av_read_frame(). What's the best way to use that from PHP? I don't think it's available from the command line or PHP-FFMpeg. Should I write a C program (using XCode) to do what I want and call it from my PHP script?

Thanks!

PHP exec() not executing swipl

I want to execute command to run SWI_Prolog. My command generated correctly, means that when I run it in command prompt I'll get the output but when running it through exec($com, $out, $ret) it wont work and the value of $ret is 1.
Generated command is:

swipl -1 -f D:\xampp\htdocs\virastar\files\script.pl -g main(
    'D:\\xampp\\htdocs\\virastar\\files\\prepared_4329.vis',
    'D:\\xampp\\htdocs\\virastar\\files\\4329_final.vis') -t halt

Once again I have to say when I run it directly in command prompt it word correctly.
Any help will highly appreciated.

samedi 25 avril 2015

strip and get the codes in between

please rescue me from this regex nightmare.

Claim Code:
7241B-2HWRXR9-2P2BA
    $1.00

I'm trying to assign it to a variable in php but all the regex and preg_replace i've tried doesn't help me pull out exactly what is in the middle which is: 7241B-2HWRXR9-2P2BA

any kind of help I can get on this is greatly appreciated!

Would Rewriting It Using Regex Shorten/Beautify The Code?

The problem is a little challenging because I want to code it using std::regex believing it would be easier to read and faster to write.

But it seems that I can only code it one way (shown below).

Somehow my mind could not see the solution using std::regex.

How would you code it?

Would using std::regex_search do the job?

/*
input: data coming in:
/product/country/123456/city/7890/g.json

input: url parameter format:
/product/country/<id1:[0-9]+>/city/<id2:[0-9]+>/g.json

output:
std::vector<std::string> urlParams

sample output:
urlParams[0] = "123456"
urlParams[1] = "7890"
*/

bool ParseIt(const char *path, const char* urlRoute, std::vector<std::string> *urlParams)
{
   const DWORD BUFSZ = 2000;
   char buf[BUFSZ];
   DWORD dwSize = strlen(urlRoute);
   urlParams.clear();

   int j = 0;
   int i = 0;
   bool good = false;
   for (i = 0; i < dwSize; i++)
   {
       char c1 = path[j++];
       char c2 = urlRoute[i];
       if (c2 == '<')
       {
           good = true;
           while (c2 != '/')
           { 
               i++;
               c2 = urlRoute[i];
           }
           int k = 0;
           memset(buf, 0, BUFSZ);
           while (c1 != '/')
           {
               buf[k++] = c1;
               c1 = path[j++];
           }
           urlParams->push_back(_strdup(buf));
           int b = 1;
       }
       if (c1 != c2)
       {
           return false;
       }
       if (c2 != '<')
       {
           if (c1 == c1)
           {

           }
           else
           {
               return false;
           }
        }

    }

    if (dwSize == i && good)
    {
        return true;
    }

    return false;
}

python RE findall() return value is an entire string

I am writing a crawler to get certain parts of a html file. But I cannot figure out how to use re.findall().

Here is an example, when I want to find all ... part in the file, I may write something like this:

re.findall("<div>.*\</div>", result_page)

if result_page is a string "<div> </div> <div> </div>", the result will be

['<div> </div> <div> </div>']

Only the entire string. This is not what I want, I am expecting the two divs separately. What should I do?

Matching Barcodes to sequences python?

I have sequence files and barcode files. The barcode files may have barcodes of any length that look like "ATTG, AGCT, ACGT" for example. The sequence files look like "ATTGCCCCCCCGGGGG, ATTGTTTTTTTT, AGCTAAAAA" for example. I need to match the barcodes to the sequences that contain them at the beginning. Then for each set of sequences with the same barcode I have to do calculations on them with the rest of the program (which is written already). I just dont know how to get them to match. Ive went through using print statements and The part where it is messed up is the "potential_barcode = line(:len(barcode)" line. Also, where it says #simple to fasta that is where I should be reading in the matched sequences. I'm pretty new at this so I probably made a lot of mistakes. Thanks for your help!

bcodefname = sys.argv[1]
infname = sys.argv[2]
barcodefile = open(bcodefname, "r")
for barcode in barcodefile:
        barcode = barcode.strip()
        print "barcode: %s" % barcode
        outfname = "%s.%s" % (bcodefname,barcode)
#           print outfname
        outf = open("outfname", "w")
        handle = open(infname, "r")
        for line in handle:
                potential_barcode = line[:len(barcode)]
                print potential_barcode
                if potential_barcode == barcode:
                        outseq = line[len(barcode):]
                        sys.stdout.write(outseq)
                        outf.write(outseq)
                        fastafname = infname + ".fasta"
                        print fastafname
                        mafftfname = fastafname + ".mafft"
                        stfname = mafftfname + ".stock"
                        print stfname
#simp to fasta#
#                       handle = open(infname, "r")
                        outf2 = open(fastafname, "w")
                        for line in handle:
                                linearr = line.split()
                                seqid = linearr[0]
                                seq = linearr[1]
                                outf2.write(">%s\n%s\n" % (seqid,seq))
#                       handle.close()
#                       outf.close()
#mafft#
                        cmd = "mafft %s > %s" % (fastafname,mafftfname)
                        sys.stderr.write("command: %s\n" % cmd)
                        os.system(cmd)
                        sys.stderr.write("command done\n")

How to extract links from a web content?

I have download a web page and I want to extract all the links in that file. this links include absolutes and relatives. for example we have :

<script type="text/javascript" src="/assets/jquery-1.8.0.min.js"></script>

or

<a href="http://ift.tt/gbk8l4" />

so after reading the file, what should I do?

How to handle x*, x+, or x? regex-like operators in an LR parser?

I have implemented recursive descent and PEG-like parsers in the past, where you could do things like this:

Path -> Segment+
Segment -> Slash Name
Segment -> /
Name -> /\w+/
Slash -> /

  • where Segment+ means "match one or more Segment"
  • and there's a plain old regular expression for matching one or more word characters with \w+

How do you typically accomplish this same sort of thing with LR grammars/parsers? All of the examples of LR parsers I have seen are very basic, such as parsing 1 + 2 * 3, or (())(), where the patterns are very simple and don't seem to involve "one or more" functionality (or zero or more with *, or optional with ?). How do you do that in an LR parser generally?

Or does LR parsing require a lexing phase first (i.e. an LR parser requires terminal and nonterminal "tokens"). Hoping that there is a way to do LR parsing without two phases like that.

How to match everything except a particular pattern after/before a specific string constant

ATS(inline, const, unused)
OTS(inline, const, unused)

I'm trying to match inline, const, unused keywords only in ATS macro. i tried ATS([^,]*) but it only matches inline keyword.

Match last occuring enclosing outer brackets

I tried now for three hours to construct the following regex match without much success. I have the following two strings:

This is a test string to illustrate the problem (example) in complex matching logic (Work / not working (in this case) to match this last occurring bracket closure)

and

Simpler version of the string (Matchable in any easy way)

I would like to define a str.match() that matches this last part of the strings above. Resulting in:

Work / not working (in this case) to match this last occurring bracket closure

and

Matchable in any easy way

Any good way to achieve this? Sadly the data is highly volatile that a strong Regex is much rather preferred instead of long functional logic. Thanks so much!

Simplest way to parse a title from an HTML file using PHP functions only, no extra classes

So far I've been trying to get a simple way to stract a title from an HTML page.

This simple:

$url = "http://localhost";

Use any function to extract the title tag using only PHP functions or regular expressions, I do not want to use any external classes such as simple_html_dom or Zend_Dom... I want to do it the simple way with PHP only... can anyone post a sample code to simply extract the title tag from localhost?

I've tried using DOMdocument() class, simple_xml_parse(), and none of them with success

I tried like this:

<?php $dom = new DOMdocument(); 
$dom->loadhtml('pag.html'); 
$items = $dom->getElementsByTagName('title');
foreach ($items as $title) { echo "title"; }

How to get value of numbers with space

I used to have strings like this:

233.43 USD
634,233 EURO

and I used to extract numbers from those strings using this:

def extractNumbersFromString(value): #This function is to get the numbers froma string
        return re.search('(\d+(?:[.,]\d*)*)', value).group(1)

Now I got strings like these as well:

2300 000 USD
430 000 EU

where there is a space between the numbers and the zeros on the right.

How can I adjust my code to extract the numbers from those strings?

Required output:

 2300000 
 430000 

My code currently gives me just this 2300 and 430 (i.e. without the zeros on the right).

How to get the number out of a HTML string without tags?

I have the following string inside the source of some website:

user_count: <b>5.122.512</b>

Is this possible to get the number out of this string, even if the tags around this number were different? I mean, "user_count:" part won't change, but the tags can be changed, to strong for example. Or the tags could be doubled, or whatever.

How can I do that?

C# Regular Expression - Extracting the number of month or year from codes

I would like only one regular expression to extract the number of days, weeks, months and/or years from the following codes:

AB7YT1M=ABC       ==> 7Y1M

AB10YT1M=ABC      ==> 10Y1M

AB30YT1M=ABC      ==> 30Y1M

ABCDEF1Y1M=A      ==> 1Y1M

ABCDEF34Y6M=A     ==> 34Y6M

ABCDEF7M=A        ==> 7M

ABCDEF1D=A      ==> 1D


@"(\d+[DWMY])(?!\w+(1))(\d+[DWMY])(?!\w+(1))|(\d+[DWMY])(?!\w+(1))"

This code does not support e.g. 30YT1M

Could someone please help find an appropriate regexp for me?

How to get a substring until a specific character with preg_match in php?

Assuming I have these variations:

1: Today is a beautiful day (Monday)

2: Today is a beautiful day

I want to get Today is a beautiful day.

I'm trying preg_match('/(?=(^\w+.+))$|(?=(^\w+.+)\s\())/ui', $string, $matches) without success.

Update MySQL table & Regexp

I have a MySQL table with 4 millions of records having a field like "hello@xyz22-03-2015". Concatenated date is not fixed for all 4 million records. I am wondering how can I remove the numbers or any string after @xyz using mysql. One possible solution must be somehow with Regular expression and I know that Mysql does not allow replace using regex, so I am wondering how this particular task can be completed. I want to remove everything after @xyz.com

Many thanks

What is the JavaScript regex to match config.*.json?

I want to match config.json and config.staging.json and config.anything.json

So far I have configFile.match /config\.(.*)\.json/i

How to use regular expression in sahi script?

I am using sahi for automate the website, when I record the actions from the sahi recorder then it record click action of a button(actually "span") as _click(_span("Done[4]"));
but when I play the recorded script then it got failed on that line as it does not found the "Done[4]".
To solve this I just tried Regular expression to click on the _span("Done[4]") but no luck.

HTML Source structure :(this get displayed in popup [ui-dialog,ui-widget])

<div class="dashboardDlgButtonPanel">
<div id="addWidgetDone_wrapper" class="input_button  ">
    <div id="addWidgetDone" class="form_input_button">
        <div class="buttonwrapper">
            <a style="width: 49px; height: 41px; display: block;" id="addWidgetDone_Link" class="PrimaryButton" href="#" s1ignore="true" data-role="button" title="">
                <span>Done</span>
            </a>
        </div>
    </div>
</div>
<div id="addWidgetCancel_wrapper" class="input_button  tertiaryButton">
    <div id="addWidgetCancel">
        <div class="buttonwrapper">
            <a id="addWidgetCancel_Link" class="link" href="#" s1ignore="true" title="">Cancel</a>
        </div>
    </div>  
</div>
</div>

I tried followings one by one:

_click(_span(/Done.*/));
_click(_span(/Done\\[[0-9]\\]/));
_click(_span(/Done\[[0-9]\]/));
_click(_span(/Done/i));
_click(_span("/Done/"));
_click(_span(new Reg Exp("Done\\[[0-9]\\]")));
_click(_span(/Done.*/,_near(_div("addWidgetDone_wrapper[1]"))));
_click(_span(/Done.*/,_near(_div(/addWidgetDone_wrapper\\[[0-9]\\]/))));
_click(_span(/Done.*/,_near(_div(/addWidgetDone_wrapper.*/))));
_click(_span(/Done.*/,_in(_div("addWidgetDone_wrapper[1]"))));
_click(_span(/Done.*/,_in(_div(/addWidgetDone_wrapper/))));
_click(_span(/Done.*/,_in(_div(/addWidgetDone_wrapper.*/))));

and many more other combination but none of them working.

Ref Link :sahi-link-1 , sahi-link-2

Can any one please tell me what wrong I am doing?

Note : In recorded action "Done[4]" the numeric part is getting changed every time.