Wednesday 24 January 2018

java: pass-by-value or pass-by-reference

I'd two code
snippets:


First


class
PassByTest{
public static void main(String... args){
PassByTest
pbt=new PassByTest();
int x=10;
System.out.println("x=
"+x);
pbt.incr(x);//x is passed for increment

System.out.println("x= "+x);//x is unaffected
}
public void
incr(int x){
x+=1;

}
}

In this code the
value of x is
unaffected.


Second


import
java.io.*;
class PassByteTest{
public static void
main(String...args) throws IOException{
FileInputStream fis=new
FileInputStream(args[0]);
byte[] b=new byte[fis.available()];

fis.read(b);//how all the content is available in this byte[]?
for(int
i=0;i System.out.print((char)b[i]+"");

if(b[i]==32)
System.out.println();
}

}
}

In this all the
content of file is available in the byte[] b.
How
and Why?

Monday 22 January 2018

PHP mail() function not sending email

I am attempting to send an email using the
mail() PHP function. I had it working
until I attempted to give it a subject of "User registration", then the mail is not
sent!



Heres the code (have simplified it
greatly)




$to =
$this->post_data['register-email'];
$message = 'Hello
etc';
$headers = 'From: noreply@example.com' . "\r\n" ;
$headers .=
'Content-type: text/html; chareset=iso-8859-1\r\n';
$headers .= 'From: Website
';
mail($to, 'User Registration', $message,
$headers);


I also
attempted to use a variable containing the string of text but that didnt
work.




Why is it not sending the mail
when I add the subject
exception?



Thanks



EDIT:
updated code thats still not
working



$to =
$this->post_data['register-email'];
$message = 'Hello
etc';

$headers = 'MIME-Version: 1.0' .
"\r\n";

$headers .= "Content-type: text/html;
charset=iso-8859-1\r\n";
$headers .= 'From: Website
';
mail($to, 'User Registration', $message,
$headers);

android - Unable to get provider com.facebook.internal.FacebookInitProvider: java.lang.ClassNotFoundException

I am trying to share a photo from my application to
facebook. I have added the Facebook SDK and done the initial setup. But when I run the
application its crashing and I am getting the following
exception.



Here is my
logcat:



java.lang.RuntimeException:
Unable to get provider com.facebook.internal.FacebookInitProvider:
java.lang.ClassNotFoundException: Didn't find class
"com.facebook.internal.FacebookInitProvider" on path: DexPathList[[zip file
"/data/app/com.ignite.a01hw909350.kolamdemo-2/base.apk", zip file
"/data/app/com.ignite.a01hw909350.kolamdemo-2/split_lib_slice_1_apk.apk"],nativeLibraryDirectories=[/data/app/com.ignite.a01hw909350.kolamdemo-2/lib/arm64,
/data/app/com.ignite.a01hw909350.kolamdemo-2/base.apk!/lib/arm64-v8a,
/data/app/com.ignite.a01hw909350.kolamdemo-2/split_lib_slice_1_apk.apk!/lib/arm64-v8a,
/vendor/lib64, /system/lib64]]
at
android.app.ActivityThread.installProvider(ActivityThread.java:5267)
at
android.app.ActivityThread.installContentProviders(ActivityThread.java:4859)

at
android.app.ActivityThread.handleBindApplication(ActivityThread.java:4799)


at android.app.ActivityThread.access$1600(ActivityThread.java:168)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at
android.os.Looper.loop(Looper.java:148)
at
android.app.ActivityThread.main(ActivityThread.java:5609)
at
java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by:
java.lang.ClassNotFoundException: Didn't find class
"com.facebook.internal.FacebookInitProvider" on path: DexPathList[[zip file
"/data/app/com.ignite.a01hw909350.kolamdemo-2/base.apk", zip file
"/data/app/com.ignite.a01hw909350.kolamdemo-2/split_lib_slice_1_apk.apk"],nativeLibraryDirectories=[/data/app/com.ignite.a01hw909350.kolamdemo-2/lib/arm64,
/data/app/com.ignite.a01hw909350.kolamdemo-2/base.apk!/lib/arm64-v8a,
/data/app/com.ignite.a01hw909350.kolamdemo-2/split_lib_slice_1_apk.apk!/lib/arm64-v8a,
/vendor/lib64, /system/lib64]]
at
dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)


at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at
java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at
android.app.ActivityThread.installProvider(ActivityThread.java:5252)
at
android.app.ActivityThread.installContentProviders(ActivityThread.java:4859) 

at
android.app.ActivityThread.handleBindApplication(ActivityThread.java:4799) 

at android.app.ActivityThread.access$1600(ActivityThread.java:168) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434) 
at
android.os.Handler.dispatchMessage(Handler.java:102) 
at
android.os.Looper.loop(Looper.java:148) 
at
android.app.ActivityThread.main(ActivityThread.java:5609) 

at
java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) 

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) 
Suppressed:
java.lang.ClassNotFoundException: com.facebook.internal.FacebookInitProvider

at java.lang.Class.classForName(Native Method)
at
java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at
java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at
java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 12 more

Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader;
no stack trace
available



Here
is my
Manifest.xml




android:name=".AppController"
android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:largeHeap="true"


android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"
android:theme="@style/AppTheme">

android:value="@string/facebook_app_id"/>
android:name=".MainActivity" />

android:name=".ARCameraActivity"

android:configChanges="orientation|screenSize"

android:screenOrientation="fullSensor" />


android:name=".RegistrationActivity"

android:screenOrientation="portrait" />

android:name=".LoginActivity"
android:screenOrientation="portrait"
/>
android:name=".SplashActivity"

android:screenOrientation="portrait">


/>


android:name="android.intent.category.LAUNCHER" />




android:name=".MenuActivity"
android:screenOrientation="portrait"
/>
android:name=".ScanAndDrawActivity"

android:screenOrientation="portrait" />


android:name=".GalleryActivity"
android:screenOrientation="portrait"
/>
android:name=".PdfKolamActivity"

android:screenOrientation="portrait" />


android:name=".BluetoothService"
android:enabled="true"


android:exported="true">

android:name="com.ignite.a01hw909350.kolamdemo.BluetoothService" />





android:name=".MyScheduleReceiver"

android:enabled="true">



/>





android:name=".BotDialogActivity"

android:launchMode="singleInstance"
android:noHistory="true"

android:theme="@style/Theme.AppCompat.Light.Translucent" />
android:name=".ModelActivity" />

android:name=".PanchangActivity" />


android:name=".MyStartServiceReceiver"
android:exported="true"/>


android:name=".services.AlarmService"
android:enabled="true">


/>






android:name=".BootReceiver"
android:enabled="true">


android:name="android.intent.action.BOOT_COMPLETED" />
android:name="android.intent.action.QUICKBOOT_POWERON" />




android:authorities="com.facebook.app.FacebookContentProvider43234236033829"

android:name="com.facebook.FacebookContentProvider"

android:exported="true"/>




Here
is my build.gradle:



apply plugin:
'com.android.application'


android {

compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig
{
applicationId "com.ignite.a01hw909350.kolamdemo"
minSdkVersion
17
targetSdkVersion 25
versionCode 1
versionName
"1.0"

testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes
{
release {
minifyEnabled false
proguardFiles
getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

}
}
aaptOptions {
noCompress
'KARMarker'

noCompress 'armodel'
}

repositories {
jcenter()
maven()

}
}

dependencies {
compile fileTree(include:
['*.jar'], dir: 'libs')


androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

exclude group: 'com.android.support', module: 'support-annotations'

})
compile project(':KudanAR1')
compile
project(':eventbus-3.0.0')
compile
'com.android.support:appcompat-v7:25.3.1'
compile
'com.android.support.constraint:constraint-layout:1.0.2'
compile
'com.android.volley:volley:1.0.0'
compile
'com.scottyab:secure-preferences-lib:0.1.4'
compile
'com.jrummyapps:animated-svg-view:1.0.1'

compile
'me.zhanghai.android.materialprogressbar:library:1.3.0'
compile
'io.palaima:smoothbluetooth:0.1.0'
compile
'com.android.support:recyclerview-v7:25.3.1'
compile
'com.afollestad.material-dialogs:core:0.9.3.0'
compile
'com.flurgle:camerakit:0.9.13'
compile
'com.github.zhukic:sectioned-recyclerview:1.0.0'
compile
'com.android.support:support-vector-drawable:25.3.1'
compile
'com.android.support:cardview-v7:25.3.1'
compile
'com.prolificinteractive:material-calendarview:1.4.3'
compile
'com.github.bumptech.glide:glide:3.7.0'

compile
'com.android.support:design:25.3.1'
compile
'com.github.barteksc:android-pdf-viewer:2.4.0'
compile
'org.rajawali3d:rajawali:1.1.668@aar'
compile
'com.tapadoo.android:alerter:1.0.8'
compile
'com.google.android.gms:play-services-location:10.0.1'
compile
'uk.co.chrisjenx:calligraphy:2.3.0'
compile
'com.facebook.android:facebook-android-sdk:[4,5)'
testCompile
'junit:junit:4.12'
}



Where
is the problem coming from?

python - How to access environment variable values?

itemprop="text">

I set an environment variable that I
want to access in my Python application. How do I get this value?



Answer




Environment variables are accessed through
rel="noreferrer">os.environ



import
os
print(os.environ['HOME'])



Or
you can see a list of all the environment variables
using:



os.environ


As
sometimes you might need to see a complete
list!



# using get will return
`None` if a key is not present rather than raise a
`KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))


#
os.getenv is equivalent, and can also give a default value instead of
`None`
print(os.getenv('KEY_THAT_MIGHT_EXIST',
default_value))


href="https://docs.python.org/install/index.html#how-installation-works"
rel="noreferrer">Python default installation on Windows is
C:\Python. If you want to find out while running python you can
do:



import
sys
print(sys.prefix)



enumeration - Iterate Between Enum Values in C#













Suppose
that i have an enumeration like
that:



public enum
Cars
{
Audi = 0,
BMW,

Opel,

Renault,
Fiat,
Citroen,

AlfaRomeo,
}


Do
i have a chance to iterate between Opel and Citroen? I want to give these values as
parameters of a method.


itemprop="text">
class="normal">Answer



This will
work:




for(Cars
car=Cars.Opel; car<=Cars.Citroen; car++)
{

Console.WriteLine(car);
}


but
you have to make sure that the start value is less than the end
value.



EDIT />If you don't hardcode the start and end, but supply them as parameters, you need to
use them in the correct order. If you just switch "Opel" and "Citroen", you will get no
output.




Also (as remarked in the
comments) the underlying integer values must not contain gaps or overlaps. Luckily if
you do not specify values yourself (even the '=0' is not needed), this will be the
default behaviour. See href="http://msdn.microsoft.com/en-us/library/cc138362.aspx"
rel="noreferrer">MSDN:





When you do not specify values for the elements in the enumerator list, the
values are automatically incremented by
1.



c# - JavaScriptSerializer - JSON serialization of enum as string

itemprop="text">

I have a class that contains an
enum property, and upon serializing the object using
JavaScriptSerializer, my json result contains the integer value
of the enumeration rather than its string "name". Is there a
way to get the enum as a string in my json without having to
create a custom JavaScriptConverter? Perhaps there's an
attribute that I could decorate the enum definition, or object
property, with?




As an
example:



enum Gender { Male,
Female }

class Person
{
int Age { get; set;
}
Gender Gender { get; set;
}
}



Desired
json result:



{ "Age": 35,
"Gender": "Male"
}


Ideally looking for
answer with built-in .NET framework classes, if not possible alternatives (like
Json.net) are welcome.


itemprop="text">
class="normal">Answer



No there
is no special attribute you can use. JavaScriptSerializer
serializes enums to their numeric values and not their string
representation. You would need to use custom serialization to serialize the
enum as its name instead of numeric
value.




/>

If you can use JSON.Net instead of
JavaScriptSerializer than see href="https://stackoverflow.com/a/2870420/477420">answer on this question
provided by href="https://stackoverflow.com/users/56829/omer-bokhari">OmerBakhari:
JSON.net covers this use case (via the attribute
[JsonConverter(typeof(StringEnumConverter))]) and many others
not handled by the built in .net serializers. href="https://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm"
rel="noreferrer">Here is a link comparing features and functionalities of the
serializers.


go - Initialize a nested struct

itemprop="text">

I cannot figure out how to initialize
a nested struct. Find an example here:
href="http://play.golang.org/p/NL6VXdHrjh">http://play.golang.org/p/NL6VXdHrjh



package
main


type Configuration struct {
Val
string
Proxy struct {
Address string
Port
string
}
}

func main()
{


c := &Configuration{
Val:
"test",
Proxy: {
Address: "addr",
Port:
"80",
},

}

}



Answer




Well, any specific reason to not make Proxy
its own struct?



Anyway you have 2
options:



The proper way, simply move proxy to
its own struct, for example:



type
Configuration struct {
Val string
Proxy
Proxy

}

type Proxy struct {
Address
string
Port string
}

func main()
{

c := &Configuration{

Val:
"test",
Proxy: Proxy{
Address: "addr",
Port:
"port",
},
}
fmt.Println(c)

fmt.Println(c.Proxy.Address)
}



The
less proper and ugly way but still
works:



c :=
&Configuration{
Val: "test",
Proxy: struct {

Address string
Port string
}{
Address:
"addr",

Port: "80",

},
}

c++ - Why using while(!input.eof()) loop twice not working?





On the following lines of code is intended to put every words in the
input text file(words are separated by new lines) to a vector of strings, then to turn
each word inside out, and to see if this turned word is contained in the list of words
in the input file.



I believe my binary search
function and wordTurn function works fine.
I did several simple tests on my
code, and I found out using while(!myFile.eof()) loop twice might be the cause for my
code not working. By not working I mean I get the output file("pairs.txt") as an empty
document(it is supposed to be a list of pairs of
words).



That is, when I put some simple print
code in the second while(!myFile.eof()) loop body, it did not get printed out, from
which I concluded this loop is not reached. This is more likely, since it printed when I
commented out the first while(!myFile.eof()) loop. I originally placed the first while
loop at the else body, but this made no
difference.



What do you think is the
problem?
I tried combining those two loop body into the second loop, and it
produces something in the output file, but this was not what this code was supposed to
do, and this was logically not correct.



Any
words of advice would be greatly
appreciated.



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

vector words;
ifstream
myFile(argv[1]);
ofstream outputFile("pairs.txt");
string
vocab;
string s;
int count;


while(!myFile.eof()) { //first while(!myFile.eof()) loop
getline(myFile,
s);
words.push_back(s);
}

if(argc != 2)
{
cout << "Usage: provide the name of one input file after the
dictlookupHN executable file." << endl;
return (1);

}
else {
if(!myFile.is_open()) {
cerr << "Error:
unable to open file " << argv[1] << endl;
return (1);

}
else {
while(!myFile.eof()) { //second while(!myFile.eof())
loop
getline(myFile, vocab);
string turnedWord =
wordTurn(vocab);
if(binsearch(words, turnedWord) != "") {

outputFile << vocab << ":" << turnedWord << endl;

count++;
}
}
}

}

myFile.close();
outputFile.close();

return
0;
}

class="post-text" itemprop="text">
class="normal">Answer



The
ifstream class maintains an internal offset into the stream data, keeping track where it
has to read from, for the next operation.



When
this offset reaches the end, it stops the first loop, (eof()
returns false). You need to reset this internal position back to the beginning of the
file, before reading again.



You do that by
saying:



myFile.clear(); // clear
stream flags and error state
myFile.seekg(0, ios::beg); // reset read
position


before the
second loop.



Edit: Added call to
clear().


fopen - Permission denied error in php when try to write in a txt file

I'm trying to write in a txt file the data i get from a
html form, but I get this error: Warning: fopen(/var/www/4/datos.txt): failed to open
stream: Permission denied in /var/www/4/ComprobacionFormulario.php on line 13 Warning:
fwrite() expects parameter 1 to be resource, boolean given in
/var/www/4/ComprobacionFormulario.php on line 16 Warning: fclose() expects parameter 1
to be resource, boolean given in /var/www/4/ComprobacionFormulario.php on line
17



'datos.txt' Is the file where i'm trying to
write. Here is my php
code:




error_reporting(E_ALL);
ini_set('display_errors',
true);

$des=$_POST['description'];
$cant=$_POST['quantity'];
$prec=$_POST['price'];
$nombrearchivo="datos.txt";
$content="Description:
$des\tQuantity: $cant\tPrice: $prec\n";
$handle=fopen($nombrearchivo,
'w');


fwrite($handle,
$content);
fclose($handle);

javascript - Math.cos() gives wrong results





According to my understanding, and my calculator, cos(90
degrees)
equals 0.
In my code, I have a
function that allows me to type in degrees whenever I need
to:




function
deg(i)
{
return
i*Math.PI/180;
}


Although,
when calling Math.cos(deg(90)); the output I receive is
6.123233995736766e-17.



Why
could such a thing possibly
happen?




(Please excuse me for my bad
English)



Answer




deg(90) is
approximately equal to 90*Math.PI/180 and
your result is aproximately equal to
0.



So, everything is
fine ;)



Note that it has to be
approximate, because there is no way to represent π
precisely.


If java is passed-by-value why my object changes after executing the method?

itemprop="text">

I was debugging my method and it
somehow updates my element variable. Even if I don't work with
that variable from within the
method.




CODE:



private
static List createFormFieldsMapping(ArrayList
CDOfields,
List fieldMappings, Element element) {

System.out.println(" - Creating field mappings for "+element.name);
for
(Mapping fieldMapping : fieldMappings){
if
(fieldMapping.targetEntityFieldId!=null){
String formField =
getContactFieldNameById(fieldMapping.targetEntityFieldId);
formField =
formField.trim();

formField = formField.replaceAll("-",
"");
formField = formField.replaceAll("_", "");
formField =
formField.replaceAll(" ", "");
formField =
formField.toLowerCase();
Boolean matchFound = false;
for (String
cdoField : CDOfields){
String[] cdoFieldSplit =
cdoField.split(";",-1);
String cdoFieldModified
=cdoFieldSplit[1].trim();
cdoFieldModified = cdoFieldModified.replaceAll("-",
"");
cdoFieldModified = cdoFieldModified.replaceAll("_",
"");

cdoFieldModified = cdoFieldModified.replaceAll(" ",
"");
cdoFieldModified = cdoFieldModified.toLowerCase();
if
(cdoFieldModified.equals(formField)){
fieldMapping.targetEntityFieldId =
cdoFieldSplit[0];
matchFound = true;
break;

}
if (!matchFound){
// WRITE NOT MATCHED FORM FIELD TO A
FILE
}

}
}

}


element.processingSteps.targetEntityFieldId
is being changed



This is the way I call the
method:



List
fieldMapping = new
ArrayList();

Iterator i =
element.processingSteps.iterator();

while (i.hasNext())
{
ProcessingStep step = i.next();
if
(step.type.equals("FormStepCreateUpdateContactFromFormField")){
fieldMapping
= step.mappings;
step.execute = "never";
//i.remove();

}
}

// Update contact field IDs with CDO field
IDs
fieldMapping = createFormFieldsMapping(CDOfields, fieldMapping,
element);


Everything I
wanted was to kind of copy field mapping, process it by that method and then return back
and add it to list of
fieldMappings.



The
thing is that step.mappings is part of
element, but that step.mappings is
being put to an ArrayList
fieldMapping. By that I would assume that element should never
be edited by anything.


itemprop="text">
class="normal">Answer



I believe
this is because changing fieldMapping in this code also changes element because both are
"references" to the same
object:




fieldMapping.targetEntityFieldId
= cdoFieldSplit[0];


To
verify this is the case, add a conditional debug break (or an if-statement and a
print/log) that checks the equality of the two object
instances.



This is happening because you are
setting fieldMapping equal to the object pointed to by your
element.processingSteps.iterator() in following code.



Iterator i
= element.processingSteps.iterator();

while (i.hasNext())
{

ProcessingStep step = i.next();
if
(step.type.equals("FormStepCreateUpdateContactFromFormField")){
fieldMapping
= step.mappings;
step.execute = "never";
//i.remove();

}
}
// Update contact field IDs with CDO field IDs

fieldMapping = createFormFieldsMapping(CDOfields, fieldMapping,
element);



If
you do not want this behavior, then you need to "deep copy" the step.mappings object
when initializing fieldMapping.


Protected vs Public in terms of Inheritance in Java





When should one use Public over Protected in Java when creating
Superclasses, if a program runs without any problems with a Protected access modifier
set is there any need to change it to Public?


class="post-text" itemprop="text">
class="normal">Answer



You should
follow the rel="noreferrer">Principle of Least
Privilege
.




This means that
members should be assigned the minimum accessibility needed for the program to
work.



If an unrelated class needs access, make
it public. Typically this is done only for methods that provide
managed access to data.



If the subclass is to be
completely trusted in manipulating the data, and it needs it to work properly, you can
make the member
protected.



Else, make
it private, so no other class can access it (without going
through other more accessible methods that help encapsulate the
data).



If your program works well when it's
protected, then do not make it public.
Consider making it private, with
protected methods that access it, to encapsulate the data
better.


java - How do I break multiple foreach loops?






I have four foreach loops that iterate through the
collections and based on a condition do something.



Here is the code that I am writing
now:



boolean breakFlag =
false;
String valueFromObj2 = null;
String valueFromObj4 =
null;
for(Object1 object1: objects){
for(Object2 object2:
object1){
// I get some value from object2


valueFromObj2 = object2.getSomeValue();
for(Object3 object3 :
object2){
for(Object4 object4: object3){
// Finally I get some
value from Object4.
valueFromObj4 = object4.getSomeValue();
//
Compare with valueFromObj2 to decide either to break all the foreach loop

breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );

if(breakFlag){break;}
} // fourth loop ends here

if(breakFlag){break;}

} // third loop ends here

if(breakFlag){break;}
} // second loop ends here

if(breakFlag){break;}
} // first loop ends
here


The main object
(objects in the code) comes from a third-party provider SDK, so I cannot change anything
on that portion. I want to ask the Stack Overflow community if there is a better
approach to break all the four foreach loops. Or if there is any other way to refactor
this code to make it more readable and maintainable.



Answer




Use a label on the outermost loop, and
include this label in the break statement when you want to jump
out of all the loops. In the example below, I've modified your code to use the label
OUTERMOST:




String
valueFromObj2 = null;
String valueFromObj4 = null;
OUTERMOST:
for(Object1 object1: objects){
for(Object2 object2: object1){
//I
get some value from object2
valueFromObj2 =
object2.getSomeValue();
for(Object3 object3 : object2){

for(Object4 object4: object3){
//Finally I get some value from
Object4.

valueFromObj4 = object4.getSomeValue();

//Compare with valueFromObj2 to decide either to break all the foreach loop

if( compareTwoVariable(valueFromObj2, valueFromObj4 )) {
break
OUTERMOST;
}
}//fourth loop ends here
}//third loop
ends here
}//second loop ends here
}//first loop ends
here



java - comparison of two Strings doesn't work in android

here's my code, Eclipse doesn't show any errors, program's
working fine, but it simply doesn't do exactly what i want:)



 View image_view_danger_rate =
(ImageView) findViewById(R.id.origin);
View image_view_origin = (ImageView)
findViewById(R.id.danger_rate);

String entry_tag = (String)
descriptionResultView.findViewById(resID).getTag();

String
dangerous = "dangerous";
String not_dangerous =
"not_dangerous";

if ( entry_tag == dangerous) {

image_view_danger_rate.setBackgroundResource(R.drawable.attention);
}else if
( entry_tag == not_dangerous) {

image_view_danger_rate.setBackgroundResource(R.drawable.its_ok);

image_view_origin.setBackgroundResource(R.drawable.artificial);

}


The application
should choose between two images to pop-up on the screen, depending on a tag stored in
the xml file.
So, if the tag says "dangerous", then should be shown the
"attention"-image.
If the tag says "not_dangerous", there should be the
"its_ok"-image.



Now, displaying the images
without an if-comparison works perfectly.



If i
print out the tags as a string, it works, it prints correctly "dangerous" or
"not_dangerous", depending on the tag.



But if
there's a if-comparison as shown above, nothing happens, no image is
shown.



Please anyone
help!!=)

javafx - HelloWorld with JavaFXPorts and gradle on Android

itemprop="text">


so I'll try to build a
mobile application with Gluon and JavaFX.



So, i
follow this step.




  1. Install
    ADT and add ANDROID_HOME to my enviroment (OS
    Mac)

  2. Install SceneBuilder from official
    site

  3. Install last eclipse version
    (neon)

  4. generate a FXML file from
    ScendeBuilder


  5. With eclipse wizard, i generate
    a SingleViewGluon project

  6. import FXML on my eclipse
    project and use in my JavaFX
    application



Now I try to
generate apk from console, I'm in the root of project and
launch



./gradlew clean
build


and that's ok,
after




./gradlew
android


and i get
that's error





FAILURE: Build failed with an exception.






  • What went wrong: Failed to capture
    snapshot of input files for task 'mergeClassesIntoJar' during up-to-date
    check.
    java.io.FileNotFoundException:
    /Users/franksisca/Library/Android/sdk/extras/android/support/multidex/library/libs/android-support-multidex.jar

    (No such file or directory)


  • Try: Run
    with --stacktrace option to get the stack trace. Run with --info or --debug option to
    get more log output.





BUILD
FAILED




How i solve
this? Someone has a step-by-step tutorial to build a mobile application with
JavaFXPorts?




thanks in
advance



Answer




It seems android-support-multidex.jar which
is necessary for the task 'mergeClassesIntoJar' is not
Found. So Go to Sdk Manager.exe, which is located in the root of
ANDROID_HOME, and update all the repositories. And run the
gradle clean build.



This should probably
Work.


What is the difference between String str1 = "hello"; and String str2 = new String ("hello"); in java?

What is the difference between String str1 =
"hello";
and String str2 = new String ("hello");
in java?



I know the
str2 is a object, but what about
str1?




I mean
for example:



if both of them are object, but why



if(str1.toString() ==
str2.toString())


does
not result a true boolean?

linux - What is the meaning of "POSIX"?

style="font-weight: bold;">

Answer



style="font-weight: bold;">

Answer





What is POSIX? I have read the
Wikipedia
article
and I read it every time I encounter the term. The fact is that I
never really understood what it is.



Can anyone
please explain it to me by explaining "the need for POSIX"
too?



itemprop="text">
class="normal">Answer



href="http://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX is a
family of standards, specified by the rel="noreferrer">IEEE, to clarify and make uniform the application
programming interfaces (and ancillary issues, such as commandline shell utilities)
provided by Unix-y operating systems. When you write your programs to rely on POSIX
standards, you can be pretty sure to be able to port them easily among a large family of
Unix derivatives (including Linux, but not limited to it!); if and when you use some
Linux API that's not standardized as part of Posix, you will have a harder time if and
when you want to port that program or library to other Unix-y systems (e.g., MacOSX) in
the future.


Sunday 21 January 2018

java - Using Regex to generate Strings rather than match them

itemprop="text">

I am writing a Java utility which
helps me to generate loads of data for performance testing. It would be
really cool to be able to specify a regex for Strings so that my
generator spits out things which match this. Is there something out there already baked
which I can use to do this? Or is there a library which gets me most of the way
there?



Thanks



Answer





Edit:



As mentioned in the comments, there is a
library available at Google Code to acheive this:
href="http://code.google.com/p/xeger"
rel="noreferrer">http://code.google.com/p/xeger



See
also rel="noreferrer">https://github.com/mifmif/Generex as suggested by href="https://stackoverflow.com/a/24659605/1820">Mifmif



Original
message:



Firstly, with a complex
enough regexp, i believe this can be impossible. But you should be able to put something
together for simple regexps.




If you
take a look at the source code of the class java.util.regex.Pattern, you'll see that it
uses an internal representation of Node instances. Each of the different pattern
components have their own implementation of a Node subclass. These Nodes are organised
into a tree.



By producing a visitor that
traverses this tree, you should be able to call an overloaded generator method or some
kind of Builder that cobbles something together.



xml - What is android:ems in android application design

itemprop="text">

I am new to the android application
development. I am developing an application. While doing design for this app i am stuck
in android:ems. What is this components.


class="post-text" itemprop="text">
class="normal">Answer



The em is
simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing
sizes, such as margins and paddings, in em means they are related to the font size, and
if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld
device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and
'margin: 1em' are extremely common in
CSS.




em is basically CSS property for
font sizes



android:ems or setEms(n) sets the
width of a TextView to fit a text of n 'M' letters regardless of the actual text
extension and text size. See wikipedia Em
unit



but only when the layout_width is set to
"wrap_content". Other layout_width values override the ems width
setting.



Adding an android:textSize attribute
determines the physical width of the view to the textSize * length of a text of n 'M's
set above.


r - How to change the decimal places in the vector?

itemprop="text">

I'm having trouble with decimals. I
have a vector of numbers, for
example:




x <-
c(400000, 500000, 100000,
97500)


I would like to
turn them like this:



x <-
c(4000.00, 5000.00, 1000.00,
975.00)


I've tried
commands like round, format and
options, but all they do is to add more zeros to these numbers.
How to change the decimal places in the
vector?




Thanks in
advance!



Answer




You could use the function
formatC()



formatC(as.numeric(x/100),
format = 'f', flag='0', digits = 2)


c++ - Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

itemprop="text">


One of the most interesting
projects I've worked on in the past couple of years was a project about href="https://en.wikipedia.org/wiki/Image_processing" rel="noreferrer">image
processing. The goal was to develop a system to be able to recognize Coca-Cola
'cans' (note that I'm stressing the word 'cans', you'll see
why in a minute). You can see a sample below, with the can recognized in the
green rectangle with scale and
rotation.



src="https://i.stack.imgur.com/irQtR.png" alt="Template
matching">



Some constraints on the
project:




  • The background
    could be very noisy.

  • The can could
    have any scale or rotation or even orientation
    (within reasonable limits).


  • The image could
    have some degree of fuzziness (contours might not be entirely
    straight).

  • There could be Coca-Cola bottles in the image,
    and the algorithm should only detect the
    can!

  • The brightness of the image
    could vary a lot (so you can't rely "too much" on color
    detection).

  • The can could be partly
    hidden on the sides or the middle and possibly partly hidden behind a
    bottle.

  • There could be no can at all
    in the image, in which case you had to find nothing and write a message saying
    so.



So you could end up
with tricky things like this (which in this case had my algorithm totally
fail):



src="https://i.stack.imgur.com/Byw82.png" alt="Total
fail">




I did this project a while
ago, and had a lot of fun doing it, and I had a decent implementation. Here are some
details about my
implementation:



Language:
Done in C++ using OpenCV
library.



Pre-processing:
For the image pre-processing, i.e. transforming the image into a more raw form to give
to the algorithm, I used 2
methods:




  1. Changing color
    domain from RGB to rel="noreferrer">HSV and filtering based on "red" hue, saturation above a
    certain threshold to avoid orange-like colors, and filtering of low value to avoid dark
    tones. The end result was a binary black and white image, where all white pixels would
    represent the pixels that match this threshold. Obviously there is still a lot of crap
    in the image, but this reduces the number of dimensions you have to work
    with.
    Binarized<br />            image


  2. Noise filtering using median
    filtering (taking the median pixel value of all neighbors and replace the pixel by this
    value) to reduce noise.

  3. Using href="http://en.wikipedia.org/wiki/Canny_edge_detector" rel="noreferrer">Canny Edge
    Detection Filter to get the contours of all items after 2 precedent
    steps.
    Contour<br />            detection



Algorithm:
The algorithm itself I chose for this task was taken from href="https://rads.stackoverflow.com/amzn/click/com/0123725380"
rel="noreferrer">this awesome book on feature extraction and called href="http://en.wikipedia.org/wiki/Generalised_Hough_transform"
rel="noreferrer">Generalized Hough Transform (pretty different from the
regular Hough Transform). It basically says a few
things:




  • You can describe
    an object in space without knowing its analytical equation (which is the case
    here).

  • It is resistant to image deformations such as
    scaling and rotation, as it will basically test your image for every combination of
    scale factor and rotation factor.


  • It uses a
    base model (a template) that the algorithm will
    "learn".

  • Each pixel remaining in the contour image will
    vote for another pixel which will supposedly be the center (in terms of gravity) of your
    object, based on what it learned from the
    model.



In the end, you
end up with a heat map of the votes, for example here all the pixels of the contour of
the can will vote for its gravitational center, so you'll have a lot of votes in the
same pixel corresponding to the center, and will see a peak in the heat map as
below:



src="https://i.stack.imgur.com/wxrT1.png"
alt="GHT">



Once you have that, a simple
threshold-based heuristic can give you the location of the center pixel, from which you
can derive the scale and rotation and then plot your little rectangle around it (final
scale and rotation factor will obviously be relative to your original template). In
theory at
least...




Results:
Now, while this approach worked in the basic cases, it was severely lacking in some
areas:




  • It is
    extremely slow! I'm not stressing this enough. Almost a
    full day was needed to process the 30 test images, obviously because I had a very high
    scaling factor for rotation and translation, since some of the cans were very
    small.

  • It was completely lost when bottles were in the
    image, and for some reason almost always found the bottle instead of the can (perhaps
    because bottles were bigger, thus had more pixels, thus more
    votes)

  • Fuzzy images were also no good, since the votes
    ended up in pixel at random locations around the center, thus ending with a very noisy
    heat map.

  • In-variance in translation and rotation was
    achieved, but not in orientation, meaning that a can that was not directly facing the
    camera objective wasn't
    recognized.



Can you help
me improve my specific algorithm, using
exclusively OpenCV features, to resolve the
four specific issues
mentioned?




I hope some people will
also learn something out of it as well, after all I think not only people who ask
questions should learn. :)


itemprop="text">
class="normal">Answer



An
alternative approach would be to extract features (keypoints) using the href="https://en.wikipedia.org/wiki/Scale-invariant_feature_transform"
rel="noreferrer">scale-invariant feature transform (SIFT) or href="https://en.wikipedia.org/wiki/Speeded_up_robust_features"
rel="noreferrer">Speeded Up Robust Features
(SURF).



It is implemented in href="https://en.wikipedia.org/wiki/OpenCV" rel="noreferrer">OpenCV
2.3.1.



You can find a nice code example using
features in href="http://docs.opencv.org/2.4/doc/tutorials/features2d/feature_homography/feature_homography.html"
rel="noreferrer">Features2D + Homography to find a known
object



Both algorithms are
invariant to scaling and rotation. Since they work with features, you can also handle
rel="noreferrer">occlusion (as long as enough keypoints are
visible).




src="https://i.stack.imgur.com/kF63R.jpg" alt="Enter image description
here">



Image source: tutorial
example



The processing takes a few hundred ms
for SIFT, SURF is bit faster, but it not suitable for real-time applications. ORB uses
FAST which is weaker regarding rotation
invariance.



The original
papers





php - Laravel regex validation for price OR empty

itemprop="text">


I am trying to make a regex
for price OR empty.
I have the price part (Dutch uses comma instead of point)
which actualy
works



/^\d+(,\d{1,2})?$/


The
regex above validates ok on the value 21,99



Now
I try to add the empty part so the field can be... just empty
^$




/(^$|^\d+(,\d{1,2})?$)/


But
Laravel starts to complain as soon as I change the regex:
"Method
[validate^\d+(,\d{1,2})?$)/] does not
exist."



Works
ok:



$rules =
[

'price' =>
'regex:/^\d+(,\d{1,2})?$/'
];


Laravel
says no...:



$rules = [

'price' =>
'regex:/(^$|^\d+(,\d{1,2})?$)/'
];



Kenken9990
answer - Laravel doesn't break anymore but an empty value is still
wrong:



$rules = [

'price' =>
'regex:/^(\d+(,\d{1,2})?)?$/'
];


Answer




is this work
?




$rules = [

'price' =>
'nullable|regex:/^(\d+(,\d{1,2})?)?$/'
];


c - Does an available compiler provide an implementation of the C11 '_Atomic' keyword and its related header 'stdatomic.h'?

itemprop="text">

I know the C11 standard is only a
month old, but the drafts for _Atomic are much older. I also
know the GCC compiler makes a serious effort implementing such features in advance of
the standard becoming officially approved. but even href="http://gcc.gnu.org/wiki/Atomic" rel="nofollow">there the support is
not yet ready for prime-time.



However, I'd be
interested in other compilers as well: Visual Studio, or embedded compilers cq.
environments. Is anyone compiler provider gearing up to provide such support? Any links
are welcome.



I'm asking, because I'm working in
automotive embedded development, and I'm wondering if I should move into that direction
myself. Until now, most environments (like AutoSAR or Vector OS support) have been
providing home-grown solutions, for which the new standard now provides specific syntax
and semantics, and as long as compiler authors do not move in the direction of C11, this
will remain the only real solution.



class="post-text" itemprop="text">
class="normal">Answer



I think
support for the keyword itself will take some time, I haven't seen something yet. For
what concerns the library support (support functions) there is already more. In
particular I know of gcc that implements generic functions for atomic operations
__sync_... on integer types for most of the
platforms.



I am currently working on a
compliance layer for rel="nofollow">P99 for C11. The thread part (on top of POSIX threads) is
already there, atomics (using the gcc primitives) are soon to be completed. This will be
a generic implementation supporting atomics for all base types via macros that implement
the href="http://gustedt.wordpress.com/2012/01/02/emulating-c11-compiler-features-with-gcc-_generic/"
rel="nofollow">type generic atomic_... functions
that are foreseen in the standard.



It is almost
there, you can view a first version on the P99 site, but I'll still need some days to
finish it.


bash - How to permanently set $PATH on Linux/Unix?

itemprop="text">

I'm trying to add a directory to my
path so it will always be in my Linux path. I've
tried:



export
PATH=$PATH:/path/to/dir



This
works, however each time I exit the terminal and start a new terminal instance, this
path is lost, and I need to run the export command
again.



How can I do it so this will be set
permanently?


itemprop="text">
class="normal">Answer



There are
multiple ways to do it. The actual solution depends on the
purpose.



The variable values are usually stored
in either a list of assignments or a shell script that is run at the start of the system
or user session. In case of the shell script you must use a specific shell syntax and
export or set
commands.



System
wide





  1. /etc/environment
    List of unique assignments, allows references. Perfect for adding system-wide
    directories like /usr/local/something/bin to
    PATH variable or defining JAVA_HOME.
    Used by PAM and SystemD.

  2. /etc/environment.d/*.conf List
    of unique assignments, allows references. Perfect for adding system-wide directories
    like /usr/local/something/bin to PATH
    variable or defining JAVA_HOME. The configuration can be split
    into multiple files, usually one per each tool (Java, Go, NodeJS). Used by SystemD.

  3. /etc/xprofile Shell script
    executed while starting X Window System session. This is run for every user that logs
    into X Window System. It is a good choice for PATH entries that
    are valid for every user like /usr/local/something/bin. The
    file is included by other script so use POSIX shell syntax not the syntax of your user
    shell.

  4. /etc/profile and
    /etc/profile.d/* Shell script. This is a good choice for
    shell-only systems. Those files are read only by shells in login
    mode.

  5. /etc/.rc.
    Shell script. This is a poor choice because it is single shell specific. Used in
    non-login mode.



User
session





  1. ~/.pam_environment.
    List of unique assignments, no references allowed. Loaded by PAM at the start of every
    user session irrelevant if it is an X Window System session or shell. You cannot
    reference other variables including HOME or
    PATH so it has limited use. Used by
    PAM.

  2. ~/.xprofile Shell script.
    This is executed when the user logs into X Window System system. The variables defined
    here are visible to every X application. Perfect choice for extending
    PATH with values such as ~/bin or
    ~/go/bin or defining user specific
    GOPATH or NPM_HOME. The file is
    included by other script so use POSIX shell syntax not the syntax of your user shell.
    Your graphical text editor or IDE started by shortcut will see those
    values.

  3. ~/.profile,
    ~/._profile,
    ~/._login Shell script. It will be visible only
    for programs started from terminal or terminal emulator. It is a good choice for
    shell-only systems. Used by shells in login
    mode.

  4. ~/.rc. Shell
    script. This is a poor choice because it is single shell specific. Used by shells in
    non-login
    mode.



Notes




Gnome
on Wayland starts user login shell to get the environment. It effectively uses login
shell configurations ~/.profile,
~/._profile,
~/._login
files.



Manuals




  • environment

  • environment.d

  • bash

  • dash




Distribution
specific
documentation





Related



href="https://unix.stackexchange.com/a/46856/39410">Difference between Login Shell
and Non-Login Shell?


php - Echo result of MySQL SELECT query

I have a MySQL SELECT Query that I would like to echo in
PHP. How would I do this? I have tried everything that is listed on the PHP.net help
center, but I either do not understand it or it is not what I am looking
for.




$sql = "SELECT
gamePlayerCount FROM mpTicTacToe_gameData WHERE gameId = " . $gameId;
$result
=
mysqli_query($mySqlConnection,$sql);
var_dump($result);


I
just tried using var_dump, but it returns bool(false) instead
of the 2 that it should be returning

r faq - How to make a great R reproducible example

itemprop="text">



When discussing
performance with colleagues, teaching, sending a bug report or searching for guidance on
mailing lists and here on Stack Overflow, a href="https://stackoverflow.com/help/mcve">reproducible example is often
asked and always helpful.



What are your tips for
creating an excellent example? How do you paste data structures from href="https://stackoverflow.com/questions/tagged/r" class="post-tag" title="show
questions tagged 'r'" rel="tag">r in a text format? What other information
should you include?



Are there other tricks in
addition to using dput(), dump() or
structure()? When should you include
library() or require() statements?
Which reserved words should one avoid, in addition to c,
df, data,
etc.?




How does one make a great href="https://stackoverflow.com/questions/tagged/r" class="post-tag" title="show
questions tagged 'r'" rel="tag">r reproducible
example?



Answer




A href="https://stackoverflow.com/help/minimal-reproducible-example">minimal
reproducible example
consists of the following
items:




  • a minimal dataset,
    necessary to demonstrate the problem

  • the minimal
    runnable code necessary to reproduce the error, which can
    be run on the given dataset

  • the necessary information on
    the used packages, R version, and system it is run on.

  • in
    the case of random processes, a seed (set by set.seed()) for
    reproducibility1




For
examples of good minimal reproducible examples, see the help files
of the function you are using. In general, all the code given there fulfills the
requirements of a minimal reproducible example: data is provided, minimal code is
provided, and everything is runnable. Also look at questions on with lots of
upvotes.



Producing a minimal
dataset



For most cases, this can be easily done
by just providing a vector/data frame with some values. Or you can use one of the
built-in datasets, which are provided with most packages.
A comprehensive
list of built-in datasets can be seen with library(help =
"datasets")
. There is a short description to every dataset and more
information can be obtained for example with ?mtcars where
'mtcars' is one of the datasets in the list. Other packages might contain additional
datasets.



Making a vector is easy. Sometimes it
is necessary to add some randomness to it, and there are a whole number of functions to
make that. sample() can randomize a vector, or give a random
vector with only a few values. letters is a useful vector
containing the alphabet. This can be used for making
factors.



A few examples
:





  • random values
    : x <- rnorm(10) for normal distribution, x
    <- runif(10)
    for uniform distribution,
    ...

  • a permutation of some values : x <-
    sample(1:10)
    for vector 1:10 in random
    order.

  • a random factor : x <-
    sample(letters[1:4], 20, replace =
    TRUE)



For
matrices, one can use matrix(), eg
:



matrix(1:10, ncol =
2)



Making
data frames can be done using data.frame(). One should pay
attention to name the entries in the data frame, and to not make it overly
complicated.



An example
:



set.seed(1)
Data <-
data.frame(
X = sample(1:10),
Y = sample(c("yes", "no"), 10,
replace =
TRUE)

)


For
some questions, specific formats can be needed. For these, one can use any of the
provided as.someType functions :
as.factor, as.Date,
as.xts, ... These in combination with the vector and/or data
frame tricks.



Copy your
data



If you have some data that would be too
difficult to construct using these tips, then you can always make a subset of your
original data, using head(), subset()
or the indices. Then use dput() to give us something that can
be put in R immediately :



>
dput(iris[1:4, ]) # first four rows of the iris data
set

structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6),
Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5),
Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L),
.Label = c("setosa",
"versicolor", "virginica"), class = "factor")), .Names =
c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"),
row.names = c(NA,
4L), class =
"data.frame")


If your
data frame has a factor with many levels, the dput output can
be unwieldy because it will still list all the possible factor levels even if they
aren't present in the the subset of your data. To solve this issue, you can use the
droplevels() function. Notice below how species is a factor
with only one
level:




>
dput(droplevels(iris[1:4, ]))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7,
4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3,
1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L,
1L), .Label = "setosa",
class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width",
"Petal.Length", "Petal.Width", "Species"), row.names = c(NA,

4L), class =
"data.frame")


When
using dput, you may also want to include only relevant
columns:




>
dput(mtcars[1:3, c(2, 5, 6)]) # first three rows of columns 2, 5, and
6
structure(list(cyl = c(6, 6, 4), drat = c(3.9, 3.9, 3.85), wt = c(2.62,

2.875, 2.32)), row.names = c("Mazda RX4", "Mazda RX4 Wag", "Datsun
710"
), class =
"data.frame")


One
other caveat for dput is that it will not work for keyed
data.table objects or for grouped
tbl_df (class grouped_df) from
dplyr. In these cases you can convert back to a regular data
frame before sharing,
dput(as.data.frame(my_data)).



Worst
case scenario, you can give a text representation that can be read in using the
text parameter of read.table
:




zz <-
"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"

Data <- read.table(text=zz, header =
TRUE)



Producing
minimal code



This should be the easy part but
often isn't. What you should not do,
is:




  • add all kind of data
    conversions. Make sure the provided data is already in the correct format (unless that
    is the problem of course)

  • copy-paste a whole
    function/chunk of code that gives an error. First, try to locate which lines exactly
    result in the error. More often than not you'll find out what the problem is
    yourself.




What
you should do, is:




  • add
    which packages should be used if you use any (using
    library())

  • if you open
    connections or create files, add some code to close them or delete the files (using
    unlink())

  • if you change options,
    make sure the code contains a statement to revert them back to the original ones. (eg
    op <- par(mfrow=c(1,2)) ...some code... par(op)
    )

  • test run your code in a new, empty R session to make
    sure the code is runnable. People should be able to just copy-paste your data and your
    code in the console and get exactly the same as you
    have.




Give
extra information



In most cases, just the R
version and the operating system will suffice. When conflicts arise with packages,
giving the output of sessionInfo() can really help. When
talking about connections to other applications (be it through ODBC or anything else),
one should also provide version numbers for those, and if possible also the necessary
information on the setup.



If you are running R
in R Studio using
rstudioapi::versionInfo() can be helpful to report your RStudio
version.



If you have a problem with a specific
package you may want to provide the version of the package by giving the output of
packageVersion("name of the
package")
.



/>


1
Note: The output of set.seed()
differs between R >3.6.0 and previous versions. Do specify which R version you used
for the random process, and don't be surprised if you get slightly different results
when following old questions. To get the same result in such cases, you can use the
RNGversion()-function before
set.seed() (e.g.:
RNGversion("3.5.2")).



c - freeing memory using free()

I want to understand free() in c deallocates memory or it
simply erases the data in the allocated memory by
malloc.



#include
#include

int
main()
{
int n;
printf("enter the size of
n:\n");
scanf("%d", &n);

int*
A=(int*)malloc(5*sizeof(int));
int i;
for(i=0; i i++)
{
printf("%d\n", &A[i]);

}

free(A);


printf("\n\n-------------\n\n");


for(i=0; i i++)
{

printf("%d\n", &A[i]);

}

return
0;
}



Still
after freeing A its giving the same address of A.
What free() actually
do?

How to list the properties of a JavaScript object?

itemprop="text">

Say I create an object
thus:



var myObject =

{"ircEvent": "PRIVMSG", "method": "newURI", "regex":
"^http://.*"};


What is
the best way to retrieve a list of the property names? i.e. I would like to end up with
some variable 'keys' such
that:




keys ==
["ircEvent", "method", "regex"]


Answer




In modern browsers (IE9+, FF4+, Chrome5+,
Opera12+, Safari5+) you can use the built in href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys"
rel="noreferrer">Object.keys
method:



var keys =
Object.keys(myObject);


The
above has a full polyfill but a simplified version
is:




var getKeys =
function(obj){
var keys = [];
for(var key in obj){

keys.push(key);
}
return
keys;
}



Alternatively
replace var getKeys with
Object.prototype.keys to allow you to call
.keys() on any object. Extending the prototype has some side
effects and I wouldn't recommend doing it.



regex - How to configure htaccess file for Cake 2.3.x on 1and1 shared hosting

itemprop="text">


Using the default cakephp
htaccess file setup will not work on my domain when I want to install my Cakephp app in
a subfolder, while everything works on localhost
(xampp)



target => href="http://example.com/mycakeapp" rel="nofollow
noreferrer">http://example.com/mycakeapp



Install
needs 3 htaccess files:



root
.htaccess


#.htaccess in root



RewriteEngine on
RewriteBase /mycakeapp

RewriteRule ^$ app/webroot/ [L]
RewriteRule (.) app/webroot/$1
[L]


in app
.htaccess



RewriteEngine
on

RewriteBase /mycakeapp
RewriteRule ^$ app/webroot/
[L]
RewriteRule (.) app/ webroot/$1 [L]



in webroot .htaccess



RewriteEngine On
RewriteBase
/mycakeapp

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php
[QSA,L]



Following
cakephp documentation, and Using these htaccess files, I get error500
results.
Using RewriteBase / instead of /mycakeapp will throw 404 error
page.



php is in 5.4
version

How can I solve this?



Answer




Setup your rules like
this:



.htaccess in
DOCUMENT_ROOT



RewriteEngine
on
RewriteBase /
RewriteRule (.*) mycakeapp/$1
[L]



.htaccess
in
DOCUMENT_ROOT/mycakeapp



RewriteEngine
on
RewriteBase /mycakeapp/
RewriteRule (.*) app/webroot/$1
[L]


.htaccess
in
DOCUMENT_ROOT/mycakeapp/app




RewriteEngine
on
RewriteBase /mycakeapp/app/
RewriteRule (.*) webroot/$1
[L]


.htaccess
in
DOCUMENT_ROOT/mycakeapp/app/webroot



RewriteEngine
On
RewriteBase
/mycakeapp/app/webroot/


RewriteCond %{REQUEST_FILENAME}
!-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php
[L]

Saturday 20 January 2018

java - Adding int to short





A colleague of mine asked this question to me and I am kind of
confused.



int i =
123456;
short x =
12;


The
statement



x +=
i;


Compiles fine
however



x = x +
i;


doesn't



What
is Java doing here?


itemprop="text">
class="normal">Answer




int i = 123456;
short
x = 12;
x +=
i;


is
actually



int i =
123456;
short x = 12;
x = (short)(x +
i);


Whereas
x = x + i is simply x = x + i. It does
not automatically cast as a short and hence causes the error
(x + i is of type
int).



/>


A compound assignment
expression of the form E1 op= E2 is equivalent to
E1 = (T)((E1) op (E2)), where T is the
type of E1, except that E1 is
evaluated only once.



- href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2"
rel="noreferrer">JLS
§15.26.2




oop - Why is the clone() method protected in java.lang.Object?

itemprop="text">

What is the specific reason that href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone%28%29"
rel="noreferrer">clone() is defined as protected
in java.lang.Object?


class="post-text" itemprop="text">
class="normal">Answer



The fact
that clone is protected is extremely dubious - as is the fact that the
clone method is not declared in the
Cloneable interface.



It
makes the method pretty useless for taking copies of data because you
cannot
say
:




if(a
instanceof Cloneable) {
copy = ((Cloneable)
a).clone();
}


I
think that the design of Cloneable is now largely
regarded as a mistake
(citation below). I would normally want to be able
to make implementations of an interface Cloneable but
not necessarily make the interface
Cloneable
(similar to the use of
Serializable). This cannot be done without
reflection:



ISomething i =
...
if (i instanceof Cloneable) {

//DAMN! I Need to know
about ISomethingImpl! Unless...
copy = (ISomething)
i.getClass().getMethod("clone").invoke(i);
}




Citation From Josh Bloch's Effective Java: />"The Cloneable interface was intended as a mixin interface for objects to
advertise that they permit cloning. Unfortunately it fails to serve this purpose ...
This is a highly atypical use of interfaces and not one to be emulated ... In order for
implementing the interface to have any effect on a class, it and all of its superclasses
must obey a fairly complex, unenforceable and largely undocumented
protocol
"




javascript - Push one array into another

I have two arrays as
following.



var first =
[['2','23','33'],['2','23','33'],['2','23','33']]

var second =
['value1','value2','value3']



Now
i want to push second array into first like
this.



var first =
[['value1','value2','value3'],['2','23','33'],['2','23','33'],['2','23','33']]


Thanks
in advance

email - Why shouldn't I use PHP's mail() function?

itemprop="text">

The general opinion when it comes to
sending email messages in PHP is to stay clear of PHP's built-in
mail() function and to use a library
instead.



What I want to know are the actual
reasons and flaws in using mail() over a library or extension.
For example, the commonly specified headers that aren't included in a standard
mail() call.




Answer




href="http://www.websitebaker2.org/topics/problems-sending-mails.php"
rel="noreferrer">Quoting:





Disadvantages of the PHP mail()
function



In some cases, mails send
via
PHP mail() did not receive the

recipients although it was send by WB
without any error message. The
most

common reasons for that issue are
listed
below.




  • wrong format of
    mail header or content
    (e.g. differences in line break
    between
    Windows/Unix)

  • sendmail not
    installed or
    configured on your server
    (php.ini)



  • the mail provider of the
    recipeint does not allow mails send
    by
    PHP mail(); common spam
    protection



Errors in
the format of header or
content can cause that mails are
treated
as SPAM. In the best case,
such mails are transfered to the spam

folder of your recipient inbox or send

back to the sender. In the
worst case,
such mails are deleted without any
comment. If
sendmail is not installed
or not configured, no mails can be
send
at all.



It is common practice by free
mail
provider such as GMX, to reject mails
send via the PHP
function mail(). Very
often such mails are deleted
without

any information of the
recipient.



android - Items not removed properly from RecyclerView

itemprop="text">

I'm populating RecyclerView with
AppWidgetHostViews. They are sorted one below the other and each one of them has delete
button next to it. This is how I'm setting the RecyclerView and Adapter (event.object is
a AppWidgetHostView):



 private
List viewList = new ArrayList<>();

mAdapter =
new AppWidgetAdapter(this);

mRecycler.setLayoutManager(new
LinearLayoutManager(getActivity()));
mRecycler.setItemAnimator(new
DefaultItemAnimator());
mRecycler.setAdapter(mAdapter);

viewList.add((View) event.eventObject);

mAdapter.setData(viewList);


This
is my Adapter that holds
AppWidgetHostViews:



public class
AppWidgetAdapter extends RecyclerView.Adapter
{


private List viewList = new
ArrayList<>();
private AdapterListener
listener;

public AppWidgetAdapter(AdapterListener listener)
{
this.listener = listener;
}

public void
setData(List list) {
viewList.clear();


viewList.addAll(list);

notifyDataSetChanged();
}

@Override
public
AppWidgetHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_widget_layout,
parent, false);
return new
AppWidgetHolder(view);
}


@Override
public
void onBindViewHolder(final AppWidgetHolder holder, int position) {
final
View view = getItem(position);
holder.setView(view);

holder.setNum(String.valueOf(position));


holder.button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
int pos =
holder.getAdapterPosition();

viewList.remove(pos);

notifyItemRemoved(pos);
notifyItemRangeRemoved(pos,
viewList.size());
listener.onItemRemoved(pos);
}

});
}

private View getItem(int position) {

return !viewList.isEmpty() ? viewList.get(position) :
null;

}

@Override
public int
getItemCount() {
return
viewList.size();
}

class AppWidgetHolder extends
RecyclerView.ViewHolder {

private FrameLayout
view;

private Button button;


AppWidgetHolder(View itemView) {
super(itemView);
view =
(FrameLayout) itemView.findViewById(R.id.app_widget);
button = (Button)
itemView.findViewById(R.id.delete);

}


private void setView (View view) {

if(view.getParent() != null)
{
((ViewGroup)view.getParent()).removeView(view);
}

this.view.addView(view);
}

private void setNum (String
num) {
this.button.setText(num);

}


}


}



XML
of my ViewHolder looks like
this:



            xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="20dp">


android:layout_centerInParent="true"
android:id="@+id/delete"

android:layout_width="50dp"

android:layout_alignParentEnd="true"


android:layout_height="wrap_content"

android:layout_marginLeft="5dp"
tools:text="Del"
/>


android:layout_toStartOf="@id/delete"

android:layout_centerHorizontal="true"

android:layout_centerInParent="true"
android:id="@+id/app_widget"

android:layout_width="wrap_content"


android:layout_height="wrap_content"
android:layout_alignParentStart="true"
/>




So
inside onBindViewHolder method, I'm setting onClick listener which should remove
AppWidgetHostView in that position.. So after notifying item removed, I'm calling
listener.onItemRemoved(pos), and it's implementation in fragment looks like
this:



 @Override
public
void onItemRemoved(int position) {


viewList.remove(position);
mAdapter.setData(viewList);
}



So it again sets the
data for adapter and notifies data set
changed.



But the problem is, items aren't
properly removed when I click delete button. ViewList resizes ok, but items behave
strangely, if I add 3 items and delete second one for example, it stays on the screen
but third goes on top of it (second still visible), then, if I delete first one, it
stays, previous second one is now deleted and new second one goes on top of first one.
But if I click delete button for every item, it will delete all the views, but they will
behave strangely in that process... Any advice, hint?



Answer




Using both @Adithya and @Stanislav Bondar's
advices, I came up to solution:




This
is the onBindViewHolder method:




@Override
public void onBindViewHolder(final AppWidgetHolder holder, final int
position) {
final View view = getItem(position);

holder.setView(view);

holder.setNum(String.valueOf(position));


holder.button.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {

int pos =
holder.getAdapterPosition();
viewList.remove(pos);

listener.onItemRemoved(pos);
}

});
}



And
inside
onItemRemoved:



@Override
public
void onItemRemoved(int position) {
viewList.remove(position);

mAdapter.notifyItemRemoved(position);
}



I
had to remove the item at that position both inside adapter and fragment, because if I
had 5 items in fragment which i pass to adapter and if I remove it only in adapter, once
I pass new item again, it will send 6 items instead 5.. Maybe there is a better way, but
this did solution resolved the problem


php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...