Programs & Examples On #Handshaking

Anything related to handshaking in telecommunications, i.e. a process of automatic (software or hardware) negotiation of communication parameters between two interconnected devices.

How to create websockets server in PHP

Need to convert the the key from hex to dec before base64_encoding and then send it for handshake.

$hashedKey = sha1($key. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true);

$rawToken = "";
    for ($i = 0; $i < 20; $i++) {
      $rawToken .= chr(hexdec(substr($hashedKey,$i*2, 2)));
    }
$handshakeToken = base64_encode($rawToken) . "\r\n";

$handshakeResponse = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $handshakeToken\r\n";

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

The /sys filesystem should contain plenty information for your quest. My system (2.6.32-40-generic #87-Ubuntu) suggests:

/sys/class/tty

Which gives you descriptions of all TTY devices known to the system. A trimmed down example:

# ll /sys/class/tty/ttyUSB*
lrwxrwxrwx 1 root root 0 2012-03-28 20:43 /sys/class/tty/ttyUSB0 -> ../../devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.4/2-1.4:1.0/ttyUSB0/tty/ttyUSB0/
lrwxrwxrwx 1 root root 0 2012-03-28 20:44 /sys/class/tty/ttyUSB1 -> ../../devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.3/2-1.3:1.0/ttyUSB1/tty/ttyUSB1/

Following one of these links:

# ll /sys/class/tty/ttyUSB0/
insgesamt 0
drwxr-xr-x 3 root root    0 2012-03-28 20:43 ./
drwxr-xr-x 3 root root    0 2012-03-28 20:43 ../
-r--r--r-- 1 root root 4096 2012-03-28 20:49 dev
lrwxrwxrwx 1 root root    0 2012-03-28 20:43 device -> ../../../ttyUSB0/
drwxr-xr-x 2 root root    0 2012-03-28 20:49 power/
lrwxrwxrwx 1 root root    0 2012-03-28 20:43 subsystem -> ../../../../../../../../../../class/tty/
-rw-r--r-- 1 root root 4096 2012-03-28 20:43 uevent

Here the dev file contains this information:

# cat /sys/class/tty/ttyUSB0/dev
188:0

This is the major/minor node. These can be searched in the /dev directory to get user-friendly names:

# ll -R /dev |grep "188, *0"
crw-rw----   1 root dialout 188,   0 2012-03-28 20:44 ttyUSB0

The /sys/class/tty dir contains all TTY devices but you might want to exclude those pesky virtual terminals and pseudo terminals. I suggest you examine only those which have a device/driver entry:

# ll /sys/class/tty/*/device/driver
lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS0/device/driver -> ../../../bus/pnp/drivers/serial/
lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS1/device/driver -> ../../../bus/pnp/drivers/serial/
lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS2/device/driver -> ../../../bus/platform/drivers/serial8250/
lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS3/device/driver -> ../../../bus/platform/drivers/serial8250/
lrwxrwxrwx 1 root root 0 2012-03-28 20:43 /sys/class/tty/ttyUSB0/device/driver -> ../../../../../../../../bus/usb-serial/drivers/ftdi_sio/
lrwxrwxrwx 1 root root 0 2012-03-28 21:15 /sys/class/tty/ttyUSB1/device/driver -> ../../../../../../../../bus/usb-serial/drivers/ftdi_sio/

How to send password securely over HTTP?

I would use a server-side and client-side Diffie-Hellman key exchange system with AJAX or multiple form submits(I recommend the former), although I don't see any good implementations thereof on the internet. Remember that a JS library can always be corrupted or changed by MITM. Local storage can be used to help combat this, to an extent.

LPCSTR, LPCTSTR and LPTSTR

To answer the second part of your question, you need to do things like

LV_DISPINFO dispinfo;  
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);

because MS's LVITEM struct has an LPTSTR, i.e. a mutable T-string pointer, not an LPCTSTR. What you are doing is

1) convert string (a CString at a guess) into an LPCTSTR (which in practise means getting the address of its character buffer as a read-only pointer)

2) convert that read-only pointer into a writeable pointer by casting away its const-ness.

It depends what dispinfo is used for whether or not there is a chance that your ListView call will end up trying to write through that pszText. If it does, this is a potentially very bad thing: after all you were given a read-only pointer and then decided to treat it as writeable: maybe there is a reason it was read-only!

If it is a CString you are working with you have the option to use string.GetBuffer() -- that deliberately gives you a writeable LPTSTR. You then have to remember to call ReleaseBuffer() if the string does get changed. Or you can allocate a local temporary buffer and copy the string into there.

99% of the time this will be unnecessary and treating the LPCTSTR as an LPTSTR will work... but one day, when you least expect it...

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

To solve this problem in IntelliJ...
1) Put your .fxml files into resources directory
2) In the Start method define the path to .fxml file in the following way:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
The / seemed to solve this problem for me :)

Vector of Vectors to create matrix

What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.

One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.

Please try this out :

int num;
for(int i=0; i<RR; i++){

      vector<int>inter_mat;       //Intermediate matrix to help insert(push) contents of whole row at a time

      for(int j=0; j<CC; j++){
           cin>>num;             //Extra variable in helping push our number to vector
           vin.push_back(num);   //Inserting numbers in a row, one by one 
          }

      v.push_back(vin);          //Inserting the whole row at once to original 2D matrix 
}

Java, List only subdirectories from a directory, not files

This will literally list (that is, print) all subdirectories. It basically is a loop kind of where you don’t need to store the items in between to a list. This is what one most likely needs, so I leave it here.

Path directory = Paths.get("D:\\directory\\to\\list");

Files.walk(directory, 1).filter(entry -> !entry.equals(directory))
    .filter(Files::isDirectory).forEach(subdirectory ->
{
    // do whatever you want with the subdirectories
    System.out.println(subdirectory.getFileName());
});

Efficient way to determine number of digits in an integer

Well, the most efficient way, presuming you know the size of the integer, would be a lookup. Should be faster than the much shorter logarithm based approach. If you don't care about counting the '-', remove the + 1.

// generic solution
template <class T>
int numDigits(T number)
{
    int digits = 0;
    if (number < 0) digits = 1; // remove this line if '-' counts as a digit
    while (number) {
        number /= 10;
        digits++;
    }
    return digits;
}

// partial specialization optimization for 32-bit numbers
template<>
int numDigits(int32_t x)
{
    if (x == MIN_INT) return 10 + 1;
    if (x < 0) return numDigits(-x) + 1;

    if (x >= 10000) {
        if (x >= 10000000) {
            if (x >= 100000000) {
                if (x >= 1000000000)
                    return 10;
                return 9;
            }
            return 8;
        }
        if (x >= 100000) {
            if (x >= 1000000)
                return 7;
            return 6;
        }
        return 5;
    }
    if (x >= 100) {
        if (x >= 1000)
            return 4;
        return 3;
    }
    if (x >= 10)
        return 2;
    return 1;
}

// partial-specialization optimization for 8-bit numbers
template <>
int numDigits(char n)
{
    // if you have the time, replace this with a static initialization to avoid
    // the initial overhead & unnecessary branch
    static char x[256] = {0};
    if (x[0] == 0) {
        for (char c = 1; c != 0; c++)
            x[c] = numDigits((int32_t)c);
        x[0] = 1;
    }
    return x[n];
}

How to close form

send the WindowSettings as the parameter of the constructor of the DialogSettingsCancel and then on the button1_Click when yes is pressed call the close method of both of them.

public class DialogSettingsCancel
{
    WindowSettings parent;

    public DialogSettingsCancel(WindowSettings settings)
    {
        this.parent = settings;        
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Code to trigger when the "Yes"-button is pressed.
        this.parent.Close();
        this.Close();
    }
}

How to trim a string to N chars in Javascript?

    let trimString = function (string, length) {
      return string.length > length ? 
             string.substring(0, length) + '...' :
             string;
    };

Use Case,

let string = 'How to trim a string to N chars in Javascript';

trimString(string, 20);

//How to trim a string...

Is there a command to refresh environment variables from the command prompt in Windows?

The easiest way to add a variable to the path without rebooting for the current session is to open the command prompt and type:

PATH=(VARIABLE);%path%

and press enter.

to check if your variable loaded, type

PATH

and press enter. However, the variable will only be a part of the path until you reboot.

Cannot connect to MySQL 4.1+ using old authentication

edit: This only applies if you are in control of the MySQL server... if you're not take a look at Mysql password hashing method old vs new

First check with the SQL query

SHOW VARIABLES LIKE 'old_passwords'

(in the MySQL command line client, HeidiSQL or whatever front end you like) whether the server is set to use the old password schema by default. If this returns old_passwords,Off you just happen to have old password entries in the user table. The MySQL server will use the old authentication routine for these accounts. You can simply set a new password for the account and the new routine will be used.

You can check which routine will be used by taking a look at the mysql.user table (with an account that has access to that table)

SELECT `User`, `Host`, Length(`Password`) FROM mysql.user

This will return 16 for accounts with old passwords and 41 for accounts with new passwords (and 0 for accounts with no password at all, you might want to take care of those as well).
Either use the user management tools of the MySQL front end (if there are any) or

SET PASSWORD FOR 'User'@'Host'=PASSWORD('yourpassword');
FLUSH Privileges;

(replace User and Host with the values you got from the previous query.) Then check the length of the password again. It should be 41 now and your client (e.g. mysqlnd) should be able to connect to the server.

see also the MySQL documentation: * http://dev.mysql.com/doc/refman/5.0/en/old-client.html
* http://dev.mysql.com/doc/refman/5.0/en/password-hashing.html
* http://dev.mysql.com/doc/refman/5.0/en/set-password.html

Get unique values from arraylist in java

You can use Java 8 Stream API.

Method distinct is an intermediate operation that filters the stream and allows only distinct values (by default using the Object::equals method) to pass to the next operation.
I wrote an example below for your case,

// Create the list with duplicates.
List<String> listAll = Arrays.asList("CO2", "CH4", "SO2", "CO2", "CH4", "SO2", "CO2", "CH4", "SO2");

// Create a list with the distinct elements using stream.
List<String> listDistinct = listAll.stream().distinct().collect(Collectors.toList());

// Display them to terminal using stream::collect with a build in Collector.
String collectAll = listAll.stream().collect(Collectors.joining(", "));
System.out.println(collectAll); //=> CO2, CH4, SO2, CO2, CH4 etc..
String collectDistinct = listDistinct.stream().collect(Collectors.joining(", "));
System.out.println(collectDistinct); //=> CO2, CH4, SO2

How to set the font style to bold, italic and underlined in an Android TextView?

I don't know about underline, but for bold and italic there is "bolditalic". There is no mention of underline here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:textStyle

Mind you that to use the mentioned bolditalic you need to, and I quote from that page

Must be one or more (separated by '|') of the following constant values.

so you'd use bold|italic

You could check this question for underline: Can I underline text in an android layout?

TypeError: can only concatenate list (not "str") to list

I think what you want to do is add a new item to your list, so you have change the line newinv=inventory+str(add) with this one:

newinv = inventory.append(add)

What you are doing now is trying to concatenate a list with a string which is an invalid operation in Python.

However I think what you want is to add and delete items from a list, in that case your if/else block should be:

if selection=="use":
    print(inventory)
    remove=input("What do you want to use? ")
    inventory.remove(remove)
    print(inventory)

elif selection=="pickup":
    print(inventory)
    add=input("What do you want to pickup? ")
    inventory.append(add)
    print(inventory)

You don't need to build a new inventory list every time you add a new item.

How to change content on hover

The CSS content property along with ::after and ::before pseudo-elements have been introduced for this.

.item:hover a p.new-label:after{
    content: 'ADD';
}

JSFiddle Demo

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

  • The first danger lies in reload(sys).

    When you reload a module, you actually get two copies of the module in your runtime. The old module is a Python object like everything else, and stays alive as long as there are references to it. So, half of the objects will be pointing to the old module, and half to the new one. When you make some change, you will never see it coming when some random object doesn't see the change:

    (This is IPython shell)
    
    In [1]: import sys
    
    In [2]: sys.stdout
    Out[2]: <colorama.ansitowin32.StreamWrapper at 0x3a2aac8>
    
    In [3]: reload(sys)
    <module 'sys' (built-in)>
    
    In [4]: sys.stdout
    Out[4]: <open file '<stdout>', mode 'w' at 0x00000000022E20C0>
    
    In [11]: import IPython.terminal
    
    In [14]: IPython.terminal.interactiveshell.sys.stdout
    Out[14]: <colorama.ansitowin32.StreamWrapper at 0x3a9aac8>
    
  • Now, sys.setdefaultencoding() proper

    All that it affects is implicit conversion str<->unicode. Now, utf-8 is the sanest encoding on the planet (backward-compatible with ASCII and all), the conversion now "just works", what could possibly go wrong?

    Well, anything. And that is the danger.

    • There may be some code that relies on the UnicodeError being thrown for non-ASCII input, or does the transcoding with an error handler, which now produces an unexpected result. And since all code is tested with the default setting, you're strictly on "unsupported" territory here, and no-one gives you guarantees about how their code will behave.
    • The transcoding may produce unexpected or unusable results if not everything on the system uses UTF-8 because Python 2 actually has multiple independent "default string encodings". (Remember, a program must work for the customer, on the customer's equipment.)
      • Again, the worst thing is you will never know that because the conversion is implicit -- you don't really know when and where it happens. (Python Zen, koan 2 ahoy!) You will never know why (and if) your code works on one system and breaks on another. (Or better yet, works in IDE and breaks in console.)

How to get the command line args passed to a running process on unix/linux systems?

This will do the trick:

xargs -0 < /proc/<pid>/cmdline

Without the xargs, there will be no spaces between the arguments, because they have been converted to NULs.

Converting datetime.date to UTC timestamp in Python

For unix systems only:

>>> import datetime
>>> d = datetime.date(2011,01,01)
>>> d.strftime("%s")  # <-- THIS IS THE CODE YOU WANT
'1293832800'

Note 1: dizzyf observed that this applies localized timezones. Don't use in production.

Note 2: Jakub Narebski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).

EXTRACT() Hour in 24 Hour format

The problem is not with extract, which can certainly handle 'military time'. It looks like you have a default timestamp format which has HH instead of HH24; or at least that's the only way I can see to recreate this:

SQL> select value from nls_session_parameters
  2  where parameter = 'NLS_TIMESTAMP_FORMAT';

VALUE
--------------------------------------------------------------------------------
DD-MON-RR HH24.MI.SSXFF

SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
  2  as timestamp)) from dual;

EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
                                                                        15

alter session set nls_timestamp_format = 'DD-MON-YYYY HH:MI:SS';

Session altered.

SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
  2  as timestamp)) from dual;

select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') as timestamp)) from dual
                              *
ERROR at line 1:
ORA-01849: hour must be between 1 and 12

So the simple 'fix' is to set the format to something that does recognise 24-hours:

SQL> alter session set nls_timestamp_format = 'DD-MON-YYYY HH24:MI:SS';

Session altered.

SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
  2  as timestamp)) from dual;

EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
                                                                        15

Although you don't need the to_char at all:

SQL> select extract(hour from cast(sysdate as timestamp)) from dual;

EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
-----------------------------------------
                                       15

How can I strip HTML tags from a string in ASP.NET?

using System.Text.RegularExpressions;

string str = Regex.Replace(HttpUtility.HtmlDecode(HTMLString), "<.*?>", string.Empty);

How do I pretty-print existing JSON data with Java?

If you are using jackson you can easily achieve this with configuring a SerializationFeature in your ObjectMapper:

com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();

mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

mapper.writeValueAsString(<yourObject>);

Thats it.

Getting String Value from Json Object Android

You can use getString

String name = jsonObject.getString("name");
// it will throws exception if the key you specify doesn't exist

or optString

String name = jsonObject.optString("name");
// it will returns the empty string ("") if the key you specify doesn't exist

Firebase TIMESTAMP to date and Time

inside Firebase Functions transform the timestamp like so:

timestampObj.toDate()
timestampObj.toMillis().toString()

documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp

How can I temporarily disable a foreign key constraint in MySQL?

A very simple solution with phpMyAdmin:

  • In your table, go to the SQL tab
  • After you edit the SQL command that you want to run, there is a check box next to GO, named 'Enable foreign key checks' .
  • Uncheck this check box and run your SQL. It will be automatically rechecked after executing.

ToString() function in Go

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

How do I make a LinearLayout scrollable?

Place all your layouts inside a ScrollView with width and height set to fill_parent.

How to color System.out.println output?

No, but there are third party API's that can handle it

http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

Edit: of course there are newer articles than that one I posted, the information is still viable though.

Draw a line in a div

No need for css, you can just use the HR tag from HTML

<hr />

Difference in make_shared and normal shared_ptr in C++

About efficiency and concernig time spent on allocation, I made this simple test below, I created many instances through these two ways (one at a time):

for (int k = 0 ; k < 30000000; ++k)
{
    // took more time than using new
    std::shared_ptr<int> foo = std::make_shared<int> (10);

    // was faster than using make_shared
    std::shared_ptr<int> foo2 = std::shared_ptr<int>(new int(10));
}

The thing is, using make_shared took the double time compared with using new. So, using new there are two heap allocations instead of one using make_shared. Maybe this is a stupid test but doesn't it show that using make_shared takes more time than using new? Of course, I'm talking about time used only.

Android canvas draw rectangle

paint.setStrokeWidth(3);

paint.setColor(BLACK);

and either one of your drawRect should work.

OSError: [Errno 8] Exec format error

Have you tried this?

Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 

Edited per the apt comment from @J.F.Sebastian

How to place div in top right hand corner of page

<style type="text/css">
 .topcorner{
  position:absolute;
  top:10;
  right:15;
  }
</style>

You ca also use this in CSS external file.

Check if URL has certain string with PHP

$url = " www.domain.com/car/audi/";
if (strpos($url, "car")!==false){
    echo "Car here";
}
else {
   echo "No car here :(";
}

See strpos manual

What is the definition of "interface" in object oriented programming

Let us consider a Man(User or an Object) wants some work to be done. He will contact a middle man(Interface) who will be having a contract with the companies(real world objects created using implemented classes). Few types of works will be defined by him which companies will implement and give him results. Each and every company will implement the work in its own way but the result will be same. Like this User will get its work done using an single interface. I think Interface will act as visible part of the systems with few commands which will be defined internally by the implementing inner sub systems.

How can I align the columns of tables in Bash?

printf is great, but people forget about it.

$ for num in 1 10 100 1000 10000 100000 1000000; do printf "%10s %s\n" $num "foobar"; done
         1 foobar
        10 foobar
       100 foobar
      1000 foobar
     10000 foobar
    100000 foobar
   1000000 foobar

$ for((i=0;i<array_size;i++));
do
    printf "%10s %10d %10s" stringarray[$i] numberarray[$i] anotherfieldarray[%i]
done

Notice I used %10s for strings. %s is the important part. It tells it to use a string. The 10 in the middle says how many columns it is to be. %d is for numerics (digits).

man 1 printf for more info.

Delete with "Join" in Oracle sql Query

Recently I learned of the following syntax:

DELETE (SELECT *
        FROM productfilters pf
        INNER JOIN product pr
            ON pf.productid = pr.id
        WHERE pf.id >= 200
            AND pr.NAME = 'MARK')

I think it looks much cleaner then other proposed code.

Correct way of using log4net (logger naming)

Regarding how you log messages within code, I would opt for the second approach:

ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");

Where messages sent to the log above will be 'named' using the fully-qualifed type Bar, e.g.

MyNamespace.Foo.Bar [INFO] message

The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar specifically to DEBUG:

<log4net>
    <!-- appenders go here -->
    <root>
        <level value="INFO" />
        <appender-ref ref="myLogAppender" />
    </root>

    <logger name="MyNamespace.Foo.Bar">
        <level value="DEBUG" />
    </logger>
</log4net>

The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog", you loose much of this power!

Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.

For further reading, here is a codeproject article I wrote on logging:

Where are environment variables stored in the Windows Registry?

CMD:

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment

PowerShell:

Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment

Powershell/.NET: (see EnvironmentVariableTarget Enum)

[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

How do I call Objective-C code from Swift?

See Apple's guide to Using Swift with Cocoa and Objective-C. This guide covers how to use Objective-C and C code from Swift and vice versa and has recommendations for how to convert a project or mix and match Objective-C/C and Swift parts in an existing project.

The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. As seen in the documentation, this Objective-C:

UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

turns into this Swift code:

let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)

Xcode also does this translation on the fly — you can use Open Quickly while editing a Swift file and type an Objective-C class name, and it'll take you to a Swift-ified version of the class header. (You can also get this by cmd-clicking on an API symbol in a Swift file.) And all the API reference documentation in the iOS 8 and OS X v10.10 (Yosemite) developer libraries is visible in both Objective-C and Swift forms (e.g. UIView).

Difference between dict.clear() and assigning {} in Python

d = {} will create a new instance for d but all other references will still point to the old contents. d.clear() will reset the contents, but all references to the same instance will still be correct.

Attempt to write a readonly database - Django w/ SELinux error

Here my solution:

root@fiq:/home/django/django_project# chmod 777 db.sqlite3
root@fiq:/home/django/django_project# cd ..
root@fiq:/home/django# chmod 777 *

Go to <'your_website/admin'> put username and password.. That's it.

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

IntelliJ show JavaDocs tooltip on mouse over

File-->Settings-->Editor

Check "Show quick doc on mouse"

Now when you put the mouse over a method a tooltip with the documentation will appear. Sometimes the tooltip size is too small and you will have to resize it moving the mouse down to the bottom of the tooltip.

Why is there no xrange function in Python3?

Some performance measurements, using timeit instead of trying to do it manually with time.

First, Apple 2.7.2 64-bit:

In [37]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.05 s per loop

Now, python.org 3.3.0 64-bit:

In [83]: %timeit collections.deque((x for x in range(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.32 s per loop

In [84]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.31 s per loop

In [85]: %timeit collections.deque((x for x in iter(range(10000000)) if x%4 == 0), maxlen=0) 
1 loops, best of 3: 1.33 s per loop

Apparently, 3.x range really is a bit slower than 2.x xrange. And the OP's xrange function has nothing to do with it. (Not surprising, as a one-time call to the __iter__ slot isn't likely to be visible among 10000000 calls to whatever happens in the loop, but someone brought it up as a possibility.)

But it's only 30% slower. How did the OP get 2x as slow? Well, if I repeat the same tests with 32-bit Python, I get 1.58 vs. 3.12. So my guess is that this is yet another of those cases where 3.x has been optimized for 64-bit performance in ways that hurt 32-bit.

But does it really matter? Check this out, with 3.3.0 64-bit again:

In [86]: %timeit [x for x in range(10000000) if x%4 == 0]
1 loops, best of 3: 3.65 s per loop

So, building the list takes more than twice as long than the entire iteration.

And as for "consumes much more resources than Python 2.6+", from my tests, it looks like a 3.x range is exactly the same size as a 2.x xrange—and, even if it were 10x as big, building the unnecessary list is still about 10000000x more of a problem than anything the range iteration could possibly do.

And what about an explicit for loop instead of the C loop inside deque?

In [87]: def consume(x):
   ....:     for i in x:
   ....:         pass
In [88]: %timeit consume(x for x in range(10000000) if x%4 == 0)
1 loops, best of 3: 1.85 s per loop

So, almost as much time wasted in the for statement as in the actual work of iterating the range.

If you're worried about optimizing the iteration of a range object, you're probably looking in the wrong place.


Meanwhile, you keep asking why xrange was removed, no matter how many times people tell you the same thing, but I'll repeat it again: It was not removed: it was renamed to range, and the 2.x range is what was removed.

Here's some proof that the 3.3 range object is a direct descendant of the 2.x xrange object (and not of the 2.x range function): the source to 3.3 range and 2.7 xrange. You can even see the change history (linked to, I believe, the change that replaced the last instance of the string "xrange" anywhere in the file).

So, why is it slower?

Well, for one, they've added a lot of new features. For another, they've done all kinds of changes all over the place (especially inside iteration) that have minor side effects. And there'd been a lot of work to dramatically optimize various important cases, even if it sometimes slightly pessimizes less important cases. Add this all up, and I'm not surprised that iterating a range as fast as possible is now a bit slower. It's one of those less-important cases that nobody would ever care enough to focus on. No one is likely to ever have a real-life use case where this performance difference is the hotspot in their code.

ActiveXObject is not defined and can't find variable: ActiveXObject

A web app can request access to a sandboxed file system by calling window.requestFileSystem(). Works in Chrome.

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var fs = null;

window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (filesystem) {
    fs = filesystem;
}, errorHandler);

fs.root.getFile('Hello.txt', {
    create: true
}, null, errorHandler);

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

More info here.

IE11 prevents ActiveX from running

Does IE11 displays any message relative to the blocked execution of your ActiveX ?

You should read this and this.

Use the following JS function to detect support of ActiveX :

function IsActiveXSupported() {
    var isSupported = false;

    if(window.ActiveXObject) {
        return true;
    }

    if("ActiveXObject" in window) {
        return true;
    }

    try {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        isSupported = true;
    } catch (e) {
        if (e.name === "TypeError" || e.name === "Error") {
            isSupported = true;
        }
    }

    return isSupported;
}

How to create a custom string representation for a class object?

class foo(object):
    def __str__(self):
        return "representation"
    def __unicode__(self):
        return u"representation"

How can I count occurrences with groupBy?

I think you're just looking for the overload which takes another Collector to specify what to do with each group... and then Collectors.counting() to do the counting:

import java.util.*;
import java.util.stream.*;

class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("Hello");
        list.add("Hello");
        list.add("World");

        Map<String, Long> counted = list.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);
    }
}

Result:

{Hello=2, World=1}

(There's also the possibility of using groupingByConcurrent for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

How can I insert vertical blank space into an html document?

i always use this cheap word for vertical spaces.

    <p>Q1</p>
    <br>
    <p>Q2</p>

Insert into a MySQL table or update if exists

Try this:

INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'

Note:
Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

While variable is not defined - wait

Very late to the party but I want to supply a more modern solution to any future developers looking at this question. It's based off of Toprak's answer but simplified to make it clearer as to what is happening.

<div>Result: <span id="result"></span></div>

<script>
    var output = null;
    
    // Define an asynchronous function which will not block where it is called.
    async function test(){
        // Create a promise with the await operator which instructs the async function to wait for the promise to complete.
        await new Promise(function(resolve, reject){
            // Execute the code that needs to be completed.
            // In this case it is a timeout that takes 2 seconds before returning a result. 
            setTimeout(function(){
                // Just call resolve() with the result wherever the code completes.
                resolve("success output");
            }, 2000);
            
            // Just for reference, an 'error' has been included.
            // It has a chance to occur before resolve() is called in this case, but normally it would only be used when your code fails.
            setTimeout(function(){
                // Use reject() if your code isn't successful.
                reject("error output");
            }, Math.random() * 4000);
        })
        .then(function(result){ 
            // The result variable comes from the first argument of resolve().
            output = result; 
        })
        .catch(function(error){ 
            // The error variable comes from the first argument of reject().
            // Catch will also catch any unexpected errors that occur during execution.
            // In this case, the output variable will be set to either of those results.
            if (error) output = error; 
        });
        
        // Set the content of the result span to output after the promise returns.
        document.querySelector("#result").innerHTML = output;
    }
    
    // Execute the test async function.
    test();

    // Executes immediately after test is called.
    document.querySelector("#result").innerHTML = "nothing yet";
</script>

Here's the code without comments for easy visual understanding.

var output = null;

async function test(){
    await new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve("success output");
        }, 2000);

        setTimeout(function(){
            reject("error output");
        }, Math.random() * 4000);
    })
    .then(function(result){ 
        output = result; 
    })
    .catch(function(error){ 
        if (error) output = error; 
    });

    document.querySelector("#result").innerHTML = output;
}

test();

document.querySelector("#result").innerHTML = "nothing yet";

On a final note, according to MDN, Promises are supported on all modern browsers with Internet Explorer being the only exception. This compatibility information is also supported by caniuse. However with Bootstrap 5 dropping support for Internet Explorer, and the new Edge based on webkit, it is unlikely to be an issue for most developers.

How to use a variable for a key in a JavaScript object literal?

You can do it this way:

var thetop = 'top';
<something>.stop().animate(
    new function() {this[thetop] = 10;}, 10
);

Check whether a path is valid in Python without creating a file at the path's target

if os.path.exists(filePath):
    #the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
    #the file does not exists but write privileges are given
else:
    #can not write there

Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

PHP Notice: Undefined offset: 1 with array when reading data

I just recently had this issue and I didn't even believe it was my mistype:

Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)

And actually it was! I just accidentally typed "." rather than ","...

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

Jackson JSON custom serialization for certain fields

with the help of @JsonView we can decide fields of model classes to serialize which satisfy the minimal criteria ( we have to define the criteria) like we can have one core class with 10 properties but only 5 properties can be serialize which are needful for client only

Define our Views by simply creating following class:

public class Views
{
    static class Android{};
    static class IOS{};
    static class Web{};
}

Annotated model class with views:

public class Demo 
{
    public Demo() 
    {
    }

@JsonView(Views.IOS.class)
private String iosField;

@JsonView(Views.Android.class)
private String androidField;

@JsonView(Views.Web.class)
private String webField;

 // getters/setters
...
..
}

Now we have to write custom json converter by simply extending HttpMessageConverter class from spring as:

    public class CustomJacksonConverter implements HttpMessageConverter<Object> 
    {
    public CustomJacksonConverter() 
        {
            super();
        //this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView(Views.ClientView.class));
        this.delegate.getObjectMapper().configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
        this.delegate.getObjectMapper().setSerializationInclusion(Include.NON_NULL);

    }

    // a real message converter that will respond to methods and do the actual work
    private MappingJackson2HttpMessageConverter delegate = new MappingJackson2HttpMessageConverter();

    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return delegate.canRead(clazz, mediaType);
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return delegate.canWrite(clazz, mediaType);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return delegate.getSupportedMediaTypes();
    }

    @Override
    public Object read(Class<? extends Object> clazz,
            HttpInputMessage inputMessage) throws IOException,
            HttpMessageNotReadableException {
        return delegate.read(clazz, inputMessage);
    }

    @Override
    public void write(Object obj, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException 
    {
        synchronized(this) 
        {
            String userAgent = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("userAgent");
            if ( userAgent != null ) 
            {
                switch (userAgent) 
                {
                case "IOS" :
                    this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView(Views.IOS.class));
                    break;
                case "Android" :
                    this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView(Views.Android.class));
                    break;
                case "Web" :
                    this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView( Views.Web.class));
                    break;
                default:
                    this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView( null ));
                    break;
                }
            }
            else
            {
                // reset to default view
                this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView( null ));
            }
            delegate.write(obj, contentType, outputMessage);
        }
    }

}

Now there is need to tell spring to use this custom json convert by simply putting this in dispatcher-servlet.xml

<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean id="jsonConverter" class="com.mactores.org.CustomJacksonConverter" >
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

That's how you will able to decide which fields to get serialize.

Programmatically saving image to Django ImageField

Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField

Here is a Example:

import requests


def upload_image():
    # PATH TO DJANGO REST API
    url = "http://127.0.0.1:8080/api/gallery/"

    # MODEL FIELDS DATA
    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    #  UPLOAD FILES THROUGH REST API
    photo = open('/path/to/photo'), 'rb')
    resume = open('/path/to/resume'), 'rb')
    files = {'photo': photo, 'resume': resume}

    request = requests.post(url, data=data, files=files)
    print(request.status_code, request.reason) 

Changing Java Date one hour back

tl;dr

In UTC:

Instant.now().minus( 1 , ChronoUnit.HOURS ) 

Or, zoned:

Instant.now()
       .atZone( ZoneId.of ( "America/Montreal" ) )
       .minusHours( 1 )

Using java.time

Java 8 and later has the new java.time framework built-in.

Instant

If you only care about UTC (GMT), then use the Instant class.

Instant instant = Instant.now ();
Instant instantHourEarlier = instant.minus ( 1 , ChronoUnit.HOURS );

Dump to console.

System.out.println ( "instant: " + instant + " | instantHourEarlier: " + instantHourEarlier );

instant: 2015-10-29T00:37:48.921Z | instantHourEarlier: 2015-10-28T23:37:48.921Z

Note how in this instant happened to skip back to yesterday’s date.

ZonedDateTime

If you care about a time zone, use the ZonedDateTime class. You can start with an Instant and the assign a time zone, a ZoneId object. This class handles the necessary adjustments for anomalies such as Daylight Saving Time (DST).

Instant instant = Instant.now ();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
ZonedDateTime zdtHourEarlier = zdt.minus ( 1 , ChronoUnit.HOURS );

Dump to console.

System.out.println ( "instant: " + instant + "\nzdt: " + zdt + "\nzdtHourEarlier: " + zdtHourEarlier );

instant: 2015-10-29T00:50:30.778Z

zdt: 2015-10-28T20:50:30.778-04:00[America/Montreal]

zdtHourEarlier: 2015-10-28T19:50:30.778-04:00[America/Montreal]

Conversion

The old java.util.Date/.Calendar classes are now outmoded. Avoid them. They are notoriously troublesome and confusing.

When you must use the old classes for operating with old code not yet updated for the java.time types, call the conversion methods. Here is example code going from an Instant or a ZonedDateTime to a java.util.Date.

java.util.Date date = java.util.Date.from( instant );

…or…

java.util.Date date = java.util.Date.from( zdt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Test for multiple cases in a switch, like an OR (||)

You have to switch it!

switch (true) {
    case ( (pageid === "listing-page") || (pageid === ("home-page") ):
        alert("hello");
        break;
    case (pageid === "details-page"):
        alert("goodbye");
        break;
}

How do I get the full path to a Perl script that is executing?

On Windows using dirname and abs_path together worked best for me.

use File::Basename;
use Cwd qw(abs_path);

# absolute path of the directory containing the executing script
my $abs_dirname = dirname(abs_path($0));
print "\ndirname(abs_path(\$0)) -> $abs_dirname\n";

here's why:

# this gives the answer I want in relative path form, not absolute
my $rel_dirname = dirname(__FILE__); 
print "dirname(__FILE__) -> $rel_dirname\n"; 

# this gives the slightly wrong answer, but in the form I want 
my $full_filepath = abs_path($0);
print "abs_path(\$0) -> $full_filepath\n";

How to decorate a class?

Django has method_decorator which is a decorator that turns any decorator into a method decorator, you can see how it's implemented in django.utils.decorators:

https://github.com/django/django/blob/50cf183d219face91822c75fa0a15fe2fe3cb32d/django/utils/decorators.py#L53

https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

$(document).on("click"... not working?

if this code does not work even under document ready, most probable you assigned a return false; somewhere in your js file to that button, if it is button try to change it to a ,span, anchor or div and test if it is working.

$(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
});

set div height using jquery (stretch div height)

$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});

function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/ 
$('#content').css({"height":calculatecontsize + "px"} );
}

How to remove all ListBox items?

You should be able to use the Clear() method.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="author" content="Sandro Alvares - KingRider">
    </head>
    <body>
        <style type="text/css">
            li.title { 
                font-size: 20px; 
                font-weight: lighter; 
                padding: 15px; 
                counter-increment: ordem; 
            }
            .foo { 
                counter-reset: foo; 
                padding-left: 15px; 
            }
            .foo li { 
                list-style-type: none; 
            }
            .foo li:before { 
                counter-increment: foo; 
                content: counter(ordem) "." counter(foo) " "; 
            }
        </style>
        <ol>
            <li class="title">TITLE ONE</li>
            <ol class="foo">
                <li>text 1 one</li>
                <li>text 1 two</li>
                <li>text 1 three</li>
                <li>text 1 four</li>
            </ol>
            <li class="title">TITLE TWO</li>
            <ol class="foo">
                <li>text 2 one</li>
                <li>text 2 two</li>
                <li>text 2 three</li>
                <li>text 2 four</li>
            </ol>
            <li class="title">TITLE THREE</li>
            <ol class="foo">
                <li>text 3 one</li>
                <li>text 3 two</li>
                <li>text 3 three</li>
                <li>text 3 four</li>
            </ol>
        </ol>
    </body>
</html>

Result: http://i.stack.imgur.com/78bN8.jpg

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.

Demo:

print 1,
print 2

output:

1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

javascript remove "disabled" attribute from html input

Set the element's disabled property to false:

document.getElementById('my-input-id').disabled = false;

If you're using jQuery, the equivalent would be:

$('#my-input-id').prop('disabled', false);

For several input fields, you may access them by class instead:

var inputs = document.getElementsByClassName('my-input-class');
for(var i = 0; i < inputs.length; i++) {
    inputs[i].disabled = false;
}

Where document could be replaced with a form, for instance, to find only the elements inside that form. You could also use getElementsByTagName('input') to get all input elements. In your for iteration, you'd then have to check that inputs[i].type == 'text'.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

how to fetch array keys with jQuery?

Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
        console.log(key);
}

Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

EDIT:

In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

How to create multiple output paths in Webpack config

Please don't use any workaround because it will impact build performance.

Webpack File Manager Plugin

Easy to install copy this tag on top of the webpack.config.js

const FileManagerPlugin = require('filemanager-webpack-plugin');

Install

npm install filemanager-webpack-plugin --save-dev

Add the plugin

module.exports = {
    plugins: [
        new FileManagerPlugin({
            onEnd: {
                copy: [
                    {source: 'www', destination: './vinod test 1/'},
                    {source: 'www', destination: './vinod testing 2/'},
                    {source: 'www', destination: './vinod testing 3/'},
                ],
            },
        }),
    ],
};

Screenshot

enter image description here

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Very odd but I used the IP address (vs the hostname) and it worked for me.

Get-WmiObject -Computername MyHostName ...  
 [Fails: Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)]

Get-WmiObject -Computername 50.50.50.50
 [Successful]

How do I create executable Java program?

On the command line, navigate to the root directory of the Java files you wish to make executable.

Use this command:

jar -cvf [name of jar file] [name of directory with Java files]

This will create a directory called META-INF in the jar archive. In this META-INF there is a file called MANIFEST.MF, open this file in a text editor and add the following line:

Main-Class: [fully qualified name of your main class]

then use this command:

java -jar [name of jar file]

and your program will run :)

Subclipse svn:ignore

This is quite frustrating, but it's a containment issue (the .svn folders keep track also of ignored files). Any item that needs to be ignored is to be added to the ignore list of the immediate parent folder.

So, I had a new sub-folder with a new file in it and wanted to ignore that file but I couldn't do it because the option was grayed out. I solved it by committing the new folder first, which I wanted to (it was a cache folder), and then adding that file to the ignore list (of the newly added folder ;-), having the chance to add a pattern instead of a single file.

How to change the default GCC compiler in Ubuntu?

Between 4.8 and 6 with all --slaves:

update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 \
                    10 \
                    --slave   /usr/bin/cc cc /usr/bin/gcc-4.8 \
                    --slave   /usr/bin/c++ c++ /usr/bin/g++-4.8 \
                    --slave   /usr/bin/g++ g++ /usr/bin/g++-4.8 \
                    --slave   /usr/bin/gcov gcov /usr/bin/gcov-4.8 \
                    --slave   /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-4.8 \
                    --slave   /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-4.8 \
                    --slave   /usr/bin/gcc-ar gcc-ar /usr/bin/gcc-ar-4.8 \
                    --slave   /usr/bin/gcc-nm gcc-nm /usr/bin/gcc-nm-4.8 \
                    --slave   /usr/bin/gcc-ranlib gcc-ranlib /usr/bin/gcc-ranlib-4.8

and

update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 \
                    15 \
                    --slave   /usr/bin/cc cc /usr/bin/gcc-6 \
                    --slave   /usr/bin/c++ c++ /usr/bin/g++-6 \
                    --slave   /usr/bin/g++ g++ /usr/bin/g++-6 \
                    --slave   /usr/bin/gcov gcov /usr/bin/gcov-6 \
                    --slave   /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-6 \
                    --slave   /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-6 \
                    --slave   /usr/bin/gcc-ar gcc-ar /usr/bin/gcc-ar-6 \
                    --slave   /usr/bin/gcc-nm gcc-nm /usr/bin/gcc-nm-6 \
                    --slave   /usr/bin/gcc-ranlib gcc-ranlib /usr/bin/gcc-ranlib-6

Change between them with update-alternatives --config gcc.

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

Regex match everything after question mark?

Check out this site: http://rubular.com/ Basically the site allows you to enter some example text (what you would be looking for on your site) and then as you build the regular expression it will highlight what is being matched in real time.

How to send HTTP request in java?

Here's a complete Java 7 program:

class GETHTTPResource {
  public static void main(String[] args) throws Exception {
    try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
      System.out.println(s.useDelimiter("\\A").next());
    }
  }
}

The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.

Generate a random number in the range 1 - 10

If by numbers between 1 and 10 you mean any float that is >= 1 and < 10, then it's easy:

select random() * 9 + 1

This can be easily tested with:

# select min(i), max(i) from (
    select random() * 9 + 1 as i from generate_series(1,1000000)
) q;
       min       |       max
-----------------+------------------
 1.0000083274208 | 9.99999571684748
(1 row)

If you want integers, that are >= 1 and < 10, then it's simple:

select trunc(random() * 9 + 1)

And again, simple test:

# select min(i), max(i) from (
    select trunc(random() * 9 + 1) as i from generate_series(1,1000000)
) q;
 min | max
-----+-----
   1 |   9
(1 row)

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Gwerder's solution wont work because hash = hmac.read(); happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write statement is un-necessary in this example.

Instead do this:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});

More formally, if you wish, the line

hmac.end(text, function () {

could be written

hmac.end(text, 'utf8', function () {

because in this example text is a utf string

Using jQuery to test if an input has focus

An alternative to using classes to mark the state of an element is the internal data store functionality.

P.S.: You are able to store booleans and whatever you desire using the data() function. It's not just about strings :)

$("...").mouseover(function ()
{
    // store state on element
}).mouseout(function ()
{
    // remove stored state on element
});

And then it's just a matter of accessing the state of elements.

Eclipse : Maven search dependencies doesn't work

For me for this issue worked to:

  • remove ~/.m2
  • enable "Full Index Enabled" in maven repository view on central repository
  • "Rebuild Index" on central maven repository

After eclipse restart everything worked well.

Google Chrome Full Black Screen

If it happens in Chrome version > 45.x,

(1) try: System | Settings | Advanced settings
     uncheck "Use hardware acceleration when available", restart chrome.

(2) If (1) doesn't help, restart your computer

(3) If the black screen still occurs, try Chrome Cleanup Tool to reset your chrome.
     https://www.google.com/chrome/cleanup-tool/

List directory tree structure in python?

There is a package (I created) called seedir for doing this and other things with folder tree diagrams:

>>> import seedir as sd
>>> sd.seedir('/path/to/some/path/or/package', style='emoji')

 package/
+- __init__.py
+- subpackage1/
¦ +- __init__.py
¦ +- moduleX.py
¦ +- moduleY.py
+- subpackage2/
¦ +- __init__.py
¦ +- moduleZ.py
+- moduleA.py

Something similar to the style OP used can be done with:

>>> sd.seedir('/path/to/folder', style='spaces', indent=4, anystart='- ')

- package/
    - __init__.py
    - subpackage1/
        - __init__.py
        - moduleX.py
        - moduleY.py
    - subpackage2/
        - __init__.py
        - moduleZ.py
    - moduleA.py

DataGridView.Clear()

try:

datagrid.DataSource = null;
datagrid.DataBind();

Basically you will need to clear the datasource your binding to the grid.

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

Visual Studio keyboard shortcut to display IntelliSense

If you have arrived at this question because IntelliSense has stopped working properly and you are hoping to force it to show you what you need, then most likely none of these solutions are going to work.

Closing and restarting Visual Studio should fix the problem.

adding to window.onload event?

You can use attachEvent(ie8) and addEventListener instead

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

Rails: How does the respond_to block work?

I'd like to understand how the respond_to block actually works. What type of variable is format? Are .html and .json methods of the format object?

In order to understand what format is, you could first look at the source for respond_to, but quickly you'll find that what really you need to look at is the code for retrieve_response_from_mimes.

From here, you'll see that the block that was passed to respond_to (in your code), is actually called and passed with an instance of Collector (which within the block is referenced as format). Collector basically generates methods (I believe at Rails start-up) based on what mime types rails knows about.

So, yes, the .html and .json are methods defined (at runtime) on the Collector (aka format) class.

How to get UTC timestamp in Ruby?

if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"

Time.now.utc.to_formatted_s(:number)  # using Rails

Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby

Hibernate: How to set NULL query-parameter value with HQL?

This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:

@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)

The below code absolutely works and it is great if you keep all your queries in orm.xml

from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type

If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.

Notes:

The issue may be a specific MySql quirk. I only tested with Oracle.

The above query assumes that there are table rows where c.status is null

The where clause is prioritized so that the parameter is checked first.

The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.

If you needed to skip the :status where_clause altogether; you can code like so:

from CountryDTO c where (:status is null or c.status = :status) and c.type =:type

and it is equivalent to:

sql.append(" where ");
if(status != null){
  sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");

Jenkins Host key verification failed

I ran into this issue and it turned out the problem was that the jenkins service wasn't being run as the jenkins user. So running the commands as the jenkins user worked just fine.

Close application and launch home screen on Android

Keep in mind that when working with applications that use persistent socket connections, the finish() method does not release the connection. Under normal circumstances, finish() is the best option, but if you absolutely need to exit an app and release all resource it's using then use killProcess. I've had no problems using it.

SVN "Already Locked Error"

If your SVN repository is locked by AnkhSVN, just use "cleanup" command from AnkhSVN to release the lock! ;)

Eclipse Error: "Failed to connect to remote VM"

Create setenv.bat file in nib folder of Tomcat. Add SET JPDA_ADDRESS = 8787 ; Override the jpda port Open cmd, go to bin folder of Tomcat and Start tomcat using catalina jpda start Set up a debug point on eclipse Next compile your project. Check localhost:8080/ Deploy the war or jar under webapps folder and this must deploy war on Tomcat. Then send the request. the debug point will get hit NOTE : Don't edit catalina.bat file. make changes in setenv.bat file

Using $setValidity inside a Controller

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

This solution WORKS , I had the same issue and after hours I came up to this:

(1) Go to your pom.xml

(2) Add this Dependency :

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>


(3) Run your Project

Subtracting Number of Days from a Date in PL/SQL

Use sysdate-1 to subtract one day from system date.

select sysdate, sysdate -1 from dual;

Output:

SYSDATE  SYSDATE-1
-------- ---------
22-10-13 21-10-13 

How to solve javax.net.ssl.SSLHandshakeException Error?

I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

P.S I cant get source code before the weekend since external SSH is disabled in my office :(

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

django templates: include and extends

From Django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

So Django doesn't grab any blocks from your commondata.html and it doesn't know what to do with rendered html outside blocks.

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

How to use code to open a modal in Angular 2?

The below answer is in reference to the latest ng-bootstrap

Install

npm install --save @ng-bootstrap/ng-bootstrap

app.module.ts

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...

    NgbModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Component Controller

import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-app-registration',
  templateUrl: './app-registration.component.html',
  styleUrls: ['./app-registration.component.css']
})

export class AppRegistrationComponent implements OnInit {

  @ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef

  constructor(private modalService: NgbModal) { }

  openModal(){
    this.modalService.open(this.editModal);
  }

}

Component HTML

<ng-template #editModal let-modal>

<div class="modal-header">
  <h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
  <button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

<div class="modal-body">
  
  <form>
    <div class="form-group">
      <label for="dateOfBirth">Date of birth</label>
      <div class="input-group">
        <input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
        </div>
      </div>
    </div>
  </form>

</div>

<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
</div>

</ng-template>

check android application is in foreground or not?

Android Architecture Components library you can use the ProcessLifecycleOwner to set up a listener to the whole application process for onStart and onStop events. To do this, make your application class implement the LifecycleObserver interface and add some annotations for onStart and onStop to your foreground and background methods.

class ArchLifecycleApp : Application(), LifecycleObserver {

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Log.d("Awww", "App in background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Log.d("Yeeey", "App in foreground")
    }

}

Java POI : How to read Excel cell value and not the formula computing it?

SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked . I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies . Full code is given below with exact imports.

 import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;

    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.util.CellReference;
    import org.apache.poi.sl.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellType;
    import org.apache.poi.ss.usermodel.CellValue;
    import org.apache.poi.ss.usermodel.FormulaEvaluator;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;


    public class ReadExcelFormulaValue {

        private static final CellType NUMERIC = null;
        public static void main(String[] args) {
            try {
                readFormula();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static void readFormula() throws IOException {
            FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
            org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

            CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
            Row row = sheet.getRow(cellReference.getRow());
            Cell cell = row.getCell(cellReference.getCol());

            CellValue cellValue = evaluator.evaluate(cell);
            System.out.println("Cell type month  is "+cellValue.getCellTypeEnum());
            System.out.println("getNumberValue month is  "+cellValue.getNumberValue());     
          //  System.out.println("getStringValue "+cellValue.getStringValue());


            cellReference = new CellReference("H2"); // pass the cell which contains the formula
             row = sheet.getRow(cellReference.getRow());
             cell = row.getCell(cellReference.getCol());

            cellValue = evaluator.evaluate(cell);
            System.out.println("getNumberValue DAY is  "+cellValue.getNumberValue());    


        }

    }

How to write to error log file in PHP

If you don't want to change anything in your php.ini file, according to PHP documentation, you can do this.

error_log("Error message\n", 3, "/mypath/php.log");

The first parameter is the string to be sent to the log. The second parameter 3 means expect a file destination. The third parameter is the log file path.

Select first occurring element after another element

For your literal example you'd want to use the adjacent selector (+).

h4 + p {color:red}//any <p> that is immediately preceded by an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>

However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).

h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>

It's known to be buggy in IE 7+ unfortunately.

how to define ssh private key for servers fetched by dynamic inventory in files

I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.

The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):

[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem

Here is the patch for ec2.py:

204a205,206
>     'ssh_key_path': '~/.ssh',
>     'ssh_key_suffix': '.pem',
422a425,428
>         # SSH key setup
>         self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
>         self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
> 
1490a1497
>         instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)

how can I set visible back to true in jquery

Using ASP.NET's visible="false" property will set the visibility attribute where as I think when you call show() in jQuery it modifies the display attribute of the CSS style.

So doing the latter won't rectify the former.

You need to do this:

$("#test1").attr("visibility", "visible");

How to convert Javascript datetime to C# datetime?

DateTime.Parse is a much better bet. JS dates and C# dates do not start from the same root.

Sample:

DateTime dt = DateTime.ParseExact("Tue Jul 12 2011 16:00:00 GMT-0700",
                                  "ddd MMM d yyyy HH:mm:ss tt zzz",
                                  CultureInfo.InvariantCulture);

Read input stream twice

if your InputStream support using mark, then you can mark() your inputStream and then reset() it . if your InputStrem doesn't support mark then you can use the class java.io.BufferedInputStream,so you can embed your stream inside a BufferedInputStream like this

    InputStream bufferdInputStream = new BufferedInputStream(yourInputStream);
    bufferdInputStream.mark(some_value);
    //read your bufferdInputStream 
    bufferdInputStream.reset();
    //read it again

How do I run a simple bit of code in a new thread?

There are many ways of running separate threads in .Net, each has different behaviors. Do you need to continue running the thread after the GUI quits? Do you need to pass information between the thread and GUI? Does the thread need to update the GUI? Should the thread do one task then quit, or should it continue running? The answers to these questions will tell you which method to use.

There is a good async method article at the Code Project web site that describes the various methods and provides sample code.

Note this article was written before the async/await pattern and Task Parallel Library were introduced into .NET.

Android/Java - Date Difference in days

        Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
        Date today = new Date();
        long diff =  today.getTime() - userDob.getTime();
        int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
        int hours = (int) (diff / (1000 * 60 * 60));
        int minutes = (int) (diff / (1000 * 60));
        int seconds = (int) (diff / (1000));

In Python, what does dict.pop(a,b) mean?

>>> def func(a, *args, **kwargs):
...   print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
... 
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}

>>> def anotherfunct(beta, *args):
...   print 'beta %s, args %s' % (beta, args)
... 
>>> def func(a, *args, **kwargs):
...   anotherfunct(a, *args)
... 
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>> 

How to 'bulk update' with Django?

Update:

Django 2.2 version now has a bulk_update.

Old answer:

Refer to the following django documentation section

Updating multiple objects at once

In short you should be able to use:

ModelClass.objects.filter(name='bar').update(name="foo")

You can also use F objects to do things like incrementing rows:

from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)

See the documentation.

However, note that:

  • This won't use ModelClass.save method (so if you have some logic inside it won't be triggered).
  • No django signals will be emitted.
  • You can't perform an .update() on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter() and .exclude() methods.

How to quickly and conveniently create a one element arraylist

Fixed size List

The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T...) like

// Returns a List backed by a varargs T.
return Arrays.asList(s);

Variable size List

If it needs vary in size you can construct an ArrayList and the fixed-sizeList like

return new ArrayList<String>(Arrays.asList(s));

and (in Java 7+) you can use the diamond operator <> to make it

return new ArrayList<>(Arrays.asList(s));

Single Element List

Collections can return a list with a single element with list being immutable:

Collections.singletonList(s)

The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.

REST HTTP status codes for failed validation or invalid duplicate

200

Ugh... (309, 400, 403, 409, 415, 422)... a lot of answers trying to guess, argue and standardize what is the best return code for a successful HTTP request but a failed REST call.

It is wrong to mix HTTP status codes and REST status codes.

However, I saw many implementations mixing them, and many developers may not agree with me.

HTTP return codes are related to the HTTP Request itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.

For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:

  • URI is wrong (HTTP)
  • No users are found (REST)

"403 Forbidden/Access Denied" may mean:

  • Special permission needed. Browsers can handle it by asking the user/password. (HTTP)
  • Wrong access permissions configured on the server. (HTTP)
  • You need to be authenticated (REST)

And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...

From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.

If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the HTTP server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as HTTP result, right?

Instead of this you may return 200 HTTP code with some options:

  • "error" object in JSON result if something goes wrong
  • Empty JSON array/object if no record found
  • A bool result/success flag in combination with previous options for a better handling.

Also, some internet providers may intercept your requests and return you a 404 HTTP code. This does not means that your data are not found, but it's something wrong at transport level.

From Wiki:

In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".

Why not simply answer with something like this?

{
  "result": false,
  "error": {"code": 102, "message": "Validation failed: Wrong NAME."}
}

Google always returns 200 as status code in their Geocoding API, even if the request logically fails: https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes

Facebook always return 200 for successful HTTP requests, even if REST request fails: https://developers.facebook.com/docs/graph-api/using-graph-api/error-handling

It's simple, HTTP status codes are for HTTP requests. REST API is Your, define Your status codes.

How can I remove time from date with Moment.js?

The correct way would be to specify the input as per your requirement which will give you more flexibility.

The present definition includes the following

LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A'

You can use any of these or change the input passed into moment().format(). For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

The question, essentially, is "how to concatenate arrays in Ruby". Naturally the answer is to use concat or + as mentioned in nearly every answer.

A natural extension to the question would be "how to perform row-wise concatenation of 2D arrays in Ruby". When I googled "ruby concatenate matrices", this SO question was the top result so I thought I would leave my answer to that (unasked but related) question here for posterity.


In some applications you might want to "concatenate" two 2D arrays row-wise. Something like,

[[a, b], | [[x],    [[a, b, x],
 [c, d]] |  [y]] =>  [c, d, y]]

This is something like "augmenting" a matrix. For example, I used this technique to create a single adjacency matrix to represent a graph out of a bunch of smaller matrices. Without this technique I would have had to iterate over the components in a way that could have been error prone or frustrating to think about. I might have had to do an each_with_index, for example. Instead I combined zip and flatten as follows,

# given two multi-dimensional arrays that you want to concatenate row-wise
m1 = [[:a, :b], [:c, :d]]
m2 = [[:x], [:y]]

m1m2 = m1.zip(m2).map(&:flatten)
# => [[:a, :b, :x], [:c, :d, :y]]

Undefined function mysql_connect()

I was also stuck with the same problem of undefined MySQL_connect().I tried to make changes in PHP.ini file but it was giving me the same error. Then I came to this solution where I changed my code from depreciated php functions to new functions.

$con=mysqli_connect($host,$user,$password);

mysqli_select_db($con,dbname); 
//To select the database

session_start(); //To start the session

$query=mysqli_query($con,your query); 
//made query after establishing connection with database.

I hope this will help you . This solution is correctly working for me .

EDIT:

If you upgrade form old php you need to apt-get install php7.0-mysql

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How can I rename column in laravel using migration?

Renaming Columns (Laravel 5.x)

To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*

Or you can simply required the package using composer...

composer require doctrine/dbal

Source: https://laravel.com/docs/5.0/schema#renaming-columns

Note: Use make:migration and not migrate:make for Laravel 5.x

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I know this is a little off the OPs original request but I came across this while looking for a way to use Invoke-WebRequest against a site requiring basic authentication.

The difference is, I did not want to record the password in the script. Instead, I wanted to prompt the script runner for credentials for the site.

Here's how I handled it

$creds = Get-Credential

$basicCreds = [pscredential]::new($Creds.UserName,$Creds.Password)

Invoke-WebRequest -Uri $URL -Credential $basicCreds

The result is the script runner is prompted with a login dialog for the U/P then, Invoke-WebRequest is able to access the site with those credentials. This works because $Creds.Password is already an encrypted string.

I hope this helps someone looking for a similar solution to the above question but without saving the username or PW in the script

Make UINavigationBar transparent

The below code expands upon the top answer chosen for this thread, to get rid of the bottom border and set text color:

  1. The last two coded lines of this code set transparency. I borrowed that code from this thread and it worked perfectly!

  2. The "clipsToBounds" property was code I found which got rid of the bottom border line with OR without transparency set (so if you decide to go with a solid white/black/etc. background instead, there will still be no border line).

  3. The "tintColor" line (2nd coded line) set my back button to a light grey

  4. I kept barTintColor as a backup. I don't know why transparency would not work, but if it doesn't, I want my bg white as I used to have it

    let navigationBarAppearace = UINavigationBar.appearance()
    navigationBarAppearace.tintColor = UIColor.lightGray
    navigationBarAppearace.barTintColor = UIColor.white
    navigationBarAppearace.clipsToBounds = true
    navigationBarAppearace.isTranslucent = true
    navigationBarAppearace.setBackgroundImage(UIImage(), for: .default)
    navigationBarAppearace.shadowImage = UIImage()
    

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

List of IP addresses/hostnames from local network in Python

One of the answers in this question might help you. There seems to be a platform agnostic version for python, but I haven't tried it yet.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

The solution needs to add these headers to the server response.

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'

If you have access to the server, you can add them and this will solve your problem

OR

You can try concatentaing this in front of the url:

https://cors-anywhere.herokuapp.com/

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Need to make sure you have the numeric keypad and the tab key working too

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

List and kill at jobs on UNIX

at -l to list jobs, which gives return like this:

age2%> at -l
11      2014-10-21 10:11 a hoppent
10      2014-10-19 13:28 a hoppent

atrm 10 kills job 10

Or so my sysadmin told me, and it

How to access form methods and controls from a class in C#?

You need access to the object.... you can't simply ask the form class....

eg...

you would of done some thing like

Form1.txtLog.Text = "blah"

instead of

Form1 blah = new Form1();
blah.txtLog.Text = "hello"

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

MySQL ORDER BY multiple column ASC and DESC

@DRapp is a genius. I never understood how he coded his SQL,so I tried coding it in my own understanding.


    SELECT 
      f.username,
      f.point,
      f.avg_time
    FROM
      (
      SELECT
        userscores.username,
        userscores.point,
        userscores.avg_time
      FROM
        (
        SELECT
          users.username,
          scores.point,
          scores.avg_time
        FROM
          scores
        JOIN users
        ON scores.user_id = users.id
        ORDER BY scores.point DESC
        ) userscores
      ORDER BY
        point DESC,
        avg_time
      ) f
    GROUP BY f.username
    ORDER BY point DESC

It yields the same result by using GROUP BY instead of the user @variables.

How do I print uint32_t and uint16_t variables value?

You need to include inttypes.h if you want all those nifty new format specifiers for the intN_t types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d or %u in case the sizes are different to what you think.

It includes stdint.h and extends it with quite a few other things, such as the macros that can be used for the printf/scanf family of calls. This is covered in section 7.8 of the ISO C99 standard.

For example, the following program:

#include <stdio.h>
#include <inttypes.h>
int main (void) {
    uint32_t a=1234;
    uint16_t b=5678;
    printf("%" PRIu32 "\n",a);
    printf("%" PRIu16 "\n",b);
    return 0;
}

outputs:

1234
5678

Node.js Port 3000 already in use but it actually isn't?

It may be an admin process running in the background and netstat doesn't show this.
Use tasklist | grep node to find the PID of this admin process and then kill PID

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

Thread pooling in C++11

This is copied from my answer to another very similar post, hope it can help:

1) Start with maximum number of threads a system can support:

int Num_Threads =  thread::hardware_concurrency();

2) For an efficient threadpool implementation, once threads are created according to Num_Threads, it's better not to create new ones, or destroy old ones (by joining). There will be performance penalty, might even make your application goes slower than the serial version.

Each C++11 thread should be running in their function with an infinite loop, constantly waiting for new tasks to grab and run.

Here is how to attach such function to the thread pool:

int Num_Threads = thread::hardware_concurrency();
vector<thread> Pool;
for(int ii = 0; ii < Num_Threads; ii++)
{  Pool.push_back(thread(Infinite_loop_function));}

3) The Infinite_loop_function

This is a "while(true)" loop waiting for the task queue

void The_Pool:: Infinite_loop_function()
{
    while(true)
    {
        {
            unique_lock<mutex> lock(Queue_Mutex);

            condition.wait(lock, []{return !Queue.empty() || terminate_pool});
            Job = Queue.front();
            Queue.pop();
        }
        Job(); // function<void()> type
    }
};

4) Make a function to add job to your Queue

void The_Pool:: Add_Job(function<void()> New_Job)
{
    {
        unique_lock<mutex> lock(Queue_Mutex);
        Queue.push(New_Job);
    }
    condition.notify_one();
}

5) Bind an arbitrary function to your Queue

Pool_Obj.Add_Job(std::bind(&Some_Class::Some_Method, &Some_object));

Once you integrate these ingredients, you have your own dynamic threading pool. These threads always run, waiting for job to do.

I apologize if there are some syntax errors, I typed these code and and I have a bad memory. Sorry that I cannot provide you the complete thread pool code, that would violate my job integrity.

Edit: to terminate the pool, call the shutdown() method:

XXXX::shutdown(){
{
    unique_lock<mutex> lock(threadpool_mutex);
    terminate_pool = true;} // use this flag in condition.wait

    condition.notify_all(); // wake up all threads.

    // Join all threads.
    for(std::thread &every_thread : thread_vector)
    {   every_thread.join();}

    thread_vector.clear();  
    stopped = true; // use this flag in destructor, if not set, call shutdown() 
}

How to auto resize and adjust Form controls with change in resolution

in the form load event add this line

this.WindowState = FormWindowState.Maximized;

How to select an element with 2 classes

Just chain them together:

.a.b {
  color: #666;
}

How to disable anchor "jump" when loading a page?

I have not had any consistent success with these solutions.

Apparently due to the fact that the jump happens before Javascript => reference(http://forum.jquery.com/topic/preventing-anchor-jump)

My solution is to position all anchors at the top by default with CSS.

.scroll-target{position:fixed;top:0;left:0;}

Then use jquery to scroll to the parent of the target anchor, or a sibling(maybe an empty em tag)

<a class="scroll-target" name="section3"></a><em>&nbsp</em>

jquery example for scrolling for when URL is entered with hash
(page must not be already loaded in window/tab, this covers links from other/outside sources)

setTimeout(function() {
    if (window.location.hash) {               
        var hash = window.location.hash.substr(1);   
        var scrollPos = $('.scroll-target[name="'+hash+'"]').siblings('em').offset().top; 
        $("html, body").animate({ scrollTop: scrollPos }, 1000);    
    }
}, 1);

Also you'll want to prevent default for anchor clicks while on the page and then scroll to their targets

<a class="scroll-to" href="#section3">section three</a>

and jquery

$('a.scroll-to').click(function(){
    var target = $(this).attr('href').substr(1);
    var scrollPos = $('.scroll-target[name="'+target+'"]').siblings('em').offset().top; 
    $("html, body").animate({ scrollTop: scrollPos }, 1000);
    return false;
});

The good thing about this method is the anchor tag targets, remain structurally beside the relevant content, although their CSS position is at the top.

This should mean that search engine crawlers won't have a problem.

Cheers, I hope this helps
Gray

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

PHP: How to get current time in hour:minute:second?

Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.

Looking up a function is easy, just visit http://php.net/<function name> and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.

We immediately learn a couple things about this function by examining its signature:

string date ( string $format [, int $timestamp = time() ] )

First, it returns a string. That's what the first string in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).

date("d-m-Y") // produces something like 03-12-2012

In this code, d represents the day of the month (with a leading 0 is necessary). m represents the month, again with a leading zero if necessary. And Y represents the full 4-digit year. All of these are documented in the aforementioned link.

To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:

h   12-hour format of an hour with leading zeros    01 through 12
i   Minutes with leading zeros                      00 to 59
s   Seconds, with leading zeros                     00 through 59

With this in mind, we can no create a new format string:

date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13

Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.

Is it correct to use DIV inside FORM?

Your question doesn't address what you want to put in the DIV tags, which is probably why you've received some incomplete/wrong answers. The truth is that you can, as Royi said, put DIV tags inside of your forms. You don't want to do this for labels, for instance, but if you have a form with a bunch of checkboxes that you want to lay out into three columns, then by all means, use DIV tags (or SPAN, HEADER, etc.) to accomplish the look and feel you're trying to achieve.

Open Facebook Page in Facebook App (if installed) on Android

Here's a solution that mixes the code by Jared Rummler and AndroidMechanic.

Note: fb://facewebmodal/f?href= redirects to a weird facebook page that doesn't have the like and other important buttons, which is why I try fb://page/. It works fine with the current Facebook version (126.0.0.21.77, June 1st 2017). The catch might be useless, I left it just in case.

public static String getFacebookPageURL(Context context)
{
    final String FACEBOOK_PAGE_ID = "123456789";
    final String FACEBOOK_URL = "MyFacebookPage";

    if(appInstalledOrNot(context, "com.facebook.katana"))
    {
        try
        {
            return "fb://page/" + FACEBOOK_PAGE_ID;
            // previous version, maybe relevant for old android APIs ?
            // return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        }
        catch(Exception e) {}
    }
    else
    {
        return FACEBOOK_URL;
    }

}

Here's the appInstalledOrNot function which I took (and modified) from Aerrow's answer to this post

private static boolean appInstalledOrNot(Context context, String uri)
{
    PackageManager pm = context.getPackageManager();
    try
    {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    }
    catch(PackageManager.NameNotFoundException e)
    {
    }

    return false;
}

How to get the Facebook ID of a page:

  1. Go to your page
  2. Right-click and View Page Source
  3. Find in page: fb://page/?id=
  4. Here you go!

How to find out what type of a Mat object is with Mat::type() in OpenCV

In OpenCV header "types_c.h" there are a set of defines which generate these, the format is CV_bits{U|S|F}C<number_of_channels>
So for example CV_8UC3 means 8 bit unsigned chars, 3 colour channels - each of these names map onto an arbitrary integer with the macros in that file.

Edit: See "types_c.h" for example:

#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))

eg.
depth = CV_8U = 0
cn = 3
CV_CN_SHIFT = 3

CV_MAT_DEPTH(0) = 0
(((cn)-1) << CV_CN_SHIFT) = (3-1) << 3 = 2<<3 = 16

So CV_8UC3 = 16 but you aren't supposed to use this number, just check type() == CV_8UC3 if you need to know what type an internal OpenCV array is.
Remember OpenCV will convert the jpeg into BGR (or grey scale if you pass '0' to imread) - so it doesn't tell you anything about the original file.

Postgres: clear entire database before re-creating / re-populating from bash script

If you want to clean your database named "example_db":

1) Login to another db(for example 'postgres'):

psql postgres

2) Remove your database:

DROP DATABASE example_db;

3) Recreate your database:

CREATE DATABASE example_db;

/bin/sh: pushd: not found

Run "apt install bash" It will install everything you need and the command will work

Animate element transform rotate

Just use CSS transitions:

$(element).css( { transition: "transform 0.5s",
                  transform:  "rotate(" + amount + "deg)" } );

setTimeout( function() { $(element).css( { transition: "none" } ) }, 500 );

As example I set the duration of the animation to 0.5 seconds.

Note the setTimeout to remove the transition css property after the animation is over (500 ms)


For readability I omitted vendor prefixes.

This solution requires browser's transition support off course.

ReactJS Two components communicating

There is such possibility even if they are not Parent - Child relationship - and that's Flux. There is pretty good (for me personally) implementation for that called Alt.JS (with Alt-Container).

For example you can have Sidebar that is dependent on what is set in component Details. Component Sidebar is connected with SidebarActions and SidebarStore, while Details is DetailsActions and DetailsStore.

You could use then AltContainer like that

<AltContainer stores={{
                    SidebarStore: SidebarStore
                }}>
                    <Sidebar/>
</AltContainer>

{this.props.content}

Which would keep stores (well I could use "store" instead of "stores" prop). Now, {this.props.content} CAN BE Details depending on the route. Lets say that /Details redirect us to that view. Details would have for example a checkbox that would change Sidebar element from X to Y if it would be checked.

Technically there is no relationship between them and it would be hard to do without flux. BUT WITH THAT it is rather easy.

Now let's get to DetailsActions. We will create there

class SiteActions {
constructor() {
    this.generateActions(
        'setSiteComponentStore'
    );
}

setSiteComponent(value) {
    this.dispatch({value: value});
}
}

and DetailsStore

class SiteStore {
constructor() {
    this.siteComponents = {
        Prop: true
    };

    this.bindListeners({
        setSiteComponent: SidebarActions.COMPONENT_STATUS_CHANGED
    })
}

setSiteComponent(data) {
    this.siteComponents.Prop = data.value;
}
}

And now, this is the place where magic begin.

As You can see there is bindListener to SidebarActions.ComponentStatusChanged which will be used IF setSiteComponent will be used.

now in SidebarActions

    componentStatusChanged(value){
    this.dispatch({value: value});
}

We have such thing. It will dispatch that object on call. And it will be called if setSiteComponent in store will be used (that you can use in component for example during onChange on Button ot whatever)

Now in SidebarStore we will have

    constructor() {
    this.structures = [];

    this.bindListeners({
        componentStatusChanged: SidebarActions.COMPONENT_STATUS_CHANGED
    })
}

    componentStatusChanged(data) {
    this.waitFor(DetailsStore);

    _.findWhere(this.structures[0].elem, {title: 'Example'}).enabled = data.value;
}

Now here you can see, that it will wait for DetailsStore. What does it mean? more or less it means that this method need to wait for DetailsStoreto update before it can update itself.

tl;dr One Store is listening on methods in a store, and will trigger an action from component action, which will update its own store.

I hope it can help you somehow.

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Jackson - How to process (deserialize) nested JSON?

Your data is problematic in that you have inner wrapper objects in your array. Presumably your Vendor object is designed to handle id, name, company_id, but each of those multiple objects are also wrapped in an object with a single property vendor.

I'm assuming that you're using the Jackson Data Binding model.

If so then there are two things to consider:

The first is using a special Jackson config property. Jackson - since 1.9 I believe, this may not be available if you're using an old version of Jackson - provides UNWRAP_ROOT_VALUE. It's designed for cases where your results are wrapped in a top-level single-property object that you want to discard.

So, play around with:

objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);

The second is using wrapper objects. Even after discarding the outer wrapper object you still have the problem of your Vendor objects being wrapped in a single-property object. Use a wrapper to get around this:

class VendorWrapper
{
    Vendor vendor;

    // gettors, settors for vendor if you need them
}

Similarly, instead of using UNWRAP_ROOT_VALUES, you could also define a wrapper class to handle the outer object. Assuming that you have correct Vendor, VendorWrapper object, you can define:

class VendorsWrapper
{
    List<VendorWrapper> vendors = new ArrayList<VendorWrapper>();

    // gettors, settors for vendors if you need them
}

// in your deserialization code:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonInput, VendorsWrapper.class); 

The object tree for VendorsWrapper is analogous to your JSON:

VendorsWrapper:
    vendors:
    [
        VendorWrapper
            vendor: Vendor,
        VendorWrapper:
            vendor: Vendor,
        ...
    ]

Finally, you might use the Jackson Tree Model to parse this into JsonNodes, discarding the outer node, and for each JsonNode in the ArrayNode, calling:

mapper.readValue(node.get("vendor").getTextValue(), Vendor.class);

That might result in less code, but it seems no less clumsy than using two wrappers.

Maximum execution time in phpMyadmin

In php.ini you must check mysql.connect_timeout either. That's responsible for socket closing and returning the Fatal. So, for example, change it to:

mysql.connect_timeout = 3600

That time will be always counted in seconds, so in my example you have 1 hour.

JSON and XML comparison

Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.

An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.

Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.

Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.

After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.

Anyway, only testing will provides the answer for your particular use-case (if speed is really the only matter, and not standard nor safety nor integrity…).

Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.

Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.

Update 2015-03-01

Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Coding for the HTTP protocol (alongside with compress, deflate and gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters (iana.org).

Is there 'byte' data type in C++?

No, there is no type called "byte" in C++. What you want instead is unsigned char (or, if you need exactly 8 bits, uint8_t from <cstdint>, since C++11). Note that char is not necessarily an accurate alternative, as it means signed char on some compilers and unsigned char on others.

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Python 3 Building an array of bytes

I think Scapy is what are you looking for.

http://www.secdev.org/projects/scapy/

you can build and send frames (packets) with it

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

How to determine CPU and memory consumption from inside a process?

Windows

Some of the above values are easily available from the appropriate WIN32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)

Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!


  • Total Virtual Memory:

    #include "windows.h"
    
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    

    Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.

  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

     DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    
  • Virtual Memory currently used by current process:

    #include "windows.h"
    #include "psapi.h"
    
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
    



  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
    
  • Physical Memory currently used by current process:

    Same code as in "Virtual Memory currently used by current process" and then

    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
    



  • CPU currently used:

    #include "TCHAR.h"
    #include "pdh.h"
    
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuTotal;
    
    void init(){
        PdhOpenQuery(NULL, NULL, &cpuQuery);
        // You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
        PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
        PdhCollectQueryData(cpuQuery);
    }
    
    double getCurrentValue(){
        PDH_FMT_COUNTERVALUE counterVal;
    
        PdhCollectQueryData(cpuQuery);
        PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
        return counterVal.doubleValue;
    }
    
  • CPU currently used by current process:

    #include "windows.h"
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    static HANDLE self;
    
    void init(){
        SYSTEM_INFO sysInfo;
        FILETIME ftime, fsys, fuser;
    
        GetSystemInfo(&sysInfo);
        numProcessors = sysInfo.dwNumberOfProcessors;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&lastCPU, &ftime, sizeof(FILETIME));
    
        self = GetCurrentProcess();
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
        memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
    }
    
    double getCurrentValue(){
        FILETIME ftime, fsys, fuser;
        ULARGE_INTEGER now, sys, user;
        double percent;
    
        GetSystemTimeAsFileTime(&ftime);
        memcpy(&now, &ftime, sizeof(FILETIME));
    
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&sys, &fsys, sizeof(FILETIME));
        memcpy(&user, &fuser, sizeof(FILETIME));
        percent = (sys.QuadPart - lastSysCPU.QuadPart) +
            (user.QuadPart - lastUserCPU.QuadPart);
        percent /= (now.QuadPart - lastCPU.QuadPart);
        percent /= numProcessors;
        lastCPU = now;
        lastUserCPU = user;
        lastSysCPU = sys;
    
        return percent * 100;
    }
    

Linux

On Linux the choice that seemed obvious at first was to use the POSIX APIs like getrusage() etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?

In the end I got all values via a combination of reading the pseudo-filesystem /proc and kernel calls.

  • Total Virtual Memory:

    #include "sys/types.h"
    #include "sys/sysinfo.h"
    
    struct sysinfo memInfo;
    
    sysinfo (&memInfo);
    long long totalVirtualMem = memInfo.totalram;
    //Add other values in next statement to avoid int overflow on right hand side...
    totalVirtualMem += memInfo.totalswap;
    totalVirtualMem *= memInfo.mem_unit;
    
  • Virtual Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
    //Add other values in next statement to avoid int overflow on right hand side...
    virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
    virtualMemUsed *= memInfo.mem_unit;
    
  • Virtual Memory currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    int parseLine(char* line){
        // This assumes that a digit will be found and the line ends in " Kb".
        int i = strlen(line);
        const char* p = line;
        while (*p <'0' || *p > '9') p++;
        line[i-3] = '\0';
        i = atoi(p);
        return i;
    }
    
    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmSize:", 7) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    



  • Total Physical Memory (RAM):

    Same code as in "Total Virtual Memory" and then

    long long totalPhysMem = memInfo.totalram;
    //Multiply in next statement to avoid int overflow on right hand side...
    totalPhysMem *= memInfo.mem_unit;
    
  • Physical Memory currently used:

    Same code as in "Total Virtual Memory" and then

    long long physMemUsed = memInfo.totalram - memInfo.freeram;
    //Multiply in next statement to avoid int overflow on right hand side...
    physMemUsed *= memInfo.mem_unit;
    
  • Physical Memory currently used by current process:

    Change getValue() in "Virtual Memory currently used by current process" as follows:

    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmRSS:", 6) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    



  • CPU currently used:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
    
    void init(){
        FILE* file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
            &lastTotalSys, &lastTotalIdle);
        fclose(file);
    }
    
    double getCurrentValue(){
        double percent;
        FILE* file;
        unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
    
        file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
            &totalSys, &totalIdle);
        fclose(file);
    
        if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
            totalSys < lastTotalSys || totalIdle < lastTotalIdle){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
                (totalSys - lastTotalSys);
            percent = total;
            total += (totalIdle - lastTotalIdle);
            percent /= total;
            percent *= 100;
        }
    
        lastTotalUser = totalUser;
        lastTotalUserLow = totalUserLow;
        lastTotalSys = totalSys;
        lastTotalIdle = totalIdle;
    
        return percent;
    }
    
  • CPU currently used by current process:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    #include "sys/times.h"
    #include "sys/vtimes.h"
    
    static clock_t lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    
    void init(){
        FILE* file;
        struct tms timeSample;
        char line[128];
    
        lastCPU = times(&timeSample);
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        file = fopen("/proc/cpuinfo", "r");
        numProcessors = 0;
        while(fgets(line, 128, file) != NULL){
            if (strncmp(line, "processor", 9) == 0) numProcessors++;
        }
        fclose(file);
    }
    
    double getCurrentValue(){
        struct tms timeSample;
        clock_t now;
        double percent;
    
        now = times(&timeSample);
        if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
            timeSample.tms_utime < lastUserCPU){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            percent = (timeSample.tms_stime - lastSysCPU) +
                (timeSample.tms_utime - lastUserCPU);
            percent /= (now - lastCPU);
            percent /= numProcessors;
            percent *= 100;
        }
        lastCPU = now;
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        return percent;
    }
    

TODO: Other Platforms

I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by getrusage() and similar functions? If someone with Unix know-how could edit this answer and fill in the details?!

ERROR! MySQL manager or server PID file could not be found! QNAP

I had the same issue. It turns out I added incorrect variables to the my.cnf file. Once I removed them and restarted mysql started with no issue.

Copying files from server to local computer using SSH

It depends on what your local OS is.

If your local OS is Unix-like, then try:

scp username@remoteHost:/remote/dir/file.txt /local/dir/

If your local OS is Windows ,then you should use pscp.exe utility. For example, below command will download file.txt from remote to D: disk of local machine.

pscp.exe username@remoteHost:/remote/dir/file.txt d:\

It seems your Local OS is Unix, so try the former one.


For those who don't know what pscp.exe is and don't know where it is, you can always go to putty official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

Cleanest way to toggle a boolean variable in Java?

The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang

BooleanUtils.negate(theBoolean)

Conditional Count on a field

Using ANSI SQL-92 CASE Statements, you could do something like this (derived table plus case):

 SELECT jobId, jobName, SUM(Priority1)
 AS Priority1, SUM(Priority2) AS
 Priority2, SUM(Priority3) AS
 Priority3, SUM(Priority4) AS
 Priority4,  SUM(Priority5) AS
 Priority5 FROM (
     SELECT jobId, jobName,
     CASE WHEN Priority = 1 THEN 1 ELSE 0 END AS Priority1,
     CASE WHEN Priority = 2 THEN 1 ELSE 0 END AS Priority2,
     CASE WHEN Priority = 3 THEN 1 ELSE 0 END AS Priority3,
     CASE WHEN Priority = 4 THEN 1 ELSE 0 END AS Priority4,
     CASE WHEN Priority = 5 THEN 1 ELSE 0 END AS Priority5
     FROM TableName


)

How to convert SQL Server's timestamp column to datetime format

My coworkers helped me with this:

select CONVERT(VARCHAR(10), <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(VARCHAR(10), <tms_column>, 112);

or

select CONVERT(DATE, <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(DATE, <tms_column>, 112);

How to get parameters from a URL string?

Dynamic function which parse string url and get value of query parameter passed in URL

function getParamFromUrl($url,$paramName){
  parse_str(parse_url($url,PHP_URL_QUERY),$op);// fetch query parameters from string and convert to associative array
  return array_key_exists($paramName,$op) ? $op[$paramName] : "Not Found"; // check key is exist in this array
}

Call Function to get result

echo getParamFromUrl('https://google.co.in?name=james&surname=bond','surname'); // bond will be o/p here

How do you tell if a checkbox is selected in Selenium for Java?

For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):

NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the ! sign at the beginning of the statement.

if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected()) 
{
  driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}

How To Include CSS and jQuery in my WordPress plugin?

To include CSS and jQuery in your plugin is easy, try this:

// register jquery and style on initialization
add_action('init', 'register_script');
function register_script() {
    wp_register_script( 'custom_jquery', plugins_url('/js/custom-jquery.js', __FILE__), array('jquery'), '2.5.1' );

    wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
}

// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');

function enqueue_style(){
   wp_enqueue_script('custom_jquery');

   wp_enqueue_style( 'new_style' );
}

I found this great snipped from this site How to include jQuery and CSS in WordPress – The WordPress Way

Hope that helps.

Counting duplicates in Excel

This can be done using pivot tables. See this youtube video for a walkthrough: Quickly Count Duplicates in Excel List With Pivot Table.

To count the number of times each item is duplicated in an Excel list, you can use a pivot table, instead of manually creating a list with formulas.

How to quietly remove a directory with content in PowerShell

2018 Update

In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName to silently delete the directory .\DirName with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.

Imitating a blink tag with CSS3 animations

if you want some glow effect use this

@keyframes blink {
  50% {
    opacity: 0.0;
  }
}
@-webkit-keyframes blink {
  50% {
    opacity: 0.0;
  }
}

atom-text-editor::shadow  .bracket-matcher .region {
    border:none;
    background-color: rgba(195,195,255,0.1);
    border-bottom: 1px solid rgb(155,155,255);
    box-shadow: 0px 0px 9px 4px rgba(155,155,255,0.1);
    border-radius: 3px;
    animation: blink 2s steps(115, start) infinite;
    -webkit-animation: blink 2s steps(115, start) infinite;
}

How can I split a delimited string into an array in PHP?

In simple way you can go with explode($delimiter, $string);

But in a broad way, with Manual Programming :

        $string = "ab,cdefg,xyx,ht623";
        $resultArr = [];
        $strLength = strlen($string);
        $delimiter = ',';
        $j = 0;
        $tmp = '';
        for ($i = 0; $i < $strLength; $i++) {
            if($delimiter === $string[$i]) {
                $j++;
                $tmp = '';
                continue;
            }
            $tmp .= $string[$i];
            $resultArr[$j] = $tmp;
        }

Outpou : print_r($resultArr);

Array
(
    [0] => ab
    [1] => cdefg
    [2] => xyx
    [3] => ht623
)

Is it possible to hide the cursor in a webpage using CSS or Javascript?

For whole html document try this

html * {cursor:none}

Or if some css overwrite your cursor: none use !important

html * {cursor:none!important}

Why use 'virtual' for class properties in Entity Framework model definitions?

It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.

Edit to clarify "create a proxy around": By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".

The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.

If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.

Edit to describe why properties would be marked as virtual

Properties such as:

 public ICollection<RSVP> RSVPs { get; set; }

Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.

//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
    return _RSVPs;
}

public void set_RSVPs(RSVP value)
{
    _RSVPs = value;
}

private RSVP _RSVPs;

That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get and set functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:

 public virtual ICollection<RSVP> RSVPs;

Matlab: Running an m-file from command-line

On Linux you can do the same and you can actually send back to the shell a custom error code, like the following:

#!/bin/bash
matlab -nodisplay -nojvm -nosplash -nodesktop -r \ 
      "try, run('/foo/bar/my_script.m'), catch, exit(1), end, exit(0);"
echo "matlab exit code: $?"

it prints matlab exit code: 1 if the script throws an exception, matlab exit code: 0 otherwise.

On postback, how can I check which control cause postback in Page_Init event

Here's some code that might do the trick for you (taken from Ryan Farley's blog)

public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

SQL Server insert if not exists best practice

Semantically you are asking "insert Competitors where doesn't already exist":

INSERT Competitors (cName)
SELECT DISTINCT Name
FROM CompResults cr
WHERE
   NOT EXISTS (SELECT * FROM Competitors c
              WHERE cr.Name = c.cName)

Get last 3 characters of string

Many ways this can be achieved.

Simple approach should be taking Substring of an input string.

var result = input.Substring(input.Length - 3);

Another approach using Regular Expression to extract last 3 characters.

var result = Regex.Match(input,@"(.{3})\s*$");

Working Demo

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

After following the steps from @Johnride, I still got the same error.

This fixed the problem:

Tools-> Options-> Select no proxy

source: https://www.youtube.com/watch?v=uI1j-8F8eN4

How to pause for specific amount of time? (Excel/VBA)

Function Delay(ByVal T As Integer)
    'Function can be used to introduce a delay of up to 99 seconds
    'Call Function ex:  Delay 2 {introduces a 2 second delay before execution of code resumes}
        strT = Mid((100 + T), 2, 2)
            strSecsDelay = "00:00:" & strT
    Application.Wait (Now + TimeValue(strSecsDelay))
End Function

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

it would be helpful to know if you use linux or windows. in linux the settings are located in ~/.smartgit/3. You could try to remove this folder. Imho this is also worth a try in Windows.

Build and Install unsigned apk on device without the development server?

React Version 0.62.1

In your root project directory

Make sure you have already directory android/app/src/main/assets/, if not create directory, after that create new file and save as index.android.bundle and put your file in like this android/app/src/main/assets/index.android.bundle

After that run this

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

cd android && ./gradlew assembleDebug

Then you can get apk in app/build/outputs/apk/debug/app-debug.apk

Changing website favicon dynamically

A more modern approach:

const changeFavicon = link => {
  let $favicon = document.querySelector('link[rel="icon"]')
  // If a <link rel="icon"> element already exists,
  // change its href to the given link.
  if ($favicon !== null) {
    $favicon.href = link
  // Otherwise, create a new element and append it to <head>.
  } else {
    $favicon = document.createElement("link")
    $favicon.rel = "icon"
    $favicon.href = link
    document.head.appendChild($favicon)
  }
}

You can then use it like this:

changeFavicon("http://www.stackoverflow.com/favicon.ico")

Purpose of a constructor in Java?

As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.

Example:

Say you have an Animal class something like

class Animal{
   private String name;
   private String type;
}

Lets see what happens when you try to create an instance of Animal class, say a Dog named Puppy. Now you have have to initialize name = Puppy and type = Dog. So, how can you do that. A way of doing it is having a constructor like

    Animal(String nameProvided, String typeProvided){
         this.name = nameProvided;
         this.type = typeProvided;
     }

Now when you create an object of class Animal, something like Animal dog = new Animal("Puppy", "Dog"); your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.

Now you might ask what if I didn't provide an argument to my constructor something like

Animal xyz = new Animal();

This is a default Constructor which initializes the object with default values i.e. in our Animal class name and type values corresponding to xyz object would be name = null and type = null

Getting command-line password input in Python

Use getpass for this purpose.

getpass.getpass - Prompt the user for a password without echoing

What is an attribute in Java?

Attributes is same term used alternativly for properties or fields or data members or class members.