Programs & Examples On #Fitbounds

Google Maps API v3: Can I setZoom after fitBounds?

this work's for me with API v3 but with setting fixed zoom:

var bounds = new google.maps.LatLngBounds();
// extend bounds with each point

gmap.setCenter(bounds.getCenter()); 
gmap.setZoom( 6 );

Unix ls command: show full path when using options

Try this, works for me: ls -d /a/b/c/*

Android: No Activity found to handle Intent error? How it will resolve

Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:

Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
                    startActivity(i);

In this statement replace ActivityName by Name of Class of Activity, this code resides in.

How to count frequency of characters in a string?

We can use frequency method of Collections class for this. Split the string into string array. Use HashSet to remove duplicates and check frequency of each object in HashSet using frequency method of Collections

void usingCollections(){

  String input = "cuttack";

  String [] stringArray = input.split("");

  Set<String> s = new HashSet(Arrays.asList(stringArray));

  for(String abc : s){

    System.out.println (abc + ":"+Collections.frequency(Arrays.asList(stringArray),abc));

  }
}

Download a file from NodeJS Server using Express

Use res.download()

It transfers the file at path as an “attachment”. For instance:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

How to select first child with jQuery?

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

increase font size of hyperlink text html

Your font tag is not correct, so it won't work in some browsers. The px unit is used with CSS, not HTML attributes. The font tag should look like this:

<font size="100">

Well, actually it shouldn't be there at all. The font tag is deprecated, you should use CSS to style the content, like you do already with the text-decoration:

<a href="selectTopic?html" style="font-size: 100px; text-decoration: none">HTML 5</a>

To separate the content from the styling, you should of course work towards putting the CSS in a style sheet rather than as inline style attributes. That way you can apply one style to several elements without having to put the same style attribute in all of them.

Example:

<a href="selectTopic?html" class="topic">HTML 5</a>

CSS:

.topic { font-size: 100px; text-decoration: none; }

jQuery: How to capture the TAB keypress within a Textbox

$('#textbox').live('keypress', function(e) {
    if (e.keyCode === 9) {
        e.preventDefault();
        // do work
    }
});

Check if a process is running or not on Windows with Python

import psutil

def check_process_status(process_name):
    """
    Return status of process based on process name.
    """
    process_status = [ proc.status() for proc in psutil.process_iter() if proc.name() == process_name ]
    if process_status:
        print("Process name %s and staus %s"%(process_name, process_status[0]))
    else:
        print("Process name not valid", process_name)

The entity cannot be constructed in a LINQ to Entities query

Here is one way to do this without declaring aditional class:

public List<Product> GetProducts(int categoryID)
{
    var query = from p in db.Products
            where p.CategoryID == categoryID
            select new { Name = p.Name };
    var products = query.ToList().Select(r => new Product
    {
        Name = r.Name;
    }).ToList();

    return products;
}

However, this is only to be used if you want to combine multiple entities in a single entity. The above functionality (simple product to product mapping) is done like this:

public List<Product> GetProducts(int categoryID)
{
    var query = from p in db.Products
            where p.CategoryID == categoryID
            select p;
    var products = query.ToList();

    return products;
}

how to set "camera position" for 3d plots using python/matplotlib?

By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init. I've used the below script to first create the plot, then I determined a good elevation, or elev, from which to view my plot. I then adjusted the azimuth angle, or azim, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.

    from mpl_toolkits.mplot3d import Axes3D
    ax = Axes3D(fig)
    ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
    for ii in xrange(0,360,1):
        ax.view_init(elev=10., azim=ii)
        savefig("movie%d.png" % ii)

How do I get next month date from today's date and insert it in my database?

$nextm = date('m', strtotime('+1 month', strtotime(date('Y-m-01'))));

How to copy directories with spaces in the name

There's no need to add space before closing quote if path doesn't contain trailing backslash, so following command should work:

robocopy "C:\Source Path" "C:\Destination Path" /option1 /option2...

But, following will not work:

robocopy "C:\Source Path\" "C:\Destination Path\" /option1 /option2...

This is due to the escaping issue that is described here:

The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the closing quote " at the end of the line will be escaped \".

How to convert a string with Unicode encoding to a string of letters

Updates regarding answers suggesting using The Apache Commons Lang's: StringEscapeUtils.unescapeJava() - it was deprecated,

Deprecated. as of 3.6, use commons-text StringEscapeUtils instead

The replacement is Apache Commons Text's StringEscapeUtils.unescapeJava()

Laravel view not found exception

In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index') all started working.

Changing specific text's color using NSMutableAttributedString in Swift

Based on the answers before I created a string extension

extension String {

func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
     let range = (self as NSString).range(of: highlightedWords)
     let result = NSMutableAttributedString(string: self)

     for attribute in attributes {
         result.addAttributes(attribute, range: range)
     }

     return result
    }
}

You can pass the attributes for the text to the method

Call like this

  let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
  myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)

How do I UPDATE from a SELECT in SQL Server?

The following example uses a derived table, a SELECT statement after the FROM clause, to return the old and new values for further updates:

UPDATE x
SET    x.col1 = x.newCol1,
       x.col2 = x.newCol2
FROM   (SELECT t.col1,
               t2.col1 AS newCol1,
               t.col2,
               t2.col2 AS newCol2
        FROM   [table] t
               JOIN other_table t2
                 ON t.ID = t2.ID) x

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

What causes java.lang.IncompatibleClassChangeError?

My answer, I believe, will be Intellij specific.

I had rebuilt clean, even going as far as to manually delete the "out" and "target" dirs. Intellij has a "invalidate caches and restart", which sometimes clears odd errors. This time it didn't work. The dependency versions all looked correct in the project settings->modules menu.

The final answer was to manually delete my problem dependency from my local maven repo. An old version of bouncycastle was the culprit(I knew I had just changed versions and that would be the problem) and although the old version showed up no where in what was being built, it solved my problem. I was using intellij version 14 and then upgraded to 15 during this process.

How to wait for 2 seconds?

The documentation for WAITFOR() doesn't explicitly lay out the required string format.

This will wait for 2 seconds:

WAITFOR DELAY '00:00:02';

The format is hh:mi:ss.mmm.

How to call a REST web service API from JavaScript?

I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.

The API includes a lot more, but start with the fetch() method. It takes two arguments:

  1. A URL or an object representing the request.
  2. Optional init object containing the method, headers, body etc.

Simple GET:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json');
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Recreating the previous top answer, a POST:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json', {
    method: 'POST',
    body: myBody, // string or object
    headers: {
      'Content-Type': 'application/json'
    }
  });
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Invert "if" statement to reduce nesting

There are several advantages to this sort of coding but for me the big win is, if you can return quick you can improve the speed of your application. IE I know that because of Precondition X that I can return quickly with an error. This gets rid of the error cases first and reduces the complexity of your code. In a lot of cases because the cpu pipeline can be now be cleaner it can stop pipeline crashes or switches. Secondly if you are in a loop, breaking or returning out quickly can save you a lots of cpu. Some programmers use loop invariants to do this sort of quick exit but in this you can broke your cpu pipeline and even create memory seek problem and mean the the cpu needs to load from outside cache. But basically I think you should do what you intended, that is end the loop or function not create a complex code path just to implement some abstract notion of correct code. If the only tool you have is a hammer then everything looks like a nail.

compare two files in UNIX

There are 3 basic commands to compare files in unix:

  1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

  2. comm : This command is used to find out the records available in one but not in another

  3. diff

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

Here a minimal POC class w/ all the cruft removed

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

public class UncShareWithCredentials : IDisposable
{
    private string _uncShare;

    public UncShareWithCredentials(string uncShare, string userName, string password)
    {
        var nr = new Native.NETRESOURCE
        {
            dwType = Native.RESOURCETYPE_DISK,
            lpRemoteName = uncShare
        };

        int result = Native.WNetUseConnection(IntPtr.Zero, nr, password, userName, 0, null, null, null);
        if (result != Native.NO_ERROR)
        {
            throw new Win32Exception(result);
        }
        _uncShare = uncShare;
    }

    public void Dispose()
    {
        if (!string.IsNullOrEmpty(_uncShare))
        {
            Native.WNetCancelConnection2(_uncShare, Native.CONNECT_UPDATE_PROFILE, false);
            _uncShare = null;
        }
    }

    private class Native
    {
        public const int RESOURCETYPE_DISK = 0x00000001;
        public const int CONNECT_UPDATE_PROFILE = 0x00000001;
        public const int NO_ERROR = 0;

        [DllImport("mpr.dll")]
        public static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID,
            int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);

        [DllImport("mpr.dll")]
        public static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);

        [StructLayout(LayoutKind.Sequential)]
        public class NETRESOURCE
        {
            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            public string lpLocalName;
            public string lpRemoteName;
            public string lpComment;
            public string lpProvider;
        }
    }
}

You can directly use \\server\share\folder w/ WNetUseConnection, no need to strip it to \\server part only beforehand.

Javascript variable access in HTML

Here you go: http://codepen.io/anon/pen/cKflA

Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ

Is it valid to have a html form inside another html form?

A. It is not valid HTML nor XHTML

In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:

"form must not contain other form elements."

http://www.w3.org/TR/xhtml1/#prohibitions

As for the older HTML 3.2 spec, the section on the FORMS element states that:

"Every form must be enclosed within a FORM element. There can be several forms in a single document, but the FORM element can't be nested."

B. The Workaround

There are workarounds using JavaScript without needing to nest form tags.

"How to create a nested form." (despite title this is not nested form tags, but a JavaScript workaround).

Answers to this StackOverflow question

Note: Although one can trick the W3C Validators to pass a page by manipulating the DOM via scripting, it's still not legal HTML. The problem with using such approaches is that the behavior of your code is now not guaranteed across browsers. (since it's not standard)

MVC pattern on Android

I think the most useful simplified explanation is here: http://www.cs.otago.ac.nz/cosc346/labs/COSC346-lab2.2up.pdf

From everything else I've seen and read here, implementing all these things makes it harder and does not fit in well with other parts of android.

Having an activity implement other listeners is already the standard Android way. The most harmless way would be to add the Java Observer like the slides describe and group the onClick and other types of actions into functions that are still in the Activity.

The Android way is that the Activity does both. Fighting it doesn't really make extending or doing future coding any easier.

I agree with the 2nd post. It's sort of already implemented, just not the way people are used to. Whether or not it's in the same file or not, there is separation already. There is no need to create extra separation to make it fit other languages and OSes.

CSS customized scroll bar in div

Give this a try

Source : https://nicescroll.areaaperta.com/

Simple Implementation

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

  function() { 

    $("html").niceScroll();

  }

);
</script>

It is a jQuery plugin scrollbar, so your scrollbars are controllable and look the same across the various OS's.

PHP __get and __set magic methods

Intenta con:

__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}

Changing selection in a select with the Chosen plugin

In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:

jQuery("body").on("click", ".result-selected", function() {
    var locID = jQuery(this).attr('class').split('__').pop();
    // I have a class name: class="result-selected locvalue__209"
    var arrayCurrent = jQuery('#searchlocation').val();
    var index = arrayCurrent.indexOf(locID);
    if (index > -1) {
        arrayCurrent.splice(index, 1);
    }
    jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

How to insert element into arrays at specific position?

In case you are just looking to insert an item into an array at a certain position (based on @clausvdb answer):

function array_insert($arr, $insert, $position) {
    $i = 0;
    $ret = array();
    foreach ($arr as $key => $value) {
            if ($i == $position) {
                $ret[] = $insert;
            }
            $ret[] = $value;
            $i++;
    }
    return $ret;
}

How to convert String to long in Java?

Use Long.parseLong()

 Long.parseLong("0", 10)        // returns 0L
 Long.parseLong("473", 10)      // returns 473L
 Long.parseLong("-0", 10)       // returns 0L
 Long.parseLong("-FF", 16)      // returns -255L
 Long.parseLong("1100110", 2)   // returns 102L
 Long.parseLong("99", 8)        // throws a NumberFormatException
 Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
 Long.parseLong("Hazelnut", 36) // returns 1356099454469L
 Long.parseLong("999")          // returns 999L

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

PHP Create and Save a txt file to root directory

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>

What is the difference between jQuery: text() and html() ?

Use .text(…) when you intend to display the value as a simple text.

Use .html(…) when you intend to display the value as a html formatted text (or HTML content).

You should definitely use .text(...) when you’re not sure that your text (e.g. coming from an input control) do not contain characters/tags that has special meaning in HTML. This is really important because this could result in the text will not display properly but it could also cause that an unwanted JS script snippet (e.g. coming from another user input) to be activated.

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

Should I always use a parallel stream when possible?

Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.

As a rule, performance gains from parallelism are best on streams over ArrayList , HashMap , HashSet , and ConcurrentHashMap instances; arrays; int ranges; and long ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by the spliterator method on Stream and Iterable.

Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.

Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch

How can I detect the encoding/codepage of a text file

I've done something similar in Python. Basically, you need lots of sample data from various encodings, which are broken down by a sliding two-byte window and stored in a dictionary (hash), keyed on byte-pairs providing values of lists of encodings.

Given that dictionary (hash), you take your input text and:

  • if it starts with any BOM character ('\xfe\xff' for UTF-16-BE, '\xff\xfe' for UTF-16-LE, '\xef\xbb\xbf' for UTF-8 etc), I treat it as suggested
  • if not, then take a large enough sample of the text, take all byte-pairs of the sample and choose the encoding that is the least common suggested from the dictionary.

If you've also sampled UTF encoded texts that do not start with any BOM, the second step will cover those that slipped from the first step.

So far, it works for me (the sample data and subsequent input data are subtitles in various languages) with diminishing error rates.

ORACLE IIF Statement

Two other alternatives:

  1. a combination of NULLIF and NVL2. You can only use this if emp_id is NOT NULL, which it is in your case:

    select nvl2(nullif(emp_id,1),'False','True') from employee;
    
  2. simple CASE expression (Mt. Schneiders used a so-called searched CASE expression)

    select case emp_id when 1 then 'True' else 'False' end from employee;
    

Flutter.io Android License Status Unknown

After doing lots of analysis for my Ubuntu 20.04 I have found the solution

for me the error was /home/rk/Android/Sdk/tools/bin/sdkmanager was missing write permission.

  1. chmod +w home/rk/Android/Sdk/tools/bin/sdkmanager

Then run the below command.

  1. flutter doctor --android-licenses

it automatically process the licences.

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset

Access-control-allow-origin with multiple domains

I managed to solve this in the Request handling code following advice from 'monsur'.

string origin = WebOperationContext.Current.IncomingRequest.Headers.Get("Origin");

WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", origin);

How to get milliseconds from LocalDateTime in Java 8

I'm not entirely sure what you mean by "current milliseconds" but I'll assume it's the number of milliseconds since the "epoch," namely midnight, January 1, 1970 UTC.

If you want to find the number of milliseconds since the epoch right now, then use System.currentTimeMillis() as Anubian Noob has pointed out. If so, there's no reason to use any of the new java.time APIs to do this.

However, maybe you already have a LocalDateTime or similar object from somewhere and you want to convert it to milliseconds since the epoch. It's not possible to do that directly, since the LocalDateTime family of objects has no notion of what time zone they're in. Thus time zone information needs to be supplied to find the time relative to the epoch, which is in UTC.

Suppose you have a LocalDateTime like this:

LocalDateTime ldt = LocalDateTime.of(2014, 5, 29, 18, 41, 16);

You need to apply the time zone information, giving a ZonedDateTime. I'm in the same time zone as Los Angeles, so I'd do something like this:

ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));

Of course, this makes assumptions about the time zone. And there are edge cases that can occur, for example, if the local time happens to name a time near the Daylight Saving Time (Summer Time) transition. Let's set these aside, but you should be aware that these cases exist.

Anyway, if you can get a valid ZonedDateTime, you can convert this to the number of milliseconds since the epoch, like so:

long millis = zdt.toInstant().toEpochMilli();

Table header to stay fixed at the top when user scrolls it out of view with jQuery

function fix_table_header_position(){
 var width_list = [];
 $("th").each(function(){
    width_list.push($(this).width());
 });
 $("tr:first").css("position", "absolute");
 $("tr:first").css("z-index", "1000");
 $("th, td").each(function(index){
    $(this).width(width_list[index]);
 });

 $("tr:first").after("<tr height=" + $("tr:first").height() + "></tr>");}

This is my solution

adb connection over tcp not working now

This answer is late, but hopefully it helps others.

I have had the same experience of not being able to connect. Rebooting phone and PC does not help. I found the fix at: http://developer.android.com/tools/help/adb.html at the bottom of the page.

Basically you follow these steps:

  1. Connect phone with usb cable to PC.
  2. Issue command: adb usb
  3. Issue command: adb tcpip 5555
  4. Issue command: adb connect xxx.xxx.xxx.xxx

Where xxx.xxx.xxx.xxx is your phone's IP address.

Select from one table matching criteria in another?

You should make tags their own table with a linking table.

items:
id    object
1     lamp  
2     table   
3     stool  
4     bench 

tags:
id     tag
1      furniture
2      chair

items_tags:
item_id tag_id
1       1
2       1
3       1
4       1
3       2
4       2

Android button with different background colors

in Mono Android you can use filter like this:

your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

PHP "php://input" vs $_POST

First, a basic truth about PHP.

PHP was not designed to explicitly give you a pure REST (GET, POST, PUT, PATCH, DELETE) like interface for handling HTTP requests.

However, the $_SERVER, $_COOKIE, $_POST, $_GET, and $_FILES superglobals, and the function filter_input_array() are very useful for the average person's / layman's needs.

The number one hidden advantage of $_POST (and $_GET) is that your input data is url-decoded automatically by PHP. You never even think about having to do it, especially for query string parameters within a standard GET request, or HTTP body data submitted with a POST request.

Other HTTP Request Methods

Those studying the underlying HTTP protocol and its various request methods come to understand that there are many HTTP request methods, including the often referenced PUT, PATCH (not used in Google's Apigee), and DELETE.

In PHP, there are no superglobals or input filter functions for getting HTTP request body data when POST is not used. What are disciples of Roy Fielding to do? ;-)

However, then you learn more ...

That being said, as you advance in your PHP programming knowledge and want to use JavaScript's XmlHttpRequest object (jQuery for some), you come to see the limitation of this scheme.

$_POST limits you to the use of two media types in the HTTP Content-Type header:

  1. application/x-www-form-urlencoded, and
  2. multipart/form-data

Thus, if you want to send data values to PHP on the server, and have it show up in the $_POST superglobal, then you must urlencode it on the client-side and send said data as key/value pairs--an inconvenient step for novices (especially when trying to figure out if different parts of the URL require different forms of urlencoding: normal, raw, etc..).

For all you jQuery users, the $.ajax() method is converting your JSON to URL encoded key/value pairs before transmitting them to the server. You can override this behavior by setting processData: false. Just read the $.ajax() documentation, and don't forget to send the correct media type in the Content-Type header.

php://input, but ...

Even if you use php://input instead of $_POST for your HTTP POST request body data, it will not work with an HTTP Content-Type of multipart/form-data This is the content type that you use on an HTML form when you want to allow file uploads!

<form enctype="multipart/form-data" accept-charset="utf-8" action="post">
    <input type="file" name="resume">
</form>

Therefore, in traditional PHP, to deal with a diversity of content types from an HTTP POST request, you will learn to use $_POST or filter_input_array(POST), $_FILES, and php://input. There is no way to just use one, universal input source for HTTP POST requests in PHP.

You cannot get files through $_POST, filter_input_array(POST), or php://input, and you cannot get JSON/XML/YAML in either filter_input_array(POST) or $_POST.

PHP Manual: php://input

php://input is a read-only stream that allows you to read raw data from the request body...php://input is not available with enctype="multipart/form-data".

PHP Frameworks to the rescue?

PHP frameworks like Codeigniter 4 and Laravel use a facade to provide a cleaner interface (IncomingRequest or Request objects) to the above. This is why professional PHP developers use frameworks instead of raw PHP.

Of course, if you like to program, you can devise your own facade object to provide what frameworks do. It is because I have taken time to investigate this issue that I am able to write this answer.

URL encoding? What the heck!!!???

Typically, if you are doing a normal, synchronous (when the entire page redraws) HTTP requests with an HTML form, the user-agent (web browser) will urlencode your form data for you. If you want to do an asynchronous HTTP requests using the XmlHttpRequest object, then you must fashion a urlencoded string and send it, if you want that data to show up in the $_POST superglobal.

How in touch are you with JavaScript? :-)

Converting from a JavaScript array or object to a urlencoded string bothers many developers (even with new APIs like Form Data). They would much rather just be able to send JSON, and it would be more efficient for the client code to do so.

Remember (wink, wink), the average web developer does not learn to use the XmlHttpRequest object directly, global functions, string functions, array functions, and regular expressions like you and I ;-). Urlencoding for them is a nightmare. ;-)

PHP, what gives?

PHP's lack of intuitive XML and JSON handling turns many people off. You would think it would be part of PHP by now (sigh).

So many media types (MIME types in the past)

XML, JSON, and YAML all have media types that can be put into an HTTP Content-Type header.

  • application/xml
  • applicaiton/json
  • application/yaml (although IANA has no official designation listed)

Look how many media-types (formerly, MIME types) are defined by IANA.

Look how many HTTP headers there are.

php://input or bust

Using the php://input stream allows you to circumvent the baby-sitting / hand holding level of abstraction that PHP has forced on the world. :-) With great power comes great responsibility!

Now, before you deal with data values streamed through php://input, you should / must do a few things.

  1. Determine if the correct HTTP method has been indicated (GET, POST, PUT, PATCH, DELETE, ...)
  2. Determine if the HTTP Content-Type header has been transmitted.
  3. Determine if the value for the Content-Type is the desired media type.
  4. Determine if the data sent is well formed XML / JSON / YAML / etc.
  5. If necessary, convert the data to a PHP datatype: array or object.
  6. If any of these basic checks or conversions fails, throw an exception!

What about the character encoding?

AH, HA! Yes, you might want the data stream being sent into your application to be UTF-8 encoded, but how can you know if it is or not?

Two critical problems.

  1. You do not know how much data is coming through php://input.
  2. You do not know for certain the current encoding of the data stream.

Are you going to attempt to handle stream data without knowing how much is there first? That is a terrible idea. You cannot rely exclusively on the HTTP Content-Length header for guidance on the size of streamed input because it can be spoofed.

You are going to need a:

  1. Stream size detection algorithm.
  2. Application defined stream size limits (Apache / Nginx / PHP limits may be too broad).

Are you going to attempt to convert stream data to UTF-8 without knowing the current encoding of the stream? How? The iconv stream filter (iconv stream filter example) seems to want a starting and ending encoding, like this.

'convert.iconv.ISO-8859-1/UTF-8'

Thus, if you are conscientious, you will need:

  1. Stream encoding detection algorithm.
  2. Dynamic / runtime stream filter definition algorithm (because you cannot know the starting encoding a priori).

(Update: 'convert.iconv.UTF-8/UTF-8' will force everything to UTF-8, but you still have to account for characters that the iconv library might not know how to translate. In other words, you have to some how define what action to take when a character cannot be translated: 1) Insert a dummy character, 2) Fail / throw and exception).

You cannot rely exclusively on the HTTP Content-Encoding header, as this might indicate something like compression as in the following. This is not what you want to make a decision off of in regards to iconv.

Content-Encoding: gzip

Therefore, the general steps might be ...

Part I: HTTP Request Related

  1. Determine if the correct HTTP method has been indicated (GET, POST, PUT, PATCH, DELETE, ...)
  2. Determine if the HTTP Content-Type header has been transmitted.
  3. Determine if the value for the Content-Type is the desired media type.

Part II: Stream Data Related

  1. Determine the size of the input stream (optional, but recommended).
  2. Determine the encoding of the input stream.
  3. If necessary, convert the input stream to the desired character encoding (UTF-8).
  4. If necessary, reverse any application level compression or encryption, and then repeat steps 4, 5, and 6.

Part III: Data Type Related

  1. Determine if the data sent is well formed XML / JSON / YMAL / etc.

(Remember, the data can still be a URL encoded string which you must then parse and URL decode).

  1. If necessary, convert the data to a PHP datatype: array or object.

Part IV: Data Value Related

  1. Filter input data.

  2. Validate input data.

Now do you see?

The $_POST superglobal, along with php.ini settings for limits on input, are simpler for the layman. However, dealing with character encoding is much more intuitive and efficient when using streams because there is no need to loop through superglobals (or arrays, generally) to check input values for the proper encoding.

Check if a class is derived from a generic class

@EnocNRoll - Ananda Gopal 's answer is interesting, but in case an instance is not instantiated beforehand or you want to check with a generic type definition, I'd suggest this method:

public static bool TypeIs(this Type x, Type d) {
    if(null==d) {
        return false;
    }

    for(var c = x; null!=c; c=c.BaseType) {
        var a = c.GetInterfaces();

        for(var i = a.Length; i-->=0;) {
            var t = i<0 ? c : a[i];

            if(t==d||t.IsGenericType&&t.GetGenericTypeDefinition()==d) {
                return true;
            }
        }
    }

    return false;
}

and use it like:

var b = typeof(char[]).TypeIs(typeof(IList<>)); // true

There are four conditional cases when both t(to be tested) and d are generic types and two cases are covered by t==d which are (1)neither t nor d is a generic definition or (2) both of them are generic definitions. The rest cases are one of them is a generic definition, only when d is already a generic definition we have the chance to say a t is a d but not vice versa.

It should work with arbitrary classes or interfaces you want to test, and returns what as if you test an instance of that type with the is operator.

node.js Error: connect ECONNREFUSED; response from server

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

How to trigger an event in input text after I stop typing/writing?

We can use useDebouncedCallback to perform this task in react.

import { useDebouncedCallback } from 'use-debounce'; - install npm packge for same if not installed

const [searchText, setSearchText] = useState('');

const onSearchTextChange = value => {
    setSearchText(value);
  };

//call search api
  const [debouncedOnSearch] = useDebouncedCallback(searchIssues, 500);
  useEffect(() => {
    debouncedOnSearch(searchText);
  }, [searchText, debouncedOnSearch]);

Get host domain from URL?

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

How to add and remove classes in Javascript without jQuery

Another approach to add the class to element using pure JavaScript

For adding class:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved");

Note: but not supported in IE <= 9 or Safari <=5.0

Is using 'var' to declare variables optional?

Var doesn't let you, the programmer, declare a variable because Javascript doesn't have variables. Javascript has objects. Var declares a name to an undefined object, explicitly. Assignment assigns a name as a handle to an object that has been given a value.

Using var tells the Javacript interpreter two things:

  1. not to use delegation reverse traversal look up value for the name, instead use this one
  2. not to delete the name

Omission of var tells the Javacript interpreter to use the first-found previous instance of an object with the same name.

Var as a keyword arose from a poor decision by the language designer much in the same way that Javascript as a name arose from a poor decision.

ps. Study the code examples above.

Find out the history of SQL queries

You can use this sql statement to get the history for any date:

SELECT * FROM V$SQL V where  to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60

grep a tab in UNIX

The answer is simpler. Write your grep and within the quote type the tab key, it works well at least in ksh

grep "  " *

How to `wget` a list of URLs in a text file?

Quick man wget gives me the following:

[..]

-i file

--input-file=file

Read URLs from a local or external file. If - is specified as file, URLs are read from the standard input. (Use ./- to read from a file literally named -.)

If this function is used, no URLs need be present on the command line. If there are URLs both on the command line and in an input file, those on the command lines will be the first ones to be retrieved. If --force-html is not specified, then file should consist of a series of URLs, one per line.

[..]

So: wget -i text_file.txt

Maven fails to find local artifact

Even I faced this issue and solved it with 2 ways:

1) In your IDE select project and clean all projects then install all the maven dependencies by right clicking on project -> go to maven and Update project dependencies select all projects at once to install the same. Once this is done run the particular project

2) Else What you can do is check in the pom.xml for the dependencies for which you are getting error and "mvn clean install" those dependent project first and the install maven dependencies of the current project in which you facing issue. By this the dependencies of the local project will be build and jars will be created.

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

Use PHP composer to clone git repo

That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require (which is always needed) with a matching version constraint.

In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.


For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:

  • The "repositories" field is specified in the root composer.json (it's a root-only field, repository definitions from required packages are ignored)
  • The repositories definition points to a valid VCS repo
  • If the type is "git" instead of "vcs" (as in your question), make sure it is in fact a git repo
  • You have a require for the package in question
  • The constraint in the require matches the versions provided by the VCS repo. You can use composer show <packagename> to find the available versions. In this case ~2.3 would be a good option.
  • The name in the require matches the name in the remote composer.json. In this case, it is gedmo/doctrine-extensions.

Here is a sample composer.json that installs the same package via a VCS repo:

{
    "repositories": [
        {
            "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
            "type": "git"
        }
    ],
    "require": {
        "gedmo/doctrine-extensions": "~2.3"
    }
}

The VCS repo docs explain all of this quite well.


If there is a git (or other VCS) repository with a composer.json available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.

Avoid package repos (see also the docs).

How to find the Target *.exe file of *.appref-ms

ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\.

From there, use the search function to find your application.

How to redirect to Index from another controller?

You can use the following code:

return RedirectToAction("Index", "Home");

See RedirectToAction

Getting a link to go to a specific section on another page

I tried the above answer - using page.html#ID_name it gave me a 404 page doesn't exist error.

Then instead of using .html, I simply put a slash / before the # and that worked fine. So my example on the sending page between the link tags looks like:

<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>

Just use / instead of .html.

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

how to fix java.lang.IndexOutOfBoundsException

You do not have any elements in the list so can't access the first element.

Inputting a default image in case the src attribute of an html <img> is not valid?

I recently had to build a fall back system which included any number of fallback images. Here's how I did it using a simple JavaScript function.

HTML

<img src="some_image.tiff"
    onerror="fallBackImg(this);"
    data-fallIndex="1"
    data-fallback1="some_image.png"
    data-fallback2="some_image.jpg">

JavaScript

function fallBackImg(elem){
    elem.onerror = null;
    let index = +elem.dataset.fallIndex;
    elem.src = elem.dataset[`fallback${index}`];
    index++;
    elem.dataset.fallbackindex = index;
}

I feel like it's a pretty lightweight way of handling many fallback images.

Dump Mongo Collection into JSON format

If you want to dump all collections, run this command:

mongodump -d {DB_NAME}   -o /tmp 

It will generate all collections data in json and bson extensions into /tmp/{DB_NAME} directory

How to make connection to Postgres via Node.js

We can also use postgresql-easy. It is built on node-postgres and sqlutil. Note: pg_connection.js & your_handler.js are in the same folder. db.js is in the config folder placed.

pg_connection.js

const PgConnection = require('postgresql-easy');
const dbConfig = require('./config/db');
const pg = new PgConnection(dbConfig);
module.exports = pg;

./config/db.js

module.exports =  {
  database: 'your db',
  host: 'your host',
  port: 'your port',
  user: 'your user',
  password: 'your pwd',
}

your_handler.js

  const pg_conctn = require('./pg_connection');

  pg_conctn.getAll('your table')
    .then(res => {
         doResponseHandlingstuff();
      })
    .catch(e => {
         doErrorHandlingStuff()     
      })

Dockerfile copy keep subdirectory structure

To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.

COPY ./files/. /files/

Reading all files in a directory, store them in objects, and send the object

async/await

const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)

try {
  async function emitData(directory) {
    let filenames = await pathnames
    var ob = {}
    const data = filenames.map(async function(filename, i) {
      if (filename.includes(".")) {
        var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
          encoding: "utf8",
        })
        ob[filename.replace(".js", "")] = await storedFile
        socket.emit("init", { data: ob })
      }
      return ob
    })
  }

  emitData(directory)
} catch (err) {
  console.log(err)
}

Who wants to try with generators?

How to select the first row for each group in MySQL?

From MySQL 5.7 documentation

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.

This means that @Jader Dias's solution wouldn't work everywhere.

Here is a solution that would work when ONLY_FULL_GROUP_BY is enabled:

SET @row := NULL;
SELECT
    SomeColumn,
    AnotherColumn
FROM (
    SELECT
        CASE @id <=> SomeColumn AND @row IS NOT NULL 
            WHEN TRUE THEN @row := @row+1 
            ELSE @row := 0 
        END AS rownum,
        @id := SomeColumn AS SomeColumn,
        AnotherColumn
    FROM
        SomeTable
    ORDER BY
        SomeColumn, -AnotherColumn DESC
) _values
WHERE rownum = 0
ORDER BY SomeColumn;

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

How does the @property decorator work in Python?

This point is been cleared by many people up there but here is a direct point which I was searching. This is what I feel is important to start with the @property decorator. eg:-

class UtilityMixin():
    @property
    def get_config(self):
        return "This is property"

The calling of function "get_config()" will work like this.

util = UtilityMixin()
print(util.get_config)

If you notice I have not used "()" brackets for calling the function. This is the basic thing which I was searching for the @property decorator. So that you can use your function just like a variable.

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

How to access html form input from asp.net code behind

Simplest way IMO is to include an ID and runat server tag on all your elements.

<div id="MYDIV" runat="server" />

Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().

Hex to ascii string conversion

strtol() is your friend here. The third parameter is the numerical base that you are converting.

Example:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main(int argc, char **argv)
{
    long int num  = 0;
    long int num2 =0;
    char * str. = "f00d";
    char * str2 = "0xf00d";

    num = strtol( str, 0, 16);  //converts hexadecimal string to long.
    num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.

    printf( "%ld\n", num);
    printf( "%ld\n", num);
}

Why is the use of alloca() not considered good practice?

Lots of interesting answers to this "old" question, even some relatively new answers, but I didn't find any that mention this....

When used properly and with care, consistent use of alloca() (perhaps application-wide) to handle small variable-length allocations (or C99 VLAs, where available) can lead to lower overall stack growth than an otherwise equivalent implementation using oversized local arrays of fixed length. So alloca() may be good for your stack if you use it carefully.

I found that quote in.... OK, I made that quote up. But really, think about it....

@j_random_hacker is very right in his comments under other answers: Avoiding the use of alloca() in favor of oversized local arrays does not make your program safer from stack overflows (unless your compiler is old enough to allow inlining of functions that use alloca() in which case you should upgrade, or unless you use alloca() inside loops, in which case you should... not use alloca() inside loops).

I've worked on desktop/server environments and embedded systems. A lot of embedded systems don't use a heap at all (they don't even link in support for it), for reasons that include the perception that dynamically allocated memory is evil due to the risks of memory leaks on an application that never ever reboots for years at a time, or the more reasonable justification that dynamic memory is dangerous because it can't be known for certain that an application will never fragment its heap to the point of false memory exhaustion. So embedded programmers are left with few alternatives.

alloca() (or VLAs) may be just the right tool for the job.

I've seen time & time again where a programmer makes a stack-allocated buffer "big enough to handle any possible case". In a deeply nested call tree, repeated use of that (anti-?)pattern leads to exaggerated stack use. (Imagine a call tree 20 levels deep, where at each level for different reasons, the function blindly over-allocates a buffer of 1024 bytes "just to be safe" when generally it will only use 16 or less of them, and only in very rare cases may use more.) An alternative is to use alloca() or VLAs and allocate only as much stack space as your function needs, to avoid unnecessarily burdening the stack. Hopefully when one function in the call tree needs a larger-than-normal allocation, others in the call tree are still using their normal small allocations, and the overall application stack usage is significantly less than if every function blindly over-allocated a local buffer.

But if you choose to use alloca()...

Based on other answers on this page, it seems that VLAs should be safe (they don't compound stack allocations if called from within a loop), but if you're using alloca(), be careful not to use it inside a loop, and make sure your function can't be inlined if there's any chance it might be called within another function's loop.

Dots in URL causes 404 with ASP.NET mvc and IIS

Add URL Rewrite rule to Web.config archive. You need to have the URL Rewrite module already installed in IIS. Use the following rewrite rule as inspiration for your own.

<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Add trailing slash for some URLs" stopProcessing="true">
        <match url="^(.*(\.).+[^\/])$" />
          <conditions>
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Redirect" url="{R:1}/" />
      </rule>
    </rules>
    </rewrite>
</system.webServer>

</configuration> 

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

What does set -e mean in a bash script?

From help set :

  -e  Exit immediately if a command exits with a non-zero status.

But it's considered bad practice by some (bash FAQ and irc freenode #bash FAQ authors). It's recommended to use:

trap 'do_something' ERR

to run do_something function when errors occur.

See http://mywiki.wooledge.org/BashFAQ/105

Android : How to set onClick event for Button in List item of ListView

Class for ArrayList & ArrayAdapter

class RequestClass {
    private String Id;
    private String BookingTime;
    private String UserName;
    private String Rating;

    public RequestClass(String Id,String bookingTime,String userName,String rating){
        this.Id=Id;
        this.BookingTime=bookingTime;
        this.UserName=userName;
        this.Rating=rating;
    }

    public String getId(){return Id; }
    public String getBookingTime(){return BookingTime; }
    public String getUserName(){return UserName; }
    public String getRating(){return Rating; }


}

Main Activity:

 ArrayList<RequestClass> _requestList;
    _requestList=new ArrayList<>();
                    try {
                        JSONObject jsonobject = new JSONObject(result);
                        JSONArray JO = jsonobject.getJSONArray("Record");
                        JSONObject object;
                        for (int i = 0; i < JO.length(); i++) {
                            object = (JSONObject) JO.get(i);

                            _requestList.add(new RequestClass( object.optString("playerID"),object.optString("booking_time"),
                                    object.optString("username"),object.optString("rate") ));
                        }//end of for loop

                        RequestCustomAdapter adapter = new RequestCustomAdapter(context, R.layout.requestlayout, _requestList);
                        listView.setAdapter(adapter);

Custom Adapter Class

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by wajid on 1/12/2018.
 */

class RequestCustomAdapter extends ArrayAdapter<RequestClass> {
    Context mContext;
    int mResource;
    public RequestCustomAdapter(Context context, int resource,ArrayList<RequestClass> objects) {
        super(context, resource, objects);
        mContext=context;
        mResource=resource;
    }
    public static class ViewHolder{
        RelativeLayout _layout;
        TextView _bookingTime;
        TextView _ratingTextView;
        TextView _userNameTextView;
        Button acceptButton;
        Button _rejectButton;
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent){
       final ViewHolder holder;
        if(convertView == null) {
            LayoutInflater inflater=LayoutInflater.from(mContext);
            convertView=inflater.inflate(mResource,parent,false);
            holder=new ViewHolder();
            holder._layout = convertView.findViewById(R.id.requestLayout);
            holder._bookingTime = convertView.findViewById(R.id.bookingTime);
            holder._userNameTextView = convertView.findViewById(R.id.userName);
            holder._ratingTextView = convertView.findViewById(R.id.rating);
            holder.acceptButton = convertView.findViewById(R.id.AcceptRequestButton);
            holder._rejectButton = convertView.findViewById(R.id.RejectRequestButton);

            holder._rejectButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(mContext, holder._rejectButton.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            holder.acceptButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(mContext, holder.acceptButton.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });


            convertView.setTag(holder);

        }
        else{
            holder=(ViewHolder)convertView.getTag();

        }
        holder._bookingTime.setText(getItem(position).getBookingTime());
        if(!getItem(position).getUserName().equals("")){

            holder._userNameTextView.setText(getItem(position).getUserName());
        }
        if(!getItem(position).getRating().equals("")){
            holder._ratingTextView.setText(getItem(position).getRating());
        }
        return  convertView;
    }

}

ListView in Main xml:

<ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:id="@+id/AllRequestListView">

    </ListView>

Resource Layout for list view requestlayout.xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/requestLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bookingTime"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bookingTime"
        android:text="Temp Name"
        android:id="@+id/userName"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/userName"
        android:text="No Rating"
        android:id="@+id/rating"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/AcceptRequestButton"
        android:focusable="false"
        android:layout_below="@+id/rating"
        android:text="Accept"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/RejectRequestButton"
        android:layout_below="@+id/AcceptRequestButton"
        android:focusable="false"
        android:text="Reject"
        />

</RelativeLayout>

annotation to make a private method public only for test classes

We recently released a library that helps a lot to access private fields, methods and inner classes through reflection : BoundBox

For a class like

public class Outer {
    private static class Inner {
        private int foo() {return 2;}
    }
}

It provides a syntax like :

Outer outer = new Outer();
Object inner = BoundBoxOfOuter.boundBox_new_Inner();
new BoundBoxOfOuter.BoundBoxOfInner(inner).foo();

The only thing you have to do to create the BoundBox class is to write @BoundBox(boundClass=Outer.class) and the BoundBoxOfOuter class will be instantly generated.

Error "The connection to adb is down, and a severe error has occurred."

Devices window ? toolbar more menu ? Reset adb

For displaying the devices window: Menu Window ? Show view ? Other ? Android ? Devices

How to Batch Rename Files in a macOS Terminal?

you can install rename command by using brew. just do brew install rename and use it.

Axios having CORS issue

May help to someone:

I'm sending data from react application to golang server.

Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"). Error has fixed.

React form submit function:

async handleSubmit(e) {
    e.preventDefault();

    const headers = {
        'Content-Type': 'text/plain'
    };

    await axios.post(
        'http://localhost:3001/login',
        {
            user_name: this.state.user_name,
            password: this.state.password,
        },
        {headers}
        ).then(response => {
            console.log("Success ========>", response);
        })
        .catch(error => {
            console.log("Error ========>", error);
        }
    )
}

Go server got Router,

func main()  {
    router := mux.NewRouter()

    router.HandleFunc("/login", Login.Login).Methods("POST")

    log.Fatal(http.ListenAndServe(":3001", router))
}

Login.go,

func Login(w http.ResponseWriter, r *http.Request)  {

    var user = Models.User{}
    data, err := ioutil.ReadAll(r.Body)

    if err == nil {
        err := json.Unmarshal(data, &user)
        if err == nil {
            user = Postgres.GetUser(user.UserName, user.Password)
            w.Header().Set("Access-Control-Allow-Origin", "*")
            json.NewEncoder(w).Encode(user)
        }
    }
}

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I find it important to note that python 3 defines the opening modes differently to the answers here that were correct for Python 2.

The Pyhton 3 opening modes are:

'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
----
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (for backwards compatibility; should not be used in new code)

The modes r, w, x, a are combined with the mode modifiers b or t. + is optionally added, U should be avoided.

As I found out the hard way, it is a good idea to always specify t when opening a file in text mode since r is an alias for rt in the standard open() function but an alias for rb in the open() functions of all compression modules (when e.g. reading a *.bz2 file).

Thus the modes for opening a file should be:

rt / wt / xt / at for reading / writing / creating / appending to a file in text mode and

rb / wb / xb / ab for reading / writing / creating / appending to a file in binary mode.

Use + as before.

Is there any way to have a fieldset width only be as wide as the controls in them?

Going further of Mihai solution, cross-browser left aligned:

<TABLE>
  <TR>
    <TD>
      <FORM>
        <FIELDSET>
          ...
        </FIELDSET>
      </FORM>
    </TD>
  </TR>
</TABLE>

Cross-browser right aligned:

<TABLE>
  <TR>
    <TD WIDTH=100%></TD>
    <TD>
      <FORM>
        <FIELDSET>
          ...
        </FIELDSET>
      </FORM>
    </TD>
  </TR>
</TABLE>

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Getting unique items from a list

Apart from the Distinct extension method of LINQ, you could use a HashSet<T> object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode) rather than an IEqualityComparer).

In fact, if it's appropiate for your situation, I would just use a HashSet for storing the items in the first place.

Python: Generate random number between x and y which is a multiple of 5

>>> import random
>>> random.randrange(5,60,5)

should work in any Python >= 2.

Multi value Dictionary

I know this is an old thread, but - since it's not been mentioned this works

  Dictionary<string, object> LookUp = new Dictionary<string, object>();
  LookUp.Add("bob", new { age = "23", height = "2.1m", weight = "110kg"});
  LookUp.Add("jasper", new { age = "33", height = "1.75m", weight = "90kg"});
  foreach(KeyValuePair<string, object> entry in LookUp )
  {
      object person = entry.Value;
      Console.WriteLine("Person name:" + entry.Key + " Age: "  + person.age);          
  }

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Hey I was following the tutorial on tutorialpoint.com. Add after you complete Step 2 - Install Apache Common Logging API: You must import external jar libraries to the project from the files downloaded at this step. For me the file name was "commons-logging-1.1.1".

Letsencrypt add domain to existing certificate

Apache on Ubuntu, using the Apache plugin:

sudo certbot certonly --cert-name example.com -d m.example.com,www.m.example.com

The above command is vividly explained in the Certbot user guide on changing a certificate's domain names. Note that the command for changing a certificate's domain names applies to adding new domain names as well.

Edit

If running the above command gives you the error message

Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.

follow these instructions from the Let's Encrypt Community

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

Converting an OpenCV Image to Black and White

Simply you can write the following code snippet to convert an OpenCV image into a grey scale image

import cv2
image = cv2.imread('image.jpg',0)
cv2.imshow('grey scale image',image)

Observe that the image.jpg and the code must be saved in same folder.

Note that:

  • ('image.jpg') gives a RGB image
  • ('image.jpg',0) gives Grey Scale Image.

What is the difference between `sorted(list)` vs `list.sort()`?

What is the difference between sorted(list) vs list.sort()?

  • list.sort mutates the list in-place & returns None
  • sorted takes any iterable & returns a new list, sorted.

sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

  • Use list.sort when you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sorted when you want to retain the original sort order or when you wish to create a new list that only your local code owns.

Can a list's original positions be retrieved after list.sort()?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

"And which is faster? And how much faster?"

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

Python 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.

Poke ran his own code as well, here's the code:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.

To trigger an event after ng-repeat has rendered try this directive:

var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {
                scope.$emit('ngRepeatFinished');
            });
        }
    }
}
});

Complete example in angular: http://jsfiddle.net/ADukg/6880/

I got the directive from here: Use AngularJS just for routing purposes

How to quit a java app from within the program

The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.

How to convert string representation of list to a list?

>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval:

With ast.literal_eval you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and None.

C++ static virtual members?

No, this is not possible, because static member functions lack a this pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.

virtual functions in a class needs the this pointer, and is very coupled to the class, hence they can't be static.

jQuery remove selected option from this

$('#some_select_box option:selected').remove();

Using unset vs. setting a variable to empty

Based on the comments above, here is a simple test:

isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset()   { [ -z "$(isunset "$1")" ] && echo 1; }

Example:

$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo=     ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar  ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set

How to configure postgresql for the first time?

You probably need to update your pg_hba.conf file. This file controls what users can log in from what IP addresses. I think that the postgres user is pretty locked-down by default.

How to pretty print nested dictionaries?

You can use print-dict

from print_dict import pd

dict1 = {
    'key': 'value'
} 

pd(dict1)

Output:

{
    'key': 'value'
}

Output of this Python code:

{
    'one': 'value-one',
    'two': 'value-two',
    'three': 'value-three',
    'four': {
        '1': '1',
        '2': '2',
        '3': [1, 2, 3, 4, 5],
        '4': {
            'method': <function custom_method at 0x7ff6ecd03e18>,
            'tuple': (1, 2),
            'unicode': '?',
            'ten': 'value-ten',
            'eleven': 'value-eleven',
            '3': [1, 2, 3, 4]
        }
    },
    'object1': <__main__.Object1 object at 0x7ff6ecc588d0>,
    'object2': <Object2 info>,
    'class': <class '__main__.Object1'>
}

Install:

$ pip install print-dict

Disclosure: I'm the author of print-dict

bash: mkvirtualenv: command not found

Use this procedure to create virtual env in ubuntu

Step 1

Install pip

   sudo apt-get install python-pip

step 2

Install virtualenv

   sudo pip install virtualenv

step 3

Create a dir to store your virtualenvs (I use ~/.virtualenvs)

   mkdir ~/.virtualenvs

or use this command to install specific version of python in env

virtualenv -p /usr/bin/python3.6 venv

step 4

   sudo pip install virtualenvwrapper

step 5

   sudo nano ~/.bashrc

step 6

Add this two line code at the end of the bashrc file

  export WORKON_HOME=~/.virtualenvs
  source /usr/local/bin/virtualenvwrapper.sh

step 7

Open new terminal (recommended)

step 8

Create a new virtualenv

  mkvirtualenv myawesomeproject

step 9

To load or switch between virtualenvs, use the workon command:

  workon myawesomeproject

step 10

To exit your new virtualenv, use

 deactivate

and make sure using pip vs pip3

OR follow the steps below to install virtual environment using python3

Install env

python3 -m venv my-project-env

and activate your virtual environment using the following command:

source my-project-env/bin/activate

or if you want particular python version

virtualenv --python=python3.7.5 myenv

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

You have to add

<script>jQuery.noConflict();</script>

after

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Android List View Drag and Drop sort

Am adding this answer for the purpose of those who google about this..

There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this

You can find it here also the sample code is available here.

What this code basically does is that it creates a dynamic listview by the extension of listview that supports cell dragging and swapping. So that you can use the DynamicListView instead of your basic ListView and that's it you have implemented a ListView with Drag and Drop.

Gradle project refresh failed after Android Studio update

Although this has been answered a long time ago, I had the same problem with an app after updating to

Gradle 2.1.2

The solution I found (on top of the one given by @WarrenFaith was to:

File -> Synchronize

This solved all the errors generated by the Gradle update.

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

How to center a checkbox in a table cell?

How about this... http://jsfiddle.net/gSaPb/


Check out my example on jsFiddle: http://jsfiddle.net/QzPGu. Code snippet:

_x000D_
_x000D_
td {
  text-align: center;
  /* center checkbox horizontally */
  vertical-align: middle;
  /* center checkbox vertically */
}

table {
  border: 1px solid;
  width: 200px;
}

tr {
  height: 80px;
}
_x000D_
<table>
  <tr>
    <td>
      <input type="checkbox" name="myTextEditBox" value="checked" /> checkbox
    </td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

stdcall and cdecl

I want to improve on @adf88's answer. I feel that pseudocode for the STDCALL does not reflect the way of how it happens in reality. 'a', 'b', and 'c' aren't popped from the stack in the function body. Instead they are popped by the ret instruction (ret 12 would be used in this case) that in one swoop jumps back to the caller and at the same time pops 'a', 'b', and 'c' from the stack.

Here is my version corrected according to my understanding:

STDCALL:

/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable

/* 2. STDCALL 'Function' body in pseaudo-assembler */ copy 'a' (from stack) to register A copy 'b' (from stack) to register B add A and B, store result in A copy 'c' (from stack) to register B add A and B, store result in A jump back to caller code and at the same time pop 'a', 'b' and 'c' off the stack (a, b and c are removed from the stack in this step, result in register A)

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

This solution doesn't require you to put a scrollable class on all your scrollable divs so is more general. Scrolling is allowed on all elements which are, or are children of, INPUT elements contenteditables and overflow scroll or autos.

I use a custom selector and I also cache the result of the check in the element to improve performance. No need to check the same element every time. This may have a few issues as only just written but thought I'd share.

$.expr[':'].scrollable = function(obj) {
    var $el = $(obj);
    var tagName = $el.prop("tagName");
    return (tagName !== 'BODY' && tagName !== 'HTML') && (tagName === 'INPUT' || $el.is("[contentEditable='true']") || $el.css("overflow").match(/auto|scroll/));
};
function preventBodyScroll() {
    function isScrollAllowed($target) {
        if ($target.data("isScrollAllowed") !== undefined) {
            return $target.data("isScrollAllowed");
        }
        var scrollAllowed = $target.closest(":scrollable").length > 0;
        $target.data("isScrollAllowed",scrollAllowed);
        return scrollAllowed;
    }
    $('body').bind('touchmove', function (ev) {
        if (!isScrollAllowed($(ev.target))) {
            ev.preventDefault();
        }
    });
}

How to generate Javadoc HTML files in Eclipse?

To quickly add a Javadoc use following shortcut:

Windows: alt + shift + J

Mac: ? + Alt + J

Depending on selected context, a Javadoc will be printed. To create Javadoc written by OP, select corresponding method and hit the shotcut keys.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

End-line characters from lines read from text file, using Python

Simple. Use splitlines()

L = open("myFile.txt", "r").read().splitlines();
for line in L: 
    process(line) # this 'line' will not have '\n' character at the end

Clear and reset form input fields

Very easy:

_x000D_
_x000D_
handleSubmit(e){_x000D_
    e.preventDefault();_x000D_
    e.target.reset();_x000D_
}
_x000D_
<form onSubmit={this.handleSubmit.bind(this)}>_x000D_
  ..._x000D_
</form>
_x000D_
_x000D_
_x000D_

Good luck :)

How can I trigger a Bootstrap modal programmatically?

If you are looking for a programmatical modal creation, you might love this:

http://nakupanda.github.io/bootstrap3-dialog/

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.

Global keyboard capture in C# application

If a global hotkey would suffice, then RegisterHotKey would do the trick

How many parameters are too many?

I would base my answer on how often the function is called.

If it is an init function that is only ever called once then let it take 10 parms or more, who cares.

If it is called a bunch of times per frame then I tend to make a structure and just pass a pointer to it since that tends to be faster ( assuming that you are not rebuilding the struct every time as well ).

What's the idiomatic syntax for prepending to a short python list?

If you can go the functional way, the following is pretty clear

new_list = [x] + your_list

Of course you haven't inserted x into your_list, rather you have created a new list with x preprended to it.

How do I use InputFilter to limit characters in an EditText in Android?

To avoid Special Characters in input type

public static InputFilter filter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String blockCharacterSet = "~#^|$%*!@/()-'\":;,?{}=!$^';,?×÷<>{}€£¥?%~`¤??_|«»¡¿°•???¦???????????????:-);-):-D:-(:'(:O 1234567890";
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};

You can set filter to your edit text like below

edtText.setFilters(new InputFilter[] { filter });

What is the default boolean value in C#?

It can be treated as defensive programming approach from the compiler - the variables must be assigned before it can be used.

What in the world are Spring beans?

Well you understood it partially. You have to tailor the beans according to your need and inform Spring container to manage it when required, by using a methodology populalrly known as IoC (Inversion of Control) coined by Martin Fowler, also known as Dependency Injection (DI).

You wire the beans in a way, so that you do not have to take care of the instantiating or evaluate any dependency on the bean. This is popularly known as Hollywood Principle.

Google is the best tool to explore more on this in addition to the links you would get flooded with here in this question. :)

LINQ Aggregate algorithm explained

A picture is worth a thousand words

Reminder:
Func<X, Y, R> is a function with two inputs of type X and Y, that returns a result of type R.

Enumerable.Aggregate has three overloads:


Overload 1:

A Aggregate<A>(IEnumerable<A> a, Func<A, A, A> f)

Aggregate1

Example:

new[]{1,2,3,4}.Aggregate((x, y) => x + y);  // 10


This overload is simple, but it has the following limitations:

  • the sequence must contain at least one element,
    otherwise the function will throw an InvalidOperationException.
  • elements and result must be of the same type.



Overload 2:

B Aggregate<A, B>(IEnumerable<A> a, B bIn, Func<B, A, B> f)

Aggregate2

Example:

var hayStack = new[] {"straw", "needle", "straw", "straw", "needle"};
var nNeedles = hayStack.Aggregate(0, (n, e) => e == "needle" ? n+1 : n);  // 2


This overload is more general:

  • a seed value must be provided (bIn).
  • the collection can be empty,
    in this case, the function will yield the seed value as result.
  • elements and result can have different types.



Overload 3:

C Aggregate<A,B,C>(IEnumerable<A> a, B bIn, Func<B,A,B> f, Func<B,C> f2)


The third overload is not very useful IMO.
The same can be written more succinctly by using overload 2 followed by a function that transforms its result.


The illustrations are adapted from this excellent blogpost.

Java: Enum parameter in method

I like this a lot better. reduces the if/switch, just do.

private enum Alignment { LEFT, RIGHT;

void process() {
//Process it...
} 
};    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  align.process();
}

of course, it can be:

String process(...) {
//Process it...
} 

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

mailto using javascript

I don't know if it helps, but using jQuery, to hide an email address, I did :

    $(function() {
        // planque l'adresse mail
        var mailSplitted 
            = ['mai', 'to:mye', 'mail@', 'addre', 'ss.fr'];

        var link = mailSplitted.join('');
        link = '<a href="' + link + '"</a>';
        $('mytag').wrap(link);
    });

I hope it helps.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

First of all lets be clear about what a WebElement is.

A WebElement is a reference to an element in the DOM.

A StaleElementException is thrown when the element you were interacting is destroyed and then recreated. Most complex web pages these days will move things about on the fly as the user interacts with it and this requires elements in the DOM to be destroyed and recreated.

When this happens the reference to the element in the DOM that you previously had becomes stale and you are no longer able to use this reference to interact with the element in the DOM. When this happens you will need to refresh your reference, or in real world terms find the element again.

kubectl apply vs kubectl create?

We love Kubernetes is because once we give them what we want it goes on to figure out how to achieve it without our any involvement.

"create" is like playing GOD by taking things into our own hands. It is good for local debugging when you only want to work with the POD and not care abt Deployment/Replication Controller.

"apply" is playing by the rules. "apply" is like a master tool that helps you create and modify and requires nothing from you to manage the pods.

Can a local variable's memory be accessed outside its scope?

It can, because a is a variable allocated temporarily for the lifetime of its scope (foo function). After you return from foo the memory is free and can be overwritten.

What you're doing is described as undefined behavior. The result cannot be predicted.

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Explicitly specifying the max_iter resolves the warning as the default max_iter is 100. [For Logistic Regression].

 logreg = LogisticRegression(max_iter=1000)

intellij incorrectly saying no beans of type found for autowired repository

in my situation my class folder was in wrong address so check if your class is in correct package.

How to loop through a plain JavaScript object with the objects as members?

The solution that work for me is the following

_private.convertParams=function(params){
    var params= [];
    Object.keys(values).forEach(function(key) {
        params.push({"id":key,"option":"Igual","value":params[key].id})
    });
    return params;
}

Populating a data frame in R in a loop

You could do it like this:

 iterations = 10
 variables = 2

 output <- matrix(ncol=variables, nrow=iterations)

 for(i in 1:iterations){
  output[i,] <- runif(2)

 }

 output

and then turn it into a data.frame

 output <- data.frame(output)
 class(output)

what this does:

  1. create a matrix with rows and columns according to the expected growth
  2. insert 2 random numbers into the matrix
  3. convert this into a dataframe after the loop has finished.

Can we call the function written in one JavaScript in another JS file?

You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');

CSV file written with Python has blank lines between each row

Note: It seems this is not the preferred solution because of how the extra line was being added on a Windows system. As stated in the python document:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Windows is one such platform where that makes a difference. While changing the line terminator as I described below may have fixed the problem, the problem could be avoided altogether by opening the file in binary mode. One might say this solution is more "elegent". "Fiddling" with the line terminator would have likely resulted in unportable code between systems in this case, where opening a file in binary mode on a unix system results in no effect. ie. it results in cross system compatible code.

From Python Docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Original:

As part of optional paramaters for the csv.writer if you are getting extra blank lines you may have to change the lineterminator (info here). Example below adapated from the python page csv docs. Change it from '\n' to whatever it should be. As this is just a stab in the dark at the problem this may or may not work, but it's my best guess.

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), lineterminator='\n')
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

Difference between HashMap, LinkedHashMap and TreeMap

  • HashMap:

    • Order not maintains
    • Faster than LinkedHashMap
    • Used for store heap of objects
  • LinkedHashMap:

    • LinkedHashMap insertion order will be maintained
    • Slower than HashMap and faster than TreeMap
    • If you want to maintain an insertion order use this.
  • TreeMap:

    • TreeMap is a tree-based mapping
    • TreeMap will follow the natural ordering of key
    • Slower than HashMap and LinkedHashMap
    • Use TreeMap when you need to maintain natural(default) ordering

Simple dynamic breadcrumb

hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.

//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);

I dont know if that is the most elegant way, but it now works for me.

I add that code before this one on line 13 or something

// Find out the index for the last value in our path array
$last = end(array_keys($path));

How can you use php in a javascript function

Try this may work..

<html>
   <?php $num = 1; ?>
   <div id="Count"><?php echo $num; ?></div>
   <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
   <br>
   <script>
   function Inc() {
       i = parseInt(document.getElementById('Count').innerHTML);
       document.getElementById('Count').innerHTML = i+1;
   }
   </script>
</html>

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

according to @jreback here https://github.com/conda/conda/issues/1166

conda config --set ssl_verify false 

will turn off this feature, e.g. here

How to capture and save an image using custom camera in Android?

 showbookimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // create intent with ACTION_IMAGE_CAPTURE action
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                /**
 Here REQUEST_IMAGE is the unique integer value you can pass it any integer
 **/
                // start camera activity
                startActivityForResult(intent, TAKE_PICTURE);
            }

            }

        );

then u can now give the image a file name as follows and then convert it into bitmap and later on to file

 private void createImageFile(Bitmap bitmap) throws IOException {
        // Create an image file name
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        FileOutputStream stream = new FileOutputStream(image);
        stream.write(bytes.toByteArray());
        stream.close();
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        fileUri = image.getAbsolutePath();
        Picasso.with(getActivity()).load(image).into(showbookimage);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
            // get bundle
            Bundle extras = intent.getExtras();
            // get
            bitMap = (Bitmap) extras.get("data");
//            showbookimage.setImageBitmap(bitMap);
            try {
                createImageFile(bitMap);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

use picasso for images to display rather fast

How to detect when cancel is clicked on file input?

This is hacky at best, but here is a working example of my solution to detect whether or not a user has uploaded a file, and only allowing them to proceed if they have uploaded a file.

Basically hide the Continue, Save, Proceed or whatever your button is. Then in the JavaScript you grab the file name. If the file name does not have a value, then do not show the Continue button. If it does have a value, then show the button. This also works if they at first upload a file and then they try to upload a different file and click cancel.

Here is the code.

HTML:

<div class="container">
<div class="row">
    <input class="file-input" type="file" accept="image/*" name="fileUpload" id="fileUpload" capture="camera">
    <label for="fileUpload" id="file-upload-btn">Capture or Upload Photo</label>
</div>
<div class="row padding-top-two-em">
    <input class="btn btn-success hidden" id="accept-btn" type="submit" value="Accept & Continue"/>
    <button class="btn btn-danger">Back</button>
</div></div>

JavaScript:

$('#fileUpload').change(function () {
    var fileName = $('#fileUpload').val();
    if (fileName != "") {
        $('#file-upload-btn').html(fileName);
        $('#accept-btn').removeClass('hidden').addClass('show');
    } else {
        $('#file-upload-btn').html("Upload File");
        $('#accept-btn').addClass('hidden');
    }
});

CSS:

.file-input {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1; 
}

.file-input + label {
    font-size: 1.25em;
    font-weight: normal;
    color: white;
    background-color: blue;
    display: inline-block;
    padding: 5px;
}

.file-input:focus + label,
.file-input + label:hover {
    background-color: red;
}

.file-input + label {
    cursor: pointer;
}

.file-input + label * {
    pointer-events: none;
}

For the CSS a lot of this is to make the website and button accessible for everyone. Style your button to whatever you like.

How to convert DataSet to DataTable

A DataSet already contains DataTables. You can just use:

DataTable firstTable = dataSet.Tables[0];

or by name:

DataTable customerTable = dataSet.Tables["Customer"];

Note that you should have using statements for your SQL code, to ensure the connection is disposed properly:

using (SqlConnection conn = ...)
{
    // Code here...
}

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

Anyone getting this error with Azure build pipelines, try the below step to change environment variable of build agent

Add an Azure build pipeline task -> Azure powershell script:Inlinescript before Compile with below settings

- task: AzurePowerShell@3
  displayName: 'Azure PowerShell script: InlineScript'
  inputs:
    azureSubscription: 'NYCSCA Azure Dev/Test (ea91a274-55c6-461c-a11d-758ef02c2698)'
    ScriptType: InlineScript
    Inline: '[Environment]::SetEnvironmentVariable("NODE_OPTIONS", "--max_old_space_size=16384", "Machine")'
    FailOnStandardError: true
    azurePowerShellVersion: LatestVersion

custom facebook share button

You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)

window.fbAsyncInit = function(){
FB.init({
    appId: 'xxxxx', status: true, cookie: true, xfbml: true }); 
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if(d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; 
    js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}

So when you want to share something

<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>

And finally JS to handle click:

$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));

return false;
});

What happened to console.log in IE8?

It works in IE8. Open IE8's Developer Tools by hitting F12.

>>console.log('test')
LOG: test

Rollback one specific migration in Laravel

If you look in your migrations table, then you’ll see each migration has a batch number. So when you roll back, it rolls back each migration that was part of the last batch.

If you only want to roll back the very last migration, then just increment the batch number by one. Then next time you run the rollback command, it’ll only roll back that one migration as it’s in a “batch” of its own.

Alternatively, from Laravel 5.3 onwards, you can just run:

php artisan migrate:rollback --step=1

That will rollback the last migration, no matter what its batch number is.

What is a mixin, and why are they useful?

I think there have been some good explanations here but I wanted to provide another perspective.

In Scala, you can do mixins as has been described here but what is very interesting is that the mixins are actually 'fused' together to create a new kind of class to inherit from. In essence, you do not inherit from multiple classes/mixins, but rather, generate a new kind of class with all the properties of the mixin to inherit from. This makes sense since Scala is based on the JVM where multiple-inheritance is not currently supported (as of Java 8). This mixin class type, by the way, is a special type called a Trait in Scala.

It's hinted at in the way a class is defined: class NewClass extends FirstMixin with SecondMixin with ThirdMixin ...

I'm not sure if the CPython interpreter does the same (mixin class-composition) but I wouldn't be surprised. Also, coming from a C++ background, I would not call an ABC or 'interface' equivalent to a mixin -- it's a similar concept but divergent in use and implementation.

How to refresh Gridview after pressed a button in asp.net

Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :

 gvTypes.EditIndex = -1;
 gvTypes.DataBind();

gvTypes is my GridView ID.

How to redirect verbose garbage collection output to a file?

To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

A brief excerpt:

The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

Case-Insensitive List Search

Based on Lance Larsen answer - here's an extension method with the recommended string.Compare instead of string.Equals

It is highly recommended that you use an overload of String.Compare that takes a StringComparison parameter. Not only do these overloads allow you to define the exact comparison behavior you intended, using them will also make your code more readable for other developers. [Josh Free @ BCL Team Blog]

public static bool Contains(this List<string> source, string toCheck, StringComparison comp)
{
    return
       source != null &&
       !string.IsNullOrEmpty(toCheck) &&
       source.Any(x => string.Compare(x, toCheck, comp) == 0);
}

How can I get the current user directory?

$env:USERPROFILE = "C:\\Documents and Settings\\[USER]\\"

Create or write/append in text file

You can do it the OO way, just an alternative and flexible:

class Logger {

    private
        $file,
        $timestamp;

    public function __construct($filename) {
        $this->file = $filename;
    }

    public function setTimestamp($format) {
        $this->timestamp = date($format)." &raquo; ";
    }

    public function putLog($insert) {
        if (isset($this->timestamp)) {
            file_put_contents($this->file, $this->timestamp.$insert."<br>", FILE_APPEND);
        } else {
            trigger_error("Timestamp not set", E_USER_ERROR);
        }
    }

    public function getLog() {
        $content = @file_get_contents($this->file);
        return $content;
    }

}

Then use it like this .. let's say you have user_name stored in a session (semi pseudo code):

$log = new Logger("log.txt");
$log->setTimestamp("D M d 'y h.i A");

if (user logs in) {
    $log->putLog("Successful Login: ".$_SESSION["user_name"]);
}
if (user logs out) {
    $log->putLog("Logout: ".$_SESSION["user_name"]);
}

Check your log with this:

$log->getLog();

Result is like:

Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe


github.com/thielicious/Logger

Check if a value exists in pandas dataframe index

with DataFrame: df_data

>>> df_data
  id   name  value
0  a  ampha      1
1  b   beta      2
2  c     ce      3

I tried:

>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True

but:

>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False

So fun :D

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How to stretch div height to fill parent div - CSS

Suppose you have

<body>
  <div id="root" />
</body>

With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}

Spring Boot application can't resolve the org.springframework.boot package

I have this problem when using STS. After edited something, I see that, some workspaces when create a project will happen this problem, and others will not. So I just create a new project in workspaces will not happen.

C++ - how to find the length of an integer

Not necessarily the most efficient, but one of the shortest and most readable using C++:

std::to_string(num).length()

Select multiple columns by labels in pandas

How do I select multiple columns by labels in pandas?

Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:

loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]

          A         B         C         E         G         H         I
0 -1.666330  0.321260 -1.768185 -0.034774  0.023294  0.533451 -0.241990
1  0.911498  3.408758  0.419618 -0.462590  0.739092  1.103940  0.116119
2  1.243001 -0.867370  1.058194  0.314196  0.887469  0.471137 -1.361059
3 -0.525165  0.676371  0.325831 -1.152202  0.606079  1.002880  2.032663
4  0.706609 -0.424726  0.308808  1.994626  0.626522 -0.033057  1.725315
5  0.879802 -1.961398  0.131694 -0.931951 -0.242822 -1.056038  0.550346
6  0.199072  0.969283  0.347008 -2.611489  0.282920 -0.334618  0.243583
7  1.234059  1.000687  0.863572  0.412544  0.569687 -0.684413 -0.357968
8 -0.299185  0.566009 -0.859453 -0.564557 -0.562524  0.233489 -0.039145
9  0.937637 -2.171174 -1.940916 -1.553634  0.619965 -0.664284 -0.151388

Note that the +1 is added because when using iloc the rightmost index is exclusive.


Comments on Other Solutions

  • filter is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.

  • The "location-based" solution with loc is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.

  • Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

How to find the kth largest element in an unsorted array of length n in O(n)?

You can do it in O(n + kn) = O(n) (for constant k) for time and O(k) for space, by keeping track of the k largest elements you've seen.

For each element in the array you can scan the list of k largest and replace the smallest element with the new one if it is bigger.

Warren's priority heap solution is neater though.

java.util.NoSuchElementException: No line found

with Scanner you need to check if there is a next line with hasNextLine()

so the loop becomes

while(sc.hasNextLine()){
    str=sc.nextLine();
    //...
}

it's readers that return null on EOF

ofcourse in this piece of code this is dependent on whether the input is properly formatted

How to write UTF-8 in a CSV file

It's very simple for Python 3.x (docs).

import csv

with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')
    writer.writerow('my_utf8_string')

For Python 2.x, look here.

Force update of an Android app when a new version is available

I used a simple approach to make this work:

  1. Create Firebase database
  2. Add your latest version
  3. If the version is different than the installed version, show the popup of installing the update. It works perfectly for me...

How do I make Git ignore file mode (chmod) changes?

If you have used chmod command already then check the difference of file, It shows previous file mode and current file mode such as:

new mode : 755

old mode : 644

set old mode of all files using below command

sudo chmod 644 .

now set core.fileMode to false in config file either using command or manually.

git config core.fileMode false

then apply chmod command to change the permissions of all files such as

sudo chmod 755 .

and again set core.fileMode to true.

git config core.fileMode true

For best practises don't Keep core.fileMode false always.

Random / noise functions for GLSL

I have translated one of Ken Perlin's Java implementations into GLSL and used it in a couple projects on ShaderToy.

Below is the GLSL interpretation I did:

int b(int N, int B) { return N>>B & 1; }
int T[] = int[](0x15,0x38,0x32,0x2c,0x0d,0x13,0x07,0x2a);
int A[] = int[](0,0,0);

int b(int i, int j, int k, int B) { return T[b(i,B)<<2 | b(j,B)<<1 | b(k,B)]; }

int shuffle(int i, int j, int k) {
    return b(i,j,k,0) + b(j,k,i,1) + b(k,i,j,2) + b(i,j,k,3) +
        b(j,k,i,4) + b(k,i,j,5) + b(i,j,k,6) + b(j,k,i,7) ;
}

float K(int a, vec3 uvw, vec3 ijk)
{
    float s = float(A[0]+A[1]+A[2])/6.0;
    float x = uvw.x - float(A[0]) + s,
        y = uvw.y - float(A[1]) + s,
        z = uvw.z - float(A[2]) + s,
        t = 0.6 - x * x - y * y - z * z;
    int h = shuffle(int(ijk.x) + A[0], int(ijk.y) + A[1], int(ijk.z) + A[2]);
    A[a]++;
    if (t < 0.0)
        return 0.0;
    int b5 = h>>5 & 1, b4 = h>>4 & 1, b3 = h>>3 & 1, b2= h>>2 & 1, b = h & 3;
    float p = b==1?x:b==2?y:z, q = b==1?y:b==2?z:x, r = b==1?z:b==2?x:y;
    p = (b5==b3 ? -p : p); q = (b5==b4 ? -q : q); r = (b5!=(b4^b3) ? -r : r);
    t *= t;
    return 8.0 * t * t * (p + (b==0 ? q+r : b2==0 ? q : r));
}

float noise(float x, float y, float z)
{
    float s = (x + y + z) / 3.0;  
    vec3 ijk = vec3(int(floor(x+s)), int(floor(y+s)), int(floor(z+s)));
    s = float(ijk.x + ijk.y + ijk.z) / 6.0;
    vec3 uvw = vec3(x - float(ijk.x) + s, y - float(ijk.y) + s, z - float(ijk.z) + s);
    A[0] = A[1] = A[2] = 0;
    int hi = uvw.x >= uvw.z ? uvw.x >= uvw.y ? 0 : 1 : uvw.y >= uvw.z ? 1 : 2;
    int lo = uvw.x <  uvw.z ? uvw.x <  uvw.y ? 0 : 1 : uvw.y <  uvw.z ? 1 : 2;
    return K(hi, uvw, ijk) + K(3 - hi - lo, uvw, ijk) + K(lo, uvw, ijk) + K(0, uvw, ijk);
}

I translated it from Appendix B from Chapter 2 of Ken Perlin's Noise Hardware at this source:

https://www.csee.umbc.edu/~olano/s2002c36/ch02.pdf

Here is a public shade I did on Shader Toy that uses the posted noise function:

https://www.shadertoy.com/view/3slXzM

Some other good sources I found on the subject of noise during my research include:

https://thebookofshaders.com/11/

https://mzucker.github.io/html/perlin-noise-math-faq.html

https://rmarcus.info/blog/2018/03/04/perlin-noise.html

http://flafla2.github.io/2014/08/09/perlinnoise.html

https://mrl.nyu.edu/~perlin/noise/

https://rmarcus.info/blog/assets/perlin/perlin_paper.pdf

https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch05.html

I highly recommend the book of shaders as it not only provides a great interactive explanation of noise, but other shader concepts as well.

EDIT:

Might be able to optimize the translated code by using some of the hardware-accelerated functions available in GLSL. Will update this post if I end up doing this.

I cannot start SQL Server browser

right click on SQL Server browser and properties, then Connection tab and chose open session with system account and not this account. then apply and chose automatic and finally run the server.

Binding multiple events to a listener (without JQuery)?

For me; this code works fine and is the shortest code to handle multiple events with same (inline) functions.

var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
    element.addEventListener(event, function() {
        // your function body...
        console.log("you inserted things by paste or typing etc.");
    });
}

VS Code - Search for text in all files in a directory

  • Press Ctrl + Shift + F

    enter image description here

  • Click on 3 dots under search box.

  • Type your query in search box

  • Type ./FOLDERNAME in files to include box and click Enter

Alternative way to this is, Right click on folder and select Find in Folder

Find and replace - Add carriage return OR Newline

You can also try \x0d\x0a in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace. Using \n (line feed) is the same as \x0a

Can't access RabbitMQ web management interface after fresh install

If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:

  1. Go to the RabbitMQ command prompt.

  2. Type:

    rabbitmq-plugins enable rabbitmq_management
    

SQL Sum Multiple rows into one

If you don't want to group your result, use a window function.

You didn't state your DBMS, but this is ANSI SQL:

SELECT AccountNumber, 
       Bill, 
       BillDate, 
       SUM(Bill) over (partition by accountNumber) as account_total
FROM Table1
order by AccountNumber, BillDate;

Here is an SQLFiddle: http://sqlfiddle.com/#!15/2c35e/1

You can even add a running sum, by adding:

sum(bill) over (partition by account_number order by bill_date) as sum_to_date

which will give you the total up to the current's row date.

Why does modulus division (%) only work with integers?

The % operator does not work in C++, when you are trying to find the remainder of two numbers which are both of the type Float or Double.

Hence you could try using the fmod function from math.h / cmath.h or you could use these lines of code to avoid using that header file:

float sin(float x) {
 float temp;
 temp = (x + M_PI) / ((2 *M_PI) - M_PI);
 return limited_sin((x + M_PI) - ((2 *M_PI) - M_PI) * temp ));

}

How do I reset a sequence in Oracle?

I create a block to reset all my sequences:

DECLARE
    I_val number;
BEGIN
    FOR US IN
        (SELECT US.SEQUENCE_NAME FROM USER_SEQUENCES US)
    LOOP
        execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
        execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by -' || l_val || ' minvalue 0';
        execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
        execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by 1 minvalue 0';
    END LOOP;
END;

How to resize image (Bitmap) to a given size?

In MonoDroid here's how (c#)

/// <summary>
/// Graphics support for resizing images
/// </summary>
public static class Graphics
{
    public static Bitmap ScaleDownBitmap(Bitmap originalImage, float maxImageSize, bool filter)
    {
        float ratio = Math.Min((float)maxImageSize / originalImage.Width, (float)maxImageSize / originalImage.Height);
        int width = (int)Math.Round(ratio * (float)originalImage.Width);
        int height =(int) Math.Round(ratio * (float)originalImage.Height);

        Bitmap newBitmap = Bitmap.CreateScaledBitmap(originalImage, width, height, filter);
        return newBitmap;
    }

    public static Bitmap ScaleBitmap(Bitmap originalImage, int wantedWidth, int wantedHeight)
    {
        Bitmap output = Bitmap.CreateBitmap(wantedWidth, wantedHeight, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.SetScale((float)wantedWidth / originalImage.Width, (float)wantedHeight / originalImage.Height);
        canvas.DrawBitmap(originalImage, m, new Paint());
        return output;
    }

}

Git reset --hard and push to remote repository

For users of GitHub, this worked for me:

  1. In any branch protection rules where you wish to make the change, make sure Allow force pushes is enabled
  2. git reset --hard <full_hash_of_commit_to_reset_to>
  3. git push --force

This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.

All everyone else needs to do is the git reset command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.

Send form data with jquery ajax json

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

Use sed to replace all backslashes with forward slashes

If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:

$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml

This may be leaner and clearer that filtering through a command such as tr or sed.

Insert string in beginning of another string

It is better if you find quotation marks by using the indexof() method and then add a string behind that index.

string s="hai";
int s=s.indexof(""");

Browse and display files in a git repo without cloning

Take a look at http://git-scm.com/book/en/Git-Internals-Transfer-Protocols for info on how to do this over some transport protocols. Note this won't work for standard git over SSH.

For git over SSH, an up-to-date server-side git should allow you to git-archive directly from the remote, which you could then e.g. pipe to "tar t" to get a list of all files in a given commit.

Android - java.lang.SecurityException: Permission Denial: starting Intent

In my case, this error was due to incorrect paths used to specify intents in my preferences xml file after I renamed the project. For instance, where I had:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.olddirectory"
            android:targetClass="com.ssimon.olddirectory.RecipeEditActivity"/>
    </Preference>
</PreferenceScreen> 

I needed the following instead:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.newdirectory"
            android:targetClass="com.ssimon.newdirectory.RecipeEditActivity"/>
</Preference>

Correcting the path names fixed the problem.

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Replacing localhost with 10.0.2.2 is correct, but you can alsor replace localhost with your physical machine's ip(it is better for debug purposes). Ofc, if ip is provided by dhcp you would have to change it each time...

Good luck!

What does the ">" (greater-than sign) CSS selector mean?

The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.

An example:

article > p { }

Means only style a paragraph that comes after an article.

What's the best practice to "git clone" into an existing folder?

If you are using at least git 1.7.7 (which taught clone the --config option), to turn the current directory into a working copy:

git clone example.com/my.git ./.git --mirror --config core.bare=false

This works by:

  • Cloning the repository into a new .git folder
  • --mirror makes the new clone into a purely metadata folder as .git needs to be
  • --config core.bare=false countermands the implicit bare=true of the --mirror option, thereby allowing the repository to have an associated working directory and act like a normal clone

This obviously won't work if a .git metadata directory already exists in the directory you wish to turn into a working copy.

How can I revert multiple Git commits (already pushed) to a published repository?

If you've already pushed things to a remote server (and you have other developers working off the same remote branch) the important thing to bear in mind is that you don't want to rewrite history

Don't use git reset --hard

You need to revert changes, otherwise any checkout that has the removed commits in its history will add them back to the remote repository the next time they push; and any other checkout will pull them in on the next pull thereafter.

If you have not pushed changes to a remote, you can use

git reset --hard <hash>

If you have pushed changes, but are sure nobody has pulled them you can use

git reset --hard
git push -f

If you have pushed changes, and someone has pulled them into their checkout you can still do it but the other team-member/checkout would need to collaborate:

(you) git reset --hard <hash>
(you) git push -f

(them) git fetch
(them) git reset --hard origin/branch

But generally speaking that's turning into a mess. So, reverting:

The commits to remove are the lastest

This is possibly the most common case, you've done something - you've pushed them out and then realized they shouldn't exist.

First you need to identify the commit to which you want to go back to, you can do that with:

git log

just look for the commit before your changes, and note the commit hash. you can limit the log to the most resent commits using the -n flag: git log -n 5

Then reset your branch to the state you want your other developers to see:

git revert  <hash of first borked commit>..HEAD

The final step is to create your own local branch reapplying your reverted changes:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Continue working in my-new-branch until you're done, then merge it in to your main development branch.

The commits to remove are intermingled with other commits

If the commits you want to revert are not all together, it's probably easiest to revert them individually. Again using git log find the commits you want to remove and then:

git revert <hash>
git revert <another hash>
..

Then, again, create your branch for continuing your work:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Then again, hack away and merge in when you're done.

You should end up with a commit history which looks like this on my-new-branch

2012-05-28 10:11 AD7six             o [my-new-branch] Revert "Revert "another mistake""
2012-05-28 10:11 AD7six             o Revert "Revert "committing a mistake""
2012-05-28 10:09 AD7six             o [master] Revert "committing a mistake"
2012-05-28 10:09 AD7six             o Revert "another mistake"
2012-05-28 10:08 AD7six             o another mistake
2012-05-28 10:08 AD7six             o committing a mistake
2012-05-28 10:05 Bob                I XYZ nearly works

Better way®

Especially that now that you're aware of the dangers of several developers working in the same branch, consider using feature branches always for your work. All that means is working in a branch until something is finished, and only then merge it to your main branch. Also consider using tools such as git-flow to automate branch creation in a consistent way.

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.