lundi 31 août 2015

javascript element.style.left Not working

Setting element top,left via javascript stops working,Perviously it was working perfectly.

ifrmObj.style.left = 100;
ifrmObj.style.top = 150;

Now i have to add a 'px' with number. What is the change that i made is the reason for this issue




why this calculation results in NaN?

var player = {
    x : 10.0,
    y : 10.0,
    color : "blue",
    v : 5.0,
    size : 10,
    render : function (c) {
        c.fillStyle = this.color;
        c.fillRect(Math.round(this.x), Math.round(this.y), this.size, this.size);
    }
};

function update(delta) {
    player.x += player.v * (delta / 1000);
    console.log("px = " + player.x);
}

function mainLoop(timeStamp) {
    delta = timeStamp - lastFrameTime;
    lastFrameTime = timeStamp;
    /* measure frame rate */
    curFps = Math.round((1/delta)*1000);

    /* game logic */
    update(delta);
    render();

    requestAnimationFrame(mainLoop);
}

The update() function is called every frame when position of the player needs to be updated. value of delta is ~16.00 (time in ms). Why the value of player.x shows as NaN when printed?




Server Error in '/' Application, Resource cannot be found

Hi is someone encountered . error is asp.net 4.0? I created a login page for my DVD selling website project and provided a username and password authentication for users. I also had created username and password for an admin access. I set the default page to Home.aspx to show all information of DVD's i have in the database. At first when i run the website it work's fine it shows the front page and when i try to log-in the error occurs. I checked the name of the database in each page, make it is right such as: string dbconnectionString=ConfigurationManager.ConnectionStrings["DVDDB"].ConnectionString; and so it is correct.

Here is my code to provide security to the site, i don't think it cause i already fix the name of the server and the database on it. Just showing in case you might see an error that i don't.

**

<compilation debug="true" targetFramework="4.0" />
 <authentication mode="Forms">   <forms timeout="30">
   <!---This will setup the admin username and password that has credentials to access the website-->
    <credentials passwordFormat ="MD5">

      <user name ="admin" password ="21232F297A57A5A743894A0E4A801FC3" /><!--This include hash tag-->

    </credentials>

</forms>  </authentication>

 <authorization> 

<allow users ="?" /> 

</authorization>

<authorization>

<deny users ="?"/>

</authorization>

**

**<connectionStrings>
  <add name="DVDDB" connectionString="Server=JOHN-PC;
  Database= DVDDB;
  Integrated Security=True" providerName = "System.Data.SqlClient"/>
</connectionStrings>

**

I also check the internet for answer but it seems that the error occurs on different scenario. If someone had the exact problem like i do, i would be appreciate if you share your experiences with me. Thank you in advance




Best language to create a script or something that can mine data from website

What language would be best to be able create something that gathers data from a site like a forum's marketplace and be able to do some simple calculations like lowest price, average, highest price, etc?




How can i code some of photoshop tools in a website for the user to play with?

An example of what i want: http://ift.tt/1MYwjIz

looking to code some simple tools like a color picker, font picker, drag and drop logo/image or in general a very small environment for the user to design a flier or a business cards. i understand this might requires sets of skills but plz shoot me some ideas and languages that will enable you to create such tools in a website.

thanks.




Difference between .html and .twig files

Looking at the two files, they look very similar. Even at the top of a .twig file it says:

<!Doctype HTML>
<html lang = "en">

etc.

So clearly it is basically html. In the .php file it renders a .twig file and there are no .html files in the entire website's directory? I didn't know you could build websites with no html whatsoever?




I'm confusing in applying many to many relationship in Laravel 5

I'm making library system by using Laravel 5.1 but i'm confusing in applying the many to many relationship by Laravel between three table ( books , authors , books_authors_relationship ) if i want to make page ( author.blade.php) to display information of author and what is all books that is published by this authors and the link of this page take parameter id for author to display information of this author when click on the book author name at book page .

I have controller for book and for author , also i have model for book and for author but i don't know how i can make relation between page of book to take author id of clicked book and passing to author page ( author/1) to display information of this author through controller by using Eloquent Model !

Can you help me !




What is Twig, and PHP Templating

I am completely confused what Twig is. Is it PHP or HTML? Also, what exactly is "PHP templating"? And would I need it (or PHP at all for that matter) to create a website which simply displays information to the user? Couldn't I just use HTML, CSS and JS for that?

Also, I have seen website source code with no .html files at all only .twig files, how does this work?




Learning FrontEnd [on hold]

Is not a technical question per se but I don't seem to find anyone on any forum that can answer it. Maybe this community can help me.

Im studying LINQ and MVC, I studied ASP.NET, C# and SQL. Im oriented towards Backend but I would want to study some frontend technologies and fortify other knowledge.

Right now Im interested in: -HTML -HTML5 -XHTML -HTTP -Ajax -AngularJS -Bootstrap -CSS -JavaScript -jQuery -Knockout

I would want to know if there is any particular order I should study these technologies as I understand they have some dependencies between them to properly understand them.

If anyone can point me in the right direction that would be great.




How to simplify form with multiple identical rows?

Want an advice.. I need a module - "working hours". Just simple: Monday: 10:00 - 18:00 ... Saturday: 11:00-16:00 (some extra info).

I am trying ..

<form  id="working_hours" >
       <select name="city" id="city_working_hours"/>
      city select
            </select>  
  <label>Choose day and hours </label>
<?php foreach ($days as $key=>$value): ?>
<label> <?php echo $value;?>  </label>
open <input type="text"  name="<?php echo $key;?>_open" value="" class="time_input"/>  
   close <input type="text"  name="<?php echo $key;?>_close" value="" class="time_input"/> 
   extra <input type="text"  name="<?php echo $key;?>_extra"  value="" />

From array $days=array("monday=>"Monday", ..., "sunday"=>"Sunday").

The DB structure seems as

CITY| DAY | OPEN | CLOSE | EXTRA

7 rows per city

But it seems that it would be diff to serialize such a form. Maybe a table with a day=row (and then jquery.each), or separate form for each day? Would aprreciate any advice. I am sure that there is a simple solution...




Best way to use datas between server and angular client?

We are developing a web application using C# and Angular.

The client and the server communicate with JSON to send datas.

My problem as a fronted developer is : When they change the model's variable's name, the client doesn't still work anymore.

Example : if the model is:

public class Person 
{
   public string name;
}

In the Angular Application I use exaclty the same structure when I receive the JSON:

<h1>{{myJson.name}}</h1>

And sometimes the back-end developers change the variable's name, I need to return to update the client side, and I loose big time in debugging with that.

Any tutorial or blog or something to know what's the best way to use data between server and client ?

Thanks a lot !




Saving html file in eclipse has no effect

So I've created a Dynamic Web application with Tomcat in Eclipse and it worked fine yesterday. Now when I try making changes to a file and running it has no effect, it still runs the old version of the file as if I haven't changed anything (even if I leave the file blank and save).




Sometimes getting "java.net.connectexception connection refused" while querying geoplugin's API

I'm writing an application that queries geoplugin's IP database multiple times, and every once in a while java.net.connectexception connection refused will appear (if I'm sending 150 requests, up to 10 might get refused).
I'm sending the requests like this:

private String getContent(URL url) throws  Exception {

    HttpURLConnection http = (HttpURLConnection) url.openConnection ();
    http.connect ();

    int code = http.getResponseCode();
    if(code != 200) throw new RuntimeException("Failed to get the location. Http Status code : " + code);
    return this.getContent(http);
}

The url format is: http://ift.tt/1O3s8JV
Is there an easy way to keep resending the requests until they get accepted?




how to modify formData jquery

I want to submit a form with ajax. I get data of from using FormData like this:

var data = new FormData($(this)[0]);

one of form's input is a color value in HSV format. I want to convert it to hex value. I have a jquery function to convert it, but I don't know how can I manipulate it's value in FormData. help me please!

another question is: How can I remove some fields (key, value) from FormData?




Gather video thumbnails from an Sites without an API

On some reddit.com subpages, which focus heavily on video content, ( like reddit.com/videos for example ) the links which are beeing posted, always show thumbnails of the videos, in some cases the videos come from various types of sources.

I am wondering how they are doing this. I know that bigger services like Youtube offer APIs, which make that a rather easy task, but in other cases, when an API is not available, it is not that clear to me.

The only thing I could find researching, where services which offer thumbnails for URLs, but those where just screenshots of the full webpage, instead of video thumbnails.

So my Question basically is:

How to gather video thumbnails, from video links, when there is no API available




What is a better technology overall to build a website ASP.NET using C# or PHP

What is a better technology overall to build a website ASP.NET using C# or PHP ?, Comparison must be about speed and overall performance of the system, system may be a website or a web application or a mobile application too




Execute router commands from Web with one button click

Good day everyone, Could you help me to figure out how to write code in HTML which will execute commands on router and bring back the output. For example : I want to execute several commands like ( show ip int brief ) | First off all i need to connect via ssh on Web page, second on the web page there should be a button ( SHOW ROUTE ) and after pressing this button it should execute command " show ip int brief " and show me output.

I'm not good in web programming, so i'll be very appreciate if you explain me how to do it in every step. Thanks.

I'm trying to do it on Windows machine with XAMPP ( Appache + Mysql )

Thanks a lot.




Change response url with Java HttpResponse

I'm developing a simple WebServer with Java (Using org.apache.http.HttpRequest and org.apache.http.HttpResponse).

I have an HTML page like this:

<form action="/upload" enctype="multipart/form-data" method="post">
  <label for="datafile1">First File:</label>
   <input type="file" id="datafile1" name="datafile1" size="40"><br>
  <input type="submit">
</form>

On the Java Server i get the POST request, read the Multipart content and fill up an HttpEntity as Response but the page loaded is (obviously) "/upload"

How can I tell the browser that the response url is something else?

I have tried:

response.setHeader("Location","/");

But with HTTP Status code 200 nothing happened And with HTTP Status code 302 the browser make a new request, deleting the one I have returned.

Any ideas?




Acessing SonarQube web from external host

I run a SonarQube server on an Ubuntu 14.04. From the server's machine, there is no problem accessing to SonarQube web, but from my machine I cannot.

I looked at access.log and sonar.log but there is nothing about my access. On configuration of sonar ( sonar.properties ) I tried some different configurations: for sonar.web.host, I tried to leave it commented, set it with 0.0.0.0, 127.0.0.1, and my public IP; for sonar.web.port I tried to set it on 80, 9000 and 8080; and for sonar.web.context, I have it set to /sonar.

The ports are open because I installed an apache server and I can access to it without any problem.

Do you have some idea about what's happening?

Thank you




How to upload image through restful web services on server using Strust2

enter code here 

i had upload image in database but when i deployed the project on server it will display the image on jsp pages

public class GridAction extends ActionSupport { /** * */ private static final long serialVersionUID = -4964110302586165626L; private List listGrid; Grid grid = new Grid();

private File fileUpload;

private String fileUploadContentType;

private String fileUploadFileName;

private String ImgURL;

public String saveGrid() {
    try {
        String resultUpload = saveImage();
        if (resultUpload.equalsIgnoreCase("success")) {

            String address = Inet4Address.getLocalHost().getHostAddress();
            ImgURL = "http://" + address + ":8080/PngAppWebApp/temp/"
                    + fileUploadFileName;

            grid.setImageUrl(ImgURL);

            new GridDao().saveGrid(grid);

            return SUCCESS;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;

}

public String editGrid() {
    try {
        String resultUpload = saveImage();
        if (resultUpload.equalsIgnoreCase("success")) {

            String address = Inet4Address.getLocalHost().getHostAddress();

            ImgURL = "http://" + address + ":8080/PngAppWebApp/temp/"
                    + fileUploadFileName;

            grid.setImageUrl(getImgURL());

            new GridDao().editGrid(grid);
            return SUCCESS;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;
}

public String saveImage() throws IOException {

    try {

        ServletContext servletContext = ServletActionContext
                .getServletContext();
        String path = servletContext.getRealPath("/temp");
        System.out.println("Server path:" + path);
        String filePath = servletContext.getRealPath(path);
        System.out.println("path:" + filePath);
        File uploadDir = new File(filePath, fileUploadFileName);
        // if the folder does not exits, creating it
        if (uploadDir.exists() == false) {
            uploadDir.mkdirs();
        }
        File destFile = new File(path, fileUploadFileName);
        FileUtils.copyFile(fileUpload, destFile);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return ERROR;
    }
    return SUCCESS;
}

public String listGrid() {
    try {
        listGrid = new GridDao().listGrid();
        System.out.println("you are in ListUser");
        return SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;
}

public String preprEditGrid() {
    try {

        grid = new GridDao().preprEditGrid(grid);
        System.out.println("you are in editUser" + grid);
        return SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;
}

public String deleteGrid() {
    try {
        new GridDao().deleteGrid(grid);
        return SUCCESS;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return ERROR;

}

public List<Grid> getListGrid() {
    return listGrid;
}

public void setListGrid(List<Grid> listGrid) {
    this.listGrid = listGrid;
}

public Grid getGrid() {
    return grid;
}

public void setGrid(Grid grid) {
    this.grid = grid;
}

public File getFileUpload() {
    return fileUpload;
}

public void setFileUpload(File fileUpload) {
    this.fileUpload = fileUpload;
}

public String getFileUploadContentType() {
    return fileUploadContentType;
}

public void setFileUploadContentType(String fileUploadContentType) {
    this.fileUploadContentType = fileUploadContentType;
}

public String getFileUploadFileName() {
    return fileUploadFileName;
}

public void setFileUploadFileName(String fileUploadFileName) {
    this.fileUploadFileName = fileUploadFileName;
}

public String getImgURL() {
    return ImgURL;
}

public void setImgURL(String imgURL) {
    ImgURL = imgURL;
}

}




retrieve data from database and show in table Java web by using MVC

currently im working on the project that require to shows the data from database and im already found a lot of tutorial video but it seems not working therefore i try to post my question here and look for the problem in my code

Model code

 public ArrayList<admin> getAllTrain()
       {
             ArrayList<admin> list = new ArrayList<admin>();
            try {
            dbConnection conn = new dbConnection();
            Connection myConnection = conn.Connection();

            String sql = "SELECT * FROM train";
            Statement st = myConnection.createStatement();
            ResultSet rs = st.executeQuery(sql);

            while(rs.next())
            {
                admin a = new admin();
              a.setTid(rs.getString("tid"));
              a.setSloc(rs.getString("sloc"));
              a.setEloc(rs.getString("eloc"));
              a.setStime(rs.getString("stime"));
              a.setEtime(rs.getString("etime"));
              a.setSdate(rs.getString("sdate"));
              a.setEdate(rs.getString("edate"));
              a.setStop(rs.getString("stop"));
              a.setSeat(rs.getString("seat"));
              a.setPrice(rs.getString("price"));
              list.add(a);

            }
             st.close();
             myConnection.close();

         } catch (SQLException ex) {
        Logger.getLogger(admin.class.getName()).log(Level.SEVERE, null, ex);
    }

       return list;

   }

Servlet Code

      admin a = new admin();
             List<admin> list = a.getAllTrain();
             request.setAttribute("list", list);
                     request.getRequestDispatcher("trainManagement.jsp").forward(request, response);

JSP Code

     <form name ="frmShowData" action ="editTrainControl" >
                                            <table border ="1">
                                              <thead>
                                             <tr>
                                            <th colspan ="10"><center><h4><b>Train Details</b></h4></center></th>
                                             </tr>
                                              </thead> 
                                             <th>Train ID </th>
                                             <th>Departure Location </th>
                                             <th>Arrival Location </th>
                                             <th>Departure Time </th>
                                             <th>Arrival Time </th>
                                             <th>Departure Date </th>
                                             <th>Arrival Date </th>
                                             <th>Number of Stop </th>
                                             <th>Number of Seat </th>
                                             <th>Price </th>
                                             <c:forEach items ="${requestScope.list}" var="admin">
                                             <tr>
                                             <td><a href = "${pageContext.request.contextPath}/insertTrainControl?tid = ${admin.getTid()}">${admin.getTid()}</a></td>
                                             <td>${admin.getSloc()}</td>
                                             <td>${admin.getEloc()}</td>
                                             <td>${admin.getStime()}</td>
                                             <td>${admin.getEtime()}</td>
                                             <td>${admin.getSdate()}</td>
                                             <td>${admin.getEdate()}</td>
                                             <td>${admin.getStop()}</td>
                                             <td>${admin.getSeat()}</td>
                                             <td>${admin.getPrice()}</td>
                                             </tr>
                                             </c:forEach>
                                            </table>
                                        </form>

when i run the page there is nothing shows in the table and there is no error message in the netbean also.




dimanche 30 août 2015

Unexpected token < destroys other site functions

Im getting this error for this line of code

    jQuery("body").html(jQuery("body").html().replace(/Some Text/gi, "<strong>Some Text</strong>"));

I am just trying to attach a strong tag to every instance of the words "Some Text" across site pages.

But this error actually destroys my other site functionalities, specifically AJAX stuff.

Error: Uncaught SyntaxError: Unexpected token <

Further info on error: (anonymous function) @ (index):227




Does anyone know where I can find and post trivia?

I am a big trivia nerd and was wondering if anyone knows where I can find and also post trivia?




General consensus on using database ids in urls?

Is using database ids in urls (e.g. http://ift.tt/1UmxDFt) an acceptable practice or should it be avoided? Is it more vulnerable to security threats by exposing it?




Creating a Web Application With an API Backend

I'm just about to dive into a project and just need a little bit of guidance. My plan is to have a Google backend that is served through Cloud Endpoints as an API to a React.js frontend.

I've worked with the Google infrastructure for years, so I have no problem on the backend - but on the frontend, I have some questions.

I've never really touched React so I'm wondering whether it would work well for my needs (my needs being, consuming JSON on the frontend and rendering the data asynchronously)? My other question is, how is it possible to maintain a login system with an API outside of Google's Oauth2 that is tied to Google accounts?

Thanks!




Handle server response javafx webview

How handle post response in javafx 8 webview? Where and how I should catch this event, and how I can add handler for it?




Automatically reload static content with Jetty and Gradle

I would like static content updates to be reflected in my web app without restarting web server. I am using Gradle with Jetty plugin.

How can I do that?

Here is my gradle.build file:

...

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jetty'


...

dependencies {
    compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.14'
    testCompile 'org.testng:testng:5.14.2'
}

Here is part of my web.xml for static content:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>




Storing login details using a binary search tree

I have made a login page for my app using some HTML and JS code. I want to store the details entered by the user into a linked list or a binary search tree. How do I go about it? Just a bit of help is enough.




Running background asp web service

I am building a web service in asp.net and have to create background tasks that connect to the database on both continuous and scheduled events. What is the best way to do this?




web site images manipulation as website renders

Hi need advice on what language to use for this program. I want to be able to apply a image filter on images on all viewed websites. With the funcitionality of disabling the filter from a mouse click or keyboard command on the selected image. Abit like a user choice disableable watermark.

Please could you suggest to a novice how I would go about implementation of this idea as to the architecture of Web browsers




How can I make a rectangle in HTML that will act as a link in the webpage?

I am trying to make a rectangle in html which will contain a text and act as a link. But I can't do it and I don't know why. This is my code

my html code

But in the browser window, the width and height property doesn't work. Only the left property does the job. All I wanted was making some clickable rectangles which will act as links. If I write the same css for heading, that does work. But when it comes to link, I can't get it to work. What can I do about this guys, help me! This is what I want-these boxes will act as the links-- What I am looking for

I could not post image , so please click on the links




How should I store user-uploaded images for a web application?

On my web server, I have two folders showcase and thumbnail to store images and their thumbnails, respectively. A database fetches these images to display them on a page.

The table column in the showcase table is s_image which stores something like /showcase/urlcode.jpg.

I heard that after around 10-20k files in a folder, it starts to slow down. So should I be creating a second folder, showcase2 once it's filled up? Is there some kind of automatic creation that can do this for me?

I appreciate your input.




make a loop inside macro code, without using the loop button

could i make it a loop in code instead of using the loop button of imacro?

becoz the default looping button is 3 and i have to increase to 99999 every time,thats very time consuming, thanks in advance!

spec: MAC + firefox + imacro

SET !ERRORIGNORE YES
VERSION BUILD=8820413 RECORDER=FX
TAB T=1

URL GOTO=https://xxxss.com.xx
URL GOTO=javascript:window.scrollBy(0,300)
wait seconds=10
URL GOTO=javascript:window.scrollBy(0,830)
wait seconds=0.6




Setting up a server to execute a Python Script

I am looking to create a very basic website that has a single feature. This feature works as follows:

  • 1) The user inputs a URL to a website
  • 2) My website will scrape the given website for necessary information
  • 3) Apply whatever logic I need and return the processed information as a string
  • 4) Allow user to download returned data in .txt format.

I am working on this project with one collaborator, and he has created the scraping and logic (steps 2 and 3) in Python. I have looked around stack overflow to see if it is possible to execute python scripts in a website, and the consensus seemed to be that I will require a server that executes python, and then make HTTP requests to my server.

Unfortunately, I'm quite a junior developer and lack a lot of understanding regarding web dev, and my attempts to "dive in" have left me with more questions than answers. We have a deadline that is approximately 3 days from now, and the only part that remains is to set up a server that can execute a specific python script upon HTTP requests.

I think that the source of my confusion is a lack of understanding regarding how exactly a server works, and was hoping that the kind folks here at stack overflow could help me in:

1) better understanding what's going on "under the hood" on the server side after an HTTP request arrives (or better yet, how does an HTTP request even arrive at all?)

2) Explain to me like I'm 5 what I'll need to do to deploy my website - namely all the in-between steps that receive little attention from the other posts here at stack overflow.

Some example questions that run through my head are below:

What type of server will I need?

How will I know if it can run Python?

How does the server know that I want to execute a certain script, while upon a user entering a my website's homepage URL, land at the home screen?

I've also read up on "middle layers" such as 'CGI' - what does this accomplish?

Is setting up a server reinventing the wheel? enter code here Is there already a service out there that does what I'm looking for?




YouTube video don't load and play into android web-view

I am android developer & try to build a android application.This application load a web view(Which show a web-page).In this page there have some youtube video.When i load this page by web-view .It work perfectly.But when i try to play those video.then id don't able to show video and can't play the video .I can't understand what is error my code.Please check my code.

    webView = (WebView) findViewById(R.id.webView1);
    WebSettings webSettings = webView.getSettings();
    webView.setWebViewClient(new WebViewClient());
    webView.setWebChromeClient(new WebChromeClient());
    webView.clearCache(true);
    webView.clearHistory();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setUseWideViewPort(false);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.loadUrl(url);

Mobile screenshot :

enter image description here

If anyone know what is issue? Why it don't able to load video .please help to me.Thanks to all.




samedi 29 août 2015

Can we convert MVC Web API to android app using PhoneGap?

Is is possible to convert the MVC Web API to android application using PhoneGap.




Information not being submitted into the database

I'm not quite sure what's going on, I've done almost everything I can think of to try and resolve this issue but I'm still stuck where I left off.

So the recovery questions are being submitted into the DB but when you are set to cancel them the cancel value doesn't change whatsoever.. I'm absolutely confused.

    <?php
/*
 * @CANCEL
 * ~~~~~~~~~~~~
 * @FILE DESCRIPTION: Cancels set recovery questions
 * @LAST MODIFIED: August 29, 2015
 */

require('../includes/config.php');
require('../structure/database.php');
require('../structure/base.php');
require('../structure/user.php');

$database = new database($db_host, $db_name, $db_user, $db_password);
$base     = new base($database);
$user     = new user($database);

//get config settings from db
$config = $base->loadConfig();

//set some basic vars
$username = $user->getUsername($_COOKIE['user'], 2);
$rank     = $user->getRank($username);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ift.tt/kTyqzh">
<html xmlns:IE>

<head>
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta name="MSSmartTagsPreventParsing" content="TRUE">
<title><?php
echo $data['wb_title'];
?></title>
<link href="../css/basic-3.css" rel="stylesheet" type="text/css" media="all">
<link href="../css/main/title-5.css" rel="stylesheet" type="text/css" media="all">
<link href="../css/kbase-2.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="../img/favicon.ico" />
<?php
include('../includes/google_analytics.html');
?>
<style>
fieldset {
    text-align: left;
    border: 2px solid #625437;
    width: 95%;
    position: relative;
    margin: 10px;
    padding-left: 10px;
        background-color:transparent;
}

legend {
    color: #625437;
    font-weight: bold;
    font-size: 15px;
}

</style>
<script type="text/javascript">
function goBack()
{
    window.history.back();
}    
</script>
</head>

        <div id="body">
               <?php
$base->getNavBar($username, $path, $rank);
?><br/><br/>
                <br/><br/>
        <div style="text-align: center; background: none;">
                <div class="titleframe e">
                    <b>Cancel recovery questions</b><br />
                    <a href="../index.php">Main Menu</a>
                </div>
            </div>


            <img class="widescroll-top" src="../img/scroll/backdrop_765_top.gif" alt="" width="765" height="50" />
            <div class="widescroll">
            <div class="widescroll-bgimg">
            <div class="widescroll-content">
            <?php
if (!$user->isLoggedIn()) {
    echo 'You must be logged in to access this content.';
} else {
    $info = $database->processQuery("SELECT `cancel` FROM `recoveries` WHERE `userid` = ?", array($user->getUserId($_COOKIE['user'])), true);
    //if ($database->getRowCount() == 1) {
    //echo 'You need to have recovery questions in order to cancel them. You can <a href="set_recov.php">set them here</a> or <a href="../index.php">return to the homepage</a>.';
    if ($info[0]['cancel'] >= 1) {
        echo 'Your recovery questions have already been set to cancel.';
    } elseif (isset($_GET['confirm'])) {
        //cancel the recovery questions
        $database->processQuery("UPDATE `recoveries` SET `cancel` = ? WHERE `userid` = ?", array(
            time(),
            $user->getUserId($_COOKIE['user'])
        ), false);

        echo '<center>Your recovery questions have successfully been set to cancel.<br><center><a href="../index.php">Main page</a></center>';
    } else {
?> 


                                        <b>Are you sure you wish to cancel your recovery questions?</b> Once you confirm this action your recovery questions will be active 
                                        for another two weeks, after that they will be deleted.<br><br> This action can be reversed by clicking the "Set recovery questions" link on the website homepage.
                                        <br/><br/>
                                        <center><a href="cancel.php?confirm=1">I wish to continue</a> &nbsp; | &nbsp; <a href="../index.php">I wish to go back</a></center>

                                    <?php
    }
}

?>
                      <center><img src="../img/kbase/scroll_spacer.gif" ></center>
            <div style="clear: both;"></div>
            </div>
            </div>
            </div>
            <img class="widescroll-bottom" src="../img/scroll/backdrop_765_bottom.gif" alt="" width="765" height="50" />
        <div class="tandc"><?php
echo $data['wb_foot'];
?></div>
    </div>
    </body>
</html>

As for this being commented out

 //if ($database->getRowCount() == 1) {
    //echo 'You need to have recovery questions in order to cancel them. You can <a href="set_recov.php">set them here</a> or <a href="../index.php">return to the homepage</a>.';

It's because if it is, when the page is loaded that's all that shows...nothing else, even if the recovery options are set in the database.

Any ideas? really stuck here.




What's the quickest way to stream binary data from web server to browser?

I'm working on realtime book scanning software that operates at 30 pages per minute. One of challenges is to stream book scans to the browser very fast as they happen. Each scanned page is about 2MB and we can't quite send it real time to browser, so we downscale the image and first send a preview of about 100K, and then progressively send higher quality images. This gives an impression to user it's loading continuously and everyone is happy.

Biggest challenge is how to stream binary data most effectively without going through a lot of unnecessary steps.

Right now I send string encoded image through a websocket but that takes two extra steps - first encoding image to string on book scanning machine (it runs linux), then decoding it on client side. Does anyone know if I can send binary data somehow with websockets? (we also have to support IE9+)

What other ways I could send binary data from linux book scanning machine to browser? Are there other communication protocols? (I apologize as don't know every protocol. I'm learning and any help appreciated.)




PDF opened outside of application when earlier versions of Adobe Reader used

I have this strange issue where when I use an early enough version of Adobe Reader, PDF's that are embedded in an iframe in my web application end up being downloaded in Adobe Reader instead. The web application supports IE only (I know, bad, but I did not design it originally). So I don't know if it happens in other browsers or not. Later versions of Adobe Reader do not have this problem (11.0.7+ in particular). In my C# web application, I have a simple WebBrowser control that displays a web page which contains the iframe.

I have researched everywhere online about this. I noticed that the WebBrowser control is rendering the web pages using the IE7 rendering engine. So I figured out how to force it to render in IE11. That didn't fix the problem. I'm wondering if there is some other IE related thing like this that might be causing this problem with earlier versions of Adobe Reader? Is it something security/permissions related that is causing the PDF to be downloaded instead of embedded? What else could it be?




CSS background syntax

I've seen an curious code example. I don't know completely what center center / cover means.
center center means center the background
cover means adjust the background to the area
But what means center center / cover?

background {transparent url(...) no-repeat scroll center center / cover;}




Data read has a different length than the expected

try {
            Long contentLength = Long.valueOf(saveFile.getBytes().length);
            AmazonS3 client = new AmazonS3Client(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
            /* ObjectMetadata meta = new ObjectMetadata();                            
            meta.setContentLength(contentLength);
            meta.setContentType(contentType);
            client.putObject(bucket, saveFile, in, meta);
            client.setObjectAcl(bucket, saveFile, CannedAccessControlList.PublicRead); */

            GeneratePresignedUrlRequest imgURL = new GeneratePresignedUrlRequest(bucket, saveFile);
            destFile = client.generatePresignedUrl(imgURL).toString();
        } catch (Exception ex) {
            System.out.println(ex);
        }

I was trying to upload a photo into Amazon-S3, and it said "Data read has a different length than the expected". Even though I could avoid this error by changing

meta.setContentLength(saveFile.getBytes().length);

But it is still upload a damaged/corrupted image.




weblogic server security roles in web application

I deploy my application to weblogic server, and I have security realm configured here with SQL provider. And I have a problem that I can't login in my application with any User of security role != Admin.

My configurations are:

security roles configuration:

Admin role AppTester role

I have one user of each role.

 Security policies for application:

security policies

Sample security policy for method:

samplepolicy




vendredi 28 août 2015

IIS 7 need to replace symbol in url for asmx call

I need a specific requirement to replace symbols in a URL at IIS 7 / Virtual directory

ASMX call : http://localhost/test/testservice.asmx/getdate%3Fquerystring%3D43

%3F into ?
%3D into =

Please guide me how to do that.




960.gs li tags will not spread out across the whole page

Im not a pro at this by any means. I tried following a few youtubes on this and was able to get the columns to work fine with paragraph tags. Though when I go with a ul > li tag. The image wants to take the whole space.

Im not really sure what the cause is here. Whats most perplexing is that it looks like the li / image has a right margin of the whole space. Even when I set it to zero.

When I inspect the element - that margin says 0 0 0 0 but mousing over I see it takes the whole page...

Code below ...

<html>
<head>
    <meta charset="utf-8">
    <title>Layout Test</title>
    <link href='http://ift.tt/U0x8sL' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="css/960.css">
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">

<body>
    <div class="header">
        <h1>This is a test</h1>
    </div>
        <div class="container_12">

            <div class="grid_4">

                    <ul>
                        <li><a href="#"><img src="img/1.jpg"></a></li>
                        <li><a href="#"><img src="img/2.jpg"></a></li>
                        <li><a href="#"><img src="img/3.jpg"></a></li>
                        <li><a href="#"><img src="img/4.jpg"></a></li>
                        <li><a href="#"><img src="img/5.jpg"></a></li>
                        <li><a href="#"><img src="img/6.jpg"></a></li>
                    </ul>   

            </div>




</div>
</body>
</head>
</html>




how to make a navigation bar for a mobile device

I need the code which would make a button display the navigation bar and hide it when not needed, like the one at apple.com. here is my code so far and please point out any mistakes or improvements! May i just add that this is for a mobile device!

.nav {
background: -webkit-linear-gradient(top left, #3c8dbc 0%, #307196 100%);
background: linear-gradient(to bottom right, #3c8dbc 0%, #307196 100%);
width:150%;
height:14%;
position:fixed;
left:0;
top:0;
list-style-type:none;
text-decoration:none;
}

.nav ul li {
list-style-type:none;
text-decoration:none;
color:white;
padding:2%;
font-size:80%;
list-style-position: inside;
display:inline-block;
background-color:#63A4C9;
border:2px solid white;
width:10%;
width:60%;
top:14%;
left:0;
}

.nav a:link {
color:white;
padding:1%;
padding-left:2%;
text-decoration:none;
list-style-position: inside;
list-style-type:none;
}
.nav a:hover {
background-color:white;
color:#3c8dbc;
}
.nav a:active {
color:white;
background-color:#3c8dbc;
}
.nav a:visited {
color:white;
background-color:#3c8dbc;
}

Thank you :)




javax.faces.FacesException , java.lang.NullPointerException

The following error(full description below):

com.sun.faces.lifecycle.InvokeApplicationPhase execute WARNING: #{testeHibernate.save}: java.lang.NullPointerException javax.faces.FacesException: #{testeHibernate.save}

This happens when I upload the register button, won't let me enter the values in the database.

Class

UtilizadorDAO.java

package DAO;

import Classhiber.Utilizador;
import java.util.List;

public interface UtilizadorDAO {
    public void addutilizador (Utilizador ut);
    public List<Utilizador> findallutilizador();

}

UtilizadorDaoimpl.java

package Impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import Classhiber.Utilizador;
import DAO.UtilizadorDAO;

public class UtilizadorDAOimpl implements UtilizadorDAO {
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void addutilizador(Utilizador ut) {
        Session session = this.sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.persist(ut);
        tx.commit();
        session.close();    }

    public List<Utilizador> findallutilizador() {
        Session session = this.sessionFactory.openSession();
        List<Utilizador> Utilizadorlist = session.createQuery("from Utilizador").list();
        session.close();        
        return Utilizadorlist;
    }


}

testeHibernate.java

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import Classhiber.Utilizador;
import DAO.UtilizadorDAO;
import Impl.UtilizadorDAOimpl;
@ManagedBean
@SessionScoped
public class TesteHibernate {

    public UtilizadorDAO utdao;

    private Utilizador utiliza;

        public TesteHibernate()
{
    utdao = new UtilizadorDAOimpl();
    utiliza = new Utilizador(); 
}
    public UtilizadorDAO getUtilizadorDAO() {
        return utdao;
    }

    public void setUtiliza(UtilizadorDAOimpl ut) {
        this.utdao = ut;
    }

    public Utilizador getUtiliza() {
        return utiliza;
    }

    public void setUtiliza(Utilizador utz) {
        this.utiliza = utz;
    }

    public void save() {
        // Calling Business Service
        utiliza.setIdUt(12);
        System.out.println(utiliza.getUser());
        System.out.println(utiliza.getPass());
        System.out.println(utiliza.getTip());

        utdao.addutilizador(utiliza);
    }
    }

Spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
    xmlns:xsi="http://ift.tt/ra1lAU" xmlns:aop="http://ift.tt/OpNdV1"
    xmlns:tx="http://ift.tt/OGfeU2"
    xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG
        http://ift.tt/OpNdV1 http://ift.tt/1eQJ7vy
        http://ift.tt/OGfeU2 http://ift.tt/KC395X">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3307/xp" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>


<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>Classhiber.Utilizador</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>


    <bean id="UtilizadorDAOimpl" class="Impl.UtilizadorDAOimpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </bean>
</beans>

index.xhtml

<html xmlns="http://ift.tt/lH0Osb"
    xmlns:ui="http://ift.tt/KsEgXx"
    xmlns:h="http://ift.tt/HjFrZb"
    xmlns:f="http://ift.tt/HcrI1S"
    xmlns:p="http://ift.tt/HjFrZc">
<h:head>
    <script name="jquery/jquery.js" library="primefaces"></script>
    <title>Register Utilizador</title>
</h:head>
<h:form>
    <p:growl id="messages"></p:growl>
    <p:panelGrid columns="2">
        <p:outputLabel value="Enter Utilizdor User:"></p:outputLabel>
        <p:inputText value="#{testeHibernate.utiliza.user}"></p:inputText>
        <p:outputLabel value="Enter Utilizador Pass:"></p:outputLabel>
        <p:inputText value="#{testeHibernate.utiliza.pass}"></p:inputText>
        <p:outputLabel value="Enter Utilizador tip"></p:outputLabel>
        <p:inputText value="#{testeHibernate.utiliza.tip}"></p:inputText>                     
    </p:panelGrid>
    <p:commandButton value="Register" action="#{testeHibernate.save}" ></p:commandButton>
</h:form>
</html>

Error

Ago 28, 2015 6:23:44 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{testeHibernate.save}: java.lang.NullPointerException
javax.faces.FacesException: #{testeHibernate.save}: java.lang.NullPointerException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 26 more
Caused by: java.lang.NullPointerException
    at Impl.UtilizadorDAOimpl.addutilizador(UtilizadorDAOimpl.java:21)
    at TesteHibernate.save(TesteHibernate.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 27 more

1245
Ago 28, 2015 6:23:44 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at Impl.UtilizadorDAOimpl.addutilizador(UtilizadorDAOimpl.java:21)
    at TesteHibernate.save(TesteHibernate.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 27 more

Thank you. (Excuse me if you have any programming error severe But I am learning)




Apache .htaccess file - Enable indexing on current directory

I need to put an .htaccess file on a specific directory. I want that .htaccess file to enable the directory where the htaccess is to indexing files in that directory. Plus if access to directories is forbidden, also grant access to that specific directory. How can i do that?




How can I search my entire list using list.js, even when filters are engaged?

I have a working, searchable list with HTML and list.js. I also have 3 filters that pare the list down to a smaller list based on some information within each list item. How can I clear my filters when I start typing in the search box? Not fuzzy, just basic instant search.

    var options = {
    valueNames: ['name', 'description', 'category']
};

var featureList = new List('qme-list', options);

/* 1 = Qualifying expense 2 = Potentially qualifying epxense 3= Not a qualifying expense*/

$('#filter-1').click(function () {
    featureList.filter(function (item) {
        if (item.values().category == "1") {
            return true;
        } else {
            return false;
        }
    });
    return false;
});

$('#filter-2').click(function () {
    featureList.filter(function (item) {
        if (item.values().category == "2") {
            return true;
        } else {
            return false;
        }
    });
    return false;
});

$('#filter-3').click(function () {
    featureList.filter(function (item) {
        if (item.values().category == "3") {
            return true;
        } else {
            return false;
        }
    });
    return false;
});

$('#filter-none').click(function () {
    featureList.filter();
    return false;

});




Python tornado web server: How to use multiprocessing to speed up web application

I have a web application that runs fine when used by one user, but as more clients start using it, it is unbearably slow. The server side is written in python and uses tornado. I noticed that while the server it's running on has 4 cores, only 1 is being used, so I've started looking at python's multiprocessing. I've seen the basic example from: http://ift.tt/1w067U1 and the tornado processors from: http://ift.tt/1LGujpn (which seems a bit more complicated), but I'm still not sure this is what I'm looking for. Will running this code with 4 processors speed it up when say 50 users are viewing it at once? And if so are one of these options the way to go for implementation when using tornado web server?

Sorry for the vague and poorly written question - my lack of experience with multiprocessing is to blame for this, even after extensive research. If any example code will help with answering this question, please let me know.

Thanks!




How to avoid the duplicates in drop-down list by using linq?

I am using linq to write the query, whenever I am creating a new entry in a form,gender drop down list is generating duplicates in that list.if i create 2 new entries 2 options like this. [male female male male ]. my project is visual studio-angularJS-web api-linq-sql-entity framework.




Error loading file or assembly in Web Application

i need some pro help here, I'm trying to install the DevInfo 7 Web application on my server, had A LOT of problems with SQL Server and IIS, after 2 days, i managed to fix it, but now that IIS and SQL are working fine, i can't get past this error because i have no idea about this language (btw, i'll add some tags, but as i don't know this language, i'm not sure they are actually related to the question, if i chose a tag wrong, tell me that i take it of!)

If somebody can explain to me what's wrong, or how to fix it, i would appreciate, as i'm not creating a Web Application (i have no idea on how to do so), and only trying to install one, i may not understand (please be as simplistic as you can)

I dunno if this changes something, but i'm installing it on a Windows Server 2012, x64...

Here's the error:


Server Error in '/devinfo' Application.

Could not load file or assembly 'DI5_INIFile' or one of its dependencies. An attempt was made to load a program with an incorrect format. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'DI5_INIFile' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'DI5_INIFile' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'DI5_INIFile' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17
   System.Reflection.Assembly.Load(String assemblyString) +35
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122

[ConfigurationErrorsException: Could not load file or assembly 'DI5_INIFile' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12761078
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +152
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151

[HttpException (0x80004005): Could not load file or assembly 'DI5_INIFile' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881540
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722601




Creating a simple site in Sitecore

I am newbie to the new Sitecore 8. I have successfully done the Sitecore 8 installation. Could anyone please give me some instructions and steps on how to create a site from scratch in the new Sitecore 8.

Once I am able to create a site with one simple page, I'd like to add an option for me to incorporate a web user controls or some components (Web Forms for Marketers - WFFM) to that simple page.

Please reply.

Thank you. Sid




Will Spark program be properly used as real-time back-end in web application

The background & requirement is like this, web application framework would have two main parts: web pages, and back-end spark/sparkR computing program which is ran on cluster. There is also another java program as middleware to make those two communicate.

Java program would get some parameters from web side, then it wants to call remote spark/sparkR program by way of passing previous parameters, next it also hopes to get the returning results from spark/sparkR program, finally the java program will do some process about the results and back-pass web side.

All would like to be done in one java program as normal function calling, since real-time dispatcher is needed.

The problems are: 1. Is spark/sparkR properly used in web application for real-time requirement, how is the skill framework like...

  1. Then, how the java program will call the spark program by way of leapping over different machines/clusters . By gateway or some more skills?

  2. Would java program conveniently get the returning results from spark program as normal function calling?

  3. If all the above is OK, then, if it comes to sparkR program, is it conveniently called by java program? How will the java program use the sparkR returning object?

I shall appreciate your all help very much!




What are the advantages and disadvantages of using wordpress

What are the advantages and disadvantages of using wordpress?

I have always built my own websites purely by myself, utilizing code editors such as notepad++, and completely making my own HTML, PHP, CSS, Jquery, Javascrip, MySQL and such.

But, i am a strong believer on the fact that one should know a little bit of everything, as a bit of general knowledge doesen't hurt anyone, but actually increases or general scope of everything. But without going far from the question.

I would like the opinion on people here, on what are the main advantages and disadvantages of using something such as wordpress, and if it would be productive to try it out for a bit. And maibe start using it one day.




Dynamic title in Jekyll

I have a page whose structure is somewhat like this

---
layout: contents
title: contents
description: Contents of the posts.
permalink: contents/
---


      <ul class="posts">
        {% for post in site.posts %}
            {% if post.categories != "tips" %}
          <h2><a class="post-heading" href="{{ post.url }}">{{ post.title }}</a></h2>
          <p> {{ post.description }} </p>
          <p class="date">{{ post.date | date_to_string }}</p>
          <hr class="hr-color"></hr>
          {% endif %}
        {% endfor %}
      </ul >

Currently the URL of this page is set according to permalinks(BASE_URL/contents). I want that when a user clicks on an option( Android,Java,Web are the options) in the previous page, i get the URL of this page as BASE_URL/android or BASE_URL/Java and display the contents of that category.

Is this possible using jekyll?




Visual studio view (.cshtml) crashed and cannot recover

My view file(.cshtml) crashed and turned into as shown in image below. Actually, it happened right after the system was unexpectedly shut down. I tried other solutions like clearing temp files from bin. I tried to open it with notepad++ but it didn't work. Any help will be appreciated.enter image description here




Embedding Instagram User feed in a certain site

I stumbled upon this area where http://ift.tt/19XklQ1 where what I wanted was users/self/feed endpoint where I could get the currently authenticated users feed. Now my problem with that is it needs client side authentication like those pop up window login. What I want to do is like Facebook Activity Feed plugin where it fetches data from a certain page without client side authentication or without the users consent to authenticate.

Is there a way of authentication in instagram api that do all the work by code? since the feed I want to put in the site is my clients own instagram account.

Thanks for the help in advance.




HTTPs logout Browser-base authentication (basic authentication via browser)


I am stuck at logout function (JavaScript) to log user out of a browser-based authentication.
I can use http://ift.tt/1NLd4Tw to logout. But it can work with http only.
How to make it works with HTTPs?




Best fully managed hosting provider for WordPress?

I need WordPress Hosting at a cheap price. What is the best fully managed hosting provider for WordPress?




iOS call sap weep service

I want to create an iOS-App, which calls sap web service. I followed this steps: http://ift.tt/1LFurW4

my problem is, i don't get any data back....i can give input parameter but i don't get any data back (Response).I get the wsdl body back without output parameters.Can you help me please ?

2015-08-28 07:57:11.281 integerprobe[1094:34249] ResponseBody: ..xml version="1.0" encoding="utf-8"?>wsdl:definitions targetNamespace="urn:sap-com:document:sap:soap:functions:mc-style"....




jeudi 27 août 2015

Converting a web-based PHP file into MVC (Model View Controller)

One of our company's clients have sent us some code to fix up, it's not the greatest and needs a lot of work. However, my boss wants it to be converted into MVC form. And if possible, may be to break down the code as well, I'm only a beginner at PHP so I'm not quite so good yet and also have very little experience with MVC and yes I have been reading up on it but I still don't know how to go about converting this code into MVC form :/ I noticed there is a very long if statement which is very irritating. Help appreciated very much! This is meant to be a booking calculator for a hotel and calculates prices based on the season and how many adults, children, and infants are booked into the hotel. The website you can see it at is "book.winduvillas.com"

<?php


require(dirname(__FILE__).'/backbone/page_top.php');


/***************************************************************/


# Mainline

thisBlah();


/***************************************************************/


function thisBlah() {

    $gDate                              = $_REQUEST['date'];
    $gDate1                             = $_REQUEST['date1'];
    $gAdult1                            = $_REQUEST['adult'];
    $gChild1                            = $_REQUEST['child'];
    $gInfant1                           = $_REQUEST['infant'];
    $gRateScheduleID            = $_REQUEST['rateScheduleId'];
    $gLan_Val                           = $_REQUEST['lan_val'];


/************ NO SUPER GLOBALS BELOW THIS LINE *****************/   

    # Globals
    $date                                   = $gDate;
    $date1                              = $gDate1;
    $adult1                             = $gAdult1;
    $child1                             = $gChild1;
    $infant1                            = $gInfant1;
    $rateScheduleId             = $gRateScheduleID;
    $lan_val                            = $gLan_Val;


/***************************************************************/

# 

    if ($adult1=='') {
        $adult = 0;
    }

    if ($adult1!='') {
        $adult = $adult1;
    }

    if ($child1=='') {
        $child = 0;
    }

    if ($child1!='') {
        $child = $child1;
    }

    if ($infant1=='') {
        $infant = 0;
    }

    if ($infant1!='') {
        $infant = $infant1;
    }


/***************************************************************/


    # Date Difference
    $check_in                           = explode("/",$date);
    $check_out                      = explode("/",$date1);

    $new_in                             = $check_in[2]."-".$check_in[1]."-".$check_in[0];
    $new_out                            = $check_out[2]."-".$check_out[1]."-".$check_out[0];


/***************************************************************/


    # For Seasons

        $newyear                            = '2014';

        $new_inseason                   = $newyear."-".$check_in[1]."-".$check_in[0];

        $new_outseason              = $newyear."-".$check_out[1]."-".$check_out[0];


/***************************************************************/


    # Fetch dates from different seasons (Low, High, & Peak) -- Could use better terminology?

        $date_diff1                     = mysql_query("SELECT DATEDIFF('$new_out','$new_in') AS DiffDate");

        $date_diff                      = mysql_fetch_array($date_diff1);

        $diff                                   = $date_diff['DiffDate'];

        $date_diff2                     = mysql_query("SELECT DATEDIFF('$new_in',curdate()) AS DiffDate");

        $date_diff3                     = mysql_fetch_array($date_diff2);

        $diff2                              = $date_diff3['DiffDate'];


/***************************************************************/


    # Define booking rate based on schedule?

        $rate_schedulemod1          = mysql_query("select * from booking_rate_schedule where 'rate_schedule_id'='".$gRateScheduleID."'");

        $rate_schedulemod2          = mysql_fetch_array($rate_schedulemod1);

        $rate_schedulemod3          = $rate_schedulemod2['no_of_room'];

        $currencymod                        = mysql_query("select * from booking_currency where currency_id='".$gLan_Val."'");

        $cony                                       = mysql_fetch_array($currencymod);


/***************************************************************/


    # Calculate costs based on what season it is (Low, High, & Peak)

        $cost_cal                           = mysql_query("select * from booking_season_chart where 'start_date'<='".$new_inseason."' AND 'end_date' >='".$new_outseason."'");

        $sea_type                           = mysql_fetch_array($cost_cal);

        $season_type                    = $sea_type['season_type'];


/***************************************************************/


    # Define when seasons start and end?

        if ($season_type=='') {
            // this tag closes on Line 475


                $date_diffnew1              = mysql_fetch_array(mysql_query("SELECT DATE_ADD($new_inseason,INTERVAL 1 DAY) AS crossindate FROM dual"));

                $date_diffnew1              = $date_diffnew1['crossindate'];

                $start_season                   = mysql_fetch_array(mysql_query("select * from booking_season_chart where  '".$new_inseason."' BETWEEN 'start_date' AND 'end_date'"));

                $start_season                   = $start_season['season_type'];

                $start_enddate              = mysql_fetch_array(mysql_query("select * from booking_season_chart where  '".$new_inseason."' BETWEEN 'start_date' AND 'end_date'"));

                $start_enddate              = $start_enddate['end_date'];
                $date_diffmod                   = mysql_query("SELECT DATEDIFF('$start_enddate','$new_inseason') AS DiffDate");

                $date_diffmod                   = mysql_fetch_array($date_diffmod);
                $diffmod                            = $date_diffmod['DiffDate']+1;

                $date_diffnew2              = mysql_fetch_array(mysql_query("SELECT DATE_ADD($new_outseason,INTERVAL 1 DAY) AS crossinout FROM dual"));
                $date_diffnew2              = $date_diffnew2['crossinout'];

                $end_season                     = mysql_fetch_array(mysql_query("select * from booking_season_chart where  '".$new_outseason."' BETWEEN 'start_date' AND 'end_date'"));

                $end_season                     = $end_season['season_type'];

                $end_enddate                    = mysql_fetch_array(mysql_query("select * from booking_season_chart where  '".$new_outseason."' BETWEEN 'start_date' AND 'end_date'"));

                $end_enddate                    = $end_enddate['start_date'];

                $date_diffmodend            = mysql_query("SELECT DATEDIFF('$new_outseason','$end_enddate') AS DiffDate");

                $date_diffmodend            = mysql_fetch_array($date_diffmodend);

                $diffmodend                     = $date_diffmodend['DiffDate'];

                $total_cost           = mysql_query("select * from booking_rate_schedule where 'rate_schedule_id'='".$gRateScheduleID."'");

                $total_costnew              = mysql_fetch_array($total_cost);

                $roomtype1                      = mysql_query("select * from booking_master_room_type where 'room_type_id'='".$total_costnew['room_type_id']."'");

                $roomtype2                      = mysql_fetch_array($roomtype1);

                $roomtype3                      = $roomtype2['room_type'];

                $accomodation                   = $total_costnew['accomodation'];


/***************************************************************/


    # Rates for different seasons

                if ($start_season=='Low Season')
                    {
                        $start_rate = $total_costnew['low_season'];
                    }

                if ($start_season=='High Season')
                    {
                        $start_rate = $total_costnew['high_season'];
                    }

                if ($start_season=='Peak Season')
                    {
                        $start_rate = $total_costnew['peak_season'];
                    }

                $start_datenew = $diffmod * $start_rate;
                if ($end_season=='Low Season')
                    {
                        $end_rate = $total_costnew['low_season'];
                    }

                if ($end_season=='High Season')
                    {
                        $end_rate = $total_costnew['high_season'];
                    }

                if ($end_season=='Peak Season')
                    {
                        $end_rate = $total_costnew['peak_season'];
                    }


/***************************************************************/


    # Commencing discounts in regards to a season change

                $end_datenew                    = $diffmodend * $end_rate;

                $actual_rate                    = ($start_datenew + $end_datenew);

                $no_of_additional           = ($adult + $child) - $accomodation;


                if ($no_of_additional > 0)
                    {

                        $add_cost = mysql_query("select * from booking_additional_cost");

                        $add_cost1 = mysql_fetch_array($add_cost);

                        $add_cost2 = $add_cost1['additional_cost'];

                        $extra_charge = $add_cost2 * $no_of_additional * $diff;

                    }


                $total_cost1                    = $actual_rate + $extra_charge;

                $tax_rates                      = mysql_query("select * from booking_tax"); 

                $tax_rate                           = mysql_fetch_array($tax_rates);

                $tax                                    = ($total_cost1 * $tax_rate['tax'])/100;


                $new_season                     = mysql_query("select * from booking_discount_night where 'season_type'='".$start_season."'");

                $new_season1                    = mysql_fetch_array($new_season);

                $night_number                   = $new_season1['night_number'];

                $discount_rate              = $new_season1['discount_rate'];

                $new_season_end             = mysql_query("select * from booking_discount_night where 'season_type'='".$end_season."'");

                $new_season2                    = mysql_fetch_array($new_season_end);

                $night_number2              = $new_season2['night_number'];

                $discount_rate2             = $new_season2['discount_rate'];


                $commence_discount      = mysql_query("select * from booking_commencement_discount");

                $commence_discount1     = mysql_fetch_array($commence_discount);

                $commence_discount2     = $commence_discount1['discount_rate'];

                $commence_discount3     = $commence_discount1['day'];

                $gross_amount                   = $total_cost1 + $tax;

        $diff_night                     = $diff;


/***************************************************************/


    # Rebates

                if ($diffmodend > $night_number2)
                    {
                        $rebate4 = ($gross_amount * $discount_rate2)/100;
                    }

                if ($diffmod > $night_number)
                    {
                        $rebate = ($gross_amount * $discount_rate)/100;
                    }

                if ($diff2 < $commence_discount3)
                    {
                        $rebate1 = ($gross_amount * $commence_discount2)/100;
                    }


/***************************************************************/


            # 

                $another_discount                       = mysql_query("select * from booking_another_discount where 'season_type'='".$start_season."'");

                $rec_ano_discount                       = mysql_fetch_array($another_discount);

                $ano_night_no                               = $rec_ano_discount['night_number'];


                if ($diffmod > $ano_night_no)
                    {
                        $rebate2 = $rec_ano_discount['ano_dis_amt'];
                    }


                $another_discountend                    = mysql_query("select * from booking_another_discount where 'season_type'='".$end_season."'");

                $rec_ano_discountend                    = mysql_fetch_array($another_discountend);

                $ano_night_noend                            = $rec_ano_discountend['night_number'];


                if ($diffmodend > $ano_night_noend)
                    {
                        $rebate5 = $rec_ano_discountend['ano_dis_amt'];
                    }


                $total_discount                             = $rebate + $rebate1 + $rebate2 + $rebate4 + $rebate5;

                $final_cost                                     = $gross_amount - $total_discount;

                $noroom                                             = $total_costnew['no_of_room'];

                $diffroom                                       = $diff * $noroom;

                $roomcost                                       = $final_cost / $diffroom;

                $total1                                             = $final_cost / $diffroom;


/***************************************************************/       


            # Call the function to get the currency converted

                $final_cost_usd1                            = get_currency("USD", "USD", "$final_cost");

                $final_cost_usd                             = number_format($final_cost_usd1,2);

                $final_cost_con1                            = get_currency("USD", "$cony[currency_code]", "$final_cost");

                $final_cost_con                             = number_format($final_cost_con1,2);


/***************************************************************/       


            # 

                $actual_rate_usd1                       = get_currency("USD", "USD", "$roomcost");

                $actual_rate_usd                            = number_format($actual_rate_usd1,2);

                $actual_rate_con1                       = get_currency("USD", "$cony[currency_code]", "$roomcost");

                $actual_rate_con                            = number_format($actual_rate_con1,2);


/***************************************************************/       


            # 

                $book_cost_usd1                             = get_currency("USD", "USD", "$total_cost1");

                $book_cost_usd                              = number_format($book_cost_usd1,2);

                $tax1                                               = get_currency("USD", "USD", "$tax");

                $tax2                                               = number_format($tax1,2);


/***************************************************************/


            #

                $con1                                   = $cony[currency_code];


                if ($con1=='')
                    {
                        $con = '';
                    }

                if ($con1!='')
                    {
                        $con = $con1;
                    }


                $bedroom                                = $rate_schedulemod2['no_of_room'];

                $in_mod                                 = $check_in[0]."/".$check_in[1]."/".$check_in[2];

                $out_mod                                = $check_out[0]."/".$check_out[1]."/".$check_out[2];

                $datemod                                = $in_mod;

                $datemod1                           = $out_mod;


                $output = array
                ( 
                'final_cost_usd' => $final_cost_usd, 
                'final_cost_con' => $final_cost_con,
                'actual_rate_usd' => $actual_rate_usd,
                'actual_rate_con' => $actual_rate_con,
                'book_cost_usd' => $book_cost_usd,
                'tax' => $tax2,
                'con' => $con,
                'date' => $datemod,
                'date1' => $datemod1,
                'adult' => $adult,
                'child' => $child,
                'infant' => $infant,
                'bedroom' => $bedroom,
                'roomtype' => $roomtype3,
                'diff_night' => $diff_night
                );


                        echo json_encode($output);


            } // this is the closing tag for Line 164


/***************************************************************/


        #

             else 

            { // this tag closes on Line 762


            $total_cost                         = mysql_query("select * from booking_rate_schedule where 'rate_schedule_id'='".$gRateScheduleID."'");


            $total_costnew                  = mysql_fetch_array($total_cost);


            $roomtype1                          = mysql_query("select * from booking_master_room_type where 'room_type_id'='".$total_costnew['room_type_id']."'");


            $roomtype2                          = mysql_fetch_array($roomtype1);

            $roomtype3                          = $roomtype2['room_type'];

            $accomodation                   = $total_costnew['accomodation'];


            if ($season_type=='Low Season')
                {
                $actual_rate = $total_costnew['low_season'];
                }


            if ($season_type=='High Season')
                {
                $actual_rate = $total_costnew['high_season'];
                }


            if ($season_type=='Peak Season')
                {
                $actual_rate = $total_costnew['peak_season'];
                }


            $no_of_additional           = ($adult + $child) - $accomodation;


            if ($no_of_additional > 0)
                {
                    $add_cost           = mysql_query("select * from booking_additional_cost");
                    $add_cost1          = mysql_fetch_array($add_cost);
                    $add_cost2          = $add_cost1['additional_cost'];
                    $extra_charge   = $add_cost2 * $no_of_additional * $diff;
                }


            $total_cost1                        = ($actual_rate * $diff) + $extra_charge;


/***************************************************************/


        # Tax factor

            $tax_rates                  = mysql_query("select * from booking_tax"); 

            $tax_rate                   = mysql_fetch_array($tax_rates);

            $tax                                = ($total_cost1 * $tax_rate['tax'])/100;


/***************************************************************/


        #

            $adult1                             = $gAdult1;

            $child1                             = $gChild1;

            $infant1                            = $gInfant1;


            if ($adult1=='')
                {
                    $adult = 0;
                }


            if ($adult1!='')
                {
                    $adult = $adult1;
                }


            if ($child1=='')
                {
                    $child = 0;
                }


            if ($child1!='')
                {
                    $child = $child1;
                }


            if ($infant1=='')
                {
                    $infant = 0;
                }


            if ($infant1!='')
                {
                    $infant = $infant1;
                }


/***************************************************************/


        #

            $new_season                             = mysql_query("select * from booking_discount_night where 'season_type'='".$season_type."'");

            $new_season1                            = mysql_fetch_array($new_season);

            $night_number                       = $new_season1['night_number'];

            $discount_rate                      = $new_season1['discount_rate'];

            $commence_discount              = mysql_query("select * from booking_commencement_discount");

            $commence_discount1             = mysql_fetch_array($commence_discount);

            $commence_discount2             = $commence_discount1['discount_rate'];

            $commence_discount3             = $commence_discount1['day'];

            $gross_amount                       = $total_cost1 + $tax;

            $diff_night                             = $diff;


            if ($diff > $night_number)
                {
                    $rebate = ($gross_amount * $discount_rate)/100;
                }


            if ($diff2 < $commence_discount3)
                {
                    $rebate1 = ($gross_amount * $commence_discount2)/100;
                }


            $another_discount               = mysql_query("select * from booking_another_discount where 'season_type'='".$season_type."'");

            $rec_ano_discount               = mysql_fetch_array($another_discount);

            $ano_night_no                       = $rec_ano_discount['night_number'];


            if ($diff > $ano_night_no)
                {
                    $rebate2 = $rec_ano_discount['ano_dis_amt'];
                }


            $total_discount                     = $rebate + $rebate1 + $rebate2;

            $final_cost                             = $gross_amount - $total_discount;

            $noroom                                     = $total_costnew['no_of_room'];

            $diffroom                               = $diff * $noroom;

            $roomcost                               = $final_cost / $diffroom;

            $total1                                     = $final_cost / $diffroom;


/***************************************************************/


        # Call the function to get the currency converted

            $final_cost_usd1                    = get_currency("USD", "USD", "$final_cost");
            $final_cost_usd                     = number_format($final_cost_usd1,2);

            $final_cost_con1                    = get_currency("USD", "$cony[currency_code]", "$final_cost");
            $final_cost_con                     = number_format($final_cost_con1,2);


/***************************************************************/


        # Get original cost of room

            $actual_rate_usd1               = get_currency("USD", "USD", "$roomcost");
            $actual_rate_usd                    = number_format($actual_rate_usd1,2);

            $actual_rate_con1               = get_currency("USD", "$cony[currency_code]", "$roomcost");
            $actual_rate_con                    = number_format($actual_rate_con1,2);


/***************************************************************/


        # A

            $book_cost_usd1                     = get_currency("USD", "USD", "$total_cost1");
            $book_cost_usd                      = number_format($book_cost_usd1,2);

            $tax1                                       = get_currency("USD", "USD", "$tax");
            $tax2                                       = number_format($tax1,2);


/***************************************************************/


        #

            $con1                                       = $cony[currency_code];

            if ($con1=='')
                {
                    $con='';
                }

            if ($con1!='')
                {
                    $con = $con1;
                }


/***************************************************************/


        #

            $bedroom                                = $rate_schedulemod2['no_of_room'];

            $datemod                                = date('d M,Y',strtotime($date));
            $datemod1                           = date('d M,Y',strtotime($date1));

            $in_mod                                 = $check_in[0]."/".$check_in[1]."/".$check_in[2];
            $out_mod                                = $check_out[0]."/".$check_out[1]."/".$check_out[2];

            $datemod                                = $in_mod;
            $datemod1                           = $out_mod;


/***************************************************************/


    # Output array


            $output = array
                ( 
                    'final_cost_usd' => $final_cost_usd, 
                    'final_cost_con' => $final_cost_con,
                    'actual_rate_usd' => $actual_rate_usd,
                    'actual_rate_con' => $actual_rate_con,
                    'book_cost_usd' => $book_cost_usd,
                    'tax' => $tax2,
                    'con' => $con,
                    'date' => $datemod,
                    'date1' => $datemod1,
                    'adult' => $adult,
                    'child' => $child,
                    'infant' => $infant,
                    'bedroom' => $bedroom,
                    'roomtype' => $roomtype3,
                    'diff_night' => $diff_night
                );


            echo json_encode($output);


/***************************************************************/


            } // closing tag for Line 485
    }
?>




php after select file check that user change file name before upload

I have create to upload csv file in php. When I test that, First I select some csv file to upload and then before upload I have changed rename of that file.

Finally I get following message in that upload page.

"ERR_FILE_NOT_FOUND"

I want to catch this error and want to show some message about that




Set absolute path for root directory in HTML on local filesystem

How can I use absolute paths in my website while testing on my local filesystem? I know that I can use / to access the root directory of my website. However, this works only when my website is on the server. I want to be able to use absolute paths on my local filesystem so that I can do proper testing before uploading.

Is there a way to set a variable to a root directory in HTML? Something similar to Linux where you can define a variable WEBPATH=/home/user/website. Thus I can use e.g src="WEBPATH/folder/file.html for all the files I use in my website and I can modify WEBPATH depending on whether I am testing locally or using the server root folder.

I am open to other workarounds as well.




Copying Relations Between Models

I'm trying to create a system that automatically generates lessons based upon a rule I've created using database fields. The rule would hold a list of students and teachers as many-to-many relationships.

I want to directly transfer the relations from the course instance to the lesson instance through a post_save signal.

These are my models

class Course(models.Model):
    students = models.ManyToManyField(
        Profile,
        limit_choices_to=Q(is_teacher=False),
        related_name='course_students')
    teachers = models.ManyToManyField(
        Profile,
        limit_choices_to=Q(is_teacher=True),
        related_name='course_teachers')

class Lesson(models.Model):
    students = models.ManyToManyField(
        Profile,
        limit_choices_to=Q(is_teacher=False),
        related_name='lesson_students')
    teachers = models.ManyToManyField(
        Profile,
        limit_choices_to=Q(is_teacher=True),
        related_name='lesson_teachers')

This is my signal code

@receiver(post_save, sender=Course)
def new_course_lesson_creator(sender, instance, created, **kwargs):
    if not created:
        return
    print "Course Created!"
    teachers = instance.teachers.all()
    students = instance.students.all()
    lesson = Lesson()
    lesson.teachers.add(*teachers)
    lesson.students.add(*students)
    lesson.save()

For whatever reason this doesn't transfer the related student and teacher relations to the lesson. The "teachers" and "students" show up as empty.

Any and all help is appreciated :)




How to determine what SQL query a java web application is using to return the data?

I have been given a java web application for which I have the source code to. The application queries an Oracle database to return data back to the user in web page. I need to update a value for the returned data in the database, without knowing the table or column names. Is there a general way to determine what query the application is submitting to return the data for a particular page so I can find the right tables and columns?

I am new to java and web development so not sure where to start looking. Thanks!




JWT Protect JSON endpoints with least overhead

Is JWT is enough to protect from these?

  1. CSRF protection
  2. Request repeat attack



How to get a Backbone Model attribute after fetch?

I know that a fetch is asynchronous and it needs to use "success" in fetch. But what if I want to use the data out of the success? I wanna to get the user ID and to use it in a model "Note".

 authedUser.fetch({
            success: function(){;
                window.uid = authedUser.get("id");
            }

But if I try to do this console.log(uid); not in success I get undefined.