Tuesday, July 31, 2018

PHP/MySQL insert row then get 'id'



The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.



I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?



I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.


Answer



$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);


See mysqli_insert_id().



Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.


php - The 3 different equals



What is the difference between =, ==, and ===?




I think using one equal sign is to declare a variable while two equal signs are for a comparison condition and lastly three equal signs are for comparing values of declared variables.


Answer



You have = the assignment operator, == the 'equal' comparison operator and === the 'identical' comparison operator.



$a = $b     Assign      Sets $a to be equal to $b.
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)


For more info on the need for == and ===, and situations to use each, look at the docs.



dictionary key type confusion isinstance python





I can't understand following execution. I expected different results.



>>> f = {'ms':'ma'}
>>> isinstance(f['ms'], type(str))
False


>>> isinstance(f['ms'], type(dict))
False

>>> type(f['ms'])


Answer



type(str) and type(dict) each return type, so you are checking if your objects are instances of type, which they are not.



If you want to check if something is a string, use




isinstance(f['ms'], str)


not



isinstance(f['ms'], type(str))


And if you want to test if something is a dict, you can use




isinstance(f['ms'], dict)


not



isinstance(f['ms'], type(dict))

excel - Copy data from worksheet to html file to mail

I gather the data from different Excel sheets and paste the table and content in one sheet and then push that to html file to Outlook.



While pasting the data from the sheet to html file, it is calculating the number of columns in which the data is present.



For Example in one sheet I have pasted text which is around 500 characters on the very first row. On the next row I have pasted a 5*10 table. While copying data to html file it is calculating only 10 columns and copying the data which is in yellow in screenshot.



How do I copy all the data from Excel to html file.




If I use Sheet.UsedRange then on the basis of column it is copying data.



enter image description here



Code:




Dim rng As Range
Dim OutApp As Object

Dim OutMail As Object

With Application
.EnableEvents = False
.ScreenUpdating = False
End With

Dim htmlContent
Dim RangetoHTML
Dim lastColumn

Dim lastRow
Dim LastCol
Dim TempFile As String

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

For Each ws In ActiveWorkbook.Worksheets
If (ws.Name "Signature" And ws.Name "URL") Then
Set rng = Nothing
Set rng = ws.UsedRange


lastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row
Set rng = Range(Cells(1, 1), Cells(lastRow, 20))

'Publish the sheet to a htm file
With ActiveWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=ws.Name, _
Source:=ws.UsedRange.Address, _

HtmlType:=xlHtmlStatic)
.Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _

"align=left x:publishsource=")



htmlContent = htmlContent & RangetoHTML
'You can also use a sheet name
'Set rng = Sheets("YourSheet").UsedRange
End If
Next ws


Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
.To = "sagarwal4@dow.com"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = htmlContent

.Send 'or use .Display
End With
On Error GoTo 0

With Application
.EnableEvents = True
.ScreenUpdating = True
End With

Set OutMail = Nothing

Set OutApp = Nothing

How do I turn a C# object into a JSON string in .NET?



I have classes like these:



class MyDate
{
int year, month, day;
}

class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}


And I would like to turn a Lad object into a JSON string like this:



{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}


(without the formatting). I found this link, but it uses a namespace that's not in .NET 4. I also heard about JSON.NET, but their site seems to be down at the moment, and I'm not keen on using external DLL files. Are there other options besides manually creating a JSON string writer?


Answer



You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):



using System.Web.Script.Serialization;




var json = new JavaScriptSerializer().Serialize(obj);


A full example:



using System;
using System.Web.Script.Serialization;

public class MyDate
{
public int year;
public int month;
public int day;
}

public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}

class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}

What's the simplest way to print a Java array?



In Java, arrays don't override toString(), so if you try to print one directly, you get the className + '@' + the hex of the hashCode of the array, as defined by Object.toString():



int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // prints something like '[I@3343c8b3'



But usually, we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:



// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]

// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

//output: [John, Mary, Bob]

Answer



Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.



Examples:




  • Simple Array:




    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));


    Output:



    [John, Mary, Bob]

  • Nested Array:




    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    System.out.println(Arrays.toString(deepArray));
    //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    System.out.println(Arrays.deepToString(deepArray));


    Output:



    [[John, Mary], [Alice, Bob]]


  • double Array:



    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));


    Output:



    [7.0, 9.0, 5.0, 1.0, 3.0 ]


  • int Array:



    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));


    Output:



    [7, 9, 5, 1, 3 ]



plot explanation - What did David say to the engineer in Prometheus?

In Prometheus, when the android David is talking with the Engineer, first he stumbles a bit and stays crouched, then they are all asking him questions and David seems to translate it. Then they all stand up, the Engineer strokes his chair and snaps.


My question is, did the Engineer destroy David and go on a rampage because of what he said, or did he have another reason for that? If so, What did David say to the Engineer?


Answer


Edit: Now we know. In an interview revealed at Total Film with Dr. Anil Biltoo:



Well, according to Dr. Anil Biltoo, the film’s official translator and linguistics consultant, David did as he was asked, translating his words as follows: “This man is here because he does not want to die. He believes you can give him more life.”



The rest of the text of this article stands unedited except for the interview inserts, in italics.


We are forced to reconcile the reaction of the Engineer with:



  • His/it's original mission, to destroy the Earth.

  • His/it's momentary pause as it analyzes the situation upon awakening

  • His/it's decision to kill the team and continue its primary mission.



Does David betray his creator? His pathological hatred of all of humanity is obvious to us, but not necessarily to them. Would he use the opportunity to ask a different question than he was asked or would he comply out of duty (or programming). My suspicion is David asked exactly what he was told by Weyland. Not that it mattered, the Engineer answered only with his actions to kill the team.



My supposition still stands and is supported in the rest of the Total Film interview review:



So there we have it. David wasn’t up to anything sinister, it just turned out that the Engineer wasn’t best pleased to be interrupted by a member of the species he was charged with destroying. Apparently, the scene was initially written to involve a much longer conversation, so perhaps more details will emerge in the deleted material on the DVD. Or even in a sequel...



Why wouldn't David say what he had been asked to? He is not concerned with the question or the answer. For him, it is academic at best. He has already made his decision about humanity and given the information he has up to that point, he assumes the Engineers already have their own less than stellar opinion of humanity as well.



However, given the purported intelligence of the Engineers, and a time-table of their last visit (approximately 2,000 years ago, during a very warlike period on Earth) once he saw how violent, humanity had remained, he realized he would have to complete his mission. He did not seem conflicted in any way.



My suspicion was he recognized what David was and could extrapolate how long he had been asleep, which may have given him greater motivation to deliver his payload, fearing a galactic outbreak of this violent species. The Engineer did not seem surprised to see us, likely as a diminutive and less impressive form of itself.



I had the impression the Engineer did not fear humanity, so much as their lack of individual control. He was privy to, in a matter of seconds, hierarchical dominance behavior, aggression, anger, and directed violence. From the aspect of a species that creates life, certainly an undesirable outcome. Perhaps the same reaction we might have if a beloved pet suddenly attacked us. We would put it down, for its own good. The Engineer maintained a surprising level of apparent emotional control during his attack on the team and his subsequent launching of his ship. He did not appear to have any issues with completing his mission, so his belief in the necessity was apparent in his actions.



I would also have to credit this Engineer with some degree of forethought. He was the only one on this ship to make it back to stasis and secure himself before the pathogen was able to reach him. I suspect he thought it would be safer to be in stasis than dying in the halls.



David's experience of humanity soured him on meeting the Engineers and even though he was intellectually curious about their technology, he showed no real interest in the Engineers, themselves, likely considering them as potentially dangerous as he considered mankind. Maybe moreso, since humanity was based on their DNA. If he did give the Engineer an account of what happened or how they came to be here, rather than Wayland's requested information, I am certain, he was surprised with his/it's reaction. It was certainly not an expected outcome from David's perspective.



zend framework - Require_Once gives PHP Division By Zero Error




I'm trying to require a config file in index.php by using:



require_once __DIR__/application/common/config/Config.php;


However, PHP error logs state division by zero. The full path is /var/www/application/common/config/Config.php



How do I ensure this path is correctl represented in my require_once statement?


Answer



You need to use quotes for strings in PHP...




require_once __DIR__ . '/application/common/config/Config.php';

python - Difference between staticmethod and classmethod



What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?


Answer



Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:



class A(object):

def foo(self, x):
print "executing foo(%s, %s)" % (self, x)

@classmethod
def class_foo(cls, x):
print "executing class_foo(%s, %s)" % (cls, x)

@staticmethod
def static_foo(x):
print "executing static_foo(%s)" % x


a = A()


Below is the usual way an object instance calls a method. The object instance, a, is implicitly passed as the first argument.



a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)






With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.



a.class_foo(1)
# executing class_foo(,1)


You can also call class_foo using the class. In fact, if you define something to be
a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:




A.class_foo(1)
# executing class_foo(,1)


One use people have found for class methods is to create inheritable alternative constructors.






With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:




a.static_foo(1)
# executing static_foo(1)

A.static_foo('hi')
# executing static_foo(hi)


Staticmethods are used to group functions which have some logical connection with a class to the class.







foo is just a function, but when you call a.foo you don't just get the function,
you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument.



a is bound to foo. That is what is meant by the term "bound" below:



print(a.foo)
# >



With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.



print(a.class_foo)
# >


Here, with a staticmethod, even though it is a method, a.static_foo just returns
a good 'ole function with no arguments bound. static_foo expects 1 argument, and
a.static_foo expects 1 argument too.




print(a.static_foo)
#


And of course the same thing happens when you call static_foo with the class A instead.



print(A.static_foo)
#


plot explanation - Why did the Engineer at the start of the movie drink the dark liquid?

Why did the Engineer at the start of the movie drink the dark liquid?


From the Wikipedia article for Prometheus*:



Above a waterfall, a humanoid alien consumes a dark liquid, and a hovering spacecraft departs. After drinking the liquid the alien starts to disintegrate. The bodily remains fall into the waterfall below and the alien’s DNA triggers a biogenetic chain reaction.



* Note that since this question was posted, the Wikipedia article has been changed and no longer contains the above excerpt. This can be found in the page history for the Prometheus article.


Answer


As we can see after he drinks the liquid, his DNA seems to desintegrate into the water. But from the particules of his DNA, life is created. It is showed by the particules turning step by step into cellular life.


So my hypothesis is that his suicide was necessary to give birth to a new species: Us.


A friend of mine told me that he might have missed his flight (we can see a ship leaving), but I don't think that it is a good reason to get suicidal.


syntax - What is the use of



I am implementing node to PDF using drupal and tcpdf. In such case i am suppose to use this << tag. If i didn't give this o/p is not perfect. I can't exactly get the purpose of <<.



Could anybody please explain the concept of this?




$html = <<        
TEST

EOD;


Thanks in advance....


Answer




That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.



The HTML in your example will be:



    
TEST



Read the PHP documentation that explains it.



c++ - Instantiation of template member function



In Class.h:



class Class {
public:
template void function(T value);
};


In Class.cpp:



template void Class::function(T value) {
// do sth
}


In main.cpp:



#include "Class.h"

int main(int argc, char ** argv) {
Class a;
a.function(1);
return 0;
}


I get a linked error because Class.cpp never instantiate void Class::function(T).
You can explicitly instantiate a template class with :



template class std::vector;


How do you explicitly instantiate a template member of a non-template class ?



Thanks,


Answer



You can use the following syntax in Class.cpp:



template void Class::function(int);


The template argument can be omitted because of type deduction, which works for function templates. Thus, the above is equivalent to the following, just more concise:



template void Class::function(int);


Notice, that it is not necessary to specify the names of the function parameters - they are not part of a function's (or function template's) signature.


Cant connect my database with php




$con = mysqli_connect("localhost" "root" "") or die("Unable to connect");
mysqli_select_db("logindb", $con);
?>


This is the configuration of the connecting.




require 'config.php';
?>


This is where is connect the database to a registration page.



Can you see something wrong? This is the error i get:
Parse error: syntax error, unexpected '"root"' (T_CONSTANT_ENCAPSED_STRING)




Thanks,
Realcookie


Answer



You are missing the commas bro. Here is the corrected one



$con = mysqli_connect("localhost", "root", "") or die("Unable to connect");
mysqli_select_db($con, 'logindb');
?>


javascript - jQuery checkbox change and click event






$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));

$('#checkbox1').change(function() {
$('#textbox1').val($(this).is(':checked'));
});


$('#checkbox1').click(function() {
if (!$(this).is(':checked')) {
return confirm("Are you sure?");
}
});
});









Here .change() updates the textbox value with the checkbox status. I use .click() to confirm the action on uncheck. If the user selects cancel, the checkmark is restored but .change() fires before confirmation.



This leaves things in an inconsistent state and the textbox says false when the checkbox is checked.



How can I deal with the cancellation and keep textbox value consistent with the check state?


Answer




Tested in JSFiddle and does what you're asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked.



Updated Answer:



$(document).ready(function() {
//set initial state.
$('#textbox1').val(this.checked);

$('#checkbox1').change(function() {
if(this.checked) {

var returnVal = confirm("Are you sure?");
$(this).prop("checked", returnVal);
}
$('#textbox1').val(this.checked);
});
});


Original Answer:




$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));

$('#checkbox1').change(function() {
if($(this).is(":checked")) {
var returnVal = confirm("Are you sure?");
$(this).attr("checked", returnVal);
}
$('#textbox1').val($(this).is(':checked'));

});
});

c++ - Unnamed/anonymous namespaces vs. static functions



A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:



namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace



You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them.



My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?


Answer



The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:




The use of the static keyword is

deprecated when declaring objects in a
namespace scope, the unnamed-namespace
provides a superior alternative.




Static only applies to names of objects, functions, and anonymous unions, not to type declarations.



Edit:




The decision to deprecate this use of the static keyword (affect visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.



Unnamed namespaces still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.



Credit goes to Mike Percy for bringing this to my attention.


arrays - java.lang.NullPointerException in LinkedList[] add() method




I'm having problem when i'm adding node in Array of LinkedList.



int vertices = 100;
LinkedList[] AdjList = new LinkedList[vertices+1];


for (i = 1; i <= vertices; ++i) {

for (j = 1; j <= 6 && j + i <= vertices; ++j) {

AdjList[i].add(j); //Error occurs here.
}
}

Answer



You need to create the list before inserting into it. In your first for loop add this line, before the second for loop



AdjList[i] = new LinkedList();


Monday, July 30, 2018

How can I generate text from a RegEx?

Or "How can I RegEx in reverse?"




specifically I want to take a regex such as wks[0-9][0-9][0-9]



and create a list such as wks001,wks002,wks003, etc



I know the easiest way in this example would be to simply increment the number through addition, but say I want it to be even more sophisticated later on such as [0-9abc] I'd like to use a more sophisticated tool.



preferable would be some windows capable scripting tech, such as vbscript/powershell but I'm open to other alternatives. I guess I kind of thought this might be something that is done all the time by random number generators and such and would be a programming staple, but I lack the understanding to phrase it correctly I think.

android - Fling gesture detection on grid layout



I want to get fling gesture detection working in my Android application.




What I have is a GridLayout that contains 9 ImageViews. The source can be found here: Romain Guys's Grid Layout.



That file I take is from Romain Guy's Photostream application and has only been slightly adapted.



For the simple click situation I need only set the onClickListener for each ImageView I add to be the main activity which implements View.OnClickListener. It seems infinitely more complicated to implement something that recognizes a fling. I presume this is because it may span views?




  • If my activity implements
    OnGestureListener I don't know how to
    set that as the gesture listener for

    the Grid or the Image views that I
    add.



    public class SelectFilterActivity extends Activity implements
    View.OnClickListener, OnGestureListener { ...

  • If my activity implements
    OnTouchListener then I have no
    onFling method to override (it has
    two events as parameters allowing me

    to determine if the fling was
    noteworthy).



    public class SelectFilterActivity extends Activity implements
    View.OnClickListener, OnTouchListener { ...

  • If I make a custom View, like GestureImageView that extends ImageView I don't know how to tell the activity that a fling has occurred from the view. In any case, I tried this and the methods weren't called when I touched the screen.




I really just need a concrete example of this working across views. What, when and how should I attach this listener? I need to be able to detect single clicks also.




// Gesture detection
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
int dx = (int) (e2.getX() - e1.getX());
// don't accept the fling if it's too short
// as it may conflict with a button push
if (Math.abs(dx) > MAJOR_MOVE && Math.abs(velocityX) > Math.absvelocityY)) {
if (velocityX > 0) {

moveRight();
} else {
moveLeft();
}
return true;
} else {
return false;
}
}
});



Is it possible to lay a transparent view over the top of my screen to capture flings?



If I choose not to inflate my child image views from XML can I pass the GestureDetector as a constructor parameter to a new subclass of ImageView that I create?



This is the very simple activity that I'm trying to get the fling detection to work for: SelectFilterActivity (Adapted from photostream).



I've been looking at these sources:






Nothing has worked for me so far and I was hoping for some pointers.


Answer



Thanks to Code Shogun, whose code I adapted to my situation.



Let your activity implementOnClickListener as usual:



public class SelectFilterActivity extends Activity implements OnClickListener {


private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


/* ... */

// Gesture detection
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};


}

class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

Toast.makeText(SelectFilterActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(SelectFilterActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}


@Override
public boolean onDown(MotionEvent e) {
return true;
}
}
}


Attach your gesture listener to all the views you add to the main layout;




// Do this for each view added to the grid
imageView.setOnClickListener(SelectFilterActivity.this);
imageView.setOnTouchListener(gestureListener);


Watch in awe as your overridden methods are hit, both the onClick(View v) of the activity and the onFling of the gesture listener.



public void onClick(View v) {
Filter f = (Filter) v.getTag();
FilterFullscreenActivity.show(this, input, f);

}


The post 'fling' dance is optional but encouraged.


c++ - unresolved external symbol structs

error LNK2001: unresolved external symbol "public: static int WrappedVector::_N" (?_N@WrappedVector@@2HA)



header.h



struct WrappedVector
{
static int _N;

double *_x;
};


main.cpp



const int WrappedVector::_N = 3;


i don't understand whats wrong

Android - App crashes on Pre-Lollipop devices



My app is running well on Lollipop devices but it keep crashing on prior to version Lollipop.
I have simply implemented a banner add in my application with the following code through google documention



    // Request for Ads
AdRequest adRequest = new AdRequest.Builder()


// Add a test device to show Test Ads
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();

// Load ads into Banner Ads
mAdView.loadAd(adRequest);


using




    compileSdkVersion 23
buildToolsVersion "23.0.1"


manifest



               android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />


android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden
|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />


Error



 E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.app.aggro, PID: 13257

E/AndroidRuntime: java.lang.VerifyError:
com/google/android/gms/measurement/internal/zzv
E/AndroidRuntime: at
com.google.android.gms.measurement.AppMeasurementContentProvider
.onCreate(Unknown Source)
E/AndroidRuntime: at
android.content.ContentProvider.attachInfo(ContentProvider.java:1656)
E/AndroidRuntime: at
android.content.ContentProvider.attachInfo(ContentProvider.java:1627)
E/AndroidRuntime: at

android.app.ActivityThread.installProvider(ActivityThread.java:5015)
E/AndroidRuntime: at
android.app.ActivityThread.installContentProviders
(ActivityThread.java:4589)
E/AndroidRuntime: at
android.app.ActivityThread.handleBindApplication
(ActivityThread.java:4522)
E/AndroidRuntime: at
android.app.ActivityThread.access$1500(ActivityThread.java:151)
E/AndroidRuntime: at

android.app.ActivityThread$H.handleMessage(ActivityThread.java:1381)
E/AndroidRuntime: at
android.os.Handler.dispatchMessage(Handler.java:110)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:193)
E/AndroidRuntime: at
android.app.ActivityThread.main(ActivityThread.java:5299)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native
Method)
E/AndroidRuntime: at
java.lang.reflect.Method.invoke(Method.java:515)

E/AndroidRuntime: at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:825)
E/AndroidRuntime: at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
E/AndroidRuntime: at dalvik.system.NativeStart.main
(Native Method)


My Gradle file is




 apply plugin: 'com.android.application'

buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}

dependencies {
classpath 'io.fabric.tools:gradle:1.+'

}
}
repositories {
mavenCentral()
maven { url
"https://oss.sonatype.org/content/repositories/snapshots"}
maven { url 'https://maven.fabric.io/public' }
maven { url
"https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url 'https://dl.bintray.com/drummer-aidan/maven' }

}
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
applicationId "com.app.aggro"
minSdkVersion 15
targetSdkVersion 22
versionCode 1

versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-
android.txt'), 'proguard-rules.pro'
}
}



dexOptions{
incremental true
javaMaxHeapSize "4g"
}
defaultConfig {
multiDexEnabled true
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'

exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'

compile('com.mikepenz:materialdrawer:3.0.9@aar') {
transitive = true
}
compile('com.github.florent37:materialviewpager:1.1.0@aar') {
transitive = true
}


compile('com.crashlytics.sdk.android:crashlytics:2.4.0@aar') {
transitive = true;

}
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.mcxiaoke.volley:library:1.0.+'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.marshalchen.ultimaterecyclerview:library:0.3.11'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.jpardogo.googleprogressbar:library:1.2.0'
compile 'com.quinny898.library.persistentsearch:library:1.0.0-
SNAPSHOT'

compile project(':storage')
compile 'com.getbase:floatingactionbutton:1.10.0'
compile 'com.parse.bolts:bolts-android:1.+'
compile files('libs/activeandroid-3.1-beta.jar')
compile 'com.android.support:design:23.0.1'
compile 'it.neokree:MaterialTabs:0.11'
compile 'com.miguelcatalan:materialsearchview:1.2.0'
}



Please help me out to get out from this problem.


Answer



After expanding more than a hour on problem, I found that I have to do some modification in MyApplication Class like this:



public class MyApplication extends Application {

@Override
public void onCreate() {
super.onCreate();
// register with Active Android

ActiveAndroid.initialize(this);
}

@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}



I have overriden the attachbaseContext method and all works fine now.


php - Wordpress error open_basedir restriction in effect. File is not within the allowed path(s):

After trying a migration from another domain back to:




http://fabiolagreco.web1007.kinghost.net/





I probably mistyped the command line in PHP My Admin, to search and overwrite the domain addresses and now the wordpress will not load. It keeps showing the following error:




Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/home/fabiola/www/wordpress/wp-content/uploads/2014/07) is not within the allowed path(s): (/home/fabiolagreco/:/tmp:/usr/local/lib/php:./) in /home/fabiolagreco/www/wordpress/wp-includes/functions.php on line 1421




Site URL:





http://fabiolagreco.web1007.kinghost.net/


java - The Use of Multiple JFrames: Good or Bad Practice?




I'm developing an application which displays images, and plays sounds from a database. I'm trying to decide whether or not to use a separate JFrame to add images to the database from the GUI.



I'm just wondering whether it is good practice to use multiple JFrame windows?


Answer




I'm just wondering whether it is good practice to use multiple JFrames?





Bad (bad, bad) practice.




  • User unfriendly: The user sees multiple icons in their task bar when expecting to see only one. Plus the side effects of the coding problems..

  • A nightmare to code and maintain:


    • A modal dialog offers the easy opportunity to focus attention on the content of that dialog - choose/fix/cancel this, then proceed. Multiple frames do not.


    • A dialog (or floating tool-bar) with a parent will come to front when the parent is clicked on - you'd have to implement that in frames if that was the desired behavior.







There are any number of ways of displaying many elements in one GUI, e.g.:




  • CardLayout (short demo.). Good for:



    1. Showing wizard like dialogs.

    2. Displaying list, tree etc. selections for items that have an associated component.

    3. Flipping between no component and visible component.


  • JInternalFrame/JDesktopPane typically used for an MDI.

  • JTabbedPane for groups of components.

  • JSplitPane A way to display two components of which the importance between one or the other (the size) varies according to what the user is doing.

  • JLayeredPane far many well ..layered components.


  • JToolBar typically contains groups of actions or controls. Can be dragged around the GUI, or off it entirely according to user need. As mentioned above, will minimize/restore according to the parent doing so.

  • As items in a JList (simple example below).

  • As nodes in a JTree.

  • Nested layouts.



But if those strategies do not work for a particular use-case, try the following. Establish a single main JFrame, then have JDialog or JOptionPane instances appear for the rest of the free-floating elements, using the frame as the parent for the dialogs.



Many images




In this case where the multiple elements are images, it would be better to use either of the following instead:




  1. A single JLabel (centered in a scroll pane) to display whichever image the user is interested in at that moment. As seen in ImageViewer.

  2. A single row JList. As seen in this answer. The 'single row' part of that only works if they are all the same dimensions. Alternately, if you are prepared to scale the images on the fly, and they are all the same aspect ratio (e.g. 4:3 or 16:9).




What exactly do I lose when using extern "C" in C++?




I'm trying to develop a dynamic library in C++ to be called by an existing program written in IDL (Interactive Data Language). I know that I need to use extern "C" to disable name mangling so that IDL can call the functions it needs (the rest of the calling mechanism is pretty straightforward).



However, I'm always hesitant to use features of a language that I don't fully understand, so my question is this: What features of C++ do I lose by reverting to C linkage, if any? Namespaces would be an obvious one, I think, but does it completely disable all the other nice features of C++ too? Can I still use the C++ STL, and all the various language features (especially C++11 ones) that I've come to rely on? Or am I stuck essentially coding in C?


Answer



The only thing that gets dropped is name mangling of externally visible names. Function overloading by parameter types, as well as by parameter count, stop working as the result. Essentially, name resolution during the linking phase goes back to the plain old C mode (i.e. one name - one entry).



As far as the internals of your implementation go, you can continue using the standard library and all the other nice features of C++11. Only the names of externally visible entities get changed by extern C.



html - PHP echo H1 depending on page

How can i echo a h1 depending on the variable set on the page? The script below is breaking my page. Looks like my syntax is incorrect







if($page =="home_page") {echo "

" 'Mountain ' "

"; }
else if($page =="parts") {echo "

" 'parts ' "

"; }

else if($page =="cars") {echo "

" 'cars ' "

"; }

?>





Many thanks,
P

java - JSONObject.put(String) adds '' for each '/'





I'm just recogniced that this code:



try {
String jsonString =new JSONObject().put("test","Ha/llo").toString();
} catch (JSONException e) {

e.printStackTrace();
}


ouputs the following:



{"test":"Ha\ /llo"}



Does someone knows why it puts an \ for each / ? And how to get the real String?
My Strings i want to put are supposed to be big, so I dont want to search for \ to change it to ' '




Edit: .get decodes it again and removes the extra '\' in my case is was an server side problem.


Answer



It is escaping the / character automatically. When a valid JSON client parses your string, it should unescape it, resulting in no issues and the original text.
See JSON: why are forward slashes escaped?


Sunday, July 29, 2018

c# - Allocated on the heap or the stack?




I recently asked a question about StackOverflowExeptions and the explanations were very helpful!
However, I wrote a method and tried to figure out where T cached is allocated (heap/stack):




private Dictionary _cachedComponents = new Dictionary();

public T GetCachedComponent() where T : Component {
//Not yet sure if the next line works or throws an exception -> just ignore it
if(_cachedComponents[typeof(T)] != null) {
return (T)_cachedComponents[typeof(T)]
} else {
T cached = this.GetComponent();
_cachedComponents.Add(typeof(T), cached);

return cached;
}
}



  1. Since T cached is declared inside the method I assume it is allocated on the stack, right?

  2. But the reference is then added to the dictionary, wich should be allocated on the heap, right?

  3. The stack is "cleared" after the method returns, right?

  4. But what happens to T cached?
    Is it going to be moved to the heap?
    (Because the stack does not "carry the data" anymore but the dictionary still holds a reference)



Answer




Since T cached is declared inside the method I assume it is allocated
on the stack, right?




T being allocated in a method doesn't effect it being on the heap or the stack. The decision whether it is the former or the latter is based on whether this is a reference type or a value type.





But the reference is then added to the dictionary, wich should be
allocated on the heap, right?




Once the reference is added to the Dictionary, the key will be stored inside the dictionary, which is allocated on the heap, as it is a reference type.




The stack is "cleared" after the method returns, right?





The stack frame is cleared once the method returns.




But what happens to T cached? Is it going to be moved to the heap?




If T is cached inside the dictionary, then it is already allocated on the heap.



Overall, I assume you ask these questions as for general knowledge. You shouldn't be worrying about this too much, as what I wrote here is an implementation detail and is subject to change.


plot explanation - Why was the mummy afraid of cats - Movies & TV



In the 1999 film The Mummy. Why was the mummy afraid of cats?




I know that they were the guardians of the underworld etc. But what could the house cat that Connor had actually have done?



Or was the Mummy just so knee deep in his superstition that he never actually stopped to realise it was a harmless kitty?


Answer



Egyptians worshipped cats. Cats were deified, were thought to be holy, and the mummy was an unholy undead creature.



I am relatively certain that the movie makers wanted it to be similar to a vampire confronted with a cross, or something to that effect.


php - would null byte injection affect me if I was using a $_GET variable to make MYSQL query?










Let's say I have a $_GET variable with the name "id". The $_GET variable is then used in a mysql query to retrieve some data like SELECT text FROM database WHERE id=$_GET['id'];
Would null byte injection in my $_GET variable affect me assuming I'm using common security functions like mysql_real_escape_string(), addslashes(), and strip_tags()?


Answer




Would null byte injection in my $_GET variable affect me assuming I'm using common security functions like mysql_real_escape_string(), addslashes(), and strip_tags()?




Probably not, but a much more simple injection would affect you. Try passing this as the GET parameter:



99999 OR id=0


and run it through the query you show above. It will allow injection of arbitrary SQL even when using mysql_real_escape_string.



Contrary to popular belief, mysql_real_escape_string() will not protect you if your value is not enclosed in quotes.



If querying for numeric values, either test whether it's a number before inserting the value into the string, or put the value into quotes:



 $id = mysql_real_escape_string($_GET["id"]);
$query = "SELECT text FROM database WHERE id='$id'";


addslashes and strip_tags have no value at all in this context. They only serve to break data, but they add no security when inserting stuff in a database. Just get rid of them. (strip_tags may be appropriate later when you output something on a HTML page.)


css selectors - Is it possible to select the absolute last grand child of an element using only CSS?


















Using .a .b:last-child .c:last-child won't work in this case because of the last div.b which is empty.

html - If and else statement in PHP inside of an echo





I want to give the admin the ability to activate the user account so I have to status active and inactive
When I run my code I get 4 status
Active
Inactive
Active

Inactive
You will find here a screenshot to understand the problem I’m facing



http://i.imgur.com/2c0VcN7.png



    if(isset($_GET['id_user'])){

include("conexion.php");

$rep=$db->query("select * from user WHERE id_user=" .$_GET['id_user'] );


while($l=$rep->fetch()){
echo "



























"; // fin echo
}
}
?>

Answer



Your code may not have been properly formed. Try this instead:



    

if( isset($_GET['id_user']) ){
include("conexion.php");
$rep = $db->query( "select * from user WHERE id_user=" . $_GET['id_user'] );

// YOU ARE FETCHING A SINGLE USER... NO NEED FOR A LOOP...
// JUST GET THE ARRAY OBJECT AND USE IT DIRECTLY...
$l = $rep->fetch();
?>


























php - Sanitizing strings to make them URL and filename safe?

I have adapted from another source and added a couple extra, maybe a little overkill


/**
* Convert a string into a url safe address.
*
* @param string $unformatted
* @return string
*/
public function formatURL($unformatted) {
$url = strtolower(trim($unformatted));
//replace accent characters, forien languages
$search = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
$replace = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
$url = str_replace($search, $replace, $url);
//replace common characters
$search = array('&', '£', '$');
$replace = array('and', 'pounds', 'dollars');
$url= str_replace($search, $replace, $url);
// remove - for spaces and union characters
$find = array(' ', '&', '\r\n', '\n', '+', ',', '//');
$url = str_replace($find, '-', $url);
//delete and replace rest of special chars
$find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');
$replace = array('', '-', '');
$uri = preg_replace($find, $replace, $url);
return $uri;
}

java - Difference between declaring variables before or in loop?



I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference?
A (quite pointless) example in Java:



a) declaration before loop:




double intermediateResult;
for(int i=0; i < 1000; i++){
intermediateResult = i;
System.out.println(intermediateResult);
}


b) declaration (repeatedly) inside loop:



for(int i=0; i < 1000; i++){

double intermediateResult = i;
System.out.println(intermediateResult);
}


Which one is better, a or b?



I suspect that repeated variable declaration (example b) creates more overhead in theory, but that compilers are smart enough so that it doesn't matter. Example b has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example a.



Edit: I am especially interested in the Java case.



Answer



Which is better, a or b?



From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).



From a maintenance perspective, b is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.


The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead




When I attempt to connect to a MySQL server from PHP, I see the following error:





Deprecated: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /path/to/filename.php on line 123




The code on the referenced line is:



mysql_connect($server, $username, $password);



I am certain that the arguments are correct, and this exact code has been working for years without problem. Indeed, I obtained it from a well-sourced tutorial on PHP.




  1. Why is this happening?


  2. How can I fix it?


  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:



    error_reporting = E_ALL ^ E_DEPRECATED



    What will happen if I do that?



Answer





  1. Why is this happening?




    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.




    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.



    The manual has contained warnings against its use in new code since June 2011.



  2. How can I fix it?




    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.



    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.




    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.



  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:



    error_reporting = E_ALL ^ E_DEPRECATED


    What will happen if I do that?





    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.



    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.







What should you do?





  • You are starting a new project.



    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.


  • You have (your own) legacy codebase that currently depends upon ext/mysql.



    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.




    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.




      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.


    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.



      Consider whether you really need to upgrade to PHP v5.5 at this time.



      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.



      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.




  • You are using a third party project that depends upon ext/mysql.



    Consider whether you really need to upgrade to PHP v5.5 at this time.



    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.



    It is absolutely essential to perform regression testing.



python - How can I remove a trailing newline?

What is the Python equivalent of Perl's chomp function, which removes the last character of a string if it is a newline?

How do you append to a file in Python?




How do you append to the file instead of overwriting it? Is there a special function that appends to the file?


Answer



with open("test.txt", "a") as myfile:
myfile.write("appended text")

r - Extracting a random sample of rows in a data.frame with a nested conditional



This question builds from the SO post found here and uses code that was modified from a post on the R-help mailing list which can be seen here



I am trying to extract a random sample of rows in a data frame but with a conditional. Using the R iris data which looks like:




> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa



To take a simple random sample, the code below works fine to take a sample of 2 rows.



iris[sample(nrow(iris), 2), ]


However I am unsure how to condition the Species field. For example how to take the random sample as indicated above but only when Species != “setosa”



There are three categories of iris$Species



> summary(iris$Species)

setosa versicolor virginica
50 50 50


I am unsure how to correctly nest conditionals. One of my earlier attempts is below with the obviously incorrect results included….



> iris[sample(nrow(iris)[iris$Species != "setosa"], 2), ]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
NA NA NA NA NA
NA.1 NA NA NA NA



Thanks


Answer



I'd use which to get the vector of rows numbers from which you can sample given your condition....



iris[ sample( which( iris$Species != "setosa" ) , 2 ) , ]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#59 6.6 2.9 4.6 1.3 versicolor
#133 6.4 2.8 5.6 2.2 virginica


android - How to block "Google Search" appearing when long pressed HOME key?

I'm developing a Home screen application for android. But when the HOME key is long pressed "Google Now" search always appears - I want to avoid that. I found that the android framework does not give a HOME key press event out to application level.




Since this is a home screen app I can detect HOME key short press, but not the long press.
So how can I block/disable this system search activity coming up when HOME key is long pressed?

Saturday, July 28, 2018

character - Voldemort's physical presence pre-Goblet of Fire - Movies & TV

Voldemort returned to physical, human form in the Goblet of Fire. But can someone explain what the physical effects of using the curse on Harry as a baby had on his body? He didn't die but also, wasn't human. What was his state?



Also, when Wormtail put him into the cauldron in HP4, he was nothing more than a small baby-like creature. Where had he been before he was under Wormtail's care? He didn't look capable of taking care of himself or even moving. Was it ever explained where Wormtail actually found him?

c++ - Do the parentheses after the type name make a difference with new?



If 'Test' is an ordinary class, is there any difference between:



Test* test = new Test;


and



Test* test = new Test();


Answer



Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.



Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.




  • In C++1998 there are 2 types of initialization: zero and default

  • In C++2003 a 3rd type of initialization, value initialization was added.




Assume:



struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m


In a C++98 compiler, the following should occur:





  • new A - indeterminate value

  • new A() - zero-initialize


  • new B - default construct (B::m is uninitialized)


  • new B() - default construct (B::m is uninitialized)


  • new C - default construct (C::m is zero-initialized)


  • new C() - default construct (C::m is zero-initialized)



In a C++03 conformant compiler, things should work like so:





  • new A - indeterminate value

  • new A() - value-initialize A, which is zero-initialization since it's a POD.


  • new B - default-initializes (leaves B::m uninitialized)


  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.


  • new C - default-initializes C, which calls the default ctor.


  • new C() - value-initializes C, which calls the default ctor.




So in all versions of C++ there's a difference between new A and new A() because A is a POD.



And there's a difference in behavior between C++98 and C++03 for the case new B().



This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.


java - .nextLine() method does not take subsequent String inputs





I have a program that asks the user for an input of numbers and characters. For this I am using a Scanner class. But when I take two subsequent string inputs, the console just moves and asks the user to input the second string. The user is unable to input the first string. I have attached my code below to be more specific.



import java.util.Scanner;

class XYZ {


public static void main(String args[]) {
int x, y, z, b, c;
String p, q;
Scanner sc = new Scanner(System.in);

System.out.println("Enter a number");
b = sc.nextInt();

System.out.println("Enter a new number");
c = sc.nextInt();


System.out.println("Enter a String");
p = sc.nextLine();

System.out.println("Enter a new String");
q = sc.nextLine();

System.out.println("Enter a number");
x = sc.nextInt();


System.out.println("Enter 2nd number");
y = sc.nextInt();

System.out.println("Enter 3rd number");
z = sc.nextInt();

ABC a = new ABC();

a.PQR(b, c);
a.PQR(p, q);

a.PQR(x, y, z);
}
}

class ABC {

void PQR(int a, int b) {
int res = a + b;
System.out.println("The sum is" + " " + res);
}


void PQR(String a, String b) {
System.out.println("Thye concataneted string is" + a + " " + b);
}

void PQR(int a, int b, int c) {
int res = a * b * c;
System.out.println("The product is" + " " + res);
}
}


Answer



You need to make a dummy call to nextLine() after your call to nextInt(). The nextInt() isn't taking the "\n" into account.



Alternatively, and preferably, just use nextLine() to accept all input and whichever ones need to be ints, just use:



int i = Integer.parseInt(**string**);


Does this help?



'arrested-development' tag wiki - Movies & TV



Television show, previously of the Fox Television Network, recently NetFlix, and a proposed movie, detailing the events of a jailed Real Estate patriarch and the comedic efforts of his family to maintain the business in his absence.






There is no tag wiki for this tag … yet!




Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.



All registered users may propose new tag wikis.



(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)


c# - Enum String Name from Value




I have an enum construct like this:



public enum EnumDisplayStatus
{
None = 1,
Visible = 2,
Hidden = 3,
MarkedForDeletion = 4
}



In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.



For example, given 2 the result should be Visible.


Answer



You can convert the int back to an enumeration member with a simple cast, and then call ToString():



int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();


c# - DataGridView displays empty cells when bound to typed DataTable

I'm creating a simple application that simply populates a DataGridView with a strongly typed DataTable. My problem is that all the cells show up empty despite containing data, I have a CellDoubleClick event which can pick up the underlying value of the cell (which is typed as expected) but the column is shown as empty.


Objects of type INode all have a ToString() method defined and my assumption was that the DataGridView would be intelligent enough to call that method any show that as the cell contents but it appears not.


Here is my current test code:


        //Add some fake test data
DataTable data = new DataTable();
data.Columns.Add("Subject");
data.Columns.Add("Predicate");
data.Columns.Add("Object");
data.Columns["Subject"].DataType = typeof(INode);
data.Columns["Predicate"].DataType = typeof(INode);
data.Columns["Object"].DataType = typeof(INode);
Graph g = new Graph();
DataRow row = data.NewRow();
row["Subject"] = g.CreateURINode(new Uri("http://example.org/subject"));
row["Predicate"] = g.CreateURINode(new Uri("http://example.org/predicate"));
row["Object"] = g.CreateURINode(new Uri("http://example.org/object"));
data.Rows.Add(row);
this.dvwBrowser.DataSource = data;
this.dvwBrowser.AutoResizeColumns();

How can I get the value of the ToString() method to be displayed in the cells when I bind the DataTable to the DataGridView?

python - How do I pass a variable by reference?



The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'



class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)


def change(self, var):
var = 'Changed'


Is there something I can do to pass the variable by actual reference?


Answer



Arguments are passed by assignment. The rationale behind this is twofold:




  1. the parameter passed in is actually a reference to an object (but the reference is passed by value)


  2. some data types are mutable, but others aren't



So:




  • If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.


  • If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.





To make it even more clear, let's have some examples.



List - a mutable type



Let's try to modify the list that was passed to a method:



def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)


outer_list = ['one', 'two', 'three']

print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)


Output:




before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']


Since the parameter passed in is a reference to outer_list, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.



Now let's see what happens when we try to change the reference that was passed in as a parameter:




def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)

outer_list = ['we', 'like', 'proper', 'English']

print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)



Output:



before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']



Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed.



String - an immutable type



It's immutable, so there's nothing we can do to change the contents of the string



Now, let's try to change the reference



def try_to_change_string_reference(the_string):
print('got', the_string)

the_string = 'In a kingdom by the sea'
print('set to', the_string)

outer_string = 'It was many and many a year ago'

print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)



Output:



before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago


Again, since the the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new string, but there was no way to change where outer_string pointed.




I hope this clears things up a little.



EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.



How do we get around this?



As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:



def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)

return new_string

# then you could call it like
my_string = return_a_whole_new_string(my_string)


If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:



def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])

stuff_to_change[0] = new_string

# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)

do_something_with(wrapper[0])


Although this seems a little cumbersome.



plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...