Programs & Examples On #Shark

Shark is Apple's legacy performance analysis tool. You probably want to use a different tag.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

npm install doesn't create node_modules directory

I ran into this trying to integrate React Native into an existing swift project using cocoapods. The FB docs (at time of writing) did not specify that npm install react-native wouldn't work without first having a package.json file. Per the RN docs set your entry point: (index.js) as index.ios.js

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.

My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.

  1. Switches - (very unlikely but sometimes they get in a sick state)
  2. Routers - more likely than switches, but not much
  3. Firewall - More likely than routers. Things to look for here are resource exhaustion (license, cpu, etc)
  4. Client side filtering software - antivirus, malware detection etc.

Android : Capturing HTTP Requests with non-rooted android device

I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above

https://play.google.com/store/apps/details?id=org.sandroproxy.drony

It intercepts the requests and are shown on a LOG

Fill Combobox from database

To use the Combobox in the way you intend, you could pass in an object to the cmbTripName.Items.Add method.

That object should have FleetID and FleetName properties:

while (drd.Read())
{
    cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

The Fleet Class:

class Fleet
{
     public Fleet(string fleetId, string fleetName)
     {
           FleetId = fleetId;
           FleetName = fleetName
     }
     public string FleetId {get;set;}
     public string FleetName {get;set;}
}

Or, You could probably do away with the need for a Fleet class completely by using an anonymous type...

while (drd.Read())
{
    cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Capturing mobile phone traffic on Wireshark

I had a similar problem that inspired me to develop an app that could help to capture traffic from an Android device. The app features SSH server that allows you to have traffic in Wireshark on the fly (sshdump wireshark component). As the app uses an OS feature called VPNService to capture traffic, it does not require the root access.

The app is in early Beta. If you have any issues/suggestions, do not hesitate to let me know.

Download From Play

Tutorial in which you could read additional details

Why doesn't wireshark detect my interface?

For *nix OSes, run wireshark with sudo privileges. You need to be superuser in order to be able to view interfaces. Just like running tcpdump -D vs sudo tcpdump -D, the first one won't show any of the interfaces, won't compalain/prompt for sudo privileges either.

So, from terminal, run:

$ sudo wireshark

Python: maximum recursion depth exceeded while calling a Python object

Instead of doing recursion, the parts of the code with checkNextID(ID + 18) and similar could be replaced with ID+=18, and then if you remove all instances of return 0, then it should do the same thing but as a simple loop. You should then put a return 0 at the end and make your variables non-global.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

All you need to do is to go to the control panel > Computer Management > Services and manually start the SQL express or SQL server. It worked for me.

Good luck.

Python: Binding Socket: "Address already in use"

Try using the SO_REUSEADDR socket option before binding the socket.

comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Edit: I see you're still having trouble with this. There is a case where SO_REUSEADDR won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR enabled), then TIME_WAIT will still be in effect. It will however allow you to connect to a different host:port.

A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.

Wireshark localhost traffic capture

You can view loopback traffic live in Wireshark by having it read RawCap's output instantly. cmaynard describes this ingenious approach at the Wireshark forums. I will cite it here:

[...] if you want to view live traffic in Wireshark, you can still do it by running RawCap from one command-line and running Wireshark from another. Assuming you have cygwin's tail available, this could be accomplished using something like so:

cmd1: RawCap.exe -f 127.0.0.1 dumpfile.pcap

cmd2: tail -c +0 -f dumpfile.pcap | Wireshark.exe -k -i -

It requires cygwin's tail, and I could not find a way to do this with Windows' out-of-the-box tools. His approach works very fine for me and allows me to use all of Wiresharks filter capabilities on captured loopback traffic live.

How to filter by IP address in Wireshark?

Actually for some reason wireshark uses two different kind of filter syntax one on display filter and other on capture filter. Display filter is only useful to find certain traffic just for display purpose only. its like you are interested in all trafic but for now you just want to see specific.

but if you are interested only in certian traffic and does not care about other at all then you use the capture filter.

The Syntax for display filter is (as mentioned earlier)

ip.addr = x.x.x.x or ip.src = x.x.x.x or ip.dst = x.x.x.x

but above syntax won't work in capture filters, following are the filters

host x.x.x.x

see more example on wireshark wiki page

Change the class from factor to numeric of many columns in a data frame

I found this function on a couple other duplicate threads and have found it an elegant and general way to solve this problem. This thread shows up first on most searches on this topic, so I am sharing it here to save folks some time. I take no credit for this just so see the original posts here and here for details.

df <- data.frame(x = 1:10,
                 y = rep(1:2, 5),
                 k = rnorm(10, 5,2),
                 z = rep(c(2010, 2012, 2011, 2010, 1999), 2),
                 j = c(rep(c("a", "b", "c"), 3), "d"))

convert.magic <- function(obj, type){
  FUN1 <- switch(type,
                 character = as.character,
                 numeric = as.numeric,
                 factor = as.factor)
  out <- lapply(obj, FUN1)
  as.data.frame(out)
}

str(df)
str(convert.magic(df, "character"))
str(convert.magic(df, "factor"))
df[, c("x", "y")] <- convert.magic(df[, c("x", "y")], "factor")

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

Iterating through a JSON object

Adding another solution (Python 3) - Iterating over json files in a directory and on each file iterating over all objects and printing relevant fields.

See comments in the code.

import os,json

data_path = '/path/to/your/json/files'  

# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    # 2. Take only json files
    if filename.endswith(".json"):
        file_full_path=data_path+filename
        # 3. Open json file 
        with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
            data_in_file = json.load(json_data, strict=False)
            # 4. Iterate over objects and print relevant fields
            for json_object in data_in_file:
                print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

iPhone and WireShark

I like to use Pirni (availble for free in Cydia on a jailbroken device), or there's also Pirni Pro now for a few bucks (http://en.wikipedia.org/wiki/Pirni). I've been using the pirni-derv script available for free on Google Code (http://code.google.com/p/pirni-derv/) mixed with Pirni and it's been working very well. I recommend it.

Filter by process/PID in Wireshark

If you want to follow an application that still has to be started then it's certainly possible:

  1. Install docker (see https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/)
  2. Open a terminal and run a tiny container: docker run -t -i ubuntu /bin/bash (change "ubuntu" to your favorite distro, this doesn't have to be the same as in your real system)
  3. Install your application in the container using the same way that you would install it in a real system.
  4. Start wireshark in your real system, go to capture > options . In the window that will open you'll see all your interfaces. Instead of choosing any, wlan0, eth0, ... choose the new virtual interface docker0 instead.
  5. Start capturing
  6. Start your application in the container

You might have some doubts about running your software in a container, so here are the answers to the questions you probably want to ask:

  • Will my application work inside a container ? Almost certainly yes, but you might need to learn a bit about docker to get it working
  • Won't my application run slow ? Negligible. If your program is something that runs heavy calculations for a week then it might now take a week and 3 seconds
  • What if my software or something else breaks in the container ? That's the nice thing about containers. Whatever is running inside can only break the current container and can't hurt the rest of the system.

WCF timeout exception detailed investigation

You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};

Large WCF web service request failing with (400) HTTP Bad Request

In my case, it was not working even after trying all solutions and setting all limits to max. In last I found out that a Microsoft IIS filtering module Url Scan 3.1 was installed on IIS/website, which have it's own limit to reject incoming requests based on content size and return "404 Not found page".

It's limit can be updated in %windir%\System32\inetsrv\urlscan\UrlScan.ini file by setting MaxAllowedContentLength to the required value.

For eg. following will allow upto 300 mb requests

MaxAllowedContentLength=314572800

Hope it will help someone!

How do you monitor network traffic on the iPhone?

Run it through a proxy and monitor the traffic using Wireshark.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

What causes a TCP/IP reset (RST) flag to be sent?

RST is sent by the side doing the active close because it is the side which sends the last ACK. So if it receives FIN from the side doing the passive close in a wrong state, it sends a RST packet which indicates other side that an error has occured.

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

MongoDB not equal to

Real life example; find all but not current user:

var players = Players.find({ my_x: player.my_x,  my_y: player.my_y, userId: {$ne: Meteor.userId()} }); 

Case vs If Else If: Which is more efficient?

Many programming language optimize the switch statement so that it is much faster than a standard if-else if structure provided the cases are compiler constants. Many languages use a jump table or indexed branch table to optimize switch statements. Wikipedia has a good discussion of the switch statement. Also, here is a discussion of switch optimization in C.

One thing to note is that switch statements can be abused and, depending on the case, it may be preferable to use polymorphism instead of switch statements. See here for an example.

Main differences between SOAP and RESTful web services in Java

  • REST stands for representational state transfer whereas SOAP stands for Simple Object Access Protocol.

  • SOAP defines its own security where as REST inherits security from the underlying transport.

  • SOAP does not support error handling, but REST has built-in error handling.

  • REST is lightweight and does not require XML parsing. REST can be consumed by any client, even a web browser with Ajax and JavaScript. REST consumes less bandwidth, it does not require a SOAP header for every message.

    • REST is useful over any protocol which provide a URI. Ignore point 5 for REST as mentioned below in the picture.

SOAP vs. REST

What are valid values for the id attribute in HTML?

To reference an id with a period in it you need to use a backslash. Not sure if its the same for hyphens or underscores. For example: HTML

<div id="maintenance.instrumentNumber">############0218</div>

CSS

#maintenance\.instrumentNumber{word-wrap:break-word;}

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

Forcing Internet Explorer 9 to use standards document mode

To prevent quirks mode, define a 'doctype' like :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

To make IE render the page in IE9 document mode :

<meta http-equiv="x-ua-compatible" content="IE=9">

Please note that "IE=edge" will make IE render the page with the most recent document mode, rather than IE9 document mode.

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

'import' and 'export' may only appear at the top level

I do not know how to solve this problem differently, but this is solved simply. The loader babel should be placed at the beginning of the array and everything works.

Get position/offset of element relative to a parent container?

I did it like this in Internet Explorer.

function getWindowRelativeOffset(parentWindow, elem) {
    var offset = {
        left : 0,
        top : 0
    };
    // relative to the target field's document
    offset.left = elem.getBoundingClientRect().left;
    offset.top = elem.getBoundingClientRect().top;
    // now we will calculate according to the current document, this current
    // document might be same as the document of target field or it may be
    // parent of the document of the target field
    var childWindow = elem.document.frames.window;
    while (childWindow != parentWindow) {
        offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
        offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
        childWindow = childWindow.parent;
    }

    return offset;
};

=================== you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus on IE only as per my focus but similar things can be done for other browsers.

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

Solutions for INSERT OR UPDATE on SQL Server

That depends on the usage pattern. One has to look at the usage big picture without getting lost in the details. For example, if the usage pattern is 99% updates after the record has been created, then the 'UPSERT' is the best solution.

After the first insert (hit), it will be all single statement updates, no ifs or buts. The 'where' condition on the insert is necessary otherwise it will insert duplicates, and you don't want to deal with locking.

UPDATE <tableName> SET <field>=@field WHERE key=@key;

IF @@ROWCOUNT = 0
BEGIN
   INSERT INTO <tableName> (field)
   SELECT @field
   WHERE NOT EXISTS (select * from tableName where key = @key);
END

How to Flatten a Multidimensional Array?

This is my solution, using a reference:

function arrayFlatten($array_in, &$array_out){

    if(is_array($array_in)){
        foreach ($array_in as $element){
               arrayFlatten($element, $array_out);
        }
    }
    else{
        $array_out[] = $array_in; 
    }
}

$arr1 = array('1', '2', array(array(array('3'), '4', '5')), array(array('6')));

arrayFlatten($arr1, $arr2);

echo "<pre>";
print_r($arr2);
echo "</pre>";

T-SQL Cast versus Convert

You should also not use CAST for getting the text of a hash algorithm. CAST(HASHBYTES('...') AS VARCHAR(32)) is not the same as CONVERT(VARCHAR(32), HASHBYTES('...'), 2). Without the last parameter, the result would be the same, but not a readable text. As far as I know, You cannot specify that last parameter in CAST.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

Getting Current time to display in Label. VB.net

There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.

html select option SELECTED

foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

Bat file to run a .exe at the command prompt

Just put that line in the bat file...

Alternatively you can even make a shortcut for svcutil.exe, then add the arguments in the 'target' window.

ArrayBuffer to base64 encoded string

I used this and works for me.

function arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}



function base64ToArrayBuffer(base64) {
    var binary_string =  window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

UIButton Image + Text IOS

You should create custom imageview for image and custom label for text and you add to your button as subviews. That's it.

UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);     
[yourButton addTarget:self action:@selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:yourButton];

UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:@"images.jpg"];
[yourButton addSubview:imageView1];

UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = @"ButtonTitle";
[yourButton addSubview:label];

For testing purpose, use yourButtonSelected: method

-(void)yourButtonSelected:(id)sender{
    NSLog(@"Your Button Selected");

}

I think it will be helpful to you.

android - save image into gallery

In my case the solutions above did not work I had to do the following:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Convert string to Python class object?

In terms of arbitrary code execution, or undesired user passed names, you could have a list of acceptable function/class names, and if the input matches one in the list, it is eval'd.

PS: I know....kinda late....but it's for anyone else who stumbles across this in the future.

How can I convert a stack trace to a string?

Kotlin

Extending the Throwable class will give you the String property error.stackTraceString:

val Throwable.stackTraceString: String
  get() {
    val sw = StringWriter()
    val pw = PrintWriter(sw)
    this.printStackTrace(pw)
    return sw.toString()
  }

WAMP won't turn green. And the VCRUNTIME140.dll error

As Oriol said, you need the following redistributables before installing WAMP.

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

Using numpy to build an array of all combinations of two arrays

Here's yet another way, using pure NumPy, no recursion, no list comprehension, and no explicit for loops. It's about 20% slower than the original answer, and it's based on np.meshgrid.

def cartesian(*arrays):
    mesh = np.meshgrid(*arrays)  # standard numpy meshgrid
    dim = len(mesh)  # number of dimensions
    elements = mesh[0].size  # number of elements, any index will do
    flat = np.concatenate(mesh).ravel()  # flatten the whole meshgrid
    reshape = np.reshape(flat, (dim, elements)).T  # reshape and transpose
    return reshape

For example,

x = np.arange(3)
a = cartesian(x, x, x, x, x)
print(a)

gives

[[0 0 0 0 0]
 [0 0 0 0 1]
 [0 0 0 0 2]
 ..., 
 [2 2 2 2 0]
 [2 2 2 2 1]
 [2 2 2 2 2]]

Call a function with argument list in python

The simpliest way to wrap a function

    func(*args, **kwargs)

... is to manually write a wrapper that would call func() inside itself:

    def wrapper(*args, **kwargs):
        # do something before
        try:
            return func(*a, **kwargs)
        finally:
            # do something after

In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wrapper generator for any function anyFunc():

    def wrapperGenerator(anyFunc, *args, **kwargs):
        def wrapper(*args, **kwargs):
            try:
                # do something before
                return anyFunc(*args, **kwargs)
            finally:
                #do something after
        return wrapper

Please also note that in Python when you don't know or don't want to name all the arguments of a function, you can refer to a tuple of arguments, which is denoted by its name, preceded by an asterisk in the parentheses after the function name:

    *args

For example you can define a function that would take any number of arguments:

    def testFunc(*args):
        print args    # prints the tuple of arguments

Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:

    **kwargs

A similar example that prints the keyword arguments dictionary:

    def testFunc(**kwargs):
        print kwargs    # prints the dictionary of keyword arguments

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.

Set a persistent environment variable from cmd.exe

An example with VBScript (.vbs)

Sub sety(wsh, action, typey, vary, value)
  Dim wu
  Set wu = wsh.Environment(typey)
  wui = wu.Item(vary)
  Select Case action
    Case "ls"
      WScript.Echo wui
    Case "del"
      On Error Resume Next
      wu.remove(vary)
      On Error Goto 0
    Case "set"
      wu.Item(vary) = value
    Case "add"
      If wui = "" Then
        wu.Item(vary) = value
      ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
        wu.Item(vary) = value & ";" & wui
      End If
    Case Else
      WScript.Echo "Bad action"
  End Select
End Sub

Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
  Case 3
    value = ""
  Case 4
    value = args(3)
  Case Else
    WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
    value = "```"
End Select
If Not value = "```" Then
  ' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
  sety wsh, args(0), args(1), UCase(args(2)), value
End If

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Java Scanner class reading strings

You could have simply replaced

names[i] = in.nextLine(); with names[i] = in.next();

Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

MVC Razor view nested foreach's model

When you are using foreach loop within view for binded model ... Your model is supposed to be in listed format.

i.e

@model IEnumerable<ViewModels.MyViewModels>


        @{
            if (Model.Count() > 0)
            {            

                @Html.DisplayFor(modelItem => Model.Theme.FirstOrDefault().name)
                @foreach (var theme in Model.Theme)
                {
                   @Html.DisplayFor(modelItem => theme.name)
                   @foreach(var product in theme.Products)
                   {
                      @Html.DisplayFor(modelItem => product.name)
                      @foreach(var order in product.Orders)
                      {
                          @Html.TextBoxFor(modelItem => order.Quantity)
                         @Html.TextAreaFor(modelItem => order.Note)
                          @Html.EditorFor(modelItem => order.DateRequestedDeliveryFor)
                      }
                  }
                }
            }else{
                   <span>No Theam avaiable</span>
            }
        }

Javascript call() & apply() vs bind()?

Use bind for future calls to the function. Both apply and call invoke the function.

bind() also allows for additional arguments to be perpended to the args array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

How to import image (.svg, .png ) in a React Component

You can use require as well to render images like

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

How to iterate through range of Dates in Java?

We can migrate the logic to various methods foe Java 7, Java 8 and Java 9:

public static List<Date> getDatesRangeJava7(Date startDate, Date endDate) {
    List<Date> datesInRange = new ArrayList<>();
    Calendar startCalendar = new GregorianCalendar();
    startCalendar.setTime(startDate);
    Calendar endCalendar = new GregorianCalendar();
    endCalendar.setTime(endDate);
    while (startCalendar.before(endCalendar)) {
        Date result = startCalendar.getTime();
        datesInRange.add(result);
        startCalendar.add(Calendar.DATE, 1);
    }
    return datesInRange;
}

public static List<LocalDate> getDatesRangeJava8(LocalDate startDate, LocalDate endDate) {
    int numOfDays = (int) ChronoUnit.DAYS.between(startDate, endDate);
    return IntStream.range(0, numOfDays)
            .mapToObj(startDate::plusDays)
            .collect(Collectors.toList());
}

public static List<LocalDate> getDatesRangeJava9(LocalDate startDate, LocalDate endDate) {
    return startDate.datesUntil(endDate).collect(Collectors.toList());
}

Then we can invoke these methods as:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2010-12-20");
Date endDate = formatter.parse("2010-12-26");
List<Date> dateRangeList = getDatesRangeJava7(startDate, endDate);
System.out.println(dateRangeList);

LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
List<LocalDate> dateRangeList8 = getDatesRangeJava8(startLocalDate, endLocalDate);
System.out.println(dateRangeList8);
List<LocalDate> dateRangeList9 = getDatesRangeJava8(startLocalDate, endLocalDate);
System.out.println(dateRangeList9);

The output would be:

[Mon Dec 20 00:00:00 IST 2010, Tue Dec 21 00:00:00 IST 2010, Wed Dec 22 00:00:00 IST 2010, Thu Dec 23 00:00:00 IST 2010, Fri Dec 24 00:00:00 IST 2010, Sat Dec 25 00:00:00 IST 2010]

[2010-12-20, 2010-12-21, 2010-12-22, 2010-12-23, 2010-12-24, 2010-12-25]

[2010-12-20, 2010-12-21, 2010-12-22, 2010-12-23, 2010-12-24, 2010-12-25]

generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.

How do I replace a character in a string in Java?

//I think this will work, you don't have to replace on the even, it's just an example. 

 public void emphasize(String phrase, char ch)
    {
        char phraseArray[] = phrase.toCharArray(); 
        for(int i=0; i< phrase.length(); i++)
        {
            if(i%2==0)// even number
            {
                String value = Character.toString(phraseArray[i]); 
                value = value.replace(value,"*"); 
                phraseArray[i] = value.charAt(0);
            }
        }
    }

Bootstrap modal link

A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.

 <div class="container">
        <div class="row">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--&times;-->
                            <h4 class="modal-title text-center" id="addContact">Add Contact</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <ul class="nav nav-tabs">
                                    <li class="active">
                                        <a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
                                    </li>
                                    <li>
                                        <a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
                                    </li>
                                </ul>
                                <div class="tab-content">
                                    <div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
                                    <div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
                                </div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <a class="btn btn-info" data-dismiss="modal">Close</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Python: Converting string into decimal number

If you are converting price (in string) to decimal price then....

from decimal import Decimal

price = "14000,45"
price_in_decimal = Decimal(price.replace(',','.'))

No need for the replace if your strings already use dots as a decimal separator

Timer function to provide time in nano seconds using C++

If this is for Linux, I've been using the function "gettimeofday", which returns a struct that gives the seconds and microseconds since the Epoch. You can then use timersub to subtract the two to get the difference in time, and convert it to whatever precision of time you want. However, you specify nanoseconds, and it looks like the function clock_gettime() is what you're looking for. It puts the time in terms of seconds and nanoseconds into the structure you pass into it.

String literals and escape characters in postgresql

Partially. The text is inserted, but the warning is still generated.

I found a discussion that indicated the text needed to be preceded with 'E', as such:

insert into EscapeTest (text) values (E'This is the first part \n And this is the second');

This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.

As such:

insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');

Best way to check if MySQL results returned in PHP?

Use the one with mysql_fetch_row because "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. "

MySQL Error: : 'Access denied for user 'root'@'localhost'

Ugh- nothing worked for me! I have a CentOS 7.4 machine running mariadb 5.5.64.

What I had to do was this, right after installation of mariadb from yum;

# systemctl restart mariadb
# mysql_secure_installation

The mysql_secure_installation will take you through a number of steps, including "Set root password? [Y/n]". Just say "y" and give it a password. Answer the other questions as you wish.

Then you can get in with your password, using

# mysql -u root -p

It will survive

# systemctl restart mariadb

The Key

Then, I checked the /bin/mysql_secure_installation source code to find out how it was magically able to change the root password and none of the other answers here could. The import bit is:

do_query "UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';"

...It says SET Password=... and not SET authentication_string = PASSWORD.... So, the proper procedure for this version (5.5.64) is:

login using mysql -u root -p , using the password you already set.
Or, stop the database and start it with:
mysql_safe --skip-grant-tables --skip-networking &

From the mysql> prompt:

use mysql;
select host,user,password from user where user = 'root';
(observe your existing passwords for root).
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root' AND host = 'localhost';
select host,user,password from user where user = 'root';
flush privileges;
quit;

kill the running mysqld_safe. restart mariadb. Login as root: mysql -u -p. Use your new password.

If you want, you can set all the root passwords at once. I think this is wise:

mysql -u root -p
(login)
use mysql;
select host,user,password from user where user = 'root';
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root';
select host,user,password from user where user = 'root';
flush privileges;
quit;

This will perform updates on all the root passwords: ie, for "localhost", "127.0.0.1", and "::1"

In the future, when I go to RHEL8 or what have you, I will try to remember to check the /bin/mysql_secure_installation and see how the guys did it, who were the ones that configured mariadb for this OS.

How can I append a query parameter to an existing URL?

I suggest an improvement of the Adam's answer accepting HashMap as parameter

/**
 * Append parameters to given url
 * @param url
 * @param parameters
 * @return new String url with given parameters
 * @throws URISyntaxException
 */
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
    URI uri = new URI(url);
    String query = uri.getQuery();

    StringBuilder builder = new StringBuilder();

    if (query != null)
        builder.append(query);

    for (Map.Entry<String, String> entry: parameters.entrySet())
    {
        String keyValueParam = entry.getKey() + "=" + entry.getValue();
        if (!builder.toString().isEmpty())
            builder.append("&");

        builder.append(keyValueParam);
    }

    URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
    return newUri.toString();
}

How to get child element by index in Jquery?

Doesn't nth-child return siblings rather than children?

var $selFirst = $(".second:nth-child(1)");

will return the first element with the class '.second'.

var $selFirst = $(".selector:nth-child(1)");

should give you the first sibling of class '.selector'

Best solution to protect PHP code without encryption

You need to consider your objectives:

1) Are you trying to prevent people from reading/modifying your code? If yes, you'll need an obfuscation/encryption tool. I've used Zend Guard with good success.

2) Are you trying to prevent unauthorized redistribution of your code?? A EULA/proprietary license will give you the legal power to prevent that, but won't actually stop it. An key/activation scheme will allow you to actively monitor usage, but can be removed unless you also encrypt your code. Zend Guard also has capabilities to lock a particular script to a particular customer machine and/or create time limited versions of the code if that's what you want to do.

I'm not familiar with vBulletin and the like, but they'd either need to encrypt/obfuscate or trust their users to do the right thing. In the latter case they have the protection of having a EULA which prohibits the behaviors they find undesirable, and the legal system to back up breaches of the EULA.

If you're not prepared/able to take legal action to protect your software and you don't want to encrypt/obfuscate, your options are a) Release it with a EULA so you're have a legal option if you ever need it and hope for the best, or b) consider whether an open source license might be more appropriate and just allow redistribution.

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

and tests whether both expressions are logically True while & (when used with True/False values) tests if both are True.

In Python, empty built-in objects are typically treated as logically False while non-empty built-ins are logically True. This facilitates the common use case where you want to do something if a list is empty and something else if the list is not. Note that this means that the list [False] is logically True:

>>> if [False]:
...    print 'True'
...
True

So in Example 1, the first list is non-empty and therefore logically True, so the truth value of the and is the same as that of the second list. (In our case, the second list is non-empty and therefore logically True, but identifying that would require an unnecessary step of calculation.)

For example 2, lists cannot meaningfully be combined in a bitwise fashion because they can contain arbitrary unlike elements. Things that can be combined bitwise include: Trues and Falses, integers.

NumPy objects, by contrast, support vectorized calculations. That is, they let you perform the same operations on multiple pieces of data.

Example 3 fails because NumPy arrays (of length > 1) have no truth value as this prevents vector-based logic confusion.

Example 4 is simply a vectorized bit and operation.

Bottom Line

  • If you are not dealing with arrays and are not performing math manipulations of integers, you probably want and.

  • If you have vectors of truth values that you wish to combine, use numpy with &.

How to check if a process id (PID) exists

if [ -n "$PID" -a -e /proc/$PID ]; then
    echo "process exists"
fi

or

if [ -n "$(ps -p $PID -o pid=)" ]

In the latter form, -o pid= is an output format to display only the process ID column with no header. The quotes are necessary for non-empty string operator -n to give valid result.

How do I test if a variable is a number in Bash?

This tests if a number is a non negative integer and is both shell independent (i.e. without bashisms) and uses only shell built-ins:

INCORRECT.

As this first answer (below) allows for integers with characters in them as long as the first are not first in the variable.

[ -z "${num##[0-9]*}" ] && echo "is a number" || echo "is not a number";

CORRECT .

As jilles commented and suggested in his answer this is the correct way to do it using shell-patterns.

[ ! -z "${num##*[!0-9]*}" ] && echo "is a number" || echo "is not a number";

Moment.js - tomorrow, today and yesterday

I use a combination of add() and endOf() with moment

//...
const today = moment().endOf('day')
const tomorrow = moment().add(1, 'day').endOf('day')

if (date < today) return 'today'
if (date < tomorrow) return 'tomorrow'
return 'later'
//...

IIS AppPoolIdentity and file system write access permissions

The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights.

For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).

With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:

enter image description here

See that Special permission being inherited from c:\:

enter image description here

That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive.

In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).

You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder.

You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead.

So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates.

An ApplicationPoolIdentity's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display:

enter image description here

For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300. Right clicking on properties for the process and selecting the Security tab we see:

enter image description here

As we can see IIS APPPOOL\900300 is a member of the Users group.

Is there a simple way to delete a list element by value?

Usually Python will throw an Exception if you tell it to do something it can't so you'll have to do either:

if c in a:
    a.remove(c)

or:

try:
    a.remove(c)
except ValueError:
    pass

An Exception isn't necessarily a bad thing as long as it's one you're expecting and handle properly.

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

Switch between python 2.7 and python 3.5 on Mac OS X

I already had python3 installed(via miniconda3) and needed to install python2 alongside in that case brew install python won't install python2, so you would need brew install python@2 .

Now alias python2 refers to python2.x from /usr/bin/python

and alias python3 refers to python3.x from /Users/ishandutta2007/miniconda3/bin/python

and alias python refers to python3 by default.

Now to use python as alias for python2, I added the following to .bashrc file

alias python='/usr/bin/python'.

To go back to python3 as default just remove this line when required.

Auto code completion on Eclipse

Use the Ctrl+Space shortcut for getting all possible autocomplete options available in a particular context in the editor.

Auto Complete will also allow you to insert custom code templates into the editor, with placeholders for various inputs. For instance, attempting to auto complete the word "test" in a Java editor, in the context of a class body, will allow you to create a unit test that uses JUnit; you'll have to code the body of the method though. Some code templates like the former, come out of the box.

Configuration options of interest

  • Auto-activation delay. If the list of auto complete options is taking too long to appear, the delay can be reduced from Windows -> Preferences -> Java -> Editor -> Content Assist -> Auto Activation delay (specify the reduced delay here).
  • Auto activation trigger for Java. Accessible in the same pane, this happens to be the . character by default. When you have just keyed in typeA. and you expect to see relevant members that can be accessed, the auto completion list will automatically popup with the appropriate members, on this trigger.
  • Proposal types. If you do not want to see proposals of a particular variety, you can disable them from Windows -> Preferences -> Java -> Editor -> Content Assist -> Advanced. I typically switch off proposals of most kinds except Java and Template proposals. Hitting Ctrl+Space multiple times will cycle you through proposals of various kinds.
  • Template Proposals. These are different from your run of the mill proposals. You could add your code templates in here; it can be accessed from Windows -> Preferences -> Java -> Editor -> Templates. Configuration of existing templates is allowed and so is addition of new ones. Reserve usage however for the tedious typing tasks that do not have a template yet.

Property 'value' does not exist on type EventTarget in TypeScript

you can also create your own interface as well.

    export interface UserEvent {
      target: HTMLInputElement;
    }

       ...

    onUpdatingServerName(event: UserEvent) {
      .....
    }

Using Linq select list inside list

list.Where(m => m.application == "applicationName" && 
           m.users.Any(u => u.surname=="surname"));

if you want to filter users as TimSchmelter commented, you can use

list.Where(m => m.application == "applicationName")
    .Select(m => new Model
    {
        application = m.application,
        users = m.users.Where(u => u.surname=="surname").ToList()
    });

Git command to checkout any branch and overwrite local changes

git reset and git clean can be overkill in some situations (and be a huge waste of time).

If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch> is the best option.

If you're like me, your other option was to clean and perform a --hard reset then recompile your project.

Android ADT error, dx.jar was not loaded from the SDK folder

Also, make sure that the version of the ADT is supported by the AndroidSDKTools. That fixed my problem. In the SDK Manager, File->Reload will lead to the latest revisions.

When should we call System.exit in Java

System.exit() can be used to run shutdown hooks before the program quits. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can't (and shouldn't) be aware of each other. Then, if someone wants to quit, he can simply call System.exit(), and the shutdown hooks (if properly set up) take care of doing all necessary shutdown ceremonies such as closing files, releasing resources etc.

"This method never returns normally." means just that the method won't return; once a thread goes there, it won't come back.

Another, maybe more common, way to quit a program is to simply to reach the end of the main method. But if there are any non-daemon threads running, they will not be shut down and thus the JVM will not exit. Thus, if you have any such non-daemon threads, you need some other means (than the shutdown hooks) to shut down all non-daemon threads and release other resources. If there are no other non-daemon threads, returning from main will shut down the JVM and will call the shutdown hooks.

For some reason shutdown hooks seem to be an undervalued and misunderstood mechanism, and people are reinventing the wheel with all kind of proprietary custom hacks to quit their programs. I would encourage using shutdown hooks; it's all there in the standard Runtime that you'll be using anyway.

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

I had this error after doing some git merge from a branch where my classes extended a new interface. It was enough to Refresh (F5) the File-Tree in the Package Explorer frame of Eclipse.

It seems that Eclipse did not update everything properly and so the classes were extending a non-existing-yet interface. After refresh, all errors disappeared.

Unsafe JavaScript attempt to access frame with URL

From a child document of different origin you are not allowed access to the top window's location.hash property, but you are allowed to set the location property itself.

This means that given that the top windows location is http://example.com/page/, instead of doing

parent.location.hash = "#foobar";

you do need to know the parents location and do

parent.location = "http://example.com/page/#foobar";

Since the resource is not navigated this will work as expected, only changing the hash part of the url.

If you are using this for cross-domain communication, then I would recommend using easyXDM instead.

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

Java: Static Class?

According to the great book "Effective Java":

Item 4: Enforce noninstantiability with a private constructor

- Attempting to enforce noninstantiability by making a class abstract does not work.

- A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor:

// Noninstantiable utility class
public class UtilityClass
{
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
        throw new AssertionError();
    }
}

Because the explicit constructor is private, it is inaccessible outside of the class. The AssertionError isn’t strictly required, but it provides insurance in case the constructor is accidentally invoked from within the class. It guarantees that the class will never be instantiated under any circumstances. This idiom is mildly counterintuitive, as the constructor is provided expressly so that it cannot be invoked. It is therefore wise to include a comment, as shown above.

As a side effect, this idiom also prevents the class from being subclassed. All constructors must invoke a superclass constructor, explicitly or implicitly, and a subclass would have no accessible superclass constructor to invoke.

How to delete files recursively from an S3 bucket

In case using AWS-SKD for ruby V2.

s3.list_objects(bucket: bucket_name, prefix: "foo/").contents.each do |obj|
  next if obj.key == "foo/" 
  resp = s3.delete_object({
    bucket: bucket_name,
    key: obj.key,
  })
end

attention please, all "foo/*" under bucket will delete.

Select DataFrame rows between two dates

you can do it with pd.date_range() and Timestamp. Let's say you have read a csv file with a date column using parse_dates option:

df = pd.read_csv('my_file.csv', parse_dates=['my_date_col'])

Then you can define a date range index :

rge = pd.date_range(end='15/6/2020', periods=2)

and then filter your values by date thanks to a map:

df.loc[df['my_date_col'].map(lambda row: row.date() in rge)]

Hide axis and gridlines Highcharts

This has always worked well for me:

yAxes: [{
         ticks: {
                 display: false;
                },

How do I serialize a Python dictionary into a string, and then back to a dictionary?

If you are trying to only serialize then pprint may also be a good option. It requires the object to be serialized and a file stream.

Here's some code:

from pprint import pprint
my_dict = {1:'a',2:'b'}
with open('test_results.txt','wb') as f:
    pprint(my_dict,f)

I am not sure if we can deserialize easily. I was using json to serialize and deserialze earlier which works correctly in most cases.

f.write(json.dumps(my_dict, sort_keys = True, indent = 2, ensure_ascii=True))

However, in one particular case, there were some errors writing non-unicode data to json.

How do you change text to bold in Android?

4 ways to make Android TextView bold- Full answer is here.

  1. Using android:textStyle attribute

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXTVIEW 1" android:textStyle="bold" /> Use bold|italic for bold and italic.

  2. using setTypeface() method

    textview2.setTypeface(null, Typeface.BOLD);
    textview2.setText("TEXTVIEW 2");
    
  3. HtmlCompat.fromHtml() method, Html.fromHtml() was deprecated in API level 24.

     String html="This is <b>TEXTVIEW 3</b>";
     textview3.setText(HtmlCompat.fromHtml(html,Typeface.BOLD));
    

How do I filter query objects by date range in Django?

You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:

start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)

ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])

As discussed previously, without doing something like this, records are ignored on the last day.

Edited to avoid the use of datetime.combine -- seems more logical to stick with date instances when comparing against a DateTimeField, instead of messing about with throwaway (and confusing) datetime objects. See further explanation in comments below.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

To make it a bit more user-friendly: After you've unpacked it, go into the directory, and run bin/pycharm.sh. Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...

Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)

To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)

(Unless you are trying to debug an application, you usually do not need to see the output of it.)

Setting a windows batch file variable to the day of the week

Another spin on this topic. The below script displays a few days around the current, with day-of-week prefix.

At the core is the standalone :dpack routine that encodes the date into a value whose modulo 7 reveals the day-of-week per ISO 8601 standards (Mon == 0). Also provided is :dunpk which is the inverse function:

@echo off& setlocal enabledelayedexpansion
rem 10/23/2018 daydate.bat: Most recent version at paulhoule.com/daydate
rem Example of date manipulation within a .BAT file.
rem This is accomplished by first packing the date into a single number.
rem This demo .bat displays dates surrounding the current date, prefixed
rem with the day-of-week.

set days=0Mon1Tue2Wed3Thu4Fri5Sat6Sun
call :dgetl y m d
call :dpack p %y% %m% %d%
for /l %%o in (-3,1,3) do (
  set /a od=p+%%o
  call :dunpk y m d !od!
  set /a dow=od%%7
  for %%d in (!dow!) do set day=!days:*%%d=!& set day=!day:~,3!
  echo !day! !y! !m! !d!
)
exit /b


rem gets local date returning year month day as separate variables
rem in: %1 %2 %3=var names for returned year month day
:dgetl
setlocal& set "z="
for /f "skip=1" %%a in ('wmic os get localdatetime') do set z=!z!%%a
set /a y=%z:~0,4%, m=1%z:~4,2% %%100, d=1%z:~6,2% %%100
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b


rem packs date (y,m,d) into count of days since 1/1/1 (0..n)
rem in: %1=return var name, %2= y (1..n), %3=m (1..12), %4=d (1..31)
rem out: set %1= days since 1/1/1 (modulo 7 is weekday, Mon= 0)
:dpack
setlocal enabledelayedexpansion
set mtb=xxx  0 31 59 90120151181212243273304334& set /a r=%3*3
set /a t=%2-(12-%3)/10, r=365*(%2-1)+%4+!mtb:~%r%,3!+t/4-(t/100-t/400)-1
endlocal& set %1=%r%& exit /b


rem inverse of date packer
rem in: %1 %2 %3=var names for returned year month day
rem %4= packed date (large decimal number, eg 736989)
:dunpk
setlocal& set /a y=%4+366, y+=y/146097*3+(y%%146097-60)/36524
set /a y+=y/1461*3+(y%%1461-60)/365, d=y%%366+1, y/=366
set e=31 60 91 121 152 182 213 244 274 305 335
set m=1& for %%x in (%e%) do if %d% gtr %%x set /a m+=1, d=%d%-%%x
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b

Hadoop/Hive : Loading data from .csv on a local machine

if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.

You will need to use "Local" keyword when writing your load command.

Syntax for hiveload command

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables

Pandas column of lists, create a row for each list element

I found the easiest way was to:

  1. Convert the samples column into a DataFrame
  2. Joining with the original df
  3. Melting

Shown here:

    df.samples.apply(lambda x: pd.Series(x)).join(df).\
melt(['subject','trial_num'],[0,1,2],var_name='sample')

        subject  trial_num sample  value
    0         1          1      0  -0.24
    1         1          2      0   0.14
    2         1          3      0  -0.67
    3         2          1      0  -1.52
    4         2          2      0  -0.00
    5         2          3      0  -1.73
    6         1          1      1  -0.70
    7         1          2      1  -0.70
    8         1          3      1  -0.29
    9         2          1      1  -0.70
    10        2          2      1  -0.72
    11        2          3      1   1.30
    12        1          1      2  -0.55
    13        1          2      2   0.10
    14        1          3      2  -0.44
    15        2          1      2   0.13
    16        2          2      2  -1.44
    17        2          3      2   0.73

It's worth noting that this may have only worked because each trial has the same number of samples (3). Something more clever may be necessary for trials of different sample sizes.

PHP CURL DELETE request

I finally solved this myself. If anyone else is having this problem, here is my solution:

I created a new method:

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

Update 2

Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <title>Styles</title>_x000D_
_x000D_
    <style>_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            }_x000D_
_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
            }_x000D_
        }_x000D_
    </style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to convert XML to JSON in Python?

xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory.

Once you have that data structure, you can serialize it to JSON:

import xmltodict, json

o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'

Practical uses of git reset --soft?

You can use git reset --soft to change the version you want to have as parent for the changes you have in your index and working tree. The cases where this is useful are rare. Sometimes you might decide that the changes you have in your working tree should belong onto a different branch. Or you can use this as a simple way to collapse several commits into one (similar to squash/fold).

See this answer by VonC for a practical example: Squash the first two commits in Git?

How to call a method in MainActivity from another class?

You can easily call a method from any Fragment inside your Activity by doing a cast like this:

Java

((MainActivity)getActivity()).startChronometer();

Kotlin

(activity as MainActivity).startChronometer()

Just remember to make sure this Fragment's activity is in fact MainActivity before you do it.

Hope this helps!

select2 - hiding the search box

@Misha Kobrin's answer work well for me So I have decided to explain it more

You want to hide the search box you can do it by jQuery.

for example you have initialized select2 plugin on a drop down having id audience

element_select = '#audience';// id or class
$(element_select).select2("close").parent().hide();

The example works on all devices on which select2 works.

Automated way to convert XML files to SQL database?

There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.

And See this question too : Generating SQL using XML and XSLT

I get conflicting provisioning settings error when I try to archive to submit an iOS app

You need to add a Production Certificate and (or) Download one from your Development Acoount

enter image description here

How to check if a Constraint exists in Sql server?

You can use the one above with one caveat:

IF EXISTS(
    SELECT 1 FROM sys.foreign_keys 
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName') 
        AND name = 'CONSTRAINTNAME'
)
BEGIN 
    ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
END 

Need to use the name = [Constraint name] since a table may have multiple foreign keys and still not have the foreign key being checked for

How do I fill arrays in Java?

You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0};

Visual Studio opens the default browser instead of Internet Explorer

Right-click on an aspx file and choose 'browse with'. I think there's an option there to set as default.

How do I use a PriorityQueue?

Java 8 solution

We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :

Using lambda expression

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> pq=
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
       // or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
        pq.add("Apple");
        pq.add("PineApple");
        pq.add("Custard Apple");
        while (pq.size() != 0)
        {
            System.out.println(pq.remove());
        }
    }

This will print:

Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:

PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                             Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:

PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:

default Comparator<T> reversed() {
    return Collections.reverseOrder(this);
}

offer() vs add()

As per the doc

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

setTimeout in for-loop does not print consecutive values

You can use the extra arguments to setTimeout to pass parameters to the callback function.

for (var i = 1; i <= 2; i++) {
    setTimeout(function(j) { alert(j) }, 100, i);
}

Note: This doesn't work on IE9 and below browsers.

Java GC (Allocation Failure)

"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.

GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html

Android: How to use webcam in emulator?

I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :

http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html

His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.

HTTP Error 500.19 and error code : 0x80070021

Got precisely the same error and came to this question. As @SpaceBison mentioned in comments, this answer describes the solution - https://stackoverflow.com/a/12867753/404099. I spotted it too late and it misses some steps. This is what worked for me:

Windows Server 2012, IIS 8.5. Should work for other versions too.

  • Go to server manager, click add roles and features
  • In the roles section choose: Web Server
    • Under Security sub-section choose everything (I excluded digest, IP restrictions and URL authorization as we don't use them)
    • Under Application Development choose .NET Extensibility 4.5, ASP.NET 4.5 and both ISAPI entries
  • In the features section choose: NET 3.5, .NET 4.5, ASP.NET 4.5
  • In the web server section choose: Web Server (all), Management Tools (IIS Management Console and Management Service), Windows Authentication - if you are using any of it

Java: Insert multiple rows into MySQL with PreparedStatement

You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().

Here's a kickoff example:

public void save(List<Entity> entities) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setString(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.

See also:

Java OCR implementation

If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.

I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.

Ruby Hash to array of values

There is also this one:

hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]

Why it works:

The & calls to_proc on the object, and passes it as a block to the method.

something {|i| i.foo }
something(&:foo)

Default FirebaseApp is not initialized

By following @Gabriel Lidenor answer, initializing app with context is not work in my case. What if you are trying to create firebase-app without google-service.json ? So before initializing any number of firebase app, first need to initialize as;

FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("APP_ID")
                    .setGcmSenderId("SENDER_ID").build();
FirebaseApp.initializeApp(context, options, "[DEFAULT]");

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

jQuery 'input' event

jQuery has the following signature for the .on() method: .on( events [, selector ] [, data ], handler )

Events could be anyone of the ones listed on this reference:

https://developer.mozilla.org/en-US/docs/Web/Events

Though, they are not all supported by every browser.

Mozilla states the following about the input event:

The DOM input event is fired synchronously when the value of an or element is changed. Additionally, it fires on contenteditable editors when its contents are changed.

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

How to get the file-path of the currently executing javascript code

All browsers except Internet Explorer (any version) have document.currentScript, which always works always (no matter how the file was included (async, bookmarklet etc)).

If you want to know the full URL of the JS file you're in right now:

var script = document.currentScript;
var fullUrl = script.src;

Tadaa.

How do I iterate over the words of a string?

C++17 version without any memory allocation (except may be for std::function)

void iter_words(const std::string_view& input, const std::function<void(std::string_view)>& process_word) {

    auto itr = input.begin();

    auto consume_whitespace = [&]() {
        for(; itr != input.end(); ++itr) {
            if(!isspace(*itr))
                return;
        }
    };

    auto consume_letters = [&]() {
        for(; itr != input.end(); ++itr) {
            if(isspace(*itr))
                return;
        }
    };

    while(true) {
        consume_whitespace();
        if(itr == input.end())
            return;
        auto word_start = itr - input.begin();
        consume_letters();
        auto word_end = itr - input.begin();
        process_word(input.substr(word_start, word_end - word_start));
    }
}

int main() {
    iter_words("foo bar", [](std::string_view sv) {
        std::cout << "Got word: " <<  sv << '\n';
    });
    return 0;
}

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

Console app arguments, how arguments are passed to Main method

The main method of the runtime engine looks something like int main(int argc, char *argv[]), where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.

Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

Getting time elapsed in Objective-C

use the timeIntervalSince1970 function of the NSDate class like below:

double start = [startDate timeIntervalSince1970];
double end = [endDate timeIntervalSince1970];
double difference = end - start;

basically, this is what i use to compare the difference in seconds between 2 different dates. also check this link here

SVN undo delete before commit

To make it into a one liner you can try something like:

svn status | cut -d ' ' -f 8 | xargs svn revert

How to add a Hint in spinner in XML

The simplest way I found was this: Creates a TextView or LinearLayout and places it along with the Spinner in a RelativeLayout. Initially the textview will have the text as if it were the hint "Select one ...", after the first click this TextView is invisible, disabled and calls the Spinner that is right behind it.

Step 1:

In the activity.xml that finds the spinner put:

 <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <Spinner
        android:id="@+id/sp_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:spinnerMode="dropdown" />
    <LinearLayout
        android:id="@+id/ll_hint_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center">
        <TextView

            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Select..."/>

    </LinearLayout>
</RelativeLayout>

Step 2:

In your Activity.java type:

public class MainActivity extends AppCompatActivity {

    private LinearLayout ll_hint_spinner;
    private Spinner sp_main;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ll_hint_spinner = findViewById(R.id.ll_hint_spinner);
        sp_main = findViewById(R.id.sp_main);
        //Action after clicking LinearLayout / Spinner;
        ll_hint_spinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //By clicking "Select ..." the Spinner is requested;
                sp_main.performClick();
                //Make LinearLayout invisible
                setLinearVisibility(false);
                //Disable LinearLayout
                ll_hint_spinner.setEnabled(false);
                //After LinearLayout is off, Spinner will function normally;
                sp_main.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        sp_main.setSelection(position);
                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        setLinearVisibility(true);
                    }
                });
            }
        });
    }
    //Method to make LinearLayout invisible or visible;
    public void setLinearVisibility(boolean visible) {
        if (visible) {
            ll_hint_spinner.setVisibility(View.VISIBLE);
        } else {
            ll_hint_spinner.setVisibility(View.INVISIBLE);
        }
    }
}

Example1 SameExample2 SameExample3

The examples of the images I used a custom Spinner, but the result of the last example will be the same.

Note: I have the example in github: click here!

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

jQuery duplicate DIV into another DIV

_x000D_
_x000D_
$(document).ready(function(){  _x000D_
    $("#btn_clone").click(function(){  _x000D_
        $("#a_clone").clone().appendTo("#b_clone");  _x000D_
    });  _x000D_
});  
_x000D_
.container{_x000D_
    padding: 15px;_x000D_
    border: 12px solid #23384E;_x000D_
    background: #28BAA2;_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<!DOCTYPE html>  _x000D_
<html>  _x000D_
<head>  _x000D_
<title>jQuery Clone Method</title> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
_x000D_
_x000D_
</head>  _x000D_
<body> _x000D_
<div class="container">_x000D_
<p id="a_clone"><b> This is simple example of clone method.</b></p>  _x000D_
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p>  _x000D_
<button id="btn_clone">Click Me!</button>  _x000D_
</div> _x000D_
</body>  _x000D_
</html>  
_x000D_
_x000D_
_x000D_

For more detail and demo

Vertical (rotated) text in HTML table

-moz-transform: rotate(7.5deg);  /* FF3.5+ */
-o-transform: rotate(7.5deg);  /* Opera 10.5 */
-webkit-transform: rotate(7.5deg);  /* Saf3.1+, Chrome */
filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=1);  /* IE6,IE7 allows only 1, 2, 3 */
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; /* IE8 allows only 1 2 or 3*/

How to change a nullable column to not nullable in a Rails migration?

If you do it in a migration then you could probably do it like this:

# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)

# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false

Visualizing decision tree in scikit-learn

Simple way founded here with pydotplus (graphviz must be installed):

from IPython.display import Image  
from sklearn import tree
import pydotplus # installing pyparsing maybe needed

...

dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())

Class has no objects member

First, Install pylint-django using pip as follows:

pip install pylint-django

Goto settings.json find and make sure python linting enabled is true like this:

enter image description here

At the bottom write "python.linting.pylintPath": "pylint_django"like this:

enter image description here

OR,

Go to Settings and search for python linting

make sure Python > Linting: Pylint Enabled is checked

Under that Python > Linting: Pylint Path write pylint_django

SVN Error - Not a working copy

I made a new checkout from the same project to a different location then copied the .svn folder from it and replaced with my old .svn folder. After that called the svn update function and everything were synced properly up to date.

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it. There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh

How to iterate over each string in a list of strings and operate on it's elements

The suggestion that using range(len()) is the equivalent of using enumerate() is incorrect. They return the same results, but they are not the same.

Using enumerate() actually gives you key/value pairs. Using range(len()) does not.

Let's check range(len()) first (working from the example from the original poster):

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
    print range(len(words))

This gives us a simple list:

[0, 1, 2, 3, 4]

... and the elements in this list serve as the "indexes" in our results.

So let's do the same thing with our enumerate() version:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']    
   print enumerate(words)

This certainly doesn't give us a list:

<enumerate object at 0x7f6be7f32c30>

...so let's turn it into a list, and see what happens:

print list(enumerate(words))

It gives us:

[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]

These are actual key/value pairs.

So this ...

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

for i in range(len(words)):
    print "words[{}] = ".format(i), words[i]

... actually takes the first list (Words), and creates a second, simple list of the range indicated by the length of the first list.

So we have two simple lists, and we are merely printing one element from each list in order to get our so-called "key/value" pairs.

But they aren't really key/value pairs; they are merely two single elements printed at the same time, from different lists.

Whereas the enumerate () code:

for i, word in enumerate(words):
    print "words[{}] = {}".format(i, word)

... also creates a second list. But that list actually is a list of key/value pairs, and we are asking for each key and value from a single source -- rather than from two lists (like we did above).

So we print the same results, but the sources are completely different -- and handled completely differently.

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

How to control size of list-style-type disc in CSS?

I have always had good luck with using background images instead of trusting all browsers to interpret the bullet in exactly the same way. This would also give you tight control over the size of the bullet.

.moreLinks li {
    background: url("bullet.gif") no-repeat left 5px;
    padding-left: 1em;
}

Also, you may want to move your DIV outside of the UL. It's invalid markup as you have it now. You can use a list header LH if you must have it inside the list.

Background Image for Select (dropdown) does not work in Chrome

What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.

Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.

Remove rows with all or some NAs (missing values) in data.frame

delete.dirt <- function(DF, dart=c('NA')) {
  dirty_rows <- apply(DF, 1, function(r) !any(r %in% dart))
  DF <- DF[dirty_rows, ]
}

mydata <- delete.dirt(mydata)

Above function deletes all the rows from the data frame that has 'NA' in any column and returns the resultant data. If you want to check for multiple values like NA and ? change dart=c('NA') in function param to dart=c('NA', '?')

Why is this jQuery click function not working?

You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.

JS Code:

$(document).ready(function() {

    $("#clicker").click(function () {
        alert("Hello!");
        $(".hide_div").hide();    
    });
});

how to query LIST using linq

Well, the code you've given is invalid to start with - List is a generic type, and it has an Add method instead of add etc.

But you could do something like:

List<Person> list = new List<Person>
{
    new person{ID=1,Name="jhon",salary=2500},
    new person{ID=2,Name="Sena",salary=1500},
    new person{ID=3,Name="Max",salary=5500}.
    new person{ID=4,Name="Gen",salary=3500}
};

// The "Where" LINQ operator filters a sequence
var highEarners = list.Where(p => p.salary > 3000);

foreach (var person in highEarners)
{
    Console.WriteLine(person.Name);
}

If you want to learn details of what all the LINQ operators do, and how they can be implemented in LINQ to Objects, you might be interested in my Edulinq blog series.

Cache busting via params

Hope this should help you to inject external JS file

<script type="text/javascript"> 
var cachebuster = Math.round(new Date().getTime() / 1000); 
document.write('<scr'+'ipt type="text/javascript" src="external.js?cb=' +cachebuster+'"></scr' + 'ipt>');
</script>

Source - Cachebuster code in JavaScript

Verify External Script Is Loaded

This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.

Solution

//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length; 

if (len === 0) {
        alert('script not loaded');

        loadScript('Javascript/MyScript.js');

        if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
            alert('still not loaded');
        }
        else {
            alert('loaded now');
        }
    }
    else {
        alert('script loaded');
    }


function loadScript(scriptLocationAndName) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptLocationAndName;
    head.appendChild(script);
}

How can I update a row in a DataTable in VB.NET?

The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

dtResult.Rows(i)("Foo") = strVerse

How to sort an object array by date property?

Thanks for those brilliant answers on top. I have thought a slightly complicated answer. Just for those who want to compare different answers.

const data = [
    '2-2018', '1-2018',
    '3-2018', '4-2018',
    '1-2019', '2-2019',
    '3-2019', '4-2019',
    '1-2020', '3-2020',
    '4-2020', '1-2021'
]

let eachYearUniqueMonth = data.reduce((acc, elem) => {
    const uniqueDate = Number(elem.match(/(\d+)\-(\d+)/)[1])
    const uniqueYear = Number(elem.match(/(\d+)\-(\d+)/)[2])


    if (acc[uniqueYear] === undefined) {
        acc[uniqueYear] = []        
    } else{    
       if (acc[uniqueYear]  && !acc[uniqueYear].includes(uniqueDate)) {
          acc[uniqueYear].push(uniqueDate)
      }
    }

    return acc;
}, {})


let group = Object.keys(eachYearUniqueMonth).reduce((acc,uniqueYear)=>{
    eachYearUniqueMonth[uniqueYear].forEach(uniqueMonth=>{
    acc.push(`${uniqueYear}-${uniqueMonth}`)
  })
  
  return acc;
},[])

console.log(group);   //["2018-1", "2018-3", "2018-4", "2019-2", "2019-3", "2019-4", "2020-3", "2020-4"]


What is the Maximum Size that an Array can hold?

Since Length is an int I'd say Int.MaxValue

How to create nonexistent subdirectories recursively using Bash?

You can use the -p parameter, which is documented as:

-p, --parents

no error if existing, make parent directories as needed

So:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

How do I jump to a closing bracket in Visual Studio Code?

You can learn commands from the command palette Ctrl/Cmd + Shift + P). Look for "Go to Bracket". The keybinding is also shown there.

How to call a method with a separate thread in Java?

In Java 8 you can do this with one line of code.

If your method doesn't take any parameters, you can use a method reference:

new Thread(MyClass::doWork).start();

Otherwise, you can call the method in a lambda expression:

new Thread(() -> doWork(someParam)).start();

Does uninstalling a package with "pip" also remove the dependent packages?

You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

Null or empty check for a string variable

Try this:

ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName' 

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

How do I add PHP code/file to HTML(.html) files?

Add this line

AddHandler application/x-httpd-php .html

to httpd.conf file for what you want to do. But remember, if you do this then your web server will be very slow, because it will be parsing even static code which will not contain php code. So the better way will be to make the file extension .phtml instead of just .html.

How to know if a DateTime is between a DateRange in C#

Usually I create Fowler's Range implementation for such things.

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>         
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

Usage is pretty simple:

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)

How do I disable directory browsing?

To complete @GauravKachhadiya's answer :

IndexIgnore *.jpg

means "hide only .jpg extension files from indexing.

IndexIgnore directive uses wildcard expression to match against directories and files.

  • a star character , it matches any charactes in a string ,eg : foo or foo.extension, in the following example, we are going to turn off the directory listing, no files or dirs will appear in the index :

    IndexIgnore *

Or if you want to hide spacific files , in the directory listing, then we can use

IndexIgnore *.php

*.php => matches a string that starts with any char and ends with .php

The example above hides all files that end with .php

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

Convert an integer to an array of digits

Call this function:

  public int[] convertToArray(int number) {
    int i = 0;
    int length = (int) Math.log10(number);
    int divisor = (int) Math.pow(10, length);
    int temp[] = new int[length + 1];

    while (number != 0) {
        temp[i] = number / divisor;
        if (i < length) {
            ++i;
        }
        number = number % divisor;
        if (i != 0) {
            divisor = divisor / 10;
        }
    }
    return temp;
}

Twitter Bootstrap button click to toggle expand/collapse text section above button

Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.

You would replace his .btn with the following:

<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>

And add a small CSS for when the content is displayed:

.in.collapse+a.btn.showdetails:before { 
    content:'Hide details «';
}
.collapse+a.btn.showdetails:before { 
    content:'Show details »'; 
}

Here is his modified example

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

Correct way to initialize HashMap and can HashMap hold different value types?

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

Javascript require() function giving ReferenceError: require is not defined

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

IE 6+ .......... compatible ?
Firefox 2+ ..... compatible ?
Safari 3.2+ .... compatible ?
Chrome 3+ ...... compatible ?
Opera 10+ ...... compatible ?

http://requirejs.org/docs/download.html

Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js

and take a look at this http://requirejs.org/docs/api.html

Remove a HTML tag but keep the innerHtml

// For MSIE:
el.removeNode(false);

// Old js, w/o loops, using DocumentFragment:
function replaceWithContents (el) {
  if (el.parentElement) {
    if (el.childNodes.length) {
      var range = document.createRange();
      range.selectNodeContents(el);
      el.parentNode.replaceChild(range.extractContents(), el);
    } else {
      el.parentNode.removeChild(el);
    }
  }
}

// Modern es:
const replaceWithContents = (el) => {
  el.replaceWith(...el.childNodes);
};

// or just:
el.replaceWith(...el.childNodes);

// Today (2018) destructuring assignment works a little slower
// Modern es, using DocumentFragment.
// It may be faster than using ...rest
const replaceWithContents = (el) => {
  if (el.parentElement) {
    if (el.childNodes.length) {
      const range = document.createRange();
      range.selectNodeContents(el);
      el.replaceWith(range.extractContents());
    } else {
      el.remove();
    }
  }
};

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

How to decode HTML entities using jQuery?

Suppose you have below String.

Our Deluxe cabins are warm, cozy &amp; comfortable

var str = $("p").text(); // get the text from <p> tag
$('p').html(str).text();  // Now,decode html entities in your variable i.e 

str and assign back to

tag.

that's it.

How to set session timeout in web.config

If you want to set the timeout to 20 minutes, use something like this:

    <configuration>
      <system.web>
         <sessionState timeout="20"></sessionState>
      </system.web>
    </configuration>

Can't connect to local MySQL server through socket '/tmp/mysql.sock

sudo /usr/local/mysql/support-files/mysql.server start 

This worked for me. However, if this doesnt work then make sure that mysqld is running and try connecting.

Suppress Scientific Notation in Numpy When Creating Array From Nested List

You could write a function that converts a scientific notation to regular, something like

def sc2std(x):
    s = str(x)
    if 'e' in s:
        num,ex = s.split('e')
        if '-' in num:
            negprefix = '-'
        else:
            negprefix = ''
        num = num.replace('-','')
        if '.' in num:
            dotlocation = num.index('.')
        else:
            dotlocation = len(num)
        newdotlocation = dotlocation + int(ex)
        num = num.replace('.','')
        if (newdotlocation < 1):
            return negprefix+'0.'+'0'*(-newdotlocation)+num
        if (newdotlocation > len(num)):
            return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
        return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
    else:
        return s

Ajax - 500 Internal Server Error

I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :

Open the Web.Config file and paste these lines into the configuration section

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000"/>
    </webServices>
  </scripting>
</system.web.extensions>

String to LocalDate

As you use Joda Time, you should use DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);

If using Java 8 or later, then refer to hertzi's answer

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Short answer (asked version): (format 3.33.20150710.182906)

Please, simple use a makefile with:

MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)

program.x : source.c
       gcc $(CPPFLAGS) source.c -o program.x

and if you don't want a makefile, shorter yet, just compile with:

gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Short answer (suggested version): (format 150710.182906)

Use a double for version number:

MakeFile:

VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
      gcc $(CPPFLAGS) source.c -o program.x

Or a simple bash command:

$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")

Tip: Still don't like makefile or is it just for a not-so-small test program? Add this line:

 export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")

to your ~/.profile, and remember compile with gcc $CPPFLAGS ...


Long answer:

I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).

I was used to a function that created the version number for me. But I prefer this function to return a float. My version number can be printed by: printf("%13.6f\n", version()); which issues something like: 150710.150411 (being Year (2 digits) month day DOT hour minute seconds).

But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411

Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION to set the version directly from shell, but better of all, I recommend the third option: use a makefile.


Three forms of compiling and the results:

Using make:

beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc  program.o -o program.x

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'

Using -DVERSION:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'

Using the build-in function:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'

Source code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 #define FUNC_VERSION (0)
  6 #ifndef VERSION
  7   #define MAJOR 1
  8   #define MINOR 11
  9   #define VERSION version()
 10   #undef FUNC_VERSION
 11   #define FUNC_VERSION (1)
 12   char sversion[]="9999.9999.20150710.045535";
 13 #endif
 14 
 15 #if(FUNC_VERSION)
 16 char *version(void);
 17 #endif
 18 
 19 int main(void)
 20 {
 21 
 22   printf("__DATE__: '%s'\n", __DATE__);
 23   printf("__TIME__: '%s'\n", __TIME__);
 24 
 25   printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
 26   return 0;
 27 }
 28 
 29 /* String format: */
 30 /* __DATE__="Oct  8 2013" */
 31 /*  __TIME__="00:13:39" */
 32
 33 /* Version Function: returns the version string */
 34 #if(FUNC_VERSION)
 35 char *version(void)
 36 {
 37   const char data[]=__DATE__;
 38   const char tempo[]=__TIME__;
 39   const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
 40   char omes[4];
 41   int ano, mes, dia, hora, min, seg;
 42 
 43   if(strcmp(sversion,"9999.9999.20150710.045535"))
 44     return sversion;
 45 
 46   if(strlen(data)!=11||strlen(tempo)!=8)
 47     return NULL;
 48 
 49   sscanf(data, "%s %d %d", omes, &dia, &ano);
 50   sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
 51   mes=(strstr(nomes, omes)-nomes)/3+1;
 52   sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
 53 
 54   return sversion;
 55 }
 56 #endif

Please note that the string is limited by MAJOR<=9999 and MINOR<=9999. Of course, I set this high value that will hopefully never overflow. But using double is still better (plus, it's completely automatic, no need to set MAJOR and MINOR by hand).

Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION is defined, either by -DVERSION directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile.

Here it is the makefile I use:


MakeFile source:

  1   MAJOR = 3
  2   MINOR = 33
  3   BUILD = $(shell date +"%Y%m%d.%H%M%S")
  4   VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
  5   CC = gcc
  6   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
  7   CPPFLAGS = -DVERSION=$(VERSION)
  8   LDLIBS =
  9   
 10    %.x : %.c
 11          $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

A better version with DOUBLE

Now that I presented you "your" preferred solution, here it is my solution:

Compile with (a) makefile or (b) gcc directly:

(a) MakeFile:

   VERSION = $(shell date +"%g%m%d.%H%M%S")
   CC = gcc
   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors 
   CPPFLAGS = -DVERSION=$(VERSION)
   LDLIBS =
   %.x : %.c
         $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

(b) Or a simple bash command:

 $ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")

Source code (double version):

#ifndef VERSION
  #define VERSION version()
#endif

double version(void);

int main(void)
{
  printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
  return 0;
}

double version(void)
{
  const char data[]=__DATE__;
  const char tempo[]=__TIME__;
  const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  char omes[4];
  int ano, mes, dia, hora, min, seg;
  char sversion[]="130910.001339";
  double fv;

  if(strlen(data)!=11||strlen(tempo)!=8)
    return -1.0;

  sscanf(data, "%s %d %d", omes, &dia, &ano);
  sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
  mes=(strstr(nomes, omes)-nomes)/3+1;
  sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
  fv=atof(sversion);

  return fv;
}

Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S"), you can safely delete this function completely.


Well, that's it. A very neat and easy way to setup your version control and never worry about it again!

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

How do I change the language of moment.js?

I'm using angular2-moment, but usage must be similar.

import { MomentModule } from "angular2-moment";
import moment = require("moment");

export class AppModule {

  constructor() {
    moment.locale('ru');
  }
}

How I can get web page's content and save it into the string variable

I've run into issues with Webclient.Downloadstring before. If you do, you can try this:

WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

How to get the current time in Google spreadsheet using script editor?

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

How to measure the a time-span in seconds using System.currentTimeMillis()?

From your code it would appear that you are trying to measure how long a computation took (as opposed to trying to figure out what the current time is).

In that case, you need to call currentTimeMillis before and after the computation, take the difference, and divide the result by 1000 to convert milliseconds to seconds.

How do I convert a TimeSpan to a formatted string?

   public static class TimeSpanFormattingExtensions
   {
      public static string ToReadableString(this TimeSpan span)
      {
         return string.Join(", ", span.GetReadableStringElements()
            .Where(str => !string.IsNullOrWhiteSpace(str)));
      }

      private static IEnumerable<string> GetReadableStringElements(this TimeSpan span)
      {
         yield return GetDaysString((int)Math.Floor(span.TotalDays));
         yield return GetHoursString(span.Hours);
         yield return GetMinutesString(span.Minutes);
         yield return GetSecondsString(span.Seconds);
      }

      private static string GetDaysString(int days)
      {
         if (days == 0)
            return string.Empty;

         if (days == 1)
            return "1 day";

         return string.Format("{0:0} days", days);
      }

      private static string GetHoursString(int hours)
      {
         if (hours == 0)
            return string.Empty;

         if (hours == 1)
            return "1 hour";

         return string.Format("{0:0} hours", hours);
      }

      private static string GetMinutesString(int minutes)
      {
         if (minutes == 0)
            return string.Empty;

         if (minutes == 1)
            return "1 minute";

         return string.Format("{0:0} minutes", minutes);
      }

      private static string GetSecondsString(int seconds)
      {
         if (seconds == 0)
            return string.Empty;

         if (seconds == 1)
            return "1 second";

         return string.Format("{0:0} seconds", seconds);
      }
   }

Is there a way of setting culture for a whole application? All current threads and new threads?

This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.

How to apply border radius in IE8 and below IE8 browsers?

Firstly for technical accuracy, border-radius is not a HTML5 feature, it's a CSS3 feature.

The best script I've found to render box shadows & rounded corners in older IE versions is IE-CSS3. It translates CSS3 syntax into VML (an IE-specific Vector language like SVG) and renders them on screen.

It works a lot better on IE7-8 than on IE6, but does support IE6 as well. I didn't think much to PIE when I used it and found that (like HTC) it wasn't really built to be functional.

Maven is not working in Java 8 when Javadoc tags are incomplete

As of maven-javadoc-plugin 3.0.0 you should have been using additionalJOption to set an additional Javadoc option, so if you would like Javadoc to disable doclint, you should add the following property.

<properties>
    ...
    <additionalJOption>-Xdoclint:none</additionalJOption>
    ...
<properties>

You should also mention the version of maven-javadoc-plugin as 3.0.0 or higher.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.0.0</version>    
</plugin>

What causes a Python segmentation fault?

Segmentation fault is a generic one, there are many possible reasons for this:

  • Low memory
  • Faulty Ram memory
  • Fetching a huge data set from the db using a query (if the size of fetched data is more than swap mem)
  • wrong query / buggy code
  • having long loop (multiple recursion)

How to read a large file line by line?

Use buffering techniques to read the file.

$filename = "test.txt";
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
    $buffer = fread($source_file, 4096);  // use a buffer of 4KB
    $buffer = str_replace($old,$new,$buffer);
    ///
}

How to print a string multiple times?

def repeat_char_rows_cols(char, rows, cols):
    return (char*cols + '\n')*rows

>>> print(repeat_char_rows_cols('@', 4, 2))
@@
@@
@@
@@

Connecting to MySQL from Android with JDBC

Do you want to keep your database on mobile? Use sqlite instead of mysql.

If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

Redirect From Action Filter Attribute

It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute. If so, you should make sure that you inherit that, and not ActionFilterAttribute, in order to let ASP.NET MVC do more of the work for you.

Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Do whatever checking you need here

        // If you want the base check as well (against users/roles) call
        base.OnAuthorization(filterContext);
    }
}

There is a good question with an answer with more details here on SO.

How to create a HTTP server in Android?

This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET is required.

The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket. If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.

If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.

Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

How to list the files in current directory?

I used this answer with my local directory ( for example E:// ) it is worked fine for the first directory and for the seconde directory the output made a java null pointer exception, after searching for the reason i discover that the problem was created by the hidden directory, and this directory was created by windows to avoid this problem just use this

public void recursiveSearch(File file ) {
 File[] filesList = file.listFiles();
    for (File f : filesList) {
        if (f.isDirectory() && !f.isHidden()) {
            System.out.println("Directoy name is  -------------->" + f.getName());
            recursiveSearch(f);
        }
        if( f.isFile() ){
            System.out.println("File name is  -------------->" + f.getName());
        }
    }
}

Check object empty

You should check it against null.

If you want to check if object x is null or not, you can do:

    if(x != null)

But if it is not null, it can have properties which are null or empty. You will check those explicitly:

    if(x.getProperty() != null)

For "empty" check, it depends on what type is involved. For a Java String, you usually do:

    if(str != null && !str.isEmpty())

As you haven't mentioned about any specific problem with this, difficult to tell.

SimpleDateFormat parsing date with 'Z' literal

Java doesn't parse ISO dates correctly.

Similar to McKenzie's answer.

Just fix the Z before parsing.

Code

String string = "2013-03-05T18:05:05.000Z";
String defaultTimezone = TimeZone.getDefault().getID();
Date date = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).parse(string.replaceAll("Z$", "+0000"));

System.out.println("string: " + string);
System.out.println("defaultTimezone: " + defaultTimezone);
System.out.println("date: " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).format(date));

Result

string: 2013-03-05T18:05:05.000Z
defaultTimezone: America/New_York
date: 2013-03-05T13:05:05.000-0500

What REALLY happens when you don't free after malloc?

If you're using the memory you've allocated, then you're not doing anything wrong. It becomes a problem when you write functions (other than main) that allocate memory without freeing it, and without making it available to the rest of your program. Then your program continues running with that memory allocated to it, but no way of using it. Your program and other running programs are deprived of that memory.

Edit: It's not 100% accurate to say that other running programs are deprived of that memory. The operating system can always let them use it at the expense of swapping your program out to virtual memory (</handwaving>). The point is, though, that if your program frees memory that it isn't using then a virtual memory swap is less likely to be necessary.

Permanently hide Navigation Bar in an activity

Start by hiding in OnResume() of the activity then also keep hiding as shown below:

decorView.setOnSystemUiVisibilityChangeListener
                (new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        // Note that system bars will only be "visible" if none of the
                        // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            //visible
                            hideSystemUI();
                        } 
                    }
                    }
                });`

    public void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

How to access JSON decoded array in PHP

This may help you!

$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';



$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';

What is the proper way to re-attach detached objects in Hibernate?

I went back to the JavaDoc for org.hibernate.Session and found the following:

Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a get() or load() method is persistent. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

Thus update(), saveOrUpdate(), lock(), replicate() and merge() are the candidate options.

update(): Will throw an exception if there is a persistent instance with the same identifier.

saveOrUpdate(): Either save or update

lock(): Deprecated

replicate(): Persist the state of the given detached instance, reusing the current identifier value.

merge(): Returns a persistent object with the same identifier. The given instance does not become associated with the session.

Hence, lock() should not be used straightway and based on the functional requirement one or more of them can be chosen.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

How to get the file extension in PHP?

You could try with this for mime type

$image = getimagesize($_FILES['image']['tmp_name']);

$image['mime'] will return the mime type.

This function doesn't require GD library. You can find the documentation here.

This returns the mime type of the image.

Some people use the $_FILES["file"]["type"] but it's not reliable as been given by the browser and not by PHP.

You can use pathinfo() as ThiefMaster suggested to retrieve the image extension.

First make sure that the image is being uploaded successfully while in development before performing any operations with the image.

How to add a new line of text to an existing file in Java?

On line 2 change new FileWriter(my_file_name) to new FileWriter(my_file_name, true) so you're appending to the file rather than overwriting.

File f = new File("/path/of/the/file");
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
            bw.append(line);
            bw.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

Python os.path.join on Windows

Windows has a concept of current directory for each drive. Because of that, "c:sourcedir" means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.

Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:

"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")

Counting the number of True Booleans in a Python List

True is equal to 1.

>>> sum([True, True, False, False, False, True])
3

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

Removing an item from a select box

You can delete the selected item with this:

$("#selectBox option:selected").remove();

This is useful if you have a list and not a dropdown.

Serialize and Deserialize Json and Json Array in Unity

Assume you got a JSON like this

[
    {
        "type": "qrcode",
        "symbol": [
            {
                "seq": 0,
                "data": "HelloWorld9887725216",
                "error": null
            }
        ]
    }
]

To parse the above JSON in unity, you can create JSON model like this.

[System.Serializable]
public class QrCodeResult
{
    public QRCodeData[] result;
}

[System.Serializable]
public class Symbol
{
    public int seq;
    public string data;
    public string error;
}

[System.Serializable]
public class QRCodeData
{
    public string type;
    public Symbol[] symbol;
}

And then simply parse in the following manner...

var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");

Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html

How to read response headers in angularjs?

Why not simply try this:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log('Content-Range: ' + response.headers('Content-Range'));
  return response.data;
});

Especially if you want to return the promise so it could be a part of a promises chain.

Visual Studio 2017 - Git failed with a fatal error

If it doesn't work from Team ? Manage Connections ? Local Git Repositories ? Clone, one can try either one these two ways.

Menu File ? Start Page ? Open ? Go for Git

(or)

Menu File ? Open ? Open from source control

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

Axios Delete request with body and headers?

For those who tried everything above and still don't see the payload with the request - make sure you have:

"axios": "^0.21.1" (not 0.20.0)

Then, the above solutions work

axios.delete("URL", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data: {
        var1: "var1",
        var2: "var2"
      },
    })

You can access the payload with

req.body.var1, req.body.var2

Here's the issue:

https://github.com/axios/axios/issues/3335

How to get the root dir of the Symfony2 application?

In Symfony 3.3 you can use

$projectRoot = $this->get('kernel')->getProjectDir();

to get the web/project root.

How to make UIButton's text alignment center? Using IB

Try Like this :

yourButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
yourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;