Programs & Examples On #Limiting

Concrete Javascript Regex for Accented Characters (Diacritics)

What about this?

^([a-zA-Z]|[à-ú]|[À-Ú])+$

It will match every word with accented characters or not.

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

Safely limiting Ansible playbooks to a single machine?

There's also a cute little trick that lets you specify a single host on the command line (or multiple hosts, I guess), without an intermediary inventory:

ansible-playbook -i "imac1-local," user.yml

Note the comma (,) at the end; this signals that it's a list, not a file.

Now, this won't protect you if you accidentally pass a real inventory file in, so it may not be a good solution to this specific problem. But it's a handy trick to know!

Limiting number of displayed results when using ngRepeat

store all your data initially

function PhoneListCtrl($scope, $http) {
  $http.get('phones/phones.json').success(function(data) {
    $scope.phones = data.splice(0, 5);
    $scope.allPhones = data;
  });

  $scope.orderProp = 'age';
  $scope.howMany = 5;
  //then here watch the howMany variable on the scope and update the phones array accordingly
  $scope.$watch("howMany", function(newValue, oldValue){
    $scope.phones = $scope.allPhones.splice(0,newValue)
  });
}

EDIT had accidentally put the watch outside the controller it should have been inside.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

Generating a random & unique 8 character string using MySQL

I woudn't bother with the likelihood of collision. Just generate a random string and check if it exists. If it does, try again and you shouldn't need to do it more that a couple of times unless you have a huge number of plates already assigned.

Another solution for generating an 8-character long pseudo-random string in pure (My)SQL:

SELECT LEFT(UUID(), 8);

You can try the following (pseudo-code):

DO 
    SELECT LEFT(UUID(), 8) INTO @plate;
    INSERT INTO plates (@plate);
WHILE there_is_a_unique_constraint_violation
-- @plate is your newly assigned plate number

Since this post has received a unexpected level of attention, let me highlight ADTC's comment : the above piece of code is quite dumb and produces sequential digits.

For slightly less stupid randomness try something like this instead :

SELECT LEFT(MD5(RAND()), 8)

And for true (cryptograpically secure) randomness, use RANDOM_BYTES() rather than RAND() (but then I would consider moving this logic up to the application layer).

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Limiting the number of characters in a JTextField

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
{
    if(jTextField1.getText().length()>=5)
    {
        jTextField1.setText(jTextField1.getText().substring(0, 4));
    }
}

I have taken a jtextfield whose name is jTextField1, the code is in its key pressed event. I Have tested it and it works. And I am using the NetBeans IDE.

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

Limiting the number of characters in a string, and chopping off the rest

If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.

int maxLength = 5;
StringUtils.left(string, maxLength);

Output:

      null -> null
        "" -> ""
       "a" -> "a"
"abcd1234" -> "abcd1"

Left Documentation

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Might it be possible that you're using a WCF-based web service reference? By default, the ServiceThrottlingBehavior.MaxConcurrentCalls is 16.

You could try updating your service reference behavior's <serviceThrottling> element

<serviceThrottling
    maxConcurrentCalls="999" 
    maxConcurrentSessions="999" 
    maxConcurrentInstances="999" />

(Note that I'd recommend the settings above.) See MSDN for more information how to configure an appropriate <behavior> element.

Limiting the output of PHP's echo to 200 characters

Not sure why no one mentioned this before -

echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."

More info check - http://php.net/manual/en/function.mb-strimwidth.php

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"

Apparently the differences between these date formats are as follow:

DT_DATE A date structure that consists of year, month, day, and hour.

DT_DBDATE A date structure that consists of year, month, and day.

DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction

By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

put this line in xml

 android:inputType="number|numberDecimal"

Django - limiting query results

Actually I think the LIMIT 10 would be issued to the database so slicing would not occur in Python but in the database.

See limiting-querysets for more information.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

How do you disable viewport zooming on Mobile Safari?

sometimes those other directives in the content tag can mess up Apple's best guess/heuristic at how to layout your page, all you need to disable pinch zoom is.

<meta name="viewport" content="user-scalable=no" />

Google Maps v3 - limit viewable area and zoom level

You can listen to the dragend event, and if the map is dragged outside the allowed bounds, move it back inside. You can define your allowed bounds in a LatLngBounds object and then use the contains() method to check if the new lat/lng center is within the bounds.

You can also limit the zoom level very easily.

Consider the following example: Fiddle Demo

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps JavaScript API v3 Example: Limit Panning and Zoom</title> 
   <script type="text/javascript" 
           src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head> 
<body> 
   <div id="map" style="width: 400px; height: 300px;"></div> 

   <script type="text/javascript"> 

   // This is the minimum zoom level that we'll allow
   var minZoomLevel = 5;

   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: minZoomLevel,
      center: new google.maps.LatLng(38.50, -90.50),
      mapTypeId: google.maps.MapTypeId.ROADMAP
   });

   // Bounds for North America
   var strictBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(28.70, -127.50), 
     new google.maps.LatLng(48.85, -55.90)
   );

   // Listen for the dragend event
   google.maps.event.addListener(map, 'dragend', function() {
     if (strictBounds.contains(map.getCenter())) return;

     // We're out of bounds - Move the map back within the bounds

     var c = map.getCenter(),
         x = c.lng(),
         y = c.lat(),
         maxX = strictBounds.getNorthEast().lng(),
         maxY = strictBounds.getNorthEast().lat(),
         minX = strictBounds.getSouthWest().lng(),
         minY = strictBounds.getSouthWest().lat();

     if (x < minX) x = minX;
     if (x > maxX) x = maxX;
     if (y < minY) y = minY;
     if (y > maxY) y = maxY;

     map.setCenter(new google.maps.LatLng(y, x));
   });

   // Limit the zoom level
   google.maps.event.addListener(map, 'zoom_changed', function() {
     if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
   });

   </script> 
</body> 
</html>

Screenshot from the above example. The user will not be able to drag further south or far east in this case:

Google Maps JavaScript API v3 Example: Force stop map dragging

Limiting double to 3 decimal places

In C lang:

double truncKeepDecimalPlaces(double value, int numDecimals)
{
    int x = pow(10, numDecimals);
    return (double)trunc(value * x) / x;
}

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

Virtual Memory Usage from Java under Linux, too much memory used

This has been a long-standing complaint with Java, but it's largely meaningless, and usually based on looking at the wrong information. The usual phrasing is something like "Hello World on Java takes 10 megabytes! Why does it need that?" Well, here's a way to make Hello World on a 64-bit JVM claim to take over 4 gigabytes ... at least by one form of measurement.

java -Xms1024m -Xmx4096m com.example.Hello

Different Ways to Measure Memory

On Linux, the top command gives you several different numbers for memory. Here's what it says about the Hello World example:

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2120 kgregory  20   0 4373m  15m 7152 S    0  0.2   0:00.10 java
  • VIRT is the virtual memory space: the sum of everything in the virtual memory map (see below). It is largely meaningless, except when it isn't (see below).
  • RES is the resident set size: the number of pages that are currently resident in RAM. In almost all cases, this is the only number that you should use when saying "too big." But it's still not a very good number, especially when talking about Java.
  • SHR is the amount of resident memory that is shared with other processes. For a Java process, this is typically limited to shared libraries and memory-mapped JARfiles. In this example, I only had one Java process running, so I suspect that the 7k is a result of libraries used by the OS.
  • SWAP isn't turned on by default, and isn't shown here. It indicates the amount of virtual memory that is currently resident on disk, whether or not it's actually in the swap space. The OS is very good about keeping active pages in RAM, and the only cures for swapping are (1) buy more memory, or (2) reduce the number of processes, so it's best to ignore this number.

The situation for Windows Task Manager is a bit more complicated. Under Windows XP, there are "Memory Usage" and "Virtual Memory Size" columns, but the official documentation is silent on what they mean. Windows Vista and Windows 7 add more columns, and they're actually documented. Of these, the "Working Set" measurement is the most useful; it roughly corresponds to the sum of RES and SHR on Linux.

Understanding the Virtual Memory Map

The virtual memory consumed by a process is the total of everything that's in the process memory map. This includes data (eg, the Java heap), but also all of the shared libraries and memory-mapped files used by the program. On Linux, you can use the pmap command to see all of the things mapped into the process space (from here on out I'm only going to refer to Linux, because it's what I use; I'm sure there are equivalent tools for Windows). Here's an excerpt from the memory map of the "Hello World" program; the entire memory map is over 100 lines long, and it's not unusual to have a thousand-line list.

0000000040000000     36K r-x--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040108000      8K rwx--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040eba000    676K rwx--    [ anon ]
00000006fae00000  21248K rwx--    [ anon ]
00000006fc2c0000  62720K rwx--    [ anon ]
0000000700000000 699072K rwx--    [ anon ]
000000072aab0000 2097152K rwx--    [ anon ]
00000007aaab0000 349504K rwx--    [ anon ]
00000007c0000000 1048576K rwx--    [ anon ]
...
00007fa1ed00d000   1652K r-xs-  /usr/local/java/jdk-1.6-x64/jre/lib/rt.jar
...
00007fa1ed1d3000   1024K rwx--    [ anon ]
00007fa1ed2d3000      4K -----    [ anon ]
00007fa1ed2d4000   1024K rwx--    [ anon ]
00007fa1ed3d4000      4K -----    [ anon ]
...
00007fa1f20d3000    164K r-x--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f20fc000   1020K -----  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f21fb000     28K rwx--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
...
00007fa1f34aa000   1576K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3634000   2044K -----  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3833000     16K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3837000      4K rwx--  /lib/x86_64-linux-gnu/libc-2.13.so
...

A quick explanation of the format: each row starts with the virtual memory address of the segment. This is followed by the segment size, permissions, and the source of the segment. This last item is either a file or "anon", which indicates a block of memory allocated via mmap.

Starting from the top, we have

  • The JVM loader (ie, the program that gets run when you type java). This is very small; all it does is load in the shared libraries where the real JVM code is stored.
  • A bunch of anon blocks holding the Java heap and internal data. This is a Sun JVM, so the heap is broken into multiple generations, each of which is its own memory block. Note that the JVM allocates virtual memory space based on the -Xmx value; this allows it to have a contiguous heap. The -Xms value is used internally to say how much of the heap is "in use" when the program starts, and to trigger garbage collection as that limit is approached.
  • A memory-mapped JARfile, in this case the file that holds the "JDK classes." When you memory-map a JAR, you can access the files within it very efficiently (versus reading it from the start each time). The Sun JVM will memory-map all JARs on the classpath; if your application code needs to access a JAR, you can also memory-map it.
  • Per-thread data for two threads. The 1M block is the thread stack. I didn't have a good explanation for the 4k block, but @ericsoe identified it as a "guard block": it does not have read/write permissions, so will cause a segment fault if accessed, and the JVM catches that and translates it to a StackOverFlowError. For a real app, you will see dozens if not hundreds of these entries repeated through the memory map.
  • One of the shared libraries that holds the actual JVM code. There are several of these.
  • The shared library for the C standard library. This is just one of many things that the JVM loads that are not strictly part of Java.

The shared libraries are particularly interesting: each shared library has at least two segments: a read-only segment containing the library code, and a read-write segment that contains global per-process data for the library (I don't know what the segment with no permissions is; I've only seen it on x64 Linux). The read-only portion of the library can be shared between all processes that use the library; for example, libc has 1.5M of virtual memory space that can be shared.

When is Virtual Memory Size Important?

The virtual memory map contains a lot of stuff. Some of it is read-only, some of it is shared, and some of it is allocated but never touched (eg, almost all of the 4Gb of heap in this example). But the operating system is smart enough to only load what it needs, so the virtual memory size is largely irrelevant.

Where virtual memory size is important is if you're running on a 32-bit operating system, where you can only allocate 2Gb (or, in some cases, 3Gb) of process address space. In that case you're dealing with a scarce resource, and might have to make tradeoffs, such as reducing your heap size in order to memory-map a large file or create lots of threads.

But, given that 64-bit machines are ubiquitous, I don't think it will be long before Virtual Memory Size is a completely irrelevant statistic.

When is Resident Set Size Important?

Resident Set size is that portion of the virtual memory space that is actually in RAM. If your RSS grows to be a significant portion of your total physical memory, it might be time to start worrying. If your RSS grows to take up all your physical memory, and your system starts swapping, it's well past time to start worrying.

But RSS is also misleading, especially on a lightly loaded machine. The operating system doesn't expend a lot of effort to reclaiming the pages used by a process. There's little benefit to be gained by doing so, and the potential for an expensive page fault if the process touches the page in the future. As a result, the RSS statistic may include lots of pages that aren't in active use.

Bottom Line

Unless you're swapping, don't get overly concerned about what the various memory statistics are telling you. With the caveat that an ever-growing RSS may indicate some sort of memory leak.

With a Java program, it's far more important to pay attention to what's happening in the heap. The total amount of space consumed is important, and there are some steps that you can take to reduce that. More important is the amount of time that you spend in garbage collection, and which parts of the heap are getting collected.

Accessing the disk (ie, a database) is expensive, and memory is cheap. If you can trade one for the other, do so.

How do I address unchecked cast warnings?

Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. "Java Generics" offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:

@SuppressWarnings("unchecked")
Map<String, Number> map = getMap();
for (String s : map.keySet());
for (Number n : map.values());

If an unexpected type is encountered, you will get a runtime ClassCastException, but at least it will happen close to the source of the problem.

Limiting floats to two decimal points

I feel that the simplest approach is to use the format() function.

For example:

a = 13.949999999999999
format(a, '.2f')

13.95

This produces a float number as a string rounded to two decimal points.

Difference between declaring variables before or in loop?

This is a gotcha in VB.NET. The Visual Basic result won't reinitialize the variable in this example:

For i as Integer = 1 to 100
    Dim j as Integer
    Console.WriteLine(j)
    j = i
Next

' Output: 0 1 2 3 4...

This will print 0 the first time (Visual Basic variables have default values when declared!) but i each time after that.

If you add a = 0, though, you get what you might expect:

For i as Integer = 1 to 100
    Dim j as Integer = 0
    Console.WriteLine(j)
    j = i
Next

'Output: 0 0 0 0 0...

How to get distinct results in hibernate with joins and row-based limiting (paging)?

NullPointerException in some cases! Without criteria.setProjection(Projections.distinct(Projections.property("id"))) all query goes well! This solution is bad!

Another way is use SQLQuery. In my case following code works fine:

List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();

Distinction is done in data base! In opposite to:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

where distinction is done in memory, after load entities!

What data type to use for hashed password field and what length?

You can actually use CHAR(length of hash) to define your datatype for MySQL because each hashing algorithm will always evaluate out to the same number of characters. For example, SHA1 always returns a 40-character hexadecimal number.

File input 'accept' attribute - is it useful?

In 2015 the only way I found to make it work for both Chrome and Firefox is to put all possible extensions you want to support, including variants (including the dot in front !):

accept=".jpeg, .jpg, .jpe, .jfif, .jif"

Problem with Firefox: Using the image/jpeg mime type Firefox will only show .jpg files, very strange as if the common .jpeg was not ok...

Whatever you do, be sure to try with files having many different extensions. Maybe it even depends on the OS ... I suppose accept is case insensitive, but maybe not in every browser.

Here is the MDN docs about accept:

accept If the value of the type attribute is file, then this attribute will indicate the types of files that the server accepts, otherwise it will be ignored. The value must be a comma-separated list of unique content type specifiers:

    A file extension starting with the STOP character (U+002E). (e.g. .jpg, .png, .doc).
    A valid MIME type with no extensions.
    audio/* representing sound files. HTML5
    video/* representing video files. HTML5
    image/* representing image files. HTML5

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

Can I install the "app store" in an IOS simulator?

This is NOT possible

The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

Create an ArrayList with multiple object types?

List<Object> list = new ArrayList<>();
          list.add(1);
          list.add("1");

As the return type of ArrayList is object, you can add any type of data to ArrayList but it is not a good practice to use ArrayList because there is unnecessary boxing and unboxing.

Making TextView scrollable on Android

The "pro tip" above from Someone Somewhere (Making TextView scrollable on Android) works great, however, what if you're dynamically adding text to the ScrollView and would like to automatically scroll to the bottom after an append only when the user is at the bottom of the ScrollView? (Perhaps because if the user has scrolled up to read something you don't want to automatically reset to the bottom during an append, which would be annoying.)

Anyway, here it is:

if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
        (mScrollView.getHeight() + mTextStatus.getLineHeight())) {
    scrollToBottom();
}

The mTextStatus.getLineHeight() will make it so that you don't scrollToBottom() if the user is within one line from the end of the ScrollView.

CSS background opacity with rgba not working in IE 8

Though late, I had to use that today and found a very useful php script here that will allow you to dynamically create a png file, much like the way rgba works.

background: url(rgba.php?r=255&g=100&b=0&a=50) repeat;
background: rgba(255,100,0,0.5);

The script can be downloaded here: http://lea.verou.me/wp-content/uploads/2009/02/rgba.zip

I know it may not be the perfect solution for everybody, but it's worth considering in some cases, since it saves a lot of time and works flawlessly. Hope that helps somebody!

How to build minified and uncompressed bundle with webpack?

You can run webpack twice with different arguments:

$ webpack --minimize

then check command line arguments in webpack.config.js:

var path = require('path'),
  webpack = require('webpack'),
  minimize = process.argv.indexOf('--minimize') !== -1,
  plugins = [];

if (minimize) {
  plugins.push(new webpack.optimize.UglifyJsPlugin());
}

...

example webpack.config.js

Laravel 5.4 Specific Table Migration

First you should to make the following commands:

Step 1:

php artisan migrate:rollback

Step 2:

php artisan migrate

Your table will be back in database .

How to install a private NPM module without my own registry?

This was what I was looking for:

# Get the latest from GitHub, public repo:
$ npm install username/my-new-project --save-dev
# Bitbucket, private repo:
$ npm install git+https://token:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master

# … or from Bitbucket, public repo:
$ npm install git+ssh://[email protected]/username/my-new-project.git#master --save-dev
# Bitbucket, private repo:
$ npm install git+https://username:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# Or, if you published as npm package:
$ npm install my-new-project --save-dev

SQL Server CASE .. WHEN .. IN statement

Try this...

SELECT
    AlarmEventTransactionTableTable.TxnID,
    CASE
        WHEN DeviceID IN('7', '10', '62', '58', '60',
                 '46', '48', '50', '137', '139',
                 '142', '143', '164') THEN '01'
        WHEN DeviceID IN('8', '9', '63', '59', '61',
                 '47', '49', '51', '138', '140',
                 '141', '144', '165') THEN '02'
        ELSE 'NA' END AS clocking,
    AlarmEventTransactionTable.DateTimeOfTxn
 FROM
    multiMAXTxn.dbo.AlarmEventTransactionTable

Just remove highlighted string

SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

I've have the same problem like this, but using my own server. Maybe APACHE is allowing only limited connection to the same server. I'm increasing the max_connection and KeepAlive setting. So far so good.

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

Simple way to read single record from MySQL

'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:

with mysqli

$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();

with Zend Framework

//Inside the table class

$select = $this->select()->where('user_id = ?', 1);  
$row = $this->fetchRow($select);

How to add rows dynamically into table layout

Solution 1. Set your TableLayout tl as class member variable, only call TableLayout tl=(TableLayout)findViewById(R.id.maintable); when you initiate the class. When button clicked use tl directly, eg. tl.addView(row), don't call FindViewById anymore. So the next new row wouldn't replace the previous new row.

Solution 2. Everytime after button click save your updated data into an array, and then re-render your whole table layout by loop through the array.

How to delete a folder with files using Java

Guava 21+ to the rescue. Use only if there are no symlinks pointing out of the directory to delete.

com.google.common.io.MoreFiles.deleteRecursively(
      file.toPath(),
      RecursiveDeleteOption.ALLOW_INSECURE
) ;

(This question is well-indexed by Google, so other people usig Guava might be happy to find this answer, even if it is redundant with other answers elsewhere.)

What is the best way to implement constants in Java?

A single, generic constants class is a bad idea. Constants should be grouped together with the class they're most logically related to.

Rather than using variables of any kind (especially enums), I would suggest that you use methods. Create a method with the same name as the variable and have it return the value you assigned to the variable. Now delete the variable and replace all references to it with calls to the method you just created. If you feel that the constant is generic enough that you shouldn't have to create an instance of the class just to use it, then make the constant method a class method.

Get number days in a specified month using JavaScript?

Another possible option would be to use Datejs

Then you can do

Date.getDaysInMonth(2009, 9)     

Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)

How to concatenate two MP4 files using FFmpeg?

The accepted answer in the form of reusable PowerShell script

Param(
[string]$WildcardFilePath,
[string]$OutFilePath
)
try
{
    $tempFile = [System.IO.Path]::GetTempFileName()
    Get-ChildItem -path $wildcardFilePath | foreach  { "file '$_'" } | Out-File -FilePath $tempFile -Encoding ascii
    ffmpeg.exe -safe 0 -f concat -i $tempFile -c copy $outFilePath
}
finally
{
    Remove-Item $tempFile
}

JQuery: detect change in input field

Use $.on() to bind your chosen event to the input, don't use the shortcuts like $.keydown() etc because as of jQuery 1.7 $.on() is the preferred method to attach event handlers (see here: http://api.jquery.com/on/ and http://api.jquery.com/bind/).

$.keydown() is just a shortcut to $.bind('keydown'), and $.bind() is what $.on() replaces (among others).

To answer your question, as far as I'm aware, unless you need to fire an event on keydown specifically, the change event should do the trick for you.

$('element').on('change', function(){
    console.log('change');
});

To respond to the below comment, the javascript change event is documented here: https://developer.mozilla.org/en-US/docs/Web/Events/change

And here is a working example of the change event working on an input element, using jQuery: http://jsfiddle.net/p1m4xh08/

Newline in string attribute

<TextBlock>
    Stuff on line1 <LineBreak/>
    Stuff on line2
</TextBlock>

not that it's important to know but what you specify between the TextBlock tags is called inline content and goes into the TextBlock.Inlines property which is a InlineCollection and contains items of type Inline. Subclasses of Inline are Run and LineBreak, among others. see TextBlock.Inlines

How to remove hashbang from url?

Hash is a default vue-router mode setting, it is set because with hash, application doesn't need to connect server to serve the url. To change it you should configure your server and set the mode to HTML5 History API mode.

For server configuration this is the link to help you set up Apache, Nginx and Node.js servers:

https://router.vuejs.org/guide/essentials/history-mode.html

Then you should make sure, that vue router mode is set like following:

vue-router version 2.x

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

To be clear, these are all vue-router modes you can choose: "hash" | "history" | "abstract".

Programmatically getting the MAC of an Android device

Taken from the Android sources here. This is the actual code that shows your MAC ADDRESS in the system's settings app.

private void refreshWifiInfo() {
    WifiInfo wifiInfo = mWifiManager.getConnectionInfo();

    Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
    String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
    wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
            : getActivity().getString(R.string.status_unavailable));

    Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
    String ipAddress = Utils.getWifiIpAddresses(getActivity());
    wifiIpAddressPref.setSummary(ipAddress == null ?
            getActivity().getString(R.string.status_unavailable) : ipAddress);
}

What is the Difference Between read() and recv() , and Between send() and write()?

read() and write() are more generic, they work with any file descriptor. However, they won't work on Windows.

You can pass additional options to send() and recv(), so you may have to used them in some cases.

Define static method in source-file with declaration in header-file in C++

Static member functions must refer to static variables of that class. So in your case,

static void CP_StringToPString( std::string& inString, unsigned char *outString);

Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

CSS :selected pseudo class similar to :checked, but for <select> elements

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

What is the __del__ method, How to call it?

The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

How to avoid "StaleElementReferenceException" in Selenium?

Maybe it was added more recently, but other answers fail to mention Selenium's implicit wait feature, which does all the above for you, and is built into Selenium.

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

This will retry findElement() calls until the element has been found, or for 10 seconds.

Source - http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

Android: Difference between Parcelable and Serializable?

In Parcelable, developers write custom code for marshalling and unmarshalling so it creates fewer garbage objects in comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster), because of this custom implementation.

Serializable is a marker interface, which implies that user cannot marshal the data according to their requirements. In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API. This helps identify the Java object's member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable.

Edit: What is the meaning of marshalling and unmarshalling?

In few words, "marshalling" refers to the process of converting the data or the objects into a byte-stream, and "unmarshalling" is the reverse process of converting the byte-stream back to their original data or object. The conversion is achieved through "serialization".

http://www.jguru.com/faq/view.jsp?EID=560072

How to exclude rows that don't join with another table?

SELECT P.*
FROM primary_table P
LEFT JOIN secondary_table S on P.id = S.p_id
WHERE S.p_id IS NULL

How to start up spring-boot application via command line?

To run the spring-boot application, need to follow some step.

  1. Maven setup (ignore if already setup):

    a. Install maven from https://maven.apache.org/download.cgi

    b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).

    c. Set MAVEN_HOME in system variable. enter image description here

    d. Set path for maven

enter image description here

  1. Add Maven Plugin to POM.XML

    <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

  2. Build Spring Boot Project with Maven

       maven package
    

    or

         mvn install / mvn clean install
    
  3. Run Spring Boot app using Maven:

        mvn spring-boot:run
    
  4. [optional] Run Spring Boot app with java -jar command

         java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
    

how to console.log result of this ajax call?

Ajax call error handler will be triggered if the call itself fails.

You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.

e.preventDefault();
$.ajax(
{
    type: 'POST',
    url: requestURI,
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function(result){
        if(result.hasError == true)
        {
            if(result.error_code == 'AUTH_FAILURE')
            {
                //wrong password
                console.log('Recieved authentication error');
                $('#login_errors_auth').fadeIn();
            }
            else
            {
                //generic error here
                $('#login_errors_unknown').fadeIn();
            }
        }
    }
});

Here, "result" is the json object returned form the server which could have a structure like:

$return = array(
        'hasError' => !$validPassword,
        'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));

Remove a HTML tag but keep the innerHtml

$('b').contents().unwrap();

This selects all <b> elements, then uses .contents() to target the text content of the <b>, then .unwrap() to remove its parent <b> element.


For the greatest performance, always go native:

var b = document.getElementsByTagName('b');

while(b.length) {
    var parent = b[ 0 ].parentNode;
    while( b[ 0 ].firstChild ) {
        parent.insertBefore(  b[ 0 ].firstChild, b[ 0 ] );
    }
     parent.removeChild( b[ 0 ] );
}

This will be much faster than any jQuery solution provided here.

How can I enter latitude and longitude in Google Maps?

for higher precision. this format:

45 11.735N,004 34.281E

and this

45 23.623, 5 38.77

How to test if parameters exist in rails

if params[:one] && param[:two]
  ... excute code ..
end

You can also check if the parameters are empty by using params[:two].empty

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

How to display loading message when an iFrame is loading?

I have followed the following approach

First, add sibling div

$('<div class="loading"></div>').insertBefore("#Iframe");

and then when the iframe completed loading

$("#Iframe").load(function(){
   $(this).siblings(".loading-fetching-content").remove(); 
  });

How to change color of the back arrow in the new material theme?

This is what worked for me:

Add the below attributes to your theme.

To change toolbar/actionbar back arrow above api 21

<item name="android:homeAsUpIndicator">@drawable/your_drawable_icon</item>

To change toolbar/actionbar back arrow below api 21

<item name="homeAsUpIndicator">@drawable/your_drawable_icon</item>

To change action mode back arrow

<item name="actionModeCloseDrawable">@drawable/your_drawable_icon</item>

To remove toolbar/actionbar shadow

<item name="android:elevation" tools:targetApi="lollipop">0dp</item>
<item name="elevation">0dp</item>
<!--backward compatibility-->
<item name="android:windowContentOverlay">@null</item>

To change actionbar overflow drawable

<!--under theme-->
<item name="actionOverflowButtonStyle">@style/MenuOverflowStyle</item>

<style name="MenuOverflowStyle" parent="Widget.AppCompat.ActionButton.Overflow">
<item name="srcCompat">@drawable/ic_menu_overflow</item>

Note : 'srcCompat' is used instead of 'android:src' because of vector drawable support for api below 21

take(1) vs first()

Tip: Only use first() if:

  • You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
  • OR You know 100% that the source observable will emit 1+ items (so can never throw).

If there are zero emissions and you are not explicitly handling it (with catchError) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.

You're safer off using take(1) for the most part provided that:

  • You're OK with take(1) not emitting anything if the source completes without an emission.
  • You don't need to use an inline predicate (eg. first(x => x > 10) )

Note: You can use a predicate with take(1) like this: .pipe( filter(x => x > 10), take(1) ). There is no error with this if nothing is ever greater than 10.

What about single()

If you want to be even stricter, and disallow two emissions you can use single() which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.

Tip: Single can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError() to guarantee good behavior.


Why not always use first() instead of take(1) ?

aka. How can first potentially cause more errors?

If you have an observable that takes something from a service and then pipes it through first() you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null) or NEVER then any downstream first() operators would start throwing errors.

Now I realize that might be exactly what you want - hence why this is just a tip. The operator first appealed to me because it sounded slightly less 'clumsy' than take(1) but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.


If you have a default value (constant):

Consider also .pipe(defaultIfEmpty(42), first()) if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first would always receive a value.

Note that defaultIfEmpty is only triggered if the stream is empty, not if the value of what is emitted is null.

Can a table have two foreign keys?

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
)


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
)

Create table Table1_sal
(
  salid varchar(2),`enter code here`
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

How can I add reflection to a C++ application?

This question is a bit old now (don't know why I keep hitting old questions today) but I was thinking about BOOST_FUSION_ADAPT_STRUCT which introduces compile-time reflection.

It is up to you to map this to run-time reflection of course, and it won't be too easy, but it is possible in this direction, while it would not be in the reverse :)

I really think a macro to encapsulate the BOOST_FUSION_ADAPT_STRUCT one could generate the necessary methods to get the runtime behavior.

Configuring angularjs with eclipse IDE

Configuration worked with Eclipse Mars 4.5 version.

1) Install Eclipse Mars 4.5 from https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/mars2 This comes with Tern and embedded Node.js server

2) Install AngularJS Eclipse plugin from Eclipse Marketplace

3) Configure node.js server to the embedded nodejs server within Eclipse (found in the eclipse plugins folder) at Windows-> Preferences -> JavaScript -> Tern -> Server -> node.js. No extra configurations are required.

4) Test configuration in a html or javascript file. https://github.com/angelozerr/angularjs-eclipse

How can I install MacVim on OS X?

  1. Download the latest build from https://github.com/macvim-dev/macvim/releases

  2. Expand the archive.

  3. Put MacVim.app into /Applications/.

Done.

CSS: Center block, but align contents to the left

THIS works

<div style="display:inline-block;margin:10px auto;">
    <ul style="list-style-type:none;">
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>root keyword text box</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube.com website <em>video search text box</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>scraped keywords listbox</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>right click context menu</em>.</li>
    </ul>
</div>

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

How do I detect the Python version at runtime?

Try this code, this should work:

import platform
print(platform.python_version())

VBA (Excel) Initialize Entire Array without Looping

For VBA you need to initialise in two lines.

Sub TestArray()

Dim myArray
myArray = Array(1, 2, 4, 8)

End Sub

What in layman's terms is a Recursive Function using PHP

If you add a certain value (say, "1") to Anthony Forloney's example, everything would be clear:

function fact(1) {
  if (1 === 0) { // our base case
  return 1;
  }
  else {
  return 1 * fact(1-1); // <--calling itself.
  }
}

original:

function fact($n) {
  if ($n === 0) { // our base case
    return 1;
  }
  else {
  return $n * fact($n-1); // <--calling itself.
  }
}

How do I modify fields inside the new PostgreSQL JSON datatype?

If your field type is of json the following will work for you.

UPDATE 
table_name
SET field_name = field_name::jsonb - 'key' || '{"key":new_val}' 
WHERE field_name->>'key' = 'old_value'.

Operator '-' delete key/value pair or string element from left operand. Key/value pairs are matched based on their key value.

Operator '||' concatenate two jsonb values into a new jsonb value.

Since these are jsonb operators you just need to typecast to::jsonb

More info : JSON Functions and Operators

You can read my note here

Assigning more than one class for one event

Approach #1

function doSomething(){
    if ($(this).hasClass('clickedTag')){
        // code here
    }
    else {
         // and here
    }
}

$('.tag1').click(doSomething);
$('.tag2').click(doSomething);

// or, simplifying further
$(".tag1, .tag2").click(doSomething);

Approach #2

This will also work:

?$(".tag1, .tag2").click(function(){
   alert("clicked");    
});?

Fiddle

I prefer a separate function (approach #1) if there is a chance that logic will be reused.

See also How can I select an element with multiple classes? for handling multiple classes on the same item.

Adding attribute in jQuery

best solution: from jQuery v1.6 you can use prop() to add a property

$('#someid').prop('disabled', true);

to remove it, use removeProp()

$('#someid').removeProp('disabled');

Reference

Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.

Error in strings.xml file in Android

You may be able to use unicode equivalent both apostrophe and other characters which are not supported in xml string. Apostrophe's equivalent is "\u0027" .

Getting the text from a drop-down box

This should return the text value of the selected value

var vSkill = document.getElementById('newSkill');

var vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML;

alert(vSkillText);

Props: @Tanerax for reading the question, knowing what was asked and answering it before others figured it out.

Edit: DownModed, cause I actually read a question fully, and answered it, sad world it is.

Run Java Code Online

OpenCode appears to be a project at the MIT Media Lab for running Java Code online in a web browser interface. Years ago, I played around a lot at TopCoder. It runs a Java Web Start app, though, so you would need a Java run time installed.

What are intent-filters in Android?

intent filter is expression which present in manifest in your app that specify the type of intents that the component is to receive. If component does not have any intent filter it can receive explicit intent. If component with filter then receive both implicit and explicit intent

Run two async tasks in parallel and collect results in .NET 4.5

It's weekend now!

    public async void Go()
    {
        Console.WriteLine("Start fosterage...");

        var t1 = Sleep(5000, "Kevin");
        var t2 = Sleep(3000, "Jerry");
        var result = await Task.WhenAll(t1, t2);

        Console.WriteLine($"My precious spare time last for only {result.Max()}ms");
        Console.WriteLine("Press any key and take same beer...");
        Console.ReadKey();
    }

    private static async Task<int> Sleep(int ms, string name)
    {
            Console.WriteLine($"{name} going to sleep for {ms}ms :)");
            await Task.Delay(ms);
            Console.WriteLine("${name} waked up after {ms}ms :(";
            return ms;
    }

What version of javac built my jar?

A jar is merely a container. It is a file archive a la tar. While a jar may have interesting information contained within it's META-INF hierarchy, it has no obligation to specify the vintage of the classes within it's contents. For that, one must examine the class files therein.

As as Peter Lawrey mentioned in comment to the original question, you can't necessarily know which JDK release built a given class file, but you can find out the byte code class version of the class file contained in a jar.

Yes, this kinda sucks, but the first step is to extract one or more classes from the jar. For example:

$ jar xf log4j-1.2.15.jar

On Linux, Mac OS X or Windows with Cygwin installed, the file(1) command knows the class version.

$ file ./org/apache/log4j/Appender.class
./org/apache/log4j/Appender.class: compiled Java class data, version 45.3

Or alternatively, using javap from the JDK as @jikes.thunderbolt aptly points out:

$ javap -v ./org/apache/log4j/Appender.class | grep major
 major version: 45

For Windows environments without either file or grep

> javap -v ./org/apache/log4j/Appender.class | findstr major
 major version: 45

FWIW, I will concur that javap will tell a whole lot more about a given class file than the original question asked.

Anyway, a different class version, for example:

$ file ~/bin/classes/P.class
/home/dave/bin/classes/P.class: compiled Java class data, version 50.0

The class version major number corresponds to the following Java JDK versions:

  • 45.3 = Java 1.1
  • 46 = Java 1.2
  • 47 = Java 1.3
  • 48 = Java 1.4
  • 49 = Java 5
  • 50 = Java 6
  • 51 = Java 7
  • 52 = Java 8
  • 53 = Java 9
  • 54 = Java 10
  • 55 = Java 11
  • 56 = Java 12
  • 57 = Java 13
  • 58 = Java 14

Linux command (like cat) to read a specified quantity of characters

I know the answer is in reply to a question asked 6 years ago ...

But I was looking for something similar for a few hours and then found out that: cut -c does exactly that, with an added bonus that you could also specify an offset.

cut -c 1-5 will return Hello and cut -c 7-11 will return world. No need for any other command

CSS background image to fit height, width should auto-scale in proportion

try

.something { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -100;  
}

What is the PostgreSQL equivalent for ISNULL()

Use COALESCE() instead:

SELECT COALESCE(Field,'Empty') from Table;

It functions much like ISNULL, although provides more functionality. Coalesce will return the first non null value in the list. Thus:

SELECT COALESCE(null, null, 5); 

returns 5, while

SELECT COALESCE(null, 2, 5);

returns 2

Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.

How can I kill a process by name instead of PID?

The default kill command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash provides its own kill which accepts job numbers, like kill %1, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash version by calling

enable -n kill

For more info see kill and enable entries in bash (1).

Unsupported Media Type in postman

Thanks for all Contributions;

that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

How does "make" app know default target to build if no target is specified?

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

Where will log4net create this log file?

it will create the file in the root directory of your project/solution.

You can specify a location of choice in the web.config of your app as follows:

   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/ServiceLogs/Olympus.Core.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyyMMdd.log" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
      <maxSizeRollBackups value="-1" />
      <countDirection value="1" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
      </layout>
    </appender>

the file tag specifies the location.

How do I obtain a Query Execution Plan in SQL Server?

There are a number of methods of obtaining an execution plan, which one to use will depend on your circumstances. Usually you can use SQL Server Management Studio to get a plan, however if for some reason you can't run your query in SQL Server Management Studio then you might find it helpful to be able to obtain a plan via SQL Server Profiler or by inspecting the plan cache.

Method 1 - Using SQL Server Management Studio

SQL Server comes with a couple of neat features that make it very easy to capture an execution plan, simply make sure that the "Include Actual Execution Plan" menu item (found under the "Query" menu) is ticked and run your query as normal.

Include Action Execution Plan menu item

If you are trying to obtain the execution plan for statements in a stored procedure then you should execute the stored procedure, like so:

exec p_Example 42

When your query completes you should see an extra tab entitled "Execution plan" appear in the results pane. If you ran many statements then you may see many plans displayed in this tab.

Screenshot of an Execution Plan

From here you can inspect the execution plan in SQL Server Management Studio, or right click on the plan and select "Save Execution Plan As ..." to save the plan to a file in XML format.

Method 2 - Using SHOWPLAN options

This method is very similar to method 1 (in fact this is what SQL Server Management Studio does internally), however I have included it for completeness or if you don't have SQL Server Management Studio available.

Before you run your query, run one of the following statements. The statement must be the only statement in the batch, i.e. you cannot execute another statement at the same time:

SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON -- The is the recommended option to use

These are connection options and so you only need to run this once per connection. From this point on all statements run will be acompanied by an additional resultset containing your execution plan in the desired format - simply run your query as you normally would to see the plan.

Once you are done you can turn this option off with the following statement:

SET <<option>> OFF

Comparison of execution plan formats

Unless you have a strong preference my recommendation is to use the STATISTICS XML option. This option is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio and supplies the most information in the most convenient format.

  • SHOWPLAN_TEXT - Displays a basic text based estimated execution plan, without executing the query
  • SHOWPLAN_ALL - Displays a text based estimated execution plan with cost estimations, without executing the query
  • SHOWPLAN_XML - Displays an XML based estimated execution plan with cost estimations, without executing the query. This is equivalent to the "Display Estimated Execution Plan..." option in SQL Server Management Studio.
  • STATISTICS PROFILE - Executes the query and displays a text based actual execution plan.
  • STATISTICS XML - Executes the query and displays an XML based actual execution plan. This is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 3 - Using SQL Server Profiler

If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace. The idea is to run your query while a trace that is capturing one of the "Showplan" events is running.

Note that depending on load you can use this method on a production environment, however you should obviously use caution. The SQL Server profiling mechanisms are designed to minimize impact on the database but this doesn't mean that there won't be any performance impact. You may also have problems filtering and identifying the correct plan in your trace if your database is under heavy use. You should obviously check with your DBA to see if they are happy with you doing this on their precious database!

  1. Open SQL Server Profiler and create a new trace connecting to the desired database against which you wish to record the trace.
  2. Under the "Events Selection" tab check "Show all events", check the "Performance" -> "Showplan XML" row and run the trace.
  3. While the trace is running, do whatever it is you need to do to get the slow running query to run.
  4. Wait for the query to complete and stop the trace.
  5. To save the trace right click on the plan xml in SQL Server Profiler and select "Extract event data..." to save the plan to file in XML format.

The plan you get is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 4 - Inspecting the query cache

If you can't run your query directly and you also can't capture a profiler trace then you can still obtain an estimated plan by inspecting the SQL query plan cache.

We inspect the plan cache by querying SQL Server DMVs. The following is a basic query which will list all cached query plans (as xml) along with their SQL text. On most database you will also need to add additional filtering clauses to filter the results down to just the plans you are interested in.

SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)

Execute this query and click on the plan XML to open up the plan in a new window - right click and select "Save execution plan as..." to save the plan to file in XML format.

Notes:

Because there are so many factors involved (ranging from the table and index schema down to the data stored and the table statistics) you should always try to obtain an execution plan from the database you are interested in (normally the one that is experiencing a performance problem).

You can't capture an execution plan for encrypted stored procedures.

"actual" vs "estimated" execution plans

An actual execution plan is one where SQL Server actually runs the query, whereas an estimated execution plan SQL Server works out what it would do without executing the query. Although logically equivalent, an actual execution plan is much more useful as it contains additional details and statistics about what actually happened when executing the query. This is essential when diagnosing problems where SQL Servers estimations are off (such as when statistics are out of date).

How do I interpret a query execution plan?

This is a topic worthy enough for a (free) book in its own right.

See also:

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Hidden features of Python

Flattening a list with sum().

The sum() built-in function can be used to __add__ lists together, providing a handy way to flatten a list of lists:

Python 2.7.1 (r271:86832, May 27 2011, 21:41:45) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Pip - Fatal error in launcher: Unable to create process using '"'

I installed python 2 and python 3 both in my windows 7. After having both versions of python, I moved to download PIP.

After downloading pip via downloading the get-pip.py file and run into the command prompt and navigate to the folder containing get-pip.py file.

I Run the following command:

python get-pip.py

after downloading PIP, I was getting the following error, Fatal error in launcher: Unable to create process using '"' SOLUTION **Then what worked for me is: I just run the following below command

python3 -m pip install --upgrade pip

And my pip started working. Hope it helps !**

How to sign an android apk file

Here is a guide on how to manually sign an APK. It includes info about the new apk-signer introduced in build-tools 24.0.3 (10/2016)

Automated Process:

Use this tool (uses the new apksigner from Google):

https://github.com/patrickfav/uber-apk-signer

Disclaimer: Im the developer :)

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimzation step if you want to upload the apk to the Play Store.

zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with

jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Threfore Google implemented their own apk signer called apksigner (duh!) The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this

apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name

and can be verified with

apksigner verify my-app.apk

The official documentation can be found here.

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Aus_lacy's post gave me the idea of trying related methods, of which join does work:

In [196]:

hl.name = 'hl'
Out[196]:
'hl'
In [199]:

df.join(hl).head(4)
Out[199]:
high    low loc_h   loc_l   hl
2014-01-01 17:00:00 1.376235    1.375945    1.376235    1.375945    1.376090
2014-01-01 17:01:00 1.376005    1.375775    NaN NaN NaN
2014-01-01 17:02:00 1.375795    1.375445    NaN 1.375445    1.375445
2014-01-01 17:03:00 1.375625    1.375515    NaN NaN NaN

Some insight into why concat works on the example but not this data would be nice though!

How do you access a website running on localhost from iPhone browser

If you are not on the same network you could use this third party tool called localtunnel

http://localtunnel.me/

It basically routes your content through another server and you access that.

Getting data from Yahoo Finance

To your first question, you can't really do any query through YQL to get data for all companies. It's more oriented towards obtaining data for a smaller query. (I.e., it's not going to give you a full data dump of the whole Yahoo! Finance database.)

To your second question, here's how you can get started exploring the Yahoo! Finance tables in YQL:

  1. Start at the YQL Console
  2. In the upper left corner, make sure Show Community Tables is checked
  3. Type finance in the search field
  4. You'll see all the Yahoo Finance tables (about 15)

Then you can try some example queries like the following:

select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")

Update 2016-04-04: Here's a current screenshot showing the location of the Show Community Tables checkbox which must be clicked to see these finance tables: enter image description here

How to export the Html Tables data into PDF using Jspdf

Just follow these steps i can assure pdf file will be generated

    <html>
    <head>

    <title>Exporting table data to pdf Example</title>


    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="js/jspdf.js"></script>
    <script type="text/javascript" src="js/from_html.js"></script>
    <script type="text/javascript" src="js/split_text_to_size.js"></script>
    <script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
    <script type="text/javascript" src="js/cell.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>


    <script type="text/javascript">
        $(document).ready(function() {

            $("#exportpdf").click(function() {
                var pdf = new jsPDF('p', 'pt', 'ledger');
                // source can be HTML-formatted string, or a reference
                // to an actual DOM element from which the text will be scraped.
                source = $('#yourTableIdName')[0];

                // we support special element handlers. Register them with jQuery-style 
                // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
                // There is no support for any other type of selectors 
                // (class, of compound) at this time.
                specialElementHandlers = {
                    // element with id of "bypass" - jQuery style selector
                    '#bypassme' : function(element, renderer) {
                        // true = "handled elsewhere, bypass text extraction"
                        return true
                    }
                };
                margins = {
                    top : 80,
                    bottom : 60,
                    left : 60,
                    width : 522
                };
                // all coords and widths are in jsPDF instance's declared units
                // 'inches' in this case
                pdf.fromHTML(source, // HTML string or DOM elem ref.
                margins.left, // x coord
                margins.top, { // y coord
                    'width' : margins.width, // max width of content on PDF
                    'elementHandlers' : specialElementHandlers
                },

                function(dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('fileNameOfGeneretedPdf.pdf');
                }, margins);
            });

        });
    </script>
    </head>
    <body>
    <div id="yourTableIdName">
        <table style="width: 1020px;font-size: 12px;" border="1">
            <thead>
                <tr align="left">
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>
            </thead>


            <tbody>

                <tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
<tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
            </tbody>
        </table></div>

        <input type="button" id="exportpdf" value="Download PDF">


    </body>

    </html>

Output:

Html file output: html output

Pdf file output: pdf output

IOException: The process cannot access the file 'file path' because it is being used by another process

Had an issue while uploading an image and couldn't delete it and found a solution. gl hf

//C# .NET
var image = Image.FromFile(filePath);

image.Dispose(); // this removes all resources

//later...

File.Delete(filePath); //now works

HTML/CSS: how to put text both right and left aligned in a paragraph

I wouldn't put it in the same <p>, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

<p style="text-align:right">
 <span style="float:left">I'll be on the left</span>
 I'll be on the right
</p>

How to join two sets in one line without using "|"

Assuming you also can't use s.union(t), which is equivalent to s | t, you could try

>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])

Or, if you want a comprehension,

>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])

Converting Integers to Roman Numerals - Java

enum Numeral {
        I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
        int weight;

        Numeral(int weight) {
            this.weight = weight;
        }
    };

    public static String roman(long n) {

        if( n <= 0) {
            throw new IllegalArgumentException();
        }

        StringBuilder buf = new StringBuilder();

        final Numeral[] values = Numeral.values();
        for (int i = values.length - 1; i >= 0; i--) {
            while (n >= values[i].weight) {
                buf.append(values[i]);
                n -= values[i].weight;
            }
        }
        return buf.toString();
    }

    public static void test(long n) {
        System.out.println(n + " = " + roman(n));
    }

    public static void main(String[] args) {
        test(1999);
        test(25);
        test(944);
        test(0);
    }

How to subtract X days from a date using Java calendar?

I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the java.time.Instant class.

Example for subtracting 5 days from the current time and getting the result as Date:

new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());

Another example for subtracting 1 hour and adding 15 minutes:

Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));

If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:

minusNano()
plusNano()
getNano()

Also, keep in mind, that Date is not as accurate as Instant.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

How to pretty print XML from the command line?

This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.

Use sed to replace '<' with itself preceeded with a newline.

And as mentioned by Gilles, it's probably not a good idea to use this in production.

# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l

# check the output looks generally ok
sed 's/</\n</g' sample.xml | head

# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I tried all of the above, nothing worked for me. Then I changed tomcat port numbers both HTTP/1.1 and Tomcat admin port and it got solved.

I see other solutions above worked for the people but it is worth to try this one if any of the above doesn't work.

Thanks everyone!

Is there a naming convention for git repositories?

If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

Write to .txt file?

FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

Table with fixed header and fixed column on pure css

I've made some changes in in jsfiddle. This might be what you're trying to do.

http://jsfiddle.net/C8Dtf/81/

I have hardcoded the titles like so:

<table id="left_table" class="freeze_table">
    <tr class='tblTitle'>
         <th>Title 1</th>
         <th>Title 2</th>
    </tr>
</table>

And I added some styles as well.

.tblTitle{
   position:absolute;
    top:0px;
    margin-bottom:30px;
    background:lightblue;
}
td, th{
    padding:5px;
    height:40px;
    width:40px;
    font-size:14px;
}

Hope this is what you want :)

How can I avoid running ActiveRecord callbacks?

This solution is Rails 2 only.

I just investigated this and I think I have a solution. There are two ActiveRecord private methods that you can use:

update_without_callbacks
create_without_callbacks

You're going to have to use send to call these methods. examples:

p = Person.new(:name => 'foo')
p.send(:create_without_callbacks)

p = Person.find(1)
p.send(:update_without_callbacks)

This is definitely something that you'll only really want to use in the console or while doing some random tests. Hope this helps!

Stock ticker symbol lookup API

Google Finance does let you retrieve up to 100 stock quotes at once using the following URL:

www.google.com/finance/info?infotype=infoquoteall&q=[ticker1],[ticker2],...,[tickern]

For example:

www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG

Someone has deciphered the available fields here:

http://qsb-mac.googlecode.com/svn/trunk/Vermilion/Modules/StockQuoter/StockQuoter.py

The current price ("l") is real-time and the delay is on par with Yahoo Finance. There are a few quirks you should be aware of. A handful of stocks require an exchange prefix. For example, if you query "BTIM", you'll get a "Bad Request" error but "AMEX:BTIM" works. A few stocks don't work even with the exchange prefix. For example, querying "FTWRD" and "NASDAQ:FTWRD" both generate "Bad Request" errors even though Google Finance does have information for this NASDAQ stock.

The "el" field, if present, tells you the current pre-market or after-hours price.

Sending email through Gmail SMTP server with C#

Simple steps to fix this:

1)Sign in to your Gmail

2)Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"

Update row with data from another row in the same table

If you just need to insert a new row with a data from another row,

    insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;

How do I use LINQ Contains(string[]) instead of Contains(string)

This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):

namespace StringExtensionMethods
{
    public static class StringExtension
    {
        public static bool Contains(this string[] stringarray, string pat)
        {
            bool result = false;

            foreach (string s in stringarray)
            {
                if (s == pat)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}

Ternary operators in JavaScript without an "else"

To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

And for objects:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

Original source

LINQ order by null column where order is ascending and nulls should be last

my decision:

Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)

Javascript negative number

function negative(n) {
  return n < 0;
}

Your regex should work fine for string numbers, but this is probably faster. (edited from comment in similar answer above, conversion with +n is not needed.)

Select row and element in awk

To expand on Dennis's answer, use awk's -v option to pass the i and j values:

# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

Copying HTML code in Google Chrome's inspect element

Do the following:

  1. Select the top most element, you want to copy. (To copy all, select <html>)
  2. Right click.
  3. Select Edit as HTML
  4. New sub-window opens up with the HTML text.
  5. This is your chance. Press CTRL+A/CTRL+C and copy the entire text field to a different window.

This is a hacky way, but it's the easiest way to do this.

Is it possible to indent JavaScript code in Notepad++?

Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)

http://www.sunjw.us/jsminnpp/

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

How to analyze disk usage of a Docker container

After 1.13.0, Docker includes a new command docker system df to show docker disk usage.

$ docker system df
TYPE            TOTAL        ACTIVE     SIZE        RECLAIMABLE
Images          5            1          2.777 GB    2.647 GB (95%)
Containers      1            1          0 B         0B
Local Volumes   4            1          3.207 GB    2.261 (70%)

To show more detailed information on space usage:

$ docker system df --verbose

"CAUTION: provisional headers are shown" in Chrome debugger

I believe it happens when the actual request is not sent. Usually happens when you are loading a cached resource.

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

Removing duplicates from a String in Java

public class RemoveRepeated4rmString {

    public static void main(String[] args) {
        String s = "harikrishna";
        String s2 = "";
        for (int i = 0; i < s.length(); i++) {
            Boolean found = false;
            for (int j = 0; j < s2.length(); j++) {
                if (s.charAt(i) == s2.charAt(j)) {
                    found = true;
                    break; //don't need to iterate further
                }
            }
            if (found == false) {
                s2 = s2.concat(String.valueOf(s.charAt(i)));
            }
        }
        System.out.println(s2);
    }
}

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml contains the necessary slf4j dependencies, e.g.:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>

Bulk Record Update with SQL

The SQL you posted in your question is one way to do it. Most things in SQL have more than one way to do it.

UPDATE
  [Table1] 
SET
  [Description]=(SELECT [Description] FROM [Table2] t2 WHERE t2.[ID]=Table1.DescriptionID)

If you are planning on running this on a PROD DB, it is best to create a snapshot or mirror of it first and test it out. Verify the data ends up as you expect for a couple records. And if you are satisfied, run it on the real DB.

Generate random numbers using C++11 random library

Here is some resource you can read about pseudo-random number generator.

https://en.wikipedia.org/wiki/Pseudorandom_number_generator

Basically, random numbers in computer need a seed (this number can be the current system time).

Replace

std::default_random_engine generator;

By

std::default_random_engine generator(<some seed number>);

How to pass parameters or arguments into a gradle task

task mathOnProperties << {
    println Integer.parseInt(a)+Integer.parseInt(b)
    println new Integer(a) * new Integer(b)
}

$ gradle -Pa=3 -Pb=4 mathOnProperties
:mathOnProperties
7
12

BUILD SUCCESSFUL

Querying a linked sql server

The accepted answer works for me.

Also, in MSSQLMS, you can browse the tree in the Object Explorer to the table you want to query.

[Server] -> Server Objects -> Linked Servers -> [Linked server] -> Catalogs -> [Database] -> [table]

then Right click, Script Table as, SELECT To, New Query Window

And the query will be generated for you with the right FROM, which you can use in your JOIN

HTML5 required attribute seems not working

Make sure that novalidate attribute is not set to your form tag

How do I make a comment in a Dockerfile?

Use the # syntax for comments

From: https://docs.docker.com/engine/reference/builder/#format

# My comment here
RUN echo 'we are running some cool things'

Run CRON job everyday at specific time

From cron manual http://man7.org/linux/man-pages/man5/crontab.5.html:

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: "1,2,5,9", "0-4,8-12".

So in this case it would be:

30 10,14 * * *

Is there a reason for C#'s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

How can I print literal curly-brace characters in a string and also use .format on it?

Reason is , {} is the syntax of .format() so in your case .format() doesn't recognize {Hello} so it threw an error.

you can override it by using double curly braces {{}},

x = " {{ Hello }} {0} "

or

try %s for text formatting,

x = " { Hello } %s"
print x%(42)  

Getting reference to child component in parent component

You can use ViewChild

<child-tag #varName></child-tag>

@ViewChild('varName') someElement;

ngAfterViewInit() {
  someElement...
}

where varName is a template variable added to the element. Alternatively, you can query by component or directive type.

There are alternatives like ViewChildren, ContentChild, ContentChildren.

@ViewChildren can also be used in the constructor.

constructor(@ViewChildren('var1,var2,var3') childQuery:QueryList)

The advantage is that the result is available earlier.

See also http://www.bennadel.com/blog/3041-constructor-vs-property-querylist-injection-in-angular-2-beta-8.htm for some advantages/disadvantages of using the constructor or a field.

Note: @Query() is the deprecated predecessor of @ContentChildren()

Update

Query is currently just an abstract base class. I haven't found if it is used at all https://github.com/angular/angular/blob/2.1.x/modules/@angular/core/src/metadata/di.ts#L145

Error: Argument is not a function, got undefined

In my case (having an overview page and an "add" page) I got this with my routing setup like below. It was giving the message for the AddCtrl that could not be injected...

$routeProvider.
  when('/', {
    redirectTo: '/overview'
  }).      
  when('/overview', {
    templateUrl: 'partials/overview.html',
    controller: 'OverviewCtrl'
  }).
  when('/add', {
    templateUrl: 'partials/add.html',
    controller: 'AddCtrl'
  }).
  otherwise({
    redirectTo: '/overview'
  });

Because of the when('/' route all my routes went to the overview and the controller could not be matched on the /add route page rendering. This was confusing because I DID see the add.html template but its controller was nowhere to be found.

Removing the '/'-route when case fixed this issue for me.

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

SVN icon overlays not showing properly

Tortoise SVN on Windows happens to lose sync quite often with the real file status. In that case try doing an svn cleanup.

Another thing, it may also depend where your source files are located, different drive, network drive, etc. There's an option in Tortoise to allow icon overlay or not, on remote drives.

Check this out in: TortoiseSVN / Settings / Icon Overlays / Drive types

How do you get a string from a MemoryStream?

Using a StreamReader to convert the MemoryStream to a String.

<Extension()> _
Public Function ReadAll(ByVal memStream As MemoryStream) As String
    ' Reset the stream otherwise you will just get an empty string.
    ' Remember the position so we can restore it later.
    Dim pos = memStream.Position
    memStream.Position = 0

    Dim reader As New StreamReader(memStream)
    Dim str = reader.ReadToEnd()

    ' Reset the position so that subsequent writes are correct.
    memStream.Position = pos

    Return str
End Function

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

Linq style "For Each"

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
{
    list.Add(x + 1);
}

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
   foreach (var x in @this)
      action(x);
}

The performance impact of using instanceof in Java

instanceof is very efficient, so your performance is unlikely to suffer. However, using lots of instanceof suggests a design issue.

If you can use xClass == String.class, this is faster. Note: you don't need instanceof for final classes.

How to specify the download location with wget?

man wget: -O file --output-document=file

wget "url" -O /tmp/cron_test/<file>

How to update array value javascript?

If you want to reassign an element in an array, you can do the following:

var blah = ['Jan', 'Fed', 'Apr'];

console.log(blah);

function reassign(array, index, newValue) {
    array[index] = newValue;
    return array;
}

reassign(blah, [2], 'Mar');

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

How to strip all whitespace from string

For Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.

\s on its own always covers the ASCII whitespace:

  • (regular) space
  • tab
  • new line (\n)
  • carriage return (\r)
  • form feed
  • vertical tab

Additionally:

  • for Python 2 with re.UNICODE enabled,
  • for Python 3 without any extra actions,

...\s also covers the Unicode whitespace characters, for example:

  • non-breaking space,
  • em space,
  • ideographic space,

...etc. See the full list here, under "Unicode characters with White_Space property".

However \s DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:

  • zero-width joiner,
  • Mongolian vowel separator,
  • zero-width non-breaking space (a.k.a. byte order mark),

...etc. See the full list here, under "Related Unicode characters without White_Space property".

So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

Sources:

Proper way to return JSON using node or Express

For the header half of the question, I'm gonna give a shout out to res.type here:

res.type('json')

is equivalent to

res.setHeader('Content-Type', 'application/json')

Source: express docs:

Sets the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified type. If type contains the “/” character, then it sets the Content-Type to type.

Truncate all tables in a MySQL database in one command?

Here is my variant to have 'one statement to truncate 'em all'.

First, I am using a separate database named 'util' for my helper stored procedures. The code of my stored procedure to truncate all tables is:

DROP PROCEDURE IF EXISTS trunctables;
DELIMITER ;;
CREATE  PROCEDURE trunctables(theDb varchar(64))
BEGIN
    declare tname varchar(64);
    declare tcursor CURSOR FOR 
    SELECT table_name FROM information_schema.tables WHERE table_type <> 'VIEW' AND table_schema = theDb;
    SET FOREIGN_KEY_CHECKS = 0; 
    OPEN tcursor;
    l1: LOOP
        FETCH tcursor INTO tname;
        if tname = NULL then leave l1; end if;
        set @sql = CONCAT('truncate `', theDB, '`.`', tname, '`');
        PREPARE stmt from @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END LOOP l1;
    CLOSE tcursor;
    SET FOREIGN_KEY_CHECKS = 1; 
END ;;
DELIMITER ;

Once you have this stored procedure in your util database, you can call it like

call util.trunctables('nameofdatabase');

which is now exactly one statement :-)

Use PHP composer to clone git repo

You can include git repository to composer.json like this:

"repositories": [
{
    "type": "package",
    "package": {
        "name": "example-package-name", //give package name to anything, must be unique
        "version": "1.0",
        "source": {
            "url": "https://github.com/example-package-name.git", //git url
            "type": "git",
            "reference": "master" //git branch-name
        }
    }
}],
"require" : {
  "example-package-name": "1.0"
}

How do I resolve a path relative to an ASP.NET MVC 4 application root?

To get the absolute path use this:

String path = HttpContext.Current.Server.MapPath("~/Data/data.html");

EDIT:

To get the Controller's Context remove .Current from the above line. By using HttpContext by itself it's easier to Test because it's based on the Controller's Context therefore more localized.

I realize now that I dislike how Server.MapPath works (internally eventually calls HostingEnvironment.MapPath) So I now recommend to always use HostingEnvironment.MapPath because its static and not dependent on the context unless of course you want that...

angularjs: ng-src equivalent for background-image:url(...)

It's also possible to do something like this with ng-style:

ng-style="image_path != '' && {'background-image':'url('+image_path+')'}"

which would not attempt to fetch a non-existing image.

Export to csv/excel from kibana

To export data to csv/excel from Kibana follow the following steps:-

  1. Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.

  2. Click on caret symbol (^) which is present at the bottom of the visualization.

  3. Then you will get an option of Export:Raw Formatted as the bottom of the page.

Please find below attached image showing Export option after clicking on caret symbol.

Please find below attached image showing Export option after clicking on caret symbol.

Remove item from list based on condition

prods.Remove(prods.Find(x => x.ID == 1));

Java compile error: "reached end of file while parsing }"

You have to open and close your class with { ... } like:

public class mod_MyMod extends BaseMod
{
  public String Version()
  {
    return "1.2_02";
  }

  public void AddRecipes(CraftingManager recipes)
  {
     recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
        "#", Character.valueOf('#'), Block.dirt });
  }
}

Error C1083: Cannot open include file: 'stdafx.h'

Just running through a Visual Studio Code tutorial and came across a similiar issue.

Replace #include "stdafx.h" with #include "pch.h" which is the updated name for the precompiled headers.

Outputting data from unit test in Python

We use the logging module for this.

For example:

import logging
class SomeTest( unittest.TestCase ):
    def testSomething( self ):
        log= logging.getLogger( "SomeTest.testSomething" )
        log.debug( "this= %r", self.this )
        log.debug( "that= %r", self.that )
        # etc.
        self.assertEquals( 3.14, pi )

if __name__ == "__main__":
    logging.basicConfig( stream=sys.stderr )
    logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
    unittest.main()

That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.

My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

SQL Server: Best way to concatenate multiple columns?

Try using below:

SELECT 
    (RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
    col_1,
    col_2 
FROM 
    s_cols 
WHERE
    col_any_condition = ''
;

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

RSA encryption and decryption in Python

Watch out using Crypto!!! It is a wonderful library but it has an issue in python3.8 'cause from the library time was removed the attribute clock(). To fix it just modify the source in /usr/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.pyline 77 changing t = time.clock() int t = time.perf_counter()

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you want a table where only the columns scroll horizontally, you can position: absolute the first column (and specify its width explicitly), and then wrap the entire table in an overflow-x: scroll block. Don't bother trying this in IE7, however...

Relevant HTML & CSS:

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 0;_x000D_
  border-top: 1px solid grey;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
  margin: 0;_x000D_
  border: 1px solid grey;_x000D_
  white-space: nowrap;_x000D_
  border-top-width: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
  width: 500px;_x000D_
  overflow-x: scroll;_x000D_
  margin-left: 5em;_x000D_
  overflow-y: visible;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.headcol {_x000D_
  position: absolute;_x000D_
  width: 5em;_x000D_
  left: 0;_x000D_
  top: auto;_x000D_
  border-top-width: 1px;_x000D_
  /*only relevant for first row*/_x000D_
  margin-top: -1px;_x000D_
  /*compensate for top border*/_x000D_
}_x000D_
_x000D_
.headcol:before {_x000D_
  content: 'Row ';_x000D_
}_x000D_
_x000D_
.long {_x000D_
  background: yellow;_x000D_
  letter-spacing: 1em;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
        <tr><th class="headcol">1</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">2</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">3</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">4</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">5</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">6</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

How is an HTTP POST request made in node.js?

You can use request library. https://www.npmjs.com/package/request

var request = require('request');

To post JSON data:

var myJSONObject = { ... };
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    json: true,   // <--Very important!!!
    body: myJSONObject
}, function (error, response, body){
    console.log(response);
});

To post xml data:

var myXMLText = '<xml>...........</xml>'
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
}, function (error, response, body){
    console.log(response);
});

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

What is the use of the @Temporal annotation in Hibernate?

use this

@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_date")
private Calendar createDate;

public Calendar getCreateDate() {
    return createDate;
}

public void setCreateDate(Calendar createDate) {
    this.createDate = createDate;
}

NodeJs : TypeError: require(...) is not a function

For me, I got similar error when switched between branches - one used newer ("typescriptish") version of @google-cloud/datastore packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports value. I got the error because node_modules still had newer modules used by branch I switched from.

C++ Singleton design pattern

Has anyone mentioned std::call_once and std::once_flag? Most other approaches - including double checked locking - are broken.

One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag is the mechanism to get guaranteed safe initialization.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

Create a string of variable length, filled with a repeated character

Version that works in all browsers

This function does what you want, and performs a lot faster than the option suggested in the accepted answer :

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i <= count;)
        array[i++] = str;
    return array.join('');
}

You use it like this :

var repeatedCharacter = repeat("a", 10);

To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.

Version for moderns browsers only

In modern browsers, you can now also do this :

var repeatedCharacter = "a".repeat(10) };

This option is even faster. However, unfortunately it doesn't work in any version of Internet explorer.

The numbers in the table specify the first browser version that fully supports the method :

enter image description here

What is the purpose of using -pedantic in GCC/G++ compiler?

Others have answered sufficiently. I would just like to add a few examples of frequent extensions:

The main function returning void. This is not defined by the standard, meaning it will only work on some compilers (including GCC), but not on others. By the way, int main() and int main(int, char**) are the two signatures that the standard does define.

Another popular extension is being able to declare and define functions inside other functions:

void f()
{
    void g()
    {
       // ...
    }

    // ...
    g();
    // ...
}

This is nonstandard. If you want this kind of behavior, check out C++11 lambdas

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case I had to delete the services in my installshield project and start from square one. My original service components were added manually and I couldn't get them working, the only error I was getting was the same "Error 1920 service failed to start. Verify that you have sufficient privileges to start system services." that you were getting. After deleting my components, I re-added them using the component wizard.
enter image description here

Component Wizard looks like this

I actually had to create two new components. One was of type "Install Service".

Service Component type shown here

enter image description here

The other component I had to add was of "Control Service" type.

enter image description here

I had to choose the service that I had setup when I added the Install Service component.enter image description here

After that it worked, even though nothing looked differently from the components I had added manually. Installshield must do something behind the scenes when it wires up the service components with the component wizard.

All of this was with Install Shield 2016.

Send parameter to Bootstrap modal window?

First of all you should fix modal HTML structure. Now it's not correct, you don't need class .hide:

<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body edit-content">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Then links should point to this modal via data-target attribute:

<a href="#myModal" data-toggle="modal" id="1" data-target="#edit-modal">Edit 1</a>

Finally Js part becomes very simple:

    $('#edit-modal').on('show.bs.modal', function(e) {

        var $modal = $(this),
            esseyId = e.relatedTarget.id;

        $.ajax({
            cache: false,
            type: 'POST',
            url: 'backend.php',
            data: 'EID=' + essayId,
            success: function(data) {
                $modal.find('.edit-content').html(data);
            }
        });
    })

Demo: http://plnkr.co/edit/4XnLTZ557qMegqRmWVwU?p=preview

How to terminate a python subprocess launched with shell=True

There is a very simple way for Python 3.5 or + (Actually tested on Python 3.8)

import subprocess, signal, time
p = subprocess.Popen(['cmd'], shell=True)
time.sleep(5) #Wait 5 secs before killing
p.send_signal(signal.CTRL_C_EVENT)

Then, your code may crash at some point if you have a keyboard input detection, or sth like this. In this case, on the line of code/function where the error is given, just use:

try:
    FailingCode #here goes the code which is raising KeyboardInterrupt
except KeyboardInterrupt:
    pass

What this code is doing is just sending a "CTRL+C" signal to the running process, what will cause the process to get killed.

How to send password using sftp batch file

You need to use the command pscp and forcing it to pass through sftp protocol. pscp is automatically installed when you install PuttY, a software to connect to a linux server through ssh.

When you have your pscp command here is the command line:

pscp -sftp -pw <yourPassword> "<pathToYourFile(s)>" <username>@<serverIP>:<PathInTheServerFromTheHomeDirectory>

These parameters (-sftp and -pw) are only available with pscp and not scp. You can also add -r if you want to upload everything in a folder in a recursive way.

JQuery Number Formatting

I would recommend looking at this article on how to use javascript to handle basic formatting:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page.

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library.

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin.

Side note - check this out if you want to get a chuckle about the over use of jQuery.

Populating a ComboBox using C#

  Language[] items = new Language[]{new Language("English", "En"),
                new Language("Italian", "It")};

            languagesCombo.ValueMember = "Alias";
            languagesCombo.DisplayMember = "FullName";
            languagesCombo.DataSource = items.ToList();

            languagesCombo.DropDownStyle = ComboBoxStyle.DropDownList;

 class Language
    {
        public string FullName { get; set; }
        public string Alias { get; set; }

        public Language(string fullName, string alias)
        {
            this.FullName = fullName;
            this.Alias = alias;
        }
    }

By making your drop down box "read-only" I am assuming you want to prevent user's typing in other options as opposed to being fully read-only where users cannot select a value??

If you wanted it to be fully read-only you could set the enabled property to be false.

How to verify CuDNN installation?

The installation of CuDNN is just copying some files. Hence to check if CuDNN is installed (and which version you have), you only need to check those files.

Install CuDNN

Step 1: Register an nvidia developer account and download cudnn here (about 80 MB). You might need nvcc --version to get your cuda version.

Step 2: Check where your cuda installation is. For most people, it will be /usr/local/cuda/. You can check it with which nvcc.

Step 3: Copy the files:

$ cd folder/extracted/contents
$ sudo cp include/cudnn.h /usr/local/cuda/include
$ sudo cp lib64/libcudnn* /usr/local/cuda/lib64
$ sudo chmod a+r /usr/local/cuda/lib64/libcudnn*

Check version

You might have to adjust the path. See step 2 of the installation.

$ cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2

Notes

When you get an error like

F tensorflow/stream_executor/cuda/cuda_dnn.cc:427] could not set cudnn filter descriptor: CUDNN_STATUS_BAD_PARAM

with TensorFlow, you might consider using CuDNN v4 instead of v5.

Ubuntu users who installed it via apt: https://askubuntu.com/a/767270/10425

What happens to C# Dictionary<int, int> lookup if the key does not exist?

A helper class is handy:

public static class DictionaryHelper
{
    public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
    {
        TVal val;
        if( dictionary.TryGetValue(key, out val) )
        {
            return val;
        }
        return defaultVal;
    }
}

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

I use Ctrl-b + q which makes it flash number for each pane, redrawing them on the way.

Can two applications listen to the same port?

Yes (for TCP) you can have two programs listen on the same socket, if the programs are designed to do so. When the socket is created by the first program, make sure the SO_REUSEADDR option is set on the socket before you bind(). However, this may not be what you want. What this does is an incoming TCP connection will be directed to one of the programs, not both, so it does not duplicate the connection, it just allows two programs to service the incoming request. For example, web servers will have multiple processes all listening on port 80, and the O/S sends a new connection to the process that is ready to accept new connections.

SO_REUSEADDR

Allows other sockets to bind() to this port, unless there is an active listening socket bound to the port already. This enables you to get around those "Address already in use" error messages when you try to restart your server after a crash.

Java: How to insert CLOB into oracle database

I had similar issue. Changed one of my table column from varchar2 to CLOB. I didn't needed to change any java code. I kept it as setString(..) only so no need to change set method as setClob() etch if you are using following versions ATLEAST of Oracle and jdbc driver.

I tried in In Oracle 11g and driver ojdbc6-11.2.0.4.jar

Value does not fall within the expected range

I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.

After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file

Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line.

for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:

/usr/local/opencv/

Then run

sudo ldconfig -v

If you can't find the libraries, try running

sudo updatedb && locate libopencv_core.so.2.4

in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.

References:

About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html

About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux

How to assign Php variable value to Javascript variable?

The most secure way (in terms of special character and data type handling) is using json_encode():

var spge = <?php echo json_encode($cname); ?>;

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

I am using Laravel 8 and just installed the fruitcake/laravel-cors and use it in app/Http/Kernel.php like blow:

protected $middleware = [
      ....
         \Fruitcake\Cors\HandleCors::class,
    ];

note : add it to end of array like me

How to detect the currently pressed key?

Since .NET Framework version 3.0, it is possible to use the Keyboard.IsKeyDown method from the new System.Windows.Input namespace. For instance:

if (((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && Keyboard.IsKeyDown(Key.F))
{
    // CTRL + F is currently pressed
}

Even though it's part of WPF, that method works fine for WinForm applications (provided that you add references to PresentationCore.dll and WindowsBase.dll). Unfortunately, however, the 3.0 and 3.5 versions of the Keyboard.IsKeyDown method did not work for WinForm applications. Therefore, if you do want to use it in a WinForm application, you'll need to be targeting .NET Framework 4.0 or later in order for it to work.

Easy way to test an LDAP User's Credentials

You should check out Softerra's LDAP Browser (the free version of LDAP Administrator), which can be downloaded here :

http://www.ldapbrowser.com/download.htm

I've used this application extensively for all my Active Directory, OpenLDAP, and Novell eDirectory development, and it has been absolutely invaluable.

If you just want to check and see if a username\password combination works, all you need to do is create a "Profile" for the LDAP server, and then enter the credentials during Step 3 of the creation process :

enter image description here

By clicking "Finish", you'll effectively issue a bind to the server using the credentials, auth mechanism, and password you've specified. You'll be prompted if the bind does not work.

Is it possible to get a list of files under a directory of a website? How?

DirBuster is such a hacking script that guesses a bunch of common names as nsanders had mentioned. It literally brute forces lists of common words and file endings (.html, .php) and over time figures out the directory structure of such sites, this could discover the page as you described but would also discover many others.

Blurry text after using CSS transform: scale(); in Chrome

I have found a much better and clean solution:

.element{
 transform:scale(0.5) 
 transform-origin: 100% 0;
}

or

.element{
 transform:scale(0.5) 
 transform-origin: 0% 0;
}

Thanks to this post: Preventing blurry rendering with transform: scale

List tables in a PostgreSQL schema

For those coming across this in the future:

If you would like to see a list of relations for several schemas:

$psql mydatabase
mydatabase=# SET search_path TO public, usa;   #schema examples
SET
mydatabase=# \dt
              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | counties        | table | postgres
 public | spatial_ref_sys | table | postgres
 public | states          | table | postgres
 public | us_cities       | table | postgres
 usa    | census2010      | table | postgres

Component based game engine design

While not a complete tutorial on the subject of game engine design, I have found that this page has some good detail and examples on use of the component architecture for games.

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

Trigger event when user scroll to specific element - with jQuery

Fire scroll only once after a successful scroll

The accepted answer worked for me (90%) but I had to tweak it a little to actually fire only once.

$(window).on('scroll',function() {
            var hT = $('#comment-box-section').offset().top,
                hH = $('#comment-box-section').outerHeight(),
                wH = $(window).height(),
                wS = $(this).scrollTop();

            if (wS > ((hT+hH-wH)-500)){
                console.log('comment box section arrived! eh');
                // After Stuff
                $(window).off('scroll');
                doStuff();
            }

        });

Note: By successful scroll I mean when user has scrolled to my element or in other words when my element is in view.

Toggle Checkboxes on/off

This one works very well for me.

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });

Specifying and saving a figure with exact size in pixels

Comparison of different approaches

Here is a quick comparison of some of the approaches I've tried with images showing what the give.

Baseline example without trying to set the image dimensions

Just to have a comparison point:

base.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')

run:

./base.py
identify base.png

outputs:

fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000

enter image description here

My best approach so far: plt.savefig(dpi=h/fig.get_size_inches()[1] height-only control

I think this is what I'll go with most of the time, as it is simple and scales:

get_size.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size.png',
    format='png',
    dpi=height/fig.get_size_inches()[1]
)

run:

./get_size.py 431

outputs:

get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000

enter image description here

and

./get_size.py 1293

outputs:

main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000

enter image description here

I tend to set just the height because I'm usually most concerned about how much vertical space the image is going to take up in the middle of my text.

plt.savefig(bbox_inches='tight' changes image size

I always feel that there is too much white space around images, and tended to add bbox_inches='tight' from: Removing white space around a saved image in matplotlib

However, that works by cropping the image, and you won't get the desired sizes with it.

Instead, this other approach proposed in the same question seems to work well:

plt.tight_layout(pad=1)
plt.savefig(...

which gives the exact desired height for height equals 431:

enter image description here

Fixed height, set_aspect, automatically sized width and small margins

Ermmm, set_aspect messes things up again and prevents plt.tight_layout from actually removing the margins...

Asked at: How to obtain a fixed height in pixels, fixed data x/y aspect ratio and automatically remove remove horizontal whitespace margin in Matplotlib?

plt.savefig(dpi=h/fig.get_size_inches()[1] + width control

If you really need a specific width in addition to height, this seems to work OK:

width.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'width.png',
    format='png',
    dpi=h/hi
)

run:

./width.py 431 869

output:

width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000

enter image description here

and for a small width:

./width.py 431 869

output:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000

enter image description here

So it does seem that fonts are scaling correctly, we just get some trouble for very small widths with labels getting cut off, e.g. the 100 on the top left.

I managed to work around those with Removing white space around a saved image in matplotlib

plt.tight_layout(pad=1)

which gives:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000

enter image description here

From this, we also see that tight_layout removes a lot of the empty space at the top of the image, so I just generally always use it.

Fixed magic base height, dpi on fig.set_size_inches and plt.savefig(dpi= scaling

I believe that this is equivalent to the approach mentioned at: https://stackoverflow.com/a/13714720/895245

magic.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'magic.png',
    format='png',
    dpi=h/magic_height*dpi,
)

run:

./magic.py 431 231

outputs:

magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000

enter image description here

And to see if it scales nicely:

./magic.py 1291 693

outputs:

magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000

enter image description here

So we see that this approach also does work well. The only problem I have with it is that you have to set that magic_height parameter or equivalent.

Fixed DPI + set_size_inches

This approach gave a slightly wrong pixel size, and it makes it is hard to scale everything seamlessly.

set_size_inches.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
    0,
    60.,
    'Hello',
    # Keep font size fixed independently of DPI.
    # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
    fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
    'set_size_inches.png',
    format='png',
)

run:

./set_size_inches.py 431 231

outputs:

set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000

so the height is slightly off, and the image:

enter image description here

The pixel sizes are also correct if I make it 3 times larger:

./set_size_inches.py 1291 693

outputs:

set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000

enter image description here

We understand from this however that for this approach to scale nicely, you need to make every DPI-dependant setting proportional to the size in inches.

In the previous example, we only made the "Hello" text proportional, and it did retain its height between 60 and 80 as we'd expect. But everything for which we didn't do that, looks tiny, including:

  • line width of axes
  • tick labels
  • point markers

SVG

I could not find how to set it for SVG images, my approaches only worked for PNG e.g.:

get_size_svg.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size_svg.svg',
    format='svg',
    dpi=height/fig.get_size_inches()[1]
)

run:

./get_size_svg.py 431

and the generated output contains:

<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"

and identify says:

get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000

and if I open it in Chromium 86 the browser debug tools mouse image hover confirm that height as 460.79.

But of course, since SVG is a vector format, everything should in theory scale, so you can just convert to any fixed sized format without loss of resolution, e.g.:

inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png

gives the exact height:

TODO regenerate image, messed up the upload somehow.

I use Inkscape instead of Imagemagick's convert here because you need to mess with -density as well to get sharp SVG resizes with ImageMagick:

And setting <img height="" on the HTML should also just work for the browser.

Tested on matplotlib==3.2.2.

TypeError: a bytes-like object is required, not 'str' in python and CSV

file = open('parsed_data.txt', 'w')
for link in soup.findAll('a', attrs={'href': re.compile("^http")}): print (link)
soup_link = str(link)
print (soup_link)
file.write(soup_link)
file.flush()
file.close()

In my case, I used BeautifulSoup to write a .txt with Python 3.x. It had the same issue. Just as @tsduteba said, change the 'wb' in the first line to 'w'.

Changing website favicon dynamically

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

Javascript callback when IFRAME is finished loading?

Using onload attrbute will solve your problem.

Here is an example.

_x000D_
_x000D_
function a() {_x000D_
alert("Your iframe has been loaded");_x000D_
}
_x000D_
<iframe src="https://stackoverflow.com" onload="a()"></iframe>
_x000D_
_x000D_
_x000D_

Is this what you want?

Click here for more information.

JSON.parse vs. eval()

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:

var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"

eval(x)         //won't work
JSON.parse(x)   //does work

See this example.

How to convert an object to a byte array in C#

To access the memory of an object directly (to do a "core dump") you'll need to head into unsafe code.

If you want something more compact than BinaryWriter or a raw memory dump will give you, then you need to write some custom serialisation code that extracts the critical information from the object and packs it in an optimal way.

edit P.S. It's very easy to wrap the BinaryWriter approach into a DeflateStream to compress the data, which will usually roughly halve the size of the data.

Reload chart data via JSON with Highcharts

If you are using push to push the data to the option.series dynamically .. just use

options.series = [];  

to clear it.

options.series = [];
$("#change").click(function(){
}

Seeking useful Eclipse Java code templates

Throw an IllegalArgumentException with variable in current scope (illarg):

throw new IllegalArgumentException(${var});

Better

throw new IllegalArgumentException("Invalid ${var} " + ${var});  

How to open a URL in a new Tab using JavaScript or jQuery?

You can easily create a new tab; do like the following:

function newTab() {
     var form = document.createElement("form");
     form.method = "GET";
     form.action = "http://www.example.com";
     form.target = "_blank";
     document.body.appendChild(form);
     form.submit();
}

How do I add 24 hours to a unix timestamp in php?

Add 24*3600 which is the number of seconds in 24Hours

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to have jQuery restrict file types on upload?

function validateFileExtensions(){
        var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
        var fileErrors = new Array();

        $( "input:file").each(function(){
            var file = $(this).value;
            var ext = file.split('.').pop();
            if( $.inArray( ext, validFileExtensions ) == -1) {
                fileErrors.push(file);
            }
        });

        if( fileErrors.length > 0 ){
            var errorContainer = $("#validation-errors");
            for(var i=0; i < fileErrors.length; i++){
                errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
            }
            return false;
        }
        return true;
    }

How do I parse command line arguments in Bash?

I think this one is simple enough to use:

#!/bin/bash
#

readopt='getopts $opts opt;rc=$?;[ $rc$opt == 0? ]&&exit 1;[ $rc == 0 ]||{ shift $[OPTIND-1];false; }'

opts=vfdo:

# Enumerating options
while eval $readopt
do
    echo OPT:$opt ${OPTARG+OPTARG:$OPTARG}
done

# Enumerating arguments
for arg
do
    echo ARG:$arg
done

Invocation example:

./myscript -v -do /fizz/someOtherFile -f ./foo/bar/someFile
OPT:v 
OPT:d 
OPT:o OPTARG:/fizz/someOtherFile
OPT:f 
ARG:./foo/bar/someFile

Android/Eclipse: how can I add an image in the res/drawable folder?

You can just put it in on the file system. Eclipse will pick up the change on the next refresh. Click the folder and press F5 to refresh. BTW, make sure the file name does not have any capital letters... it will break android... and eclipse will let you know.

Difference between "char" and "String" in Java

Char is a single alphabet where as String is a sequence of characters. Char is primitive datatype where as String is a class.

Ansible: Store command's stdout in new variable?

A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact to help keep the clutter to a minimum.

So if I were to register using the variable, psk, I'd use that same variable name with creating the set_fact.

Example

- name: generate PSK
  shell: openssl rand -base64 48
  register: psk
  delegate_to: 127.0.0.1
  run_once: true

- set_fact: 
    psk={{ psk.stdout }}

- debug: var=psk
  run_once: true

Then when I run it:

$ ansible-playbook -i inventory setup_ipsec.yml

 PLAY                                                                                                                                                                                [all] *************************************************************************************************************************************************************************

 TASK [Gathering                                                                                                                                                                     Facts] *************************************************************************************************************************************************************
 ok: [hostc.mydom.com]
 ok: [hostb.mydom.com]
 ok: [hosta.mydom.com]

 TASK [libreswan : generate                                                                                                                                                          PSK] ****************************************************************************************************************************************************
 changed: [hosta.mydom.com -> 127.0.0.1]

 TASK [libreswan :                                                                                                                                                                   set_fact] ********************************************************************************************************************************************************
 ok: [hosta.mydom.com]
 ok: [hostb.mydom.com]
 ok: [hostc.mydom.com]

 TASK [libreswan :                                                                                                                                                                   debug] ***********************************************************************************************************************************************************
 ok: [hosta.mydom.com] => {
     "psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
 }

 PLAY                                                                                                                                                                                RECAP *************************************************************************************************************************************************************************
 hosta.mydom.com    : ok=4    changed=1    unreachable=0    failed=0
 hostb.mydom.com    : ok=2    changed=0    unreachable=0    failed=0
 hostc.mydom.com    : ok=2    changed=0    unreachable=0    failed=0

ValueError: invalid literal for int () with base 10

So if you have

floatInString = '5.0'

You can convert it to int with floatInInt = int(float(floatInString))

What does the question mark and the colon (?: ternary operator) mean in objective-c?

Simply, the logic would be

(condition) ? {code for YES} : {code for NO}

How can I update my ADT in Eclipse?

Reason to that is with the new update, they changed the URL for the Android Developer Tools update site to require HTTPS. If you are updating ADT, make sure you use HTTPS in the URL for the Android Developer Tools update site.

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

In addition to adding these attributes to your Id column:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

in your migration you should change your CreateTable to add the defaultValueSQL property to your column i.e.:

Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),

This will prevent you from having to manually touch your database which, as you pointed out in the comments, is something you want to avoid with Code First.

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

How to add image in a TextView text?

This might Help You

  SpannableStringBuilder ssBuilder;

        ssBuilder = new SpannableStringBuilder(" ");
        // working code ImageSpan image = new ImageSpan(textView.getContext(), R.drawable.image);
        Drawable image = ContextCompat.getDrawable(textView.getContext(), R.drawable.image);
        float scale = textView.getContext().getResources().getDisplayMetrics().density;
        int width = (int) (12 * scale + 0.5f);
        int height = (int) (18 * scale + 0.5f);
        image.setBounds(0, 0, width, height);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
        ssBuilder.setSpan(
                imageSpan, // Span to add
                0, // Start of the span (inclusive)
                1, // End of the span (exclusive)
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);// Do not extend the span when text add later

        ssBuilder.append(" " + text);
        ssBuilder = new SpannableStringBuilder(text);
        textView.setText(ssBuilder);

get user timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

As mentioned here, https://stackoverflow.com/a/50941562/2186220, use gradle plugin version 3 or higher while using 'implementation'.

Also, use the google() repository in buildscript.

buildscript {
    repositories {
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
    }
}

These changes should solve the issue.