Tuesday, 28 February 2017

What's wrong? PHP Parse error: syntax error, unexpected '}', expecting ',' or ';' in




Me and my mate we're trying to solve this for over 1.5 hours, we are still getting the same and tried almost everything we could.



Could anyone help us do that?



This is error what we're getting:



PHP Parse error: syntax error, unexpected '}', expecting ',' or ';' in



And this is the code (line) it's happening on:



if(!isset($_POST['name'])) {echo"Please fill in a valid username"} else {$ok="$ok+1"}



It's PHP.



If anyone wants the full code here it is:



$ok=0;
if(isset($_POST['submit'])) {

if(!isset($_POST['name'])) {echo"Please fill in a valid username"} else {$ok="$ok+1"}
if(!isset($_POST['pass'])) {echo"Please fill in a valid password"} else {$ok="$ok+1"}

if($ok==2){
switch($_POST['name'],$_POST['pass']){
case "FORAEROND","FORAEROND2":


THIS IS THE TEXT THAT WILL SHOW IF USERNAME IS 'FORAEROND' AND PASSWROD IS 'FORAEROND2'



break;



/*case "FORAEROND5","FORAEROND6"; KEEP FOR LATER

THIS IS THE TEXT THAT WILL SHOW IF USERNAME IS 'FORAEROND5' AND PASSWROD IS 'FORAEROND6'



break;
*/

}
}
}


Thanks to everyone who will help. :)



EDIT:




We apologize to everyone, it was really stupid, somehow we deleted or forgot ';' behind the codes, this is really stupid and awkward.


Answer



You missed ;. Each statement must ends up with a semicolon in PHP.


If statement structure in PHP




I keep getting an error with the following bit of code. It is probably some small thing but I don't see what is wrong.




while($row = mysql_fetch_array($result))
{
$varp = $row['ustk_retail'];
if ($varp<80000) { $o1 = 1; }
if (($varp=>80000) && ($varp<100000)) { $o2 = "1"; }
if (($varp=>100000) && ($varp<120000)) { $o3 = "1"; }
if (($varp=>120000) && ($varp<140000)) { $o4 = "1"; }

if (($varp=>140000) && ($varp<160000)) { $o5 = "1"; }
if (($varp=>160000) && ($varp<180000)) { $o6 = "1"; }
if (($varp=>180000) && ($varp<200000)) { $o7 = "1"; }
if (($varp=>200000) && ($varp<220000)) { $o8 = "1"; }
if (($varp=>220000) && ($varp<240000)) { $o9 = "1"; }
if (($varp=>240000) && ($varp<260000)) { $o10 = "1"; }
if (($varp=>260000) && ($varp<280000)) { $o11 = "1"; }
if (($varp=>280000) && ($varp<300000)) { $o12 = "1"; }
if ($varp>=300000) { $o13 = "1"; }
}


Answer



Greater than or equal to is >= sign, not =>



Update:
You are right. It's small but hard to find mistake.
It took me to split whole line into pieces to see where the problem is:



if 
(
$varp

=>
80000
)


So, it says parse error on line 5 and I had to doublecheck this operator.
Of course, at first I separated the problem line from the rest of the code to be certain.


c# - How to enumerate an enum



How can you enumerate an enum in C#?



E.g. the following code does not compile:



public enum Suit
{
Spades,

Hearts,
Clubs,
Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);

}
}


And it gives the following compile-time error:




'Suit' is a 'type' but is used like a 'variable'





It fails on the Suit keyword, the second one.


Answer



foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}


Note: The cast to (Suit[]) is not strictly necessary, but it does make the code 0.5 ns faster.


java - Object by Reference vs. Reference by Value



I read this comment here: Passing a String by Reference in Java?




Yes, it's a misconception. It's a huge, widespread misconception. It
leads to an interview question I hate: ("how does Java pass
arguments"). I hate it because roughly half of the interviewers
actually seem to want the wrong answer ("primitives by value, objects

by reference"). The right answer takes longer to give, and seems to
confuse some of them. And they won't be convinced: I swear I flunked a
tech screen because the CSMajor-type screener had heard the
misconception in college and believed it as gospel. Feh. – CPerkins
Aug 13 '09 at 14:34




Can someone please explain, in terms that a new programmer can grasp, what is the difference between saying:



"In Java primitives are passed by value and objects are passed by reference."




and:



"In Java nothing is passed by reference and references are passed by value."?



Are both of these statements true in some sense? I don't want to invite a rant parade, but this sounds like a really important concept, and one I still do not completely understand.


Answer



I believe the misconception lies in the fact that a variable can not contain an object to begin with. If you grasp that, then obviously variables can only contain references to objects (or primitive values). The step from there to realizing that references are passed by value (just as primitive values) is quite small.



There is a really easy test you can do to figure out if a language supports pass by reference. Ask yourself if you can write a swap function in the language, i.e. something that works like




x == A, y == B

swap(x, y);

x == B, y == A


As a Java programmer you realize quickly that you can't implement this in Java, thus you (correctly) draw the conclusion that Java does not have pass by reference.




Returning to your sentences:




  • In Java primitives are passed by value and objects are passed by reference.



This is false. I would argue that you can only pass something that is contained in a variable, and as I stated above, a variable can't contain an object, thus you can't pass an object at all in Java.




  • In Java nothing is passed by reference and references are passed by value.




This is true.


Generic C# method taking where the enum value as a parameter


Possible Duplicate:
Create Generic method constraining T to an Enum







Given a generic method that only operates on enum values



static void  method(T enum) where T ?????
{
// do something with enum...
}



How do I constrain T such that only enum values are accepted? I've tried using struct however this disallows the use calling my method with a nullable enum type.

php - Bing Ads API V12- Parse error: syntax error, unexpected '.', expecting ',' or ';'

I am using Bing Ads API V12 for php to do some Ads service related operations. The script I am using to get bing ads cost on daily basis with scheduler. Everything works fine when I try it with php v7.0 but If I try it with php v5.6.30 it is causing parse error on line 53 of AuthHelper.php



Parse error: syntax error, unexpected '.', expecting ',' or ';' on line 53


The main library block on line 53 AuthHelper.php is like this on the final class with other const



const CampaignTypes = 
CampaignType::Audience . ' ' .
CampaignType::Search . ' ' .
CampaignType::Shopping . ' ' .
CampaignType::DynamicSearchAds;


Full ref. of AuthHelper class



https://github.com/BingAds/BingAds-PHP-SDK/blob/master/samples/V12/AuthHelper.php



Possible duplicate:
Parse error: syntax error, unexpected '.', expecting ',' or ';'



So my question is how could I fix it now?
Should I wrap it with constructor ? Or anything else quick fix?

html - Use jQuery to hide a DIV when the user clicks outside of it



I am using this code:



$('body').click(function() {

$('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
event.stopPropagation();
});


And this HTML:







The problem is that I have links inside the DIV and when they no longer work when clicked.


Answer



Had the same problem, came up with this easy solution. It's even working recursive:




$(document).mouseup(function(e) 
{
var container = $("YOUR CONTAINER SELECTOR");

// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});


javascript - React state defind as property deep clone returns 'is undefined'

Answer


Answer





I'm trying to write a simple ToDo app.



Clicking on TodoItem should remove a item from state but when I do this I'm getting a TypeError: this.state is undefined. I don't know what is wrong.



My code looks like this:



---- App.js ----



import React from "react";

import TodoItem from "./components/TodoItem";

class App extends React.Component {
state = {
items: {
item1: { text: "Nazwa item1", isDone: false },
item2: { text: "Nazwa item2", isDone: false },
item3: { text: "Nazwa item3", isDone: false },
item4: { text: "Nazwa item4", isDone: false }
}

};

removeItem(key) {
const items = { ...this.state.items }; // TypeError: this.state is undefined
console.log(items);
}

render() {
return (



    {Object.keys(this.state.items).map(key => (
    removeItem={this.removeItem}
    index={key}
    key={key}
    item={this.state.items[key]}
    />
    ))}



);
}
}

export default App;


---- TodoItem.js ----




import React from "react";

const TodoItem = props => {
return (
  • props.removeItem(props.index)}>
    {props.item.text}
    {props.item.isDone ? "zrobione" : "niezrobione"}

  • );
    };


    export default TodoItem;

    Answer



    The issue is that this is bound to your function and not to the class.



    To prevent that you can use an arrow function to keep the binding of this to the class, or calling .bind method



    That should make it work:




     removeItem = (key) => {
    const items = { ...this.state.items };
    console.log(items);
    }


    or that:



    removeItem={this.removeItem.bind(this)}



    Here is a more in-depth article


    java - Convert ISO 8601 Date to a Standard String Format

    I am trying to convert a valid ISO 8601 string to a consistent format so that sort and search using simple lexicographical order is possible.




    My application could receive a date/time in any of the following formats, for example:



    2015-02-05T02:05:17.000+00:00
    2015-02-05T02:05:17+00:00
    2015-02-05T02:05:17Z


    These all represent the same date/time and I would like to convert them all to a canonical form for storage, say:



    2015-02-05T02:05:17.000Z



    My first thought was to just parse them using a technique from Converting ISO 8601-compliant String to java.util.Date, and then convert back to the desired string, but this breaks down when dealing with less precise date/times, for example:



    2015-02-05T02:05:17Z
    2015-02-05T02:05Z
    2015-02-05Z
    2015-02Z
    2015Z



    The imprecision of these times should be preserved. They should not be converted to:



    2015-02-05T00:00:00.000Z


    I've looked Java 8 and Joda-Time, but they seem to want to treat everything as specific points in time, and can't model the imprecise nature or partial dates/times.



    UPDATE:




    Using Java 8, I can do:



    OffsetDateTime dateTime = OffsetDateTime.parse("2015-02-05T02:05:17+00:00");
    System.out.println(dateTime.toString());


    which gives me:



    2015-02-05T02:05:17Z



    which is what I want, but:



    OffsetDateTime dateTime = OffsetDateTime.parse("2015-02-05T02:05:17.000+00:00");
    System.out.println(dateTime.toString());


    also gives me:



    2015-02-05T02:05:17Z



    Notice that java has thrown away the millisecond precision. Specifying 000 is treated the same as not specifying anything, which doesn't seem quite right.

    javascript - How to iterate through a json object?











    I want to iterate through a json object which is two dimensional ...
    for a one dimensional json object I do this



    for (key in data) {
    alert(data[key]);

    }


    what do i do about a two dimensional one??


    Answer



    There is no two dimensional data in Javascript, so what you have is nested objects, or a jagged array (array of arrays), or a combination (object with array properties, or array of objects). Just loop through the sub-items:



    for (var key in data) {
    var item = data[key];
    for (var key2 in item) {

    alert(item[key2]);
    }
    }

    Python 3: How is the look up in a range object faster than a look up in a list?

    I was scrolling through a lot of list vs. range related questions on StackOverflow when I came across in one of the answers that look up in a range object is a CONSTANT TIME operation! It doesn't make sense how this can be done in O(1), you're going to have to iterate through the range to see if a number exists. Does the range object work like some hashmap/dictionary?



    def usingRange(x):
    return x in range(0, 100000000)
    print(usingRange(9999999))



    def noRange(x):
    return x in list(range(0, 100000000))
    print(noRange(9999999))

    %timeit usingRange(9999999)
    %timeit noRange(9999999)


    I got the outputs as:




    True
    True
    443 ns ± 8.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    6.89 s ± 380 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


    The reason why I want to know why its constant time is because





    1. I was told not to focus so much on learning "tricks" in Python for Programming Interviews! Because everything you do, you will have TO explain the time complexity, so you either memorize that i in list1 is O(N) or you iterate using a for loop over the list:



      for j in range(len(list1)):
      if list1[j] == i:
      print(True)

      else:
      print(False)




    and then come to the conclusion that it is, in fact, O(N) because to check if an element existed you go have to iterate over each element of the list till the end of the list (worst case). But some constant time operations seem less obvious! I can live with the fact that a loop in a hash table is O(1) because there is a big concept called Hashing (not gone over it yet), but not sure how it works for range objects.




    1. I was told that it is paramount to know the basics! And do your best to explain every line of what you're writing and why you're writing it in whiteboards. Someone I know was literally ASKED to implement a HASHMAP for an SWE position at a tech VERY FAMOUS company.


    2. I have a LOT of time (1 year) to prepare and be inquisitive about stuff.


    php base64 encode appears unexpected character

    I have a xml string in php look like this.



    ......


    And I convert it to base64 form by




    base64_encode()


    However, the client say after decoding he found my xml looks like



    .......


    so return a error code to me.




    I have already try use iconv to convert my xml str from utf-16 to utf-8, set notepad++'s encoding to utf-8 without bom.
    but it's cant help.
    Cant ask the client to change his code.

    sql server - What do Clustered and Non clustered index actually mean?



    I have a limited exposure to DB and have only used DB as an application programmer. I want to know about Clustered and Non clustered indexes.
    I googled and what I found was :




    A clustered index is a special type of index that reorders the way
    records in the table are physically
    stored. Therefore table can have only
    one clustered index. The leaf nodes
    of a clustered index contain the data
    pages. A nonclustered index is a
    special type of index in which the
    logical order of the index does not
    match the physical stored order of
    the rows on disk. The leaf node of a
    nonclustered index does not consist of
    the data pages. Instead, the leaf
    nodes contain index rows.




    What I found in SO was What are the differences between a clustered and a non-clustered index?.



    Can someone explain this in plain English?


    Answer



    With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.



    With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.



    It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.



    Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.


    Monday, 27 February 2017

    coding style - Is it stylistically ok in Python to use l = list() rather than l = []?

    My question is pretty short, is it bad python "style" to use l = list() rather than l = []? Or, similarly, d = dict() instead of d = {}?




    Personally I find it more readable to write list(), dict(), set() etc. but I will avoid it if it is generally considered a "bad" way to write python code.

    .net - ASP.NET Web Site or ASP.NET Web Application?



    When I start a new ASP.NET project in Visual Studio, I can create an ASP.NET Web Application or I can create an ASP.NET Web Site.



    What is the difference between ASP.NET Web Application and ASP.NET Web Site? Why would I choose one over other?



    Is the answer different based on which version of Visual Studio I am using?


    Answer



    Website:



    The Web Site project is compiled on the fly. You end up with a lot more DLL files, which can be a pain. It also gives problems when you have pages or controls in one directory that need to reference pages and controls in another directory since the other directory may not be compiled into the code yet. Another problem can be in publishing.



    If Visual Studio isn't told to re-use the same names constantly, it will come up with new names for the DLL files generated by pages all the time. That can lead to having several close copies of DLL files containing the same class name,
    which will generate plenty of errors. The Web Site project was introduced with Visual Studio 2005, but it has turned out not to be extremely popular.



    Web Application:



    The Web Application Project was created as an add-in and now exists as part
    of SP 1 for Visual Studio 2005. The main differences are the Web Application Project
    was designed to work similar to the Web projects that shipped with Visual Studio 2003. It will compile the application into a single DLL file at build
    time. In order to update the project, it must be recompiled and the DLL file
    published for changes to occur.



    Another nice feature of the Web Application
    project is it's much easier to exclude files from the project view. In the
    Web Site project, each file that you exclude is renamed with an excluded
    keyword in the filename. In the Web Application Project, the project just
    keeps track of which files to include/exclude from the project view without
    renaming them, making things much tidier.



    Reference



    The article ASP.NET 2.0 - Web Site vs Web Application project also gives reasons on why to use one and not the other. Here is an excerpt of it:





    • You need to migrate large Visual Studio .NET 2003 applications to VS
      2005? use the Web Application project.

    • You want to open and edit any directory as a Web project without
      creating a project file? use Web Site
      project.

    • You need to add pre-build and post-build steps during compilation?
      use Web Application project.

    • You need to build a Web application using multiple Web
      projects? use Web Application project.

    • You want to generate one assembly for each page? use Web Site project.

    • You prefer dynamic compilation and working on pages without building
      entire site on each page view? use Web
      Site project.

    • You prefer single-page code model to code-behind model? use Web Site
      project.




    Web Application Projects versus Web Site Projects (MSDN) explains the differences between the web site and web application projects. Also, it discusses the configuration to be made in Visual Studio.


    c++ - Error LNK2019: external symbol

    I'm verry new at elastix and stuck at the verry beginning. I'm trying to compile a verry basic program in C++ that will make an instantiation of the using elastix library. When I tried to compile the program, I got a linker error:




    Error LNK2019: external symbol "public: virtual __cdecl elastix
    ELASTIX :: :: ~ ELASTIX (void)" (?? 1ELASTIX @ elastix FALU@@@XZ)

    unresolved referred to in the "public function: virtual void * __cdecl
    elastix eLASTIX :: :: `scalar deleting destructor '(unsigned int)" (??
    _ @ elastix GELASTIX UEAAPEAXI@@@Z)




    I' ve done some googeling and found that it is infact a popular linker problem: see this topic and this one and this particular elastix mail chain. I tried to fix it using these links but without succes. I'm wondering if you guys/girls could help me out. below you can find my source files (CMakeList.txt and C++ code) and some additional information: I run windows 7, Cmake version is 3.0.2, ITK version is 4.6, elastix version is 4.7 and Microsoft VS 2008. Thanks in advance



    CmakeList.txt
    # Example project for using elastix code from external projects.
    PROJECT( elxExternalProject )




    CMAKE_MINIMUM_REQUIRED( VERSION 2.8 )

    # Find TIK
    FIND_PACKAGE( ITK REQUIRED )
    INCLUDE( ${ITK_USE_FILE} )

    # find elastix
    SET( ELASTIX_BINARY_DIR "" CACHE PATH "Path to elastix binary folder" )
    SET( ELASTIX_USE_FILE ${ELASTIX_BINARY_DIR}/UseElastix.cmake )

    IF( EXISTS ${ELASTIX_USE_FILE} )
    MESSAGE( STATUS "Including Elastix settings." )
    INCLUDE( ${ELASTIX_USE_FILE} )
    ENDIF()

    # Build a small test executable (this test is basically the same as
    # the one found in the /src/Testing dir.
    ADD_EXECUTABLE( elxtimertest itkTimerTest.cxx )

    # Link to some libraries

    TARGET_LINK_LIBRARIES( elxtimertest
    ITKCommon elxCommon elastix )


    C++ code



    #include "elastixlib.h"
    using namespace elastix;

    int main( int argc, char *argv[] )

    {

    ELASTIX* el = new ELASTIX();
    std::cerr << "elastix created" << std::endl;

    delete el;
    return 0;
    }

    c - Where can I put an array subscript?











    This question
    asks why




    a[5] == 5[a]


    It is answered in all aspects except one...



    Why is one allowed to put an array subscript after an integer in the first place? And why isn't one allowed to write something like



    [a]5



    or



    [5]a


    or put [] in some other odd place?



    In other words, what is the definition of where an array index operator is allowed?




    EDIT I: The answers I received that quote the the standard were a little hard to grasp at first. But with the help of the responders I now understand. An array subscript (a square bracket) is allowed after a pointer or an integer. If it follows a pointer, what's inside the brackets must be an integer. If it follows an integer, what's inside the brackets must be a pointer.



    I'm accepting the less upvoted answer because he did a bit more hand-holding in getting me to understand the quote from the standard. But the answer that strictly quotes the standard is correct too. It was just harder to understand at first.



    EDIT II: I do not think my question was a duplicate. My question was about the allowed grammar regarding the array subscript operator. It was answered by quotes from the standard that never appear in the question I supposedly duplicated. It is similar, yes, but not a duplicate.


    Answer



    Postfix expression grammar from the C11 standard:



    postfix-expression:
    primary-expression

    postfix-expression [ expression ]
    postfix-expression ( argument-expression-listopt )
    postfix-expression . identifier
    postfix-expression -> identifier
    postfix-expression ++
    postfix-expression --
    ( type-name ) { initializer-list }
    ( type-name ) { initializer-list , }



    Primary expression grammar from the C11 standard:



    primary-expression:
    identifier
    constant
    string-literal
    ( expression )
    generic-selection



    And so on. 5 is an integer constant, so 5[a] match this:



    postfix-expression [ expression ]


    Hope this is what you mean.



    EDIT: I forgot to mention this, but other comments already did:



    One of the expressions shall have type ‘‘pointer to complete object type’’, the other

    expression shall have integer type, and the result has type ‘‘type’’.



    That 'integer type' it's needed to forbid non-sense floating-point constants subscripting.


    html - From where can I get a right pointing arrow character?



    Does anyone know from where I can get this http://screencast.com/t/Od362Z8Glgu character, I mean the arrow, I need one just like that to copy & paste in my html file.



    Answer



    It is a unicode character: ▶ =



    http://www.fileformat.info/info/unicode/char/25b6/index.htm



    See: What characters can be used for up/down triangle (arrow without stem) for display in HTML?


    ruby - How do I remove blank elements from an array?




    I have the following array



    cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]


    I want to remove blank elements from the array and want the following result:



    cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]



    Is there any method like compact that will do it without loops?


    Answer



    There are many ways to do this, one is reject



    noEmptyCities = cities.reject { |c| c.empty? }


    You can also use reject!, which will modify cities in place. It will either return cities as its return value if it rejected something, or nil if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).


    php - Cannot modify header information - headers already sent easy solution





    Hey guys I just wanted to share this solution that I found for the error: Cannot modify header information - headers already sent.



    Let's say one starts out with a code that contains headers like this:




    header('Content-disposition: attachment; filename="video"');
    header('Content-type: video/mp4');
    $video = $_POST['$video'] ;
    readfile("$video");
    ?>


    For some reason PHP doesn't like this. To see how to fix this view answer below.


    Answer



    To fix this type of error you can add before the in your code and add at the end of your code after ?>

    Like this:




    header('Content-disposition: attachment; filename="video"');
    header('Content-type: video/mp4');
    $video = $_POST['$video'] ;
    readfile("$video");
    ?>




    Hope this helps. This was a simple solution that I found and it works well for me and some others I know of.


    javascript - How can I know which radio button is selected via jQuery?



    I have two radio buttons and want to post the value of the selected one.
    How can I get the value with jQuery?




    I can get all of them like this:



    $("form :radio")


    How do I know which one is selected?


    Answer



    To get the value of the selected radioName item of a form with id myForm:




    $('input[name=radioName]:checked', '#myForm').val()


    Here's an example:





    $('#myForm input').on('change', function() {
    alert($('input[name=radioName]:checked', '#myForm').val());
    });




    1
    2
    3




    python - Purpose of 'if __name__ == "__main__":'




    I am trying to understand some code I found which reads command line arguments (attached below). My concern is what purpose of the "if __name__ == __main__"line is...



    Why would I use that line instead of just using the code below, main(sys.argv[1:]). What extra use does it provide?




    import sys, getopt

    def main(argv):
    inputfile = ''
    outputfile = ''
    try:
    opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
    print 'test.py -i -o '

    sys.exit(2)
    for opt, arg in opts:
    if opt == '-h':
    print 'test.py -i -o '
    sys.exit()
    elif opt in ("-i", "--ifile"):
    inputfile = arg
    elif opt in ("-o", "--ofile"):
    outputfile = arg
    print 'Input file is "', inputfile

    print 'Output file is "', outputfile

    if __name__ == "__main__":
    main(sys.argv[1:])

    Answer



    Well, imagine that someone else wants to use the functions in your module in their own program. They import your module... and it starts doing its own thing!



    With the if __name__ == "__main__", this doesn't happen. Your module only "does its thing" if it's run as the main module. Otherwise it behaves like a library. It encourages code reuse by making it easier.




    (As @Sheng mentions, you may want to import the module into another script yourself for testing purposes.)


    c++ - calling template class constructor

    I'm getting hard time figuring out solution for calling constructor of class which uses templates.



    --Header file



    template 
    class Binary_tree
    {
    string file_name;

    list arr_data;
    public:

    Binary_tree(string fname);
    void printArr();
    };


    --cpp file



    template 

    Binary_tree::Binary_tree(string fname)
    {

    File_Name = fname;
    total = 0;
    root = nullptr;

    std::ifstream filestream(fname);
    string line;

    while (!filestream.eof())
    {
    filestream >> line;

    arr_data.push_back(line);
    }
    }

    template

    void Binary_tree::printArr()
    {
    int size = arr_data.size();

    for (int i = 0; i < size; i++)

    {
    cout << "arr_data [" << i << "] is: " << arr_data[i] << endl;
    }
    }


    --main.cpp



    int main(int argc, char** argv)
    {

    Binary_tree test(file);
    test.printArr();

    return 0;
    }


    Right now I'm getting LNK1120 and LNK2019 errors.

    plot - ploting 3d graph in matlab?



    I am currently a begineer, and i am using matlab to do a data analysis. I have a a text file with data at the first row is formatted as follow:
    time;wave height 1;wave height 2;.......
    I have column until wave height 19 and rows total 4000 rows.



    Data in the first column is time in second. From 2nd column onwards, it is wave height elevation which is in meter. At the moment I like to ask matlab to plot a 3d graph with time on the x axis, wave elevation on the y axis, and wave elevation that correspond to wave height number from 1 to 19, i.e. data in column 2 row 10 has a let say 8m which is correspond to wave height 1 and time at the column 1 row 10.




    I have try the following:



    clear;    
    filename='abc.daf';
    path='C:\D';

    a=dlmread([path '\' filename],' ', 2, 1);

    [nrows,ncols]=size(a);


    t=a(1:nrows,1);%define t from text file

    for i=(1:20),
    j=(2:21);
    end

    wi=a(:,j);

    for k=(2:4000),

    l=k;
    end

    r=a(l,:);


    But everytime i use try to plot them, the for loop wi works fine, but for r=a(l,:);, the plot only either give me the last time data only but i want all data in the file to be plot.



    Is there a way i can do that. I am sorry as it is a bit confusing but i will be very thankful if anyone can help me out.




    Thank you!!!!!!!!!!


    Answer



    Once you load your data as you do in your code above your variable a should be a 4000-by-20 array. You could then create a 3-D plot in a couple of different ways. You could create a 3-D line plot using the function PLOT3, plotting one line for each column of wave elevation data:



    t = a(:,1);   %# Your time vector
    for i = 2:20 %# Loop over remaining columns
    plot3(t,(i-1).*ones(4000,1),a(:,i)); %# Plot one column
    hold on; %# Continue plotting to the same axes
    end
    xlabel('Time'); %# Time on the x-axis

    ylabel('Wave number'); %# Wave number (1-19) on y-axis
    zlabel('Wave elevation'); %# Elevation on z-axis


    Another way to plot your data in 3-D is to make a mesh or surface plot, using the functions MESH or SURF, respectively. Here's an example:



    h = surf(a(:,1),1:19,a(:,2:20)');  %'# Plot a colored surface
    set(h,'EdgeColor','none'); %# Turn off edge coloring (easier to see surface)
    xlabel('Time'); %# Time on the x-axis
    ylabel('Wave number'); %# Wave number (1-19) on y-axis

    zlabel('Wave elevation'); %# Elevation on z-axis

    Sunday, 26 February 2017

    Why does the C preprocessor interpret the word "linux" as the constant "1"?



    Why does the C preprocessor in GCC interpret the word linux (small letters) as the constant 1?




    test.c:



    #include 
    int main(void)
    {
    int linux = 5;
    return 0;
    }



    Result of $ gcc -E test.c (stop after the preprocessing stage):



    ....
    int main(void)
    {
    int 1 = 5;
    return 0;
    }



    Which -of course- yields an error.



    (BTW: There is no #define linux in the stdio.h file.)


    Answer



    In the Old Days (pre-ANSI), predefining symbols such as unix and vax was a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&R), and C code of any complexity was typically a complex maze of #ifdefs to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names like unix and assumed that programmers would simply avoid using those names for their own purposes.



    The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.



    As a result, any compiler that predefines unix or linux is non-conforming, since it will fail to compile perfectly legal code that uses something like int linux = 5;.




    As it happens, gcc is non-conforming by default -- but it can be made to conform (reasonably well) with the right command-line options:



    gcc -std=c90 -pedantic ... # or -std=c89 or -ansi
    gcc -std=c99 -pedantic
    gcc -std=c11 -pedantic


    See the gcc manual for more details.




    gcc will be phasing out these definitions in future releases, so you shouldn't write code that depends on them. If your program needs to know whether it's being compiled for a Linux target or not it can check whether __linux__ is defined (assuming you're using gcc or a compiler that's compatible with it). See the GNU C preprocessor manual for more information.



    A largely irrelevant aside: the "Best One Liner" winner of the 1987 International Obfuscated C Code Contest, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined unix macro:



    main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}


    It prints "unix", but for reasons that have absolutely nothing to do with the spelling of the macro name.


    javascript - Sort array of objects by string property value



    I have an array of JavaScript objects:




    var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf' },
    { first_nom: 'Pig', last_nom: 'Bodine' },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
    ];


    How can I sort them by the value of last_nom in JavaScript?




    I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?


    Answer



    It's easy enough to write your own comparison function:



    function compare( a, b ) {
    if ( a.last_nom < b.last_nom ){
    return -1;
    }
    if ( a.last_nom > b.last_nom ){
    return 1;

    }
    return 0;
    }

    objs.sort( compare );


    Or inline (c/o Marco Demaio):



    objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0)); 


    php - How to protect $_POST and params from hackers

    I'm using this with html2canvas.js to generate and save images from HTML.




    I use url params to make this work - eg: website.com/?price=10&name=xxx



    All ok untill here - the script works fine - images are saved in /cart/ dir



    $image = $_POST['image'];
    $username = $_POST['username'];
    $front_class = $_POST['front_plass'];
    $decoded = base64_decode(str_replace('data:image/png;base64,', '', $image));
    $date = date('d-M-Y-h-i-a', time());

    $curdir = getcwd();
    $cartDir = $curdir ."/cart";
    $userDir = $cartDir.'/'.$username;
    if (!file_exists($userDir)) {
    mkdir($cartDir.'/'.$username, 0777);
    }
    $name = $front_class."-front-".$date.".png";
    $full_path = $userDir.'/'.$name;
    $name1 = 'cart/'.$username.'/'.$name;
    function ImageFillAlpha($image, $color) {

    imagefilledrectangle($image, 0, 0, imagesx($image), imagesy($image), $color);
    }
    function imageCreateCorners($sourceImageFile, $name, $radius) {
    ...
    }
    file_put_contents($full_path, $decoded);
    imageCreateCorners($full_path, $name, 25);
    echo 'front';
    ?>



    And the js



     html2canvas($('#front'), {
    "logging": true,
    //"proxy":"html2canvasproxy.php",
    "onrendered": function(canvas){
    var dataURL = canvas.toDataURL("image/png");
    $.post('image_front.php',{
    image: dataURL,

    username: username,
    front_class: frontClass
    },function(data){
    $('.imageHolder_front').html(data);
    });
    }
    });


    The problem is that someone hacked me twice yesterday thought this and I need to protect the $_POST or the params can be the problem?




    Any help here please? I'm not really good with backend development - more with frontend.



    Thanks.

    reactjs - Cannot read property 'setState' of undefined, when running a function



    class App extends Component {
    constructor(){
    super();
    this.state = {
    sideNav: '',
    language: 'en'

    }
    }

    langEn() {
    this.setState({language: 'en'}).bind(this);
    console.log("Language changed to en");
    }

    langEs() {
    this.setState({language: 'es'}).bind(this);

    console.log("Language changed to es");
    }

    render() {

    const mouseEnter = e => {
    this.setState({sideNav: "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL"});
    }

    const mouseLeave = e => {

    this.setState({sideNav: "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv"});
    }


    return (


    onMouseEnter={mouseEnter}
    onMouseLeave={mouseLeave}

    className={this.state.sideNav}
    onSelect={(selected) => {
    // Add your code here
    }}
    >







    Dashboard







    Sites








    Tours








    Media








    Add new Site








    Language







    Profile












    );
    }
    }

    export default App;


    The error happens when I press one of the two buttons to run the lanEn or lanEs functions. I have tried alternating where they are, placing them in or out of the render() method, removing this using bind. The end goal is change the language state using these buttons and transfer it to different pages using props


    Answer



    You just need to add this piece of code in the constructor:




    this.langEn = this.langEn.bind(this);


    What the above code does is, it replaces the existing langEn function with a new function with the this context changed to class App.



    If you don't want to manually bind it in the constructor, you can go with arrow functions, which has lexical binding.


    html - Can I make browsers choose UTF-8 for viewing source code?





    I put up some source code files for viewing on the web. The problem is, browsers tend to not understand that these files are in UTF-8, and I wonder if there's anything I can do about that. (I'm sure some browsers use UTF-8 per default, but Safari at least doesn't. I have to go into the View menu and choose the encoding manually to make it look right.)



    My set of webpages is here, with several Python files and one C file: fgcode.avadeaux.net. I tried putting a charset="UTF-8" attribute in the a elements in the , but that doesn't seem to help. The Python files declare the charset in a comment on the top line, but the browser ignores that as well (which is no surprise, it's not a Python source code browser after all).



    I don't have much control over the web server, it's run by my ISP and I just put the files there. But I'd still be interested to know if this problem has a web server configuration solution.



    Solution: solved, as per links provided, by adding an .htaccess file with the following content:



    AddDefaultCharset UTF-8
    AddCharset UTF-8 .py

    AddCharset UTF-8 .c


    Only the first line wasn't enough in my case.


    Answer



    If you are allowed to place a .htaccess file in your content directory, you might be able to specify a charset there.



    YMMV depending on which server software they run, and how permissive the config is.



    See:




    How to change the default encoding to UTF-8 for Apache?



    htaccess UTF-8 encoding for .html, .css, .js - Whats the best way?


    c# - Object reference not set to an instance of an object, generating win forms control via code

    I'm making a simple space invaders type game for my class and I'm trying to generate everything through my code. I have 3 methods causing me a problem




    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.KeyCode == Keys.Space)
    GenerateBullet();
    }
    private void GenerateBullet()
    {
    playerBullet = new PictureBox()
    {
    Parent = backBoard,

    Size = new Size(4, 12),
    Visible = true,
    Enabled = true,
    Image = Properties.Resources.Untitled,
    SizeMode = PictureBoxSizeMode.StretchImage
    };
    }
    private void BulletMovement(object sender, EventArgs e)
    {
    if (playerBullet.Enabled == true)

    {
    playerBullet.Top += 4;
    }
    }


    The 3rd method that checks the enabled and moves based on that is what is throwing the error 'Object reference not set to an instance of an object.' . Is there a way to fix this without actually generating the picture through the toolbox/form design.



    The BulletMovement is called by a timer tick sorry that I didn’t make that clear

    Websocket with python Bottle + uwsgi | env vars

    I actually try to set up a bottle python application based on uwsgi. I need uwsgi for websocket support.




    My really basic code looks like that:
    (webserver.py)



    from bottle import route, run, static_file, error, template
    import uwsgi
    import bottle
    from bottle import route, template

    app = application = bottle.default_app()


    @route('/')
    def index():
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env('HTTP_ORIGIN', ''))
    while True:
    msg = uwsgi.websocket_recv()
    uwsgi.websocket_send(msg)
    return template('inputs', name='inputs')

    @route('/static/')
    def server_static(filepath):

    return static_file(filepath, root='./static/')


    I just start this file by:



    uwsgi --http-socket :80 --http-websockets --wsgi-file webserver.py


    My error message looks like that:




    ...
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env('HTTP_ORIGIN', ''))
    NameError: global name 'env' is not defined
    ...


    The websocket handshakes needs the env vars but I got no idea what it is and how to implement them to my code.



    EDIT: I already tried to import env by




    from uwsgi import env 


    but it doesn't solve the proble.

    android - What is the purpose of Looper and how to use it?




    I am new to Android. I want to know what the Looper class does and also how to use it. I have read the Android Looper class documentation but I am unable to completely understand it.
    I have seen it in a lot of places but unable to understand its purpose. Can anyone help me by defining the purpose of Looper and also by giving a simple example if possible?


    Answer



    What is Looper?



    Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).



    Where we can use Looper class?




    If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread.
    For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.



    How it works?



    There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.



    Here is the code by which you can prepare the Looper.



    class LooperThread extends Thread {

    public Handler mHandler;

    @Override
    public void run() {
    Looper.prepare();

    mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    // process incoming messages here

    }
    };

    Looper.loop();
    }
    }

    c# - How to pass a single quote ( ' ) from user input to a stored procedure, avoiding SQL injection

    Although replacing single quote with double quote before calling stored procedure should also work, something like this will also work:



    @parameter = 'Test'' A''B''C' -- Test' A'B'C




    But if you don't want to go this way, you can also try with



    Use SET QUOTED_IDENTIFIER OFF


    just before hitting the query that will also work, but remember we need QUOTED_IDENTIFIER ON for many situations.

    r - Remove legend ggplot 2.2

    I'm trying to keep the legend of one layer (smooth) and remove the legend of the other (point). I have tried shutting off the legends with guides(colour = FALSE) and geom_point(aes(color = vs), show.legend = FALSE).



    Edit: As this question and its answers are popular, a reproducible example seems in order:



    library(ggplot2)
    ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
    geom_point(aes(color = vs)) +
    geom_point(aes(shape = factor(cyl))) +
    geom_line(aes(linetype = factor(gear))) +
    geom_smooth(aes(fill = factor(gear), color = gear)) +
    theme_bw()


    enter image description here

    php - Cannot modify header information - headers already sent by... WordPress Issue




    I'm encountering this error. and I have no idea dealing with this.





    Cannot modify header information - headers already sent by (output
    started at
    /home/ben213/public_html/wp-content/themes/Bendaggers/functions.php:9)
    in /home/ben213/public_html/wp-includes/pluggable.php on line 934




    my Functions.php file line # 9 is:







    while my pluggable.php # 934 is



    function wp_redirect($location, $status = 302) {
    global $is_IIS;

    $location = apply_filters('wp_redirect', $location, $status);
    $status = apply_filters('wp_redirect_status', $status, $location);

    if ( !$location ) // allows the wp_redirect filter to cancel a redirect

    return false;

    $location = wp_sanitize_redirect($location);

    if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
    status_header($status); // This causes problems on IIS and some FastCGI setups

    header("Location: $location", true, $status);}
    endif;



    I'm having a hard time figuring this out since im not a programmer. what seems to be wrong?
    kindly help me please...


    Answer



    Your theme is printing output (text) to the browser, but then for some reason WordPress is redirecting the user (with wp_redirect) away from that page before the whole page is rendered. You can't start printing output and then redirect, or you'll get the error you see. That's what Paul Grime was getting at in his comment.



    Ken White commented with a reference to a post with a similar problem. I've fixed this in my own experience by buffering the output of the script.



    In your theme's functions.php file (which gets included every time your theme's pages load), put the following:




    //allow redirection, even if my theme starts to send output to the browser
    add_action('init', 'do_output_buffer');
    function do_output_buffer() {
    ob_start();
    }


    Now, even if part of your theme starts to send input to the browser, PHP won't send that text until the page is fully loaded, which allows WordPress to redirect users, if necessary, as part of its own logic.


    php - Use case for output buffering as the correct solution to "headers already sent"




    I see (not just on this site) a lot of question from inexperienced PHP programmers about the infamous "headers already sent... output started at" error, and many people suggest using ouput buffering as a solution.



    In my experience I have never found a situation where that error wasn't caused by a flaw in the program's logic. Are there cases where output buffering is actually the correct solution?


    Answer



    I would concur with your initial statement. Generally, solving "headers" problem with output buffering is a stopgap measure.



    The really sad/funny part of this solution is: what happens when you want to output something large, such as a file you are keeping behind a paywall? Usually it results in people replacing the "headers" problem with their scripts running out of memory.



    Whoops.


    php - WP Mail SMTP connect() failed

    Using wordpress app WP Mail SMTP to send emails using yahoo. here is what i already know:





    1. I have configured yahoo to allow insecure apps.

    2. My host does not block yahoo's port 465

    3. using pingdom i get the error:



    Delivery over IPv4 to dnsadmin@uk42.siteground.eu could not be done.



    Failed to deliver email for SOA RNAME of pureenv.co.uk (dnsadmin.uk42.siteground.eu) using dnsadmin@uk42.siteground.eu.




    DNSCheck failed to deliver email to the email address listed as the one responsible for the zone.



    the error log is below, if someone has some suggestions to what could be causing the error.



    Versions:
    WordPress: 4.9.4
    WordPress MS: No
    PHP: 7.0.28
    WP Mail SMTP: 1.2.5




    Params:
    Mailer: smtp
    Constants: No
    ErrorInfo: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
    Host: smtp.maiil.yahoo.com
    Port: 465
    SMTPSecure: ssl
    SMTPAutoTLS: bool(true)
    SMTPAuth: bool(true)




    Server:
    OpenSSL: Yes
    SMTP Debug:
    2018-03-25 20:45:08 Connection: opening to ssl://smtp.maiil.yahoo.com:465, timeout=300, options=array ( ) 2018-03-25 20:45:09 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): php_network_getaddresses: getaddrinfo failed: Name or service not known 2018-03-25 20:45:09 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): unable to connect to ssl://smtp.maiil.yahoo.com:465 (php_network_getaddresses: getaddrinfo failed: Name or service not known) 2018-03-25 20:45:09 SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0) 2018-03-25 20:45:09 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

    data structures - Array versus linked-list



    Why would someone want to use a linked-list over an array?



    Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort.



    I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array?



    This question is not a duplicate of this question because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures.


    Answer




    • It's easier to store data of different sizes in a linked list. An array assumes every element is exactly the same size.

    • As you mentioned, it's easier for a linked list to grow organically. An array's size needs to be known ahead of time, or re-created when it needs to grow.

    • Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is more complicated and/or takes more memory.

    • As long as your iterations all happen in a "foreach" context, you don't lose any performance in iteration.


    oop - PHP Oddities: Bypass Class Visibility?



    Today I was working on an old diagnostic library I had written back in the halcyon 5.1 days. That library provided highly detailed dumps of any variable you could give it, using color coding to indicate types, and using Reflection to produce a lot of insight into objects (including, depending on what flags you pass, outputting relevant PHPDoc and even source code for objects - especially useful in backtraces).



    At the time I been able to bypass member visibility to output the value of protected and private members of a class. That proved to be quite useful from a debugging perspective, particularly with respect to detailed error logs we produce.



    To bypass visibility in 5.1, I used the Reflection API, which let you see the value of protected and private members with ReflectionMethod->getValue($object). This of course is a bit of a security bypass, but it's not too bad since if you're going to view and modify values this way, you're pretty clearly breaking the object's intended API.



    PHP 5.2 stopped Reflection from being able to access protected/private members and methods. Of course this was intentional, and considered that ability to be a security concern. I simply added a try/catch around this piece of my library, and output it if the language allowed it, and didn't if it doesn't. Java Reflection AFAICR always allowed you to bypass visibility (I believe they are of the opinion that if you want it badly enough, you'll get it one way or another, visibility is just an advertised API for an object, violate this at your own risk).




    As a thought exercise, and perhaps to bring my dump library up to date, I'm curious if anyone can think of clever ways to bypass visibility in modern versions of PHP (5.2+, but of particular interest to me is PHP 5.3).



    There are three avenues which seem particularly hopeful. First: mangling serialize/unserialize:



    Class Foo {
    protected $bar;
    private $baz;
    }
    class VisibleFoo {

    public $bar;
    public $baz;
    }

    $f = new Foo();
    $data = serialize($f);
    $visibleData = str_replace($data, 'O:3:"Foo":', 'O:10:"VisibleFoo":');
    $muahaha = unserialize($visibleData);



    Of course it's more involved than this, because protected members are flagged as such: null*nullProperty, and private members are bound against their original class name: nullOriginalClassnullProperty (see PHP Serialization), but theoretically you could clean those all up and trick serialize / unserialize into exposing these values for you.



    This has a few drawbacks: first, it is fragile with respect to language versions. PHP doesn't (AFAIK) make any guarantee that the data produced by serialize() will remain consistent from version to version (indeed, the way protected and private members are represented has changed since I've used PHP). Second, and more importantly, some objects declare a __sleep() method, which might have unintended side effects of 1) not giving you access to all the private members, and 2) maybe this will tear down database connections, close file streams, or other side effects of the object thinking it's going to sleep when it is in fact not.



    A second option is to try to parse out print_r() or other built-in debugging statements to scrape values. This has the consequence of being incredibly difficult to do well beyond simple values (my old library would let you drill down into members which are themselves objects, and so forth). Interestingly it's a variant of this approach that I used to detect infinite recursion ($a->b = &$a) using var_dump().



    A third option is to subclass the target and increase its visibility that way. This will get you access to protected members, but not to private members.



    I seem to recall a few years ago reading a post by someone who had figured out a way to bypass with lambda functions or something to that effect. I can't find it any longer, and having tried a variety of variations on this idea, I've come up empty.




    TLDR version: an anyone think of some magic hoops to jump through to dredge out protected and private members of a PHP object instance?


    Answer



    Fourth option:



    $reflectionProperty->setAccessible(true);


    can be used to make any property accessible using the getValue() method, even if it's protected or private. Test the visibility, then use setAccessible(true), getValue() and setAccessible(false) to reset.



    I think this is a lot cleaner that a serialize()/unserialise() to a new class that has all properties public.... and doesn't require you to have duplicate versions of all your classes



    Saturday, 25 February 2017

    php - Help with this error message > unexpected T_OBJECT_OPERATOR



    The code below is part of an rss feed parser using WordPress's simplepie fetch_feed()...



    Code is:



        if ($enclosure = $item->get_enclosure(0))
    {
    $image_thumb = $item->get_enclosure()->get_link().'screenshot.jpg';
    $image = $item->get_enclosure()->get_link().'screenshot-full.jpg';
    }
    $link = esc_url( strip_tags( $item->get_link() ) );
    $content = $item->get_content();


    Upon trying to activate the theme in which this code appears, I'm getting the following error:



    Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/.../functions.php on line 1341



    Line 1341 is the line that starts with $image_thumb


    Answer



    My wild guess is that this is PHP 4, which doesn't support method chaining.


    C++: Expression must have a constant value when declaring array inside function





    I have looked at all the other posts with a similar topic, and none help, so please don't flag as a duplicate.



    I am defining in main() a const int SIZE = 20;. Then, I pass this as an argument to my function, Mode:



    int* Mode(int* numbers, int & mode, const int SIZE)

    {
    int occurences[SIZE];

    // Calcualte mode
    }


    However, I get the error, expression must have a constant value.



    My function call (in main) looks like this:




    int* occurencesPtr = Mode(numbersPtr, mode, SIZE);


    With SIZE being defined at the beginning to the literal 20.



    I understand that the error is because the function's version of SIZE only acquires its value when the function is called (?), but I don't know how I could work around this.



    I have even tried passing to the function a const int * const SIZEPtr = &SIZE, but that didn't work either. Help?




    EDIT: I am not trying to use a variable size!! Notice that I have made SIZE a const everywhere! I just want to use that same SIZE constant to declare my array.



    EDIT: Dynamic arrays are not what I need. I just want a normal, named, array, defined with a constant size value passed to the function.


    Answer



    There is a misconception here with what const means, probably because it's a little confusing that this works:



    const int SIZE = 20;
    int array[SIZE];



    but this doesn't:



    void foo(const int SIZE) {
    int array[SIZE];
    // ...
    }

    const int SIZE = 20;
    foo(SIZE);



    The issue is that the array size in an array declaration must be a core constant expression. Simplified, that means an expression that's evaluatable at compile time to be a constant. That is true in the first case (you can see that SIZE is the integral constant 20) but that is not true in the second case. There, the SIZE function parameter is just const - in the sense that it is nonmodifiable - and not a core constant expression. You can see the difference in that I can call foo() with something that is clearly unknowable until runtime:



    int x;
    if (std::cin >> x) {
    foo(x);
    }


    In order to pass an argument into foo, and have that argument be used as an array bound, it is not enough to have it be const - the actual integral value must be encoded into the type (unless you call foo() as constexpr which I'm assuming is not the case here). In which case, you'd have to do something like:




    template 
    void foo() { ... }

    const int SIZE = 20;
    foo();


    or:




    template 
    void foo(std::integral_constant ) { ... }

    const int SIZE = 20;
    foo(std::integral_constant{} );


    or simply have SIZE be a global constant or otherwise accessible to foo() in a way that doesn't have to do with its arguments.







    Or, there's always the simple option: use std::vector:



    void foo(const int SIZE) {
    std::vector v(SIZE);
    ...
    }

    python - How to draw bounding box on best matches?

    How can I draw a bounding box on best matches in BF MATCHER using Python?

    Escaping single quote in PHP when inserting into MySQL





    I have a perplexing issue that I can't seem to comprehend...



    I have two SQL statements:




    • The first enters information from a form into the database.


    • The second takes data from the database entered above, sends an email, and then logs the details of the transaction



    The problem is that it appears that a single quote is triggering a MySQL error on the second entry only! The first instance works without issue, but the second instance triggers the mysql_error().



    Does the data from a form get handled differently from the data captured in a form?



    Query 1 - This works without issue (and without escaping the single quote)



    $result = mysql_query("INSERT INTO job_log

    (order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
    VALUES
    ('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");


    Query 2 - This fails when entering a name with a single quote (for example, O'Brien)



    $query = mysql_query("INSERT INTO message_log
    (order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status)
    VALUES

    ('$order_id', '".date('Y-m-d H:i:s', time())."', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,'$row->secondary_email', '$subject', '$message_content', '1')");

    Answer



    You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().



    http://us3.php.net/mysql-real-escape-string



    The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").



    Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().



    javascript - Advantages of script tag before closing body tag when using events

    These days it seems like people recommend placing the script tag just before the closing body tag as such..


            



    If you are running the script immediately, this is a good thing because most of your DOM has mostly loaded. However, what if you are using the onload or DOMContentLoaded events to call your main script? In this case, it seems that it would make no difference if placing your script tag in the document head, since your code will not execute anyways until the DOM loads.


    When using the onload or DOMContentLoaded events to run your script, is there really any advantage to putting your script tag above the closing body tag vs the head?


    On the other hand, if you don't want your script to execute until DOM has loaded, why not simply place your script tag before the closing body tag and run it immediately without any events whatsoever. Seems like this would save a few lines of code while providing the same functionality.

    css - Font monospace Android 2.3

    I have a problem with a mobile website on Android Gingerbread and versions prior to this. Fonts monospace do not exactly behave as monospaces should: different characters have different widths.



    This is how it looks on a Gingerbread default web browser (I also tested on Dolphin and Opera mini):



    Gingerbread screenshot




    This is how it looks on a ICS default web browser:



    ICS screenshot



    I used the Cultive Mono downloaded from the web.







    CSS:



    #my_id span{font:12px  'Cutive Mono', serif; line-height:1.6}


    I also tried the default monospace font from the OS:



    #my_id span{font:12px  monospace; line-height:1.6}



    Does anybody know how can this issue be solved? I really need a monospace working on my mobile website.



    Thanks in advance.



    edit



    This would be an example in jsfiddle: http://jsfiddle.net/HerrSerker/dE94s/9/

    arguments - Reference — What does this symbol mean in PHP?



    What is this?



    This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.




    Why is this?



    It used to be hard to find questions about operators and other syntax tokens.¹
    The main idea is to have links to existing questions on , so it's easier for us to reference them, not to copy over content from the PHP Manual.



    Note: Since January 2013, does support special characters. Just surround the search terms by quotes, e.g. [php] "==" vs "==="



    What should I do here?



    If you have been pointed here by someone because you have asked such a question, please find the particular syntax below. The linked pages to the PHP manual along with the linked questions will likely answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a substitute to the help others provided.




    The List



    If your particular token is not listed below, you might find it in the List of Parser Tokens.






    & Bitwise Operators or References









    =& References








    &= Bitwise Operators









    && Logical Operators









    % Arithmetic Operators








    !! Logical Operators









    @ Error Control Operators








    ?: Ternary Operator









    ?? Null Coalesce Operator (since PHP 7)









    ?string
    ?int
    ?array
    ?bool
    ?float Nullable return type declaration (since PHP 7.1)









    : Alternative syntax for control structures, Ternary Operator








    :: Scope Resolution Operator









    \ Namespaces








    -> Classes And Objects









    => Arrays









    ^ Bitwise Operators








    >> Bitwise Operators









    << Bitwise Operators








    <<< Heredoc or Nowdoc









    = Assignment Operators









    == Comparison Operators








    === Comparison Operators









    !== Comparison Operators








    != Comparison Operators









    <> Comparison Operators









    <=> Comparison Operators (since PHP 7.0)








    | Bitwise Operators









    || Logical Operators








    ~ Bitwise Operators









    + Arithmetic Operators, Array Operators









    += and -= Assignment Operators








    ++ and -- Incrementing/Decrementing Operators









    .= Assignment Operators








    . String Operators









    , Function Arguments





    , Variable Declarations









    $$ Variable Variables









    ` Execution Operator








    Short Open Tags









    [] Arrays (short syntax since PHP 5.4)








    Opening and Closing tags









    ... Argument unpacking (since PHP 5.6)






    ** Exponentiation (since PHP 5.6)







    # One-line shell-style comment








    :? Nullable return types








    Answer



    Incrementing / Decrementing Operators



    ++ increment operator



    -- decrement operator




    Example    Name              Effect
    ---------------------------------------------------------------------
    ++$a Pre-increment Increments $a by one, then returns $a.
    $a++ Post-increment Returns $a, then increments $a by one.
    --$a Pre-decrement Decrements $a by one, then returns $a.
    $a-- Post-decrement Returns $a, then decrements $a by one.


    These can go before or after the variable.




    If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.



    For example:



    $apples = 10;
    for ($i = 0; $i < 10; ++$i) {
    echo 'I have ' . $apples-- . " apples. I just ate one.\n";
    }



    Live example



    In the case above ++$i is used, since it is faster. $i++ would have the same results.



    Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's.



    However, you must use $apples--, since first, you want to display the current number of apples, and then you want to subtract one from it.



    You can also increment letters in PHP:




    $i = "a";
    while ($i < "c") {
    echo $i++;
    }


    Once z is reached aa is next, and so on.





    Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.







    Posts:




    c++ - Does curly brackets matter for empty constructor?

    Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...