Sunday, June 30, 2019

wordpress - Random "502 Error Bad Gateway" in Amazon Red Hat (Not Ubuntu) - Nginx + PHP-FPM

First of all, I already searched for 502 error in Stackoverflow. There are a lot a threads, but the difference this time is that the error appears without a pattern and it's not in Ubuntu.



Everything works perfectly, but about once a week my site shows: 502 Bad Gateway.
After this first error, every connection starts showing this message. Restarting MySQL + PHP-FPM + Nginx + Varnish doesn't work.



I have to clone this instance, and make another one, to get my site up again (It is hosted in Amazon EC2).



In Nginx log it shows these line again and again:




[error] 16773#0: *7034 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.0.1


There are nothing in MySQL or Varnish log. But in PHP-FPM it shows theses type of line:



WARNING: [pool www] child 18978, script '/var/www/mysite.com/index.php' (request: "GET /index.php") executing too slow (10.303579 sec), logging
WARNING: [pool www] child 18978, script '/var/www/mysite.com/index.php' (request: "GET /index.php") execution timed out (16.971086 sec), terminating



Inside PHP-FPM slowlog it was showing:



[pool www] pid 20401
script_filename = /var/www/mysite.com/index.php
w3_require_once() /var/www/mysite.com/wp-content/plugins/w3-total-cache/inc/define.php:1478


(Inside the file "define.php" at line number 1478, it has this line of code: require_once $path;)



I thought the problem was with W3 Total Cache plugin. So I removed W3 Total Cache.

About 5 days later it happened again with this error in PHP-FPM slow log:



script_filename = /var/www/mysite.com/index.php
wpcf7_load_modules() /var/www/mysite.com/wp-content/plugins/contact-form-7/includes/functions.php:283


(Inside the file "functions.php" at line number 283, it has this line of code: include_once $file;)



The other day, the first error occurred in another part:




script_filename = /var/www/mysite.com/wp-cron.php
curl_exec() /var/www/mysite.com/wp-includes/class-http.php:1510


And again a different part of code:



[pool www] pid 20509
script_filename = /var/www/mysite.com/index.php
mysql_query() /var/www/mysite.com/wp-includes/wp-db.php:1655



CPU, RAM ... everything is stable when this error occurs (less then 20% usage).



I tried everything, but nothing worked:




  • Moved to a better server (CPU and RAM)

  • Decreased timeout from Nginx, PHP-FPM, MySQL (my page loads quickly, so I decrease timeout to kill any outlier process)

  • Changed the number of PHP-FPM spare servers

  • Changed a lot of configuration from Nginx and PHP-FPM


  • I know that there is a bug with PHP-FPM and Ubuntu that could cause this error. But I don't think there is a bug with Amazon instances (Red Hat). (And I don't want to migrate from PHP-FPM to Socks because I've read that Socks don't works well under heavy load)



This was happening about every week since 5 months ago. I'm desperate.
I got to the point that I even put Nginx and PHP-FPM in Linux's crontab, to restart theses services every day. But it didn't work too.



Anyone has any suggestion where I can solve this problem? Anything will help!!



Server:




 Amazon c3.large (2 core and 3.75GB RAM)
Linux Amazon Red Hat 4.8.2 64bits


PHP-FPM:



 listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1
listen.mode = 0664
pm = ondemand

pm.max_children = 480
pm.start_servers = 140
pm.min_spare_servers =140
pm.max_spare_servers = 250
pm.max_requests = 50
request_terminate_timeout = 15s
request_slowlog_timeout = 10s
php_admin_flag[log_errors] = on



Nginx:



  worker_processes  2;
events {
worker_connections 2048;
multi_accept on;
use epoll;
}
http {
include /etc/nginx/mime.types;

default_type application/octet-stream;
access_log off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 2048;
server_tokens off;
client_max_body_size 8m;
reset_timedout_connection on;
index index.php index.html index.htm;

keepalive_timeout 1;
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
fastcgi_send_timeout 30s;
fastcgi_read_timeout 30s;
listen 127.0.0.1:8080;
location ~ .php$ {
try_files $uri =404;
include fastcgi_params;

fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_keep_conn on;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param HTTP_HOST $host;
}
}

x86 - What is the equivalant to idiv in assembly code?

I was wondering what is the equivalent of idiv in assembly. I'm trying to learn assembly and I want to learn how these operations work without using the function idiv. I'm trying to do this with signed values.

java - Take string and compare to multiple enum types all at once





I really need help here.



If I have my separate class, lets call it FileType.java, and it looks like this:



 public enum FileType

{
JPG,GIF,PNG,BMP,OTHER
}


and then I grab a string from the user, call it inputString, how can I compare "inputString" to every single enum value, with the most minimal amount of code?



EDIT: Here is what I have tried:



    System.out.print("Please enter your photo's file type. It must be: JPG, GIF, PNG, BMP, or OTHER");

typeInput = kb.nextLine();

boolean inputMatches = false;

while(inputMatches == false)
{
System.out.print("Invalid input. Please enter your photo's file type. It must be: JPG, GIF, PNG, BMP, or OTHER");

if(typeInput.equalsIgnoreCase(FileType.values()))
{

inputMatches = true;
}
}


Ps. I am well aware that I can just set individual variables to equal the same strings as the enum values. I;m also aware that I could use .valueOf() for every single value.


Answer



You can convert input to enum instead



System.out.print("Please enter your photo's file type. It must be: JPG, GIF, PNG, BMP, or OTHER");

boolean typeInput = kb.nextLine();

inputMatches = true;
try{
FileType fileType = FileType.valueOf(inputString.toUpperCase().trim());
}catch (IllegalArgumentException e) {
inputMatches = false;
}

Difference between & and && in PHP




I am confused with & and &&. I have two PHP books. One says that they are same, but the another says they are different. I thought they are same as well.



Aren't they same?


Answer



& is bitwise AND. See Bitwise Operators. Assuming you do 14 & 7:



    14 = 1110
7 = 0111
---------

14 & 7 = 0110 = 6


&& is logical AND. See Logical Operators. Consider this truth table:



 $a     $b     $a && $b
false false false
false true false
true false false
true true true


mysql - SQL data in one field separated by coma










I have three tables items, sizes and item_sizes for many to many relationship with join i can query this:




item     size
shirt L
shirt XL
dress S
dress L
dress XL


But i want this:




item     size
shirt L, XL
dress S, L, XL


Speed doesn't matter i want only the results.I can do it with while loop but is there another way of doing this query?


Answer



select item, group_concat(size)
from the_table
group by item;



More details in the manual: http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat


incompatible types required: int found: java.lang.String (basic programming)



I have come across this error a few times, and I try many things to fix it, but I can't seem to find out what is going wrong. here is the code:




import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
String name1 = scan.nextLine();
String name2 = scan.nextLine();
int num1 = scan.nextLine();
double num2 = scan.nextLine();


System.out.println("Employee Name:" + name2 + name1);
System.out.println("Age:" + num1);
System.out.println("Salary:" + (double)num2);
}
}


And the error that shows up specicfically is:





[File: /InputExample.java Line: 9, Column: 25] incompatible types required: int found: java.lang.String



[File: /InputExample.java Line: 10, Column: 28] incompatible types required: double found: java.lang.String



Answer



You're reading in a String, but want to save it as Integer/Double. Try this:



int num1 = Integer.valueOf(scan.nextLine());



Same goes for Double.



Or as OldCurmudgeon mentioned:



int num1 = scan.nextInt();

c++ - Why emplace_back is faster than push_back?



I thought that emplace_back would be the winner, when doing something like this:




v.push_back(myClass(arg1, arg2));


because emplace_back would construct the object immediately in the vector, while push_back, would first construct an anonymous object and then would copy it to the vector. For more see this question.



Google also gives this and this questions.



I decided to compare them for a vector that would be filled by integers.




Here is the experiment code:



#include 
#include
#include
#include
#include

using namespace std;
using namespace std::chrono;


int main() {

vector v1;

const size_t N = 100000000;

high_resolution_clock::time_point t1 = high_resolution_clock::now();
for(size_t i = 0; i < N; ++i)
v1.push_back(i);

high_resolution_clock::time_point t2 = high_resolution_clock::now();

duration time_span = duration_cast>(t2 - t1);

std::cout << "push_back took me " << time_span.count() << " seconds.";
std::cout << std::endl;

vector v2;

t1 = high_resolution_clock::now();

for(size_t i = 0; i < N; ++i)
v2.emplace_back(i);
t2 = high_resolution_clock::now();
time_span = duration_cast>(t2 - t1);
std::cout << "emplace_back took me " << time_span.count() << " seconds.";
std::cout << std::endl;

return 0;
}



The result is that emplace_back is faster.



push_back took me 2.76127 seconds.
emplace_back took me 1.99151 seconds.


Why? The answer of the 1st linked question clearly says that there will be no performance difference.



Also tried with other time methods, but got identical results.




[EDIT]
Comments say that testing with ints doesn't say anything and that push_back takes a ref.



I did the same test in the code above, but instead of int I had a class A:



class A {
public:
A(int a) : a(a) {}
private:

int a;
};


Result:



push_back took me 6.92313 seconds.
emplace_back took me 6.1815 seconds.



[EDIT.2]



As denlan said, I should also change the position of the operations, so I swapped them and in both situation (int and class A), emplace_back was again the winner.



[SOLUTION]



I was running the code in debug mode, which makes the measurements invalid. For benchmarking, always run the code in release mode.


Answer



Your test case isn't very helpful. push_back takes a container element and copies/moves it into the container. emplace_back takes arbitrary arguments and constructs from those a new container element. But if you pass a single argument that's already of element type to emplace_back, you'll just use the copy/move constructor anyway.




Here's a better comparison:



Foo x; Bar y; Zip z;

v.push_back(T(x, y, z)); // make temporary, push it back
v.emplace_back(x, y, z); // no temporary, directly construct T(x, y, z) in place


The key difference, however, is that emplace_back performs explicit conversions:




std::vector> v;
v.emplace_back(new Foo(1, 'x', true)); // constructor is explicit!


This example will be mildly contrived in the future, when you should say v.push_back(std::make_unique(1, 'x', true)). However, other constructions are very nice with emplace, too:



std::vector threads;
threads.emplace_back(do_work, 10, "foo"); // call do_work(10, "foo")
threads.emplace_back(&Foo::g, x, 20, false); // call x.g(20, false)


sed awk replace lines with a pattern match



With awk or sed how could I replace each line after a pattern match?

the pattern would always start as S:\ and something else,
I need the entire line from S:\~ to the end to appear on the next lines before a blank line.



I have an input like this:



S:\dir1\subfolder1longsubf
abcdefg
1234567
permissions


S:\dir2\verylongsub
some random string
some random string

S:\dir3
some random string
some random string

S:\dir4\sub2\sub3
some random string

some random string
some random string


and I need an ouput like this:



S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf


S:\dir2\verylongsub
S:\dir2\verylongsub
S:\dir2\verylongsub

S:\dir3
S:\dir3
S:\dir3

S:\dir4\sub2\sub3

S:\dir4\sub2\sub3
S:\dir4\sub2\sub3
S:\dir4\sub2\sub3

Answer



I would use awk:



awk '/^S/ {line=$0} {print NF?line:""}' file



This stores the line starting with S. Then, it prints either this stored value or an empty line if the line is empty.



Test



$ awk '/^S/ {line=$0} {print NF?line:""}' file
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf
S:\dir1\subfolder1longsubf


S:\dir2\verylongsub
S:\dir2\verylongsub
S:\dir2\verylongsub

S:\dir3
S:\dir3
S:\dir3

S:\dir4\sub2\sub3
S:\dir4\sub2\sub3

S:\dir4\sub2\sub3
S:\dir4\sub2\sub3

PHP HTML DOM Parser






Possible Duplicate:
How to parse and process HTML with PHP?






I'm looking into HTML DOM parsers for PHP. I've found PHP Simple HTML DOM Parser. Are there any others I should be looking at?


Answer



Yes. Simple html doc is fine, but an order of magnitude slower than the built in dom parser.




$dom = new DOMDocument();
@$dom->loadHTML($html);
$x = new DOMXPath($dom);

foreach($x->query("//a") as $node)
{
$data['dom']['href'][] = $node->getAttribute("href");
}



Use that.


Swing text components fail to paste large text data from clipboard: java.io.IOException: Owner failed to convert data

I am working with a JTextArea directly and via JTextComponent interface attempting to paste text data from outside the swing-based app (notepad) into the app.



Using two different methods (shown below) I seem to be getting the same result for large amounts of text data. It works fine as long as I stick to small amounts (<25k) but pasting in a white-list of domains around 1.5MB seems to cause the IOException. I have seen a number of articles for various apps around the net referring to it being a bug in the 1.6 JVM. I'm currently using jdk1.7.0_25 and I'm wondering if anyone knows a resolution or workaround???



I'm also open to the possibility that I'm going about this thing the wrong way entirely...




code:



@Override
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
log.debug("Running {}",cmd);

if (cmd.equals("copy")){
this.component.copy();

} else if (cmd.equals("paste")){

// Simple paste -- but large data doesnt paste
this.component.paste();

} else {
log.warn("No handler for {}", cmd);
}
}




also tried:



Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable t = c.getContents(this);
if (t == null)
return;
try {

component.setText((String) t.getTransferData(DataFlavor.stringFlavor));
} catch (Exception e){
e.printStackTrace();
}



Exception:





11:35:21.030 [AWT-EventQueue-0] DEBUG c.a.y.a.c.e.CopyPasteMouseListener - Running paste
java.io.IOException: Owner failed to convert data
at sun.awt.X11.XSelection.validateDataGetter(XSelection.java:444)
at sun.awt.X11.XSelection.getData(XSelection.java:378)
at sun.awt.X11.XClipboard.getClipboardData(XClipboard.java:120)
at sun.awt.datatransfer.ClipboardTransferable.fetchOneFlavor(ClipboardTransferable.java:118)
at sun.awt.datatransfer.ClipboardTransferable.(ClipboardTransferable.java:97)
at sun.awt.X11.XClipboard.getContents(XClipboard.java:106)
at com.adjuggler.yorick.ajentconsole.console.editors.CopyPasteMouseListener.actionPerformed(CopyPasteMouseListener.java:75)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)

at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)

at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:154)
at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:182)
at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:221)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:219)
at java.awt.Dialog.show(Dialog.java:1082)
at java.awt.Component.show(Component.java:1651)

at java.awt.Component.setVisible(Component.java:1603)
at java.awt.Window.setVisible(Window.java:1014)
at java.awt.Dialog.setVisible(Dialog.java:1005)
at com.adjuggler.yorick.ajentconsole.console.editors.ConfigBox$4.actionPerformed(ConfigBox.java:183)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)

at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)

at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:154)
at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:182)
at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:221)
at java.security.AccessController.doPrivileged(Native Method)

at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:219)
at java.awt.Dialog.show(Dialog.java:1082)
at java.awt.Component.show(Component.java:1651)
at java.awt.Component.setVisible(Component.java:1603)
at java.awt.Window.setVisible(Window.java:1014)
at java.awt.Dialog.setVisible(Dialog.java:1005)
at com.adjuggler.yorick.ajentconsole.console.Console.doSettingsButton(Console.java:1510)
at com.adjuggler.yorick.ajentconsole.console.Console.actionPerformed(Console.java:716)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)

at java.security.AccessController.doPrivileged(Native Method)
at >java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at >java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at >java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)


== Update ==



Additional testing seems to indicate that this only occurs on Linux operating systems (which I use for dev) but it seems to operate on windows (which I don't use).

linked list - Template error : undefined reference




I am trying to create a class linkedList using template but when I compile it the IDE gives an error :
undefined reference to `listType::add(int)
I am not understanding why ?



linkedList.h



#ifndef LINKEDLISTS_H_INCLUDED
#define LINKEDLISTS_H_INCLUDED
#include "struct.h"
template


class listType
{
public:

void add(type1);
void print();
private:
node *head;
};



#endif // LINKEDLISTS_H_INCLUDED





LinkedList.cpp



#include "linkedLists.h"

#include "struct.h"
#include
using namespace std;

template
void listType::add(type1 temp)
{
node *t;
t->value=temp;
t->link=head;

head=t;
}
template
void listType::print()
{
node *p;
p=head;
while(p!=NULL)
{


cout<value< p=p->link;
}

}





Struct.h




#ifndef STRUCT_H_INCLUDED
#define STRUCT_H_INCLUDED
template

struct node
{

type1 value;
node *link;

};


#endif // STRUCT_H_INCLUDED





main.cpp




#include 
#include "linkedLists.h"
using namespace std;


int main()
{
listType test;
test.add(5);


}




Answer



You can't have the implementation of templated classes and functions in the cpp file.



The code has to be in the header, so the including files can see the implementation, and instantiate the correct version with their template argument type.


How do I get the current username in .NET using C#?



How do I get the current username in .NET using C#?


Answer



string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

Parsing JSON File Java




I want to parse a JSON file in java and get the following values from the file mentioned below:



{
"status": "OK",
"origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"rows": [ {
"elements": [ {

"status": "OK",
"duration": {
"value": 340110,
"text": "3 jours 22 heures"
},
"distance": {
"value": 1734542,
"text": "1 735 km"
}
}, {

"status": "OK",
"duration": {
"value": 24487,
"text": "6 heures 48 minutes"
},
"distance": {
"value": 129324,
"text": "129 km"
}
} ]

}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 288834,
"text": "3 jours 8 heures"
},
"distance": {
"value": 1489604,
"text": "1 490 km"

}
}, {
"status": "OK",
"duration": {
"value": 14388,
"text": "4 heures 0 minutes"
},
"distance": {
"value": 135822,
"text": "136 km"

}
} ]
} ]
}


From every element, i want to get the value field of both distance and duration. How do i do this?


Answer



Using the json.org reference implementation (org.json homepage, Download here). The code is a bit messy but I think it does what you are asking for. You can take alot of shortcuts by not creating all this objects but to access them directly. The reason that I do it this way is an attempt to make it easier to follow whats happening.




package com.mypackage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Main {
public static void main(String[] args) {
String jsonStr = "{\"status\": \"OK\",\"origin_addresses\": [ \"Vancouver, BC, Canada\", \"Seattle, État de Washington, États-Unis\" ],\"destination_addresses\": [ \"San Francisco, Californie, États-Unis\", \"Victoria, BC, Canada\" ],\"rows\": [ {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 340110,\"text\": \"3 jours 22 heures\"},\"distance\": {\"value\": 1734542,\"text\": \"1 735 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 24487,\"text\": \"6 heures 48 minutes\"},\"distance\": {\"value\": 129324,\"text\": \"129 km\"}} ]}, {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 288834,\"text\": \"3 jours 8 heures\"},\"distance\": {\"value\": 1489604,\"text\": \"1 490 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 14388,\"text\": \"4 heures 0 minutes\"},\"distance\": {\"value\": 135822,\"text\": \"136 km\"}} ]} ]}";


try {
JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("rows"); // Get all JSONArray rows

for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject row = rows.getJSONObject(i); // Get row object
JSONArray elements = row.getJSONArray("elements"); // Get all elements for each row as an array

for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array
JSONObject element = elements.getJSONObject(j); // Get the element object

JSONObject duration = element.getJSONObject("duration"); // Get duration sub object
JSONObject distance = element.getJSONObject("distance"); // Get distance sub object

System.out.println("Duration: " + duration.getInt("value")); // Print int value
System.out.println("Distance: " + distance.getInt("value")); // Print int value
}
}
} catch (JSONException e) {
// JSON Parsing error
e.printStackTrace();

}
}
}

plot explanation - What is the meaning of the blue lettering on the board from Cabin in the Woods?

On the board of all the monsters in The Cabin in the Woods what does the blue lettering mean written next to the Monster's name?


The board


Answer


Blue letters represent the group which bid on the monster. Do you remember the scene at the start of the movie where they start collecting money from the people working ? That's what the money is for.


For example in the movie The Redneck Torture family was chosen by the characters. The Maintenance team bet on that before the group spends their night at the cabin. Oh I forgot the intern chips in too on that same bet as well.


Saturday, June 29, 2019

javascript - getElementById() work in html file but not in js file




i cannot find answer to my question in someone else post so here it is:
getElementById return null in java script file (also while testing in console) but work in html file



HTML file







Title






Some text








JS file



var title = document.getElementById('stuff');
console.log(title);
title.style.color = "#D4F34A";

Answer




You can add a callback function for the document event DOMContentLoaded event like so, and inside that function do your desired code:



//Add this into your script file, and anything you want to have execute once the document
//is fully loaded go inside of the function
document.addEventListener("DOMContentLoaded", function(event) {
var title = document.getElementById('stuff');
console.log(title);
title.style.color = "#D4F34A";
});


php - Syntax error on return statement




I'm doing this simple website, and I have run into this error:



My function:




function user_exists($username)
{
$username = sanitize($username);
$query = mysqli_query($connect, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysqli_result($query, === 0) 1) ? true : false;
}
?>



My php error log:



PHP Parse error:  
syntax error, unexpected '===' (T_IS_IDENTICAL) in function on line 6


Line 6 is the return line.



I understand what a syntax error means, but I'm quite sure that the '===' is not the problem.


Answer




Edit : I was only talking about the ternary condition and this answer is false because the mysqli_result() function doesn't exist.



I guess you are trying to do this :



return mysqli_result($query) === 0 ? false : true;


And as Marcel Korpel said, use prepared statements to avoid security flaws.


Swift Beta performance: sorting arrays



I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:



let n = 1000000
var x = [Int](repeating: 0, count: n)
for i in 0.. x[i] = random()
}
// start clock here

let y = sort(x)
// stop clock here


In C++, a similar operation takes 0.06s on my computer.



In Python, it takes 0.6s (no tricks, just y = sorted(x) for a list of integers).



In Swift it takes 6s if I compile it with the following command:




xcrun swift -O3 -sdk `xcrun --show-sdk-path --sdk macosx`


And it takes as much as 88s if I compile it with the following command:



xcrun swift -O0 -sdk `xcrun --show-sdk-path --sdk macosx`


Timings in Xcode with "Release" vs. "Debug" builds are similar.




What is wrong here? I could understand some performance loss in comparison with C++, but not a 10-fold slowdown in comparison with pure Python.






Edit: weather noticed that changing -O3 to -Ofast makes this code run almost as fast as the C++ version! However, -Ofast changes the semantics of the language a lot — in my testing, it disabled the checks for integer overflows and array indexing overflows. For example, with -Ofast the following Swift code runs silently without crashing (and prints out some garbage):



let n = 10000000
print(n*n*n*n*n)
let x = [Int](repeating: 10, count: n)
print(x[n])



So -Ofast is not what we want; the whole point of Swift is that we have the safety nets in place. Of course, the safety nets have some impact on the performance, but they should not make the programs 100 times slower. Remember that Java already checks for array bounds, and in typical cases, the slowdown is by a factor much less than 2. And in Clang and GCC we have got -ftrapv for checking (signed) integer overflows, and it is not that slow, either.



Hence the question: how can we get reasonable performance in Swift without losing the safety nets?






Edit 2: I did some more benchmarking, with very simple loops along the lines of




for i in 0..    x[i] = x[i] ^ 12345678
}


(Here the xor operation is there just so that I can more easily find the relevant loop in the assembly code. I tried to pick an operation that is easy to spot but also "harmless" in the sense that it should not require any checks related to integer overflows.)



Again, there was a huge difference in the performance between -O3 and -Ofast. So I had a look at the assembly code:





  • With -Ofast I get pretty much what I would expect. The relevant part is a loop with 5 machine language instructions.


  • With -O3 I get something that was beyond my wildest imagination. The inner loop spans 88 lines of assembly code. I did not try to understand all of it, but the most suspicious parts are 13 invocations of "callq _swift_retain" and another 13 invocations of "callq _swift_release". That is, 26 subroutine calls in the inner loop!







Edit 3: In comments, Ferruccio asked for benchmarks that are fair in the sense that they do not rely on built-in functions (e.g. sort). I think the following program is a fairly good example:



let n = 10000
var x = [Int](repeating: 1, count: n)

for i in 0.. for j in 0.. x[i] = x[j]
}
}


There is no arithmetic, so we do not need to worry about integer overflows. The only thing that we do is just lots of array references. And the results are here—Swift -O3 loses by a factor almost 500 in comparison with -Ofast:





  • C++ -O3: 0.05 s

  • C++ -O0: 0.4 s

  • Java: 0.2 s

  • Python with PyPy: 0.5 s

  • Python: 12 s

  • Swift -Ofast: 0.05 s

  • Swift -O3: 23 s

  • Swift -O0: 443 s




(If you are concerned that the compiler might optimize out the pointless loops entirely, you can change it to e.g. x[i] ^= x[j], and add a print statement that outputs x[0]. This does not change anything; the timings will be very similar.)



And yes, here the Python implementation was a stupid pure Python implementation with a list of ints and nested for loops. It should be much slower than unoptimized Swift. Something seems to be seriously broken with Swift and array indexing.






Edit 4: These issues (as well as some other performance issues) seems to have been fixed in Xcode 6 beta 5.



For sorting, I now have the following timings:





  • clang++ -O3: 0.06 s

  • swiftc -Ofast: 0.1 s

  • swiftc -O: 0.1 s

  • swiftc: 4 s



For nested loops:





  • clang++ -O3: 0.06 s

  • swiftc -Ofast: 0.3 s

  • swiftc -O: 0.4 s

  • swiftc: 540 s



It seems that there is no reason anymore to use the unsafe -Ofast (a.k.a. -Ounchecked); plain -O produces equally good code.


Answer



tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].







Here is an in-place quicksort in Swift Beta:



func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start

var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}

var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}



And the same in C:



void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {

if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;

*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}


Both work:



var a_swift:CInt[] = [0,5,2,8,1234,-1,2]

var a_c:CInt[] = [0,5,2,8,1234,-1,2]

quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))

// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]


Both are called in the same program as written.




var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}

let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)

let swift_stop:UInt64 = mach_absolute_time();

let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();


This converts the absolute times to seconds:



static const uint64_t NANOS_PER_USEC = 1000ULL;

static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;

mach_timebase_info_data_t timebase_info;

uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;

}

double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}


Here is a summary of the compiler's optimazation levels:



[-Onone] no optimizations, the default for debug.

[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.


Time in seconds with [-Onone] for n=10_000:



Swift:            0.895296452
C: 0.001223848



Here is Swift's builtin sort() for n=10_000:



Swift_builtin:    0.77865783


Here is [-O] for n=10_000:



Swift:            0.045478346
C: 0.000784666
Swift_builtin: 0.032513488



As you can see, Swift's performance improved by a factor of 20.



As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:



Swift:            0.000706745
C: 0.000742374
Swift_builtin: 0.000603576



And for n=1_000_000:



Swift:            0.107111846
C: 0.114957179
Swift_sort: 0.092688548


For comparison, this is with [-Onone] for n=1_000_000:




Swift:            142.659763258
C: 0.162065333
Swift_sort: 114.095478272


So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.



It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:





A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.




They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.



BETA 3 UPDATE:



n=10_000 with [-O]:



Swift:            0.019697268

C: 0.000718064
Swift_sort: 0.002094721


Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.



FINAL UPDATE:



[-Onone]:




Swift:   0.678056695
C: 0.000973914


[-O]:



Swift:   0.001158492
C: 0.001192406



[-Ounchecked]:



Swift:   0.000827764
C: 0.001078914

How are C++ array members handled in copy control functions?




This is something I have wondered for a long time. Take the following example:



struct matrix
{
float data[16];
};


I know what the default constructor and destructor do in this specific example (nothing), but what about the copy constructor and the copy assignment operator?




struct matrix
{
float data[16];

// automatically generated copy constructor
matrix(const matrix& that) : // What happens here?
{
// (or here?)
}


// automatically generated copy assignment operator
matrix& operator=(const matrix& that)
{
// What happens here?

return *this;
}
};



Does it involve std::copy or std::uninitialized_copy or memcpy or memmove or what?


Answer



This is what the standard says in 12.8 (Copying class objects). Copy construction:




Each subobject is copied in the manner appropriate to its type:




  • if the subobject is of class type, the copy constructor for the class is used;

  • if the subobject is an array, each element is copied, in the manner appropriate to the element type;


  • if the subobject is of scalar type, the built-in assignment operator is used.




Copy assignment:




Each subobject is assigned in the manner appropriate to its type:





  • if the subobject is of class type, the copy assignment operator for the class is used (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);

  • if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

  • if the subobject is of scalar type, the built-in assignment operator is used.



java - Iterating over hashmap

The 'Map' data structure isn't a Collection object but Sets are.


The most common method to iterate over a Map is using the underlying .entrySet method.


// For each loop
for ( Entry entry : names ) {
System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
}
// Iterator
Iterator iterator = names.entrySet().iterator
while( iterator.hasNext() ){
Entry entry = iterator.next()
System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
}

If are interested in finding the total number of Map nodes, use the .size() method.


EDIT:


Since you want the total size of each list stored within the map, you could do something like this.


Iterator iterator = names.entrySet().iterator
int count = 0;
while( iterator.hasNext() ){
Entry entry = iterator.next()
count += entry.getValue().size()
}

java - How do I break from the main/outer loop in a double/nested loop?





If I have loop in a loop and once an if statement is satisfied I want to break main loop, how am I supposed to do that?



This is my code:



for (int d = 0; d < amountOfNeighbors; d++) {

for (int c = 0; c < myArray.size(); c++) {
if (graph.isEdge(listOfNeighbors.get(d), c)) {
if (keyFromValue(c).equals(goalWord)) { // Once this is true I want to break main loop.
System.out.println("We got to GOAL! It is "+ keyFromValue(c));
break; // This breaks the second loop, not the main one.
}
}
}
}


Answer



Using a labeled break:



mainloop:
for(){
for(){
if (some condition){
break mainloop;
}
}

}





Also See




iphone - Why is `&` (ampersand) put in front of some method parameters?



I'ver wondered, why is it that in front of an NSError, such as below, do we put: &error and not error?



E.g.




NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];


Hope you can explain, also is this always the way or only in certain situations this is needed? Thanks.


Answer



You need to take the address of error because the function needs to modify it. error is passed by pointer, so you need the "take address" operator & for it.



C and Objective-C pass parameters by value. If you pass error without an ampersand and the method that you call modifies it, your function that made the call would not see any changes, because the method would operate on its local copy of NSError*.




You know that you need an ampersand in front of the corresponding parameter if you look at the signature of the method and see ** there:



- (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error
// ^ one ^^ two

What is the Android UiThread (UI thread)




Can someone explain to me what exactly the UI thread is?
On developer.android.com it says about the runOnUiThread function




public final void runOnUiThread (Runnable action)



Since: API Level 1 Runs the specified action on the UI thread. If the
current thread is the UI thread, then the action is executed
immediately. If the current thread is not the UI thread, the action is
posted to the event queue of the UI thread.





Does the UI thread mean that this will be run everytime the activity is pushed the the background by some ui activity like incoming call or screen dimming etc.? If not, what exactly does the UI thread include ?



Thank you


Answer



The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.



For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread.




For more info on your application's Processes and Threads click here.



When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.



For more info on spawning worker threads and updating the UI from them click here



I personally only use the runOnUiThread method in my Instrumentation Tests. Since the test code does not execute in the UIThread, you need to use this method to run code that modifies the UI. So, I use it to inject click and key events into my application. I can then check the state of the application to make sure the correct things happened.



For more info on testing and running code on the UIThread click here


linux - How to run a shell script on a Unix console or Mac terminal?



I know it, forget it and relearn it again. Time to write it down.


Answer



To run a non-executable sh script, use:



sh myscript



To run a non-executable bash script, use:



bash myscript


To start an executable (which is any file with executable permission); you just specify it by its path:



/foo/bar
/bin/bar

./bar


To make a script executable, give it the necessary permission:



chmod +x bar
./bar


When a file is executable, the kernel is responsible for figuring out how to execte it. For non-binaries, this is done by looking at the first line of the file. It should contain a hashbang:




#! /usr/bin/env bash


The hashbang tells the kernel what program to run (in this case the command /usr/bin/env is ran with the argument bash). Then, the script is passed to the program (as second argument) along with all the arguments you gave the script as subsequent arguments.



That means every script that is executable should have a hashbang. If it doesn't, you're not telling the kernel what it is, and therefore the kernel doesn't know what program to use to interprete it. It could be bash, perl, python, sh, or something else. (In reality, the kernel will often use the user's default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh and bash).






Most commonly, you'll see hash bangs like so:



#!/bin/bash


The result is that the kernel will run the program /bin/bash to interpret the script. Unfortunately, bash is not always shipped by default, and it is not always available in /bin. While on Linux machines it usually is, there are a range of other POSIX machines where bash ships in various locations, such as /usr/xpg/bin/bash or /usr/local/bin/bash.



To write a portable bash script, we can therefore not rely on hard-coding the location of the bash program. POSIX already has a mechanism for dealing with that: PATH. The idea is that you install your programs in one of the directories that are in PATH and the system should be able to find your program when you want to run it by name.



Sadly, you cannot just do this:




#!bash


The kernel won't (some might) do a PATH search for you. There is a program that can do a PATH search for you, though, it's called env. Luckily, nearly all systems have an env program installed in /usr/bin. So we start env using a hardcoded path, which then does a PATH search for bash and runs it so that it can interpret your script:



#!/usr/bin/env bash


This approach has one downside: According to POSIX, the hashbang can have one argument. In this case, we use bash as the argument to the env program. That means we have no space left to pass arguments to bash. So there's no way to convert something like #!/bin/bash -exu to this scheme. You'll have to put set -exu after the hashbang instead.




This approach also has another advantage: Some systems may ship with a /bin/bash, but the user may not like it, may find it's buggy or outdated, and may have installed his own bash somewhere else. This is often the case on OS X (Macs) where Apple ships an outdated /bin/bash and users install an up-to-date /usr/local/bin/bash using something like Homebrew. When you use the env approach which does a PATH search, you take the user's preference into account and use his preferred bash over the one his system shipped with.


php - What is the difference between public, private, and protected?



When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?




Examples:



// Public
public $variable;
public function doSomething() {
// ...
}

// Private
private $variable;

private function doSomething() {
// ...
}

// Protected
protected $variable;
protected function doSomething() {
// ...
}


Answer



You use:




  • public scope to make that property/method available from anywhere, other classes and instances of the object.


  • private scope when you want your property/method to be visible in its own class only.


  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.




More: (For comprehensive information)





Let or Var in modern javascript?

"Let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope." - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let



Which one should be used in modern javascript code? let or var?



Edit:
I checked the Google JavaScript Style Guide and it states "Declarations with var: Always" (https://google.github.io/styleguide/javascriptguide.xml)




But in the tutorial at javascript.info (not sure if this is an official JavaScript website or not) it says to use let (https://javascript.info/variables)



I'm assuming I should stick to what Google recommends, but am still open to answers.



Second Edit: The above is not the most recent Google JavaScript Style Guide. In that one it states: "Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used".(https://google.github.io/styleguide/jsguide.html#features-local-variable-declarations)

multithreading - Android: Toast in a thread




How can I display Toast messages from a thread?


Answer



You can do it by calling an Activity's runOnUiThread method from your thread:



activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});


email - Outlook 2010 VBA Task with attachments

Outlook 2010 VBA, I want to create a task when send an email, but I want to add to the task all the attachments from the email, the code works good but It not add the attachment, I try to use .Attachments.Add (is not supported), .Attachments = item.Attachments return propierty is read only



it is possible? or how can I attach the hole email to the task?



thx



here is the code




Public WithEvents myOlApp As Outlook.Application



Private Sub Application_MAPILogonComplete()



End Sub



Private Sub Application_Startup()
Initialize_handler
End Sub




Public Sub Initialize_handler()
Set myOlApp = CreateObject("Outlook.Application")
End Sub



Private Sub myOlApp_ItemSend(ByVal item As Object, Cancel As Boolean)



Dim intRes As Integer
Dim strMsg As String
Dim objTask As TaskItem

Set objTask = Application.CreateItem(olTaskItem)
Dim strRecip As String
Dim att As MailItem
Dim objMail As Outlook.MailItem



strMsg = "Do you want to create a task for this message?"
intRes = MsgBox(strMsg, vbYesNo + vbExclamation, "Create Task")



If intRes = vbNo Then
Cancel = False

Else

For Each Recipient In item.Recipients
strRecip = strRecip & vbCrLf & Recipient.Address
Next Recipient



With objTask
'.Body = strRecip & vbCrLf & Item.Body

.Body = item.Body
.Subject = item.Subject
.StartDate = item.ReceivedTime
.ReminderSet = True
.ReminderTime = DateSerial(Year(Now), Month(Now), Day(Now + 1)) + #8:00:00 AM#
**.Attachments.Add (item.Attachments)**
.Save
End With

Cancel = False


End If


Set objTask = Nothing



End Sub

c++ - Using namespace std vs other alternatives




using namespace std;


So far in my computer science courses, this is all we have been told to do. Not only that, but it's all that we have been allowed to do, otherwise we get penalized on our code. I understand, through looking at code posted online, that you can use ::std or std:: to accomplish the same thing.



My question is generall why? Obviously for the sake of learners and simplicity using the global declaration is simpler, but what are the draw backs? Is it more realistic to expect ::std in a real world application? And I guess to add on to this, what is the logic/concept behind the using declaration? None of this has been explained during my courses, and I'd like to get a better grasp on it.



As a general question: if I haven't been taught this content, vectors, templates, classes, or error handling does it seem like I'm missing a lot of essential C++ functionality?




Thanks in advance!


Answer



This is really one of those things that you can discuss over beer for hours and hours, and still not have an answer everyone is happy with.



If you are nearly always using std:: functionality, then adding using namespace std; at the beginning of the file is not that bad an idea. On the other hand, if you are using things from more than one namespace (e.g. writing a compiler using llvm:: and also using std::, it may get confusing as to which parts are part of llvm and which parts are std:: - so in my compilter project, I don't have a single file with using namespace ...; - instead I write out llvm:: and std:: as needed. There are several functions (unwisely, perhaps) called Type(), and some places use something->Type()->Type() to get the type-thing that I need... Yes, it confuses even me a little at times...



I also have many things that look like Constants::ConstDecl and Token::RightParen, so that I can quickly see "what is what". All of these COULD be made shorter and "simpler", but I prefer to see where things belong most of the time.



Being more verbose helps making it easier to see where things belong - but it makes for more typing and more reading, so it is a balance.


Friday, June 28, 2019

Warning: Cannot modify header information - headers already sent when using ChromePhp.php

Answer


Answer





I wish to peek into my PHP code to see what is going on to help me rectify some issues. The PHP code is for processing the data from a form. I have tried Chrome Logger http://craig.is/writing/chrome-logger but I can't get it to send me any messages to the browser consloe.




I have built a simple test case:



file ChromeLoggerTest.html






Hi from ChromeLoggerTest.html







file ChromeLoggerTest.php



include 'ChromePhp.php';
$theDate = date("l jS \of F Y h:i:s A");
ChromePhp::log("Hello console using ChromePhp::log from ChromeLoggerTest.php. The date is: $theDate");
ChromePhp::warn("Hello console using ChromePhp::warn from ChromeLoggerTest.php. The date is: $theDate");

echo "

Hello Browser from ChromeLoggerTest.php. Welcome to my php file to test Chrome Logger. The date is $theDate

";
?>


If I type ChromeLoggerTest.html into the browser address bar I obtain in the browser window:




Warning: Cannot modify header information - headers already sent by (output started at /home/d50364/public_html/ChromeLoggerTest.html:3) in /home/d50364/public_html/scripts/ChromePhp.php on line 394



Warning: Cannot modify header information - headers already sent by (output started at /home/d50364/public_html/ChromeLoggerTest.html:3) in /home/d50364/public_html/scripts/ChromePhp.php on line 394

Hello Browser from ChromeLoggerTest.php. Welcome to my php file to test Chrome Logger. The date is Thursday 13th of November 2014 12:35:07 PM



Hi from ChromeLoggerTest.html




There is no output in the console. If I comment out the ChromePhp lines in the PHP file then the errors go away but I do not get any output in the console.



If I type scripts/ ChromeLoggerTest.php into the brwoser address bar I obtain in the browser window and browser console:



Browser:





Hello Browser from ChromeLoggerTest.php. Welcome to my php file to test Chrome Logger. The date is Thursday 13th of November 2014 12:47:13 PM




Browser console:




Hello console using ChromePhp::log from ChromeLoggerTest.php. The date is: Thursday 13th of November 2014 12:47:13 PM
Hello console using ChromePhp::warn from ChromeLoggerTest.php. The date is: Thursday 13th of November 2014 12:47:13 PM





Reading on Stackoverflow there are suggestions about using ob_start(); and ob_flush(); these have not solved my problem.



There are also suggestions that the issue might be caused by whitespace in the files. I have edited them to a single line each and this has not solved my problem.



I have verified that the files are saved without BOM.



Some relevant links:




Warning: Cannot modify header information - headers already sent by ERROR



How to fix "Headers already sent" error in PHP



https://www.geeklog.net/faqman/index.php?op=view&t=38



Setting Up ChromePhp For Wordpress Using Xampp



https://wordpress.org/support/topic/error-cannot-modify-header-information-2




https://github.com/ccampbell/chromephp/issues/15



https://github.com/ccampbell/chromephp



Thank you for taking the time to read this. Any assistance gratefully received.


Answer



Move this: before your because the the new line and the are outputs.


php - how to use Chtml::DropDownList()



i'm currently a newbie when it comes to the yii framework / php. I would like some assistance creating this Chtml::DropDownList.



http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail



Chtml::dropDownList($name, $select, $data)



I understand that $data is the array of data I will be loading in from my Database.



But can someone explain to me how $name, and $select truly works. I have a hard time finding documentation that explains this at a extremely dumbdown level.



I manage to get this piece of code working, but I would prefer using Chtml::dropdownlist.




echo $form->dropDownList($model, 'id',

Chtml::listData(UsersTeam::model()->findAllByAttributes(array('coachId'=>$model->id)), 'id', 'teamName'),
array('empty'=>'Select Team'))
?>



I would like to be able to display all teamName for the current user that he is enlisted in.



I'm currently displaying this in the model view of a User, but the information I need is from UserTeam which holds the teams for the users.




        'memberOfTeams' => array(self::MANY_MANY, 'UsersTeam', '{{teamMembers}}(userId, teamId)'),     
'coachOfTeams' => array(self::HAS_MANY, 'UsersTeam', 'coachId'),

Answer



$name is the name="mySelect" form value it will have (the one that will be passed if sent as a form i.e. $_POST['mySelect']).



$select is the preselected ID. Say you have an array...



$options = array('12' => 'Twelve', '10' => 'Ten');



And your dropdown looks like this...



echo CHtml::dropDownList('mySelect', '12', $options);


Then 'Twelve' will be the preselected item in the dropdown and $_POST['mySelect'] will be the value passed when the form is sent.



You can add additional html options to each tag, using the fourth parameter CHtml::dropDownList accepts, like so:




$htmlOptions = array(
// adds to the select element
'style' => 'cursor: pointer;',
// adds to the actual options
'options' => array(
'12' => array('title' => '12')
)
);



And updating the call to:



echo CHtml::dropDownList('mySelect', '12', $options, $htmlOptions);


The finished list would look like this:





When are value types stored in stack(C#)?



When I read next book of chapter "Value and reference types" then a question comes to my mind: "When are value types stored in stack"? Cause programmer cannot initialise any value type out of class. Cause when we initialise some variable of value type in class then variable is stored in heap.



My question is: when are value types stored in stack?



Answer



Well, firstly it is very rare that you would need to know, but basically, value-types are stored where-ever they are owned.



They are stored on the stack when they are part of the execution flow of a thread, which can mean:




  • in a "local" (a method variable) - excluding some cases (below)

  • as a floating value in part of a method, i.e. the return value from one method that is about to be passed as a value to another method - no "local" is involved, but the value is still on the stack

    • value-type parameters that are passed by-value (i.e. without ref or out) are simply a special-case of this



  • in an instance "field" (a type variable) on another value-type that is itself on the stack (for the above reasons)



They are stored on the heap (as part of an object) when:




  • in an instance "field" on a class

  • in an instance "field" on a value-type that is itself on the heap

  • in a static "field"


  • in an array

  • in a "local" (a method variable) that is part of an iterator block, an async method, or which is a "captured" variable in a lambda or anonymous method (all of which cause the local to be hoisted onto a field on a class that is generated by the compiler)

  • when "boxed" - i.e. cast into a reference-type (object, dynamic, Enum, ValueType (yes: ValueType is a reference-type; fun, eh?), ISomeInterface, etc)


c++ - What is the difference between g++ and gcc?



What is the difference between g++ and gcc? Which one of them should be used for general c++ development?



Answer



gcc and g++ are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler).



Even though they automatically determine which backends (cc1 cc1plus ...) to call depending on the file-type, unless overridden with -x language, they have some differences.



The probably most important difference in their defaults is which libraries they link against automatically.



According to GCC's online documentation link options and how g++ is invoked, g++ is equivalent to gcc -xc++ -lstdc++ -shared-libgcc (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v option (it displays the backend toolchain commands being run).


Parse JSON in JavaScript?

The standard way to parse JSON in JavaScript is JSON.parse()


The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:


const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);



The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().


When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.


jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time it was nothing more than a wrapper around JSON.parse().

java - Tag library versus scriptlets in JSP

There may be some negligible performance differences between the two options you proposed, however I do not think runtime performance is really the problem that Tag Libraries are intended to solve.


IMHO, the valid arguments against scriptlets are almost all about coding, debugging and maintenance concerns. One of the main reasons JSP has been derided for so long is not so much about JSP, but more about how people have used it. There is nothing worse then opening a JSP (that someone else wrote) in your IDE and seeing this spaghetti code mess of scriptlets and HTML. If you want to mix server side code and HTML all over the place, you might as well go and code in PHP! :)


Using Taglibs will make your JSPs way easier to develop initially, debug quicker and maintain over the long run.


I think scriptlets are such a poor option, that I always like to add something similar to this little snippet to my web.xml files when starting a new project:




*.jsp
true



This turns off scriptlet evaluation in the JSPs inside the web app, forcing developers to find better alternatives.


Another big argument for Taglibs is that you will be coding in a more rigorous manner. For example, you will have to handle any exceptions thrown in your code (one way or another) when you write a Taglib. If you write the same code in a scriptlet, you will not be prompted by your IDE or the JSP compiler to wrap the code in a try-catch block. Lazy/unprofessional programmers will probably rejoice at avoiding having to write a few lines of error handling code. Real programmers know from experience that catching exceptions and handling them properly in Java is way easier, cleaner and robust than having JSPs throw exceptions at runtime. Also if you are into JUnit etc. then unit testing taglibs is pretty straightforward - by definition you probably can't really unit test a JSP, at best you might be able to do some kind of integration test.


Also, as someone also mentioned, there is an architectural benefit to using Taglibs. The code design and reuse factor is way in favor of Taglibs. There is no easy way to share scriptlet code that is embedded in a JSP file. So you end up with copy-paste coding all over the place.

java: clone method violation




Code behind:



class A implements Cloneable
{
int i, j;

A(int i, int j)
{
this.i = i;
this.j = j;

}

A()
{
}
}

class B extends A
{
int l, m;


B()
{
}

B(int l, int m)
{
this.l = l;
this.m = m;


}

public static void main(String l[])
{
A obj = new A(1, 2);
B obj1 = (B) obj.clone(); // ERROR
}
}



I know that I am violating the meaning of clone as I am trying to assign the fields of one object to a completely different object. But its the error statement that is confusing me.



Statement: "error: clone() has protected access in Object"



Extending A should make clone() available to B also ? If that is, so values of i and j should be copied to l and m also ? Is this possible ?


Answer



clone() is protected method and to make accessible in sub-classes, override it with public access.



class A implements Cloneable{
.....

@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}

shell - How do I set a variable to the output of a command in Bash?

2nd Edit 2018-02-12: Added a different way, search at the bottom of this for long-running tasks!



2018-01-25 Edit: added a sample function (for populating variables about disk usage)




First simple, old, and compatible way



myPi=`echo '4*a(1)' | bc -l`
echo $myPi
3.14159265358979323844


Mostly compatible, second way



As nesting could become heavy, parenthesis was implemented for this




myPi=$(bc -l <<<'4*a(1)')


Nested sample:



SysStarted=$(date -d "$(ps ho lstart 1)" +%s)
echo $SysStarted
1480656334



Reading more than one variable (with Bashisms)



df -k /
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/dm-0 999320 529020 401488 57% /


If I just want a used value:




array=($(df -k /))


you could see an array variable:



declare -p array
declare -a array='([0]="Filesystem" [1]="1K-blocks" [2]="Used" [3]="Available" [
4]="Use%" [5]="Mounted" [6]="on" [7]="/dev/dm-0" [8]="999320" [9]="529020" [10]=
"401488" [11]="57%" [12]="/")'



Then:



echo ${array[9]}
529020


But I prefer this:



{ read foo ; read filesystem size using avail prct mountpoint ; } < <(df -k /)

echo $using
529020


The first read foo will just skip header line, but in only one command, you will populate 7 different variables:



declare -p avail filesystem foo mountpoint prct size using
declare -- avail="401488"
declare -- filesystem="/dev/dm-0"
declare -- foo="Filesystem 1K-blocks Used Available Use% Mounted on"

declare -- mountpoint="/"
declare -- prct="57%"
declare -- size="999320"
declare -- using="529020"


Or even:



{ read foo ; read filesystem dsk[{6,2,9}] prct mountpoint ; } < <(df -k /)
declare -p mountpoint dsk

declare -- mountpoint="/"
declare -a dsk=([2]="529020" [6]="999320" [9]="401488")


... will work with associative arrays too: read foo disk[total] disk[used] ...



Sample function for populating some variables:



#!/bin/bash


declare free=0 total=0 used=0

getDiskStat() {
local foo
{
read foo
read foo total used free foo
} < <(
df -k ${1:-/}
)

}

getDiskStat $1
echo $total $used $free


Nota: declare line is not required, just for readability.



About sudo cmd | grep ... | cut ...




shell=$(cat /etc/passwd | grep $USER | cut -d : -f 7)
echo $shell
/bin/bash


(Please avoid useless cat! So this is just one fork less:



shell=$(grep $USER 



All pipes (|) implies forks. Where another process have to be run, accessing disk, libraries calls and so on.



So using sed for sample, will limit subprocess to only one fork:



shell=$(sed echo $shell


And with Bashisms:




But for many actions, mostly on small files, Bash could do the job itself:



while IFS=: read -a line ; do
[ "$line" = "$USER" ] && shell=${line[6]}
done echo $shell
/bin/bash


or




while IFS=: read loginname encpass uid gid fullname home shell;do
[ "$loginname" = "$USER" ] && break
done echo $shell $loginname ...


Going further about variable splitting...



Have a look at my answer to How do I split a string on a delimiter in Bash?




Alternative: reducing forks by using backgrounded long-running tasks



2nd Edit 2018-02-12:



In order to prevent multiple forks like



myPi=$(bc -l <<<'4*a(1)'
myRay=12
myCirc=$(bc -l <<<" 2 * $myPi * $myRay ")



or



myStarted=$(date -d "$(ps ho lstart 1)" +%s)
mySessStart=$(date -d "$(ps ho lstart $$)" +%s)


This work fine, but running many forks is heavy and slow.




And commands like date and bc could make many operations, line by line!!



See:



bc -l <<<$'3*4\n5*6'
12
30

date -f - +%s < <(ps ho lstart 1 $$)
1516030449

1517853288


So we could use a long running background process to make many jobs, without having to initiate a new fork for each request.



We just need some file descriptors and fifos for doing this properly:



mkfifo /tmp/myFifoForBc
exec 5> >(bc -l >/tmp/myFifoForBc)
exec 6
rm /tmp/myFifoForBc


(Of course, FD 5 and 6 have to be unused!)... From there, you could use this process by:



echo "3*4" >&5
read -u 6 foo
echo $foo
12


echo >&5 "pi=4*a(1)"
echo >&5 "2*pi*12"
read -u 6 foo
echo $foo
75.39822368615503772256


Into a function newConnector



You may found my newConnector function on GitHub.Com or on my own site (Note on GitHub: there are two files on my site. Function and demo are bundled into one file which could be sourced for use or just run for demo.)




Sample:



. shell_connector.sh

tty
/dev/pts/20

ps --tty pts/20 fw
PID TTY STAT TIME COMMAND

29019 pts/20 Ss 0:00 bash
30745 pts/20 R+ 0:00 \_ ps --tty pts/20 fw

newConnector /usr/bin/bc "-l" '3*4' 12

ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30944 pts/20 S 0:00 \_ /usr/bin/bc -l
30952 pts/20 R+ 0:00 \_ ps --tty pts/20 fw


declare -p PI
bash: declare: PI: not found

myBc '4*a(1)' PI
declare -p PI
declare -- PI="3.14159265358979323844"


The function myBc lets you use the background task with simple syntax, and for date:




newConnector /bin/date '-f - +%s' @0 0
myDate '2000-01-01'
946681200
myDate "$(ps ho lstart 1)" boottime
myDate now now ; read utm idl myBc "$now-$boottime" uptime
printf "%s\n" ${utm%%.*} $uptime
42134906
42134906


ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30944 pts/20 S 0:00 \_ /usr/bin/bc -l
32615 pts/20 S 0:00 \_ /bin/date -f - +%s
3162 pts/20 R+ 0:00 \_ ps --tty pts/20 fw


From there, if you want to end one of background processes, you just have to close its fd:




eval "exec $DATEOUT>&-"
eval "exec $DATEIN>&-"
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
4936 pts/20 Ss 0:00 bash
5256 pts/20 S 0:00 \_ /usr/bin/bc -l
6358 pts/20 R+ 0:00 \_ ps --tty pts/20 fw



which is not needed, because all fd close when the main process finishes.

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...