Programs & Examples On #Onunload

window.onunload is not working properly in Chrome browser. Can any one help me?

The onunload event won't fire if the onload event did not fire. Unfortunately the onload event waits for all binary content (e.g. images) to load, and inline scripts run before the onload event fires. DOMContentLoaded fires when the page is visible, before onload does. And it is now standard in HTML 5, and you can test for browser support but note this requires the <!DOCTYPE html> (at least in Chrome). However, I can not find a corresponding event for unloading the DOM. And such a hypothetical event might not work because some browsers may keep the DOM around to perform the "restore tab" feature.

The only potential solution I found so far is the Page Visibility API, which appears to require the <!DOCTYPE html>.

How to create an integer-for-loop in Ruby?

Try Below Simple Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }

Javascript Audio Play on click

Try the below code snippet

<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onclick="play()">
    <audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>

  </body>
</html>

Getting files by creation date in .NET

            DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
            String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
            ArrayList files = new ArrayList();
            foreach (string ext in exts)
                files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());

Fatal error: Namespace declaration statement has to be the very first statement in the script in

In my case, the file was created with UTF-8-BOM encoding. I have to save it into UTF-8 encoding, then everything works fine.

How do I create test and train samples from one dataframe with pandas?

No need to convert to numpy. Just use a pandas df to do the split and it will return a pandas df.

from sklearn.model_selection import train_test_split

train, test = train_test_split(df, test_size=0.2)

And if you want to split x from y

X_train, X_test, y_train, y_test = train_test_split(df[list_of_x_cols], df[y_col],test_size=0.2)

And if you want to split the whole df

X, y = df[list_of_x_cols], df[y_col]

How to check if object has any properties in JavaScript?

for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

Member means Member property, member variable, whatever you want to call it >_>

The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"

@RequestParam vs @PathVariable

@RequestParam is use for query parameter(static values) like: http://localhost:8080/calculation/pow?base=2&ext=4

@PathVariable is use for dynamic values like : http://localhost:8080/calculation/sqrt/8

@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
    int pow = (int) Math.pow(base1, ext1);
    return pow;
}

@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
    double sqrtnum=Math.sqrt(num1);
    return sqrtnum;
}

How in node to split string by newline ('\n')?

A solution that works with all possible line endings including mixed ones and keeping empty lines as well can be achieved using two replaces and one split as follows

text.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/);

some code to test it

  var CR = "\x0D";  //   \r
  var LF = "\x0A";  //   \n

  var mixedfile = "00" + CR + LF +            // 1 x win
                  "01" + LF +                 // 1 x linux
                  "02" + CR +                 // 1 x old mac
                  "03" + CR + CR +            // 2 x old mac
                  "05" + LF + LF +            // 2 x linux
                  "07" + CR + LF + CR + LF +  // 2 x win
                  "09";

  function showarr (desc, arr)
  {
     console.log ("// ----- " + desc);
     for (var ii in arr)
        console.log (ii + ") [" + arr[ii] +  "] (len = " + arr[ii].length + ")");
  }

  showarr ("using 2 replace + 1 split", 
           mixedfile.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/));

and the output

  // ----- using 2 replace + 1 split
  0) [00] (len = 2)
  1) [01] (len = 2)
  2) [02] (len = 2)
  3) [03] (len = 2)
  4) [] (len = 0)
  5) [05] (len = 2)
  6) [] (len = 0)
  7) [07] (len = 2)
  8) [] (len = 0)
  9) [09] (len = 2)

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

pull out p-values and r-squared from a linear regression

For the final p-value displayed at the end of summary(), the function uses pf() to calculate from the summary(fit)$fstatistic values.

fstat <- summary(fit)$fstatistic
pf(fstat[1], fstat[2], fstat[3], lower.tail=FALSE)

Source: [1], [2]

What do Clustered and Non clustered index actually mean?

I realize this is a very old question, but I thought I would offer an analogy to help illustrate the fine answers above.

CLUSTERED INDEX

If you walk into a public library, you will find that the books are all arranged in a particular order (most likely the Dewey Decimal System, or DDS). This corresponds to the "clustered index" of the books. If the DDS# for the book you want was 005.7565 F736s, you would start by locating the row of bookshelves that is labeled 001-099 or something like that. (This endcap sign at the end of the stack corresponds to an "intermediate node" in the index.) Eventually you would drill down to the specific shelf labelled 005.7450 - 005.7600, then you would scan until you found the book with the specified DDS#, and at that point you have found your book.

NON-CLUSTERED INDEX

But if you didn't come into the library with the DDS# of your book memorized, then you would need a second index to assist you. In the olden days you would find at the front of the library a wonderful bureau of drawers known as the "Card Catalog". In it were thousands of 3x5 cards -- one for each book, sorted in alphabetical order (by title, perhaps). This corresponds to the "non-clustered index". These card catalogs were organized in a hierarchical structure, so that each drawer would be labeled with the range of cards it contained (Ka - Kl, for example; i.e., the "intermediate node"). Once again, you would drill in until you found your book, but in this case, once you have found it (i.e, the "leaf node"), you don't have the book itself, but just a card with an index number (the DDS#) with which you could find the actual book in the clustered index.

Of course, nothing would stop the librarian from photocopying all the cards and sorting them in a different order in a separate card catalog. (Typically there were at least two such catalogs: one sorted by author name, and one by title.) In principle, you could have as many of these "non-clustered" indexes as you want.

Very simple C# CSV reader

This fixed version of code above remember the last element of CVS row ;-)

(tested with a CSV file with 5400 rows and 26 elements by row)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Don't reload the page - this brings the error message up again. Instead, start at the beginning of the URL you were looking at a second ago, and delete everything before it. Then press enter. The error won't come back for at least another little while.

I know because FanFiction.net has the same problem, and this is how I've solved it.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

What do the makefile symbols $@ and $< mean?

The $@ and $< are special macros.

Where:

$@ is the file name of the target.

$< is the name of the first dependency.

How to change color of ListView items on focus and on click

<selector xmlns:android="http://schemas.android.com/apk/res/android" >    
    <item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" /> 
    <item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

Do you use source control for your database items?

For oracle I use self-written java programm oracle-ddl2svn for auto track changes of oracle DDL scheme in SVN

Convert a dataframe to a vector (by rows)

c(df$x, df$y)
# returns: 26 21 20 34 29 28

if the particular order is important then:

M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28 

Or more generally:

m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
  q = c(q, m[i,])
}

# returns 26 34 21 29 20 28

Superscript in CSS only?

You can do superscript with vertical-align: super, (plus an accompanying font-size reduction).

However, be sure to read the other answers here, particularly those by paulmurray and cletus, for useful information.

HTML span align center not working?

span.login-text {
    font-size: 22px;
    display:table;
    margin-left: auto;
    margin-right: auto;
}

<span class="login-text">Welcome To .....CMP</span>

For me it worked very well. try this also

how to refresh page in angular 2

Updated

How to implement page refresh in Angular 2+ note this is done within your component:

location.reload();

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

java.net.BindException: Address already in use: JVM_Bind <null>:80

I came across same issue. I was getting error Unable to open debugger port (127.0.0.1:63936): java.net.BindException "Address already in use: JVM_Bind" I tried above all option but any how its not resolved. Solution which worked for me is, I started the server and then stopped and again started in debug mode. then the server got started in debug mode.

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

Calculate the number of business days between two dates?

You just have to iterate through each day in the time range and subtract a day from the counter if its a Saturday or a Sunday.

    private float SubtractWeekend(DateTime start, DateTime end) {
        float totaldays = (end.Date - start.Date).Days;
        var iterationVal = totalDays;
        for (int i = 0; i <= iterationVal; i++) {
            int dayVal = (int)start.Date.AddDays(i).DayOfWeek;
            if(dayVal == 6 || dayVal == 0) {
                // saturday or sunday
                totalDays--;
            }
        }
        return totalDays;
    }

System.Net.WebException HTTP status code

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

Meaning of end='' in the statement print("\t",end='')?

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

How do you implement a class in C?

GTK is built entirely on C and it uses many OOP concepts. I have read through the source code of GTK and it is pretty impressive, and definitely easier to read. The basic concept is that each "class" is simply a struct, and associated static functions. The static functions all accept the "instance" struct as a parameter, do whatever then need, and return results if necessary. For Example, you may have a function "GetPosition(CircleStruct obj)". The function would simply dig through the struct, extract the position numbers, probably build a new PositionStruct object, stick the x and y in the new PositionStruct, and return it. GTK even implements inheritance this way by embedding structs inside structs. pretty clever.

How do I use Join-Path to combine more than two strings into a file path?

If you are still using .NET 2.0, then [IO.Path]::Combine won't have the params string[] overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".

Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:

Join-Path C: (Join-Path  "Program Files" "Microsoft Office")

or

Join-Path  (Join-Path  C: "Program Files") "Microsoft Office"

Facebook user url by id

The easiest and the most correct (and legal) way is to use graph api.

Just perform the request: http://graph.facebook.com/4

which returns

{
   "id": "4",
   "name": "Mark Zuckerberg",
   "first_name": "Mark",
   "last_name": "Zuckerberg",
   "link": "http://www.facebook.com/zuck",
   "username": "zuck",
   "gender": "male",
   "locale": "en_US"
}

and take the link key.

You can also reduce the traffic by using fields parameter: http://graph.facebook.com/4?fields=link to get only what you need:

{
   "link": "http://www.facebook.com/zuck",
   "id": "4"
}

HTML checkbox - allow to check only one checkbox

sapSet = mbo.getThisMboSet()
sapCount = sapSet.count()
saplist = []

if sapCount > 1:
   for i in range(sapCount):`enter code here`
     defaultCheck = sapSet.getMbo(i)
     saplist.append(defaultCheck.getInt("HNADEFACC"))
   defCount = saplist.count(1)
   if defCount > 1:
      errorgroup = " Please Note: you are allowed"
      errorkey = "  only One Default Account"
   if defCount < 1:
      errorgroup = " Please enter "
      errorkey = "  at leat One Default Account"
else:
   mbo.setValue("HNADEFACC",1,MboConstants.NOACCESSCHECK)

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

select2 onchange event only works once

Set your .on listener to check for specific select2 events. The "change" event is the same as usual but the others are specific to the select2 control thus:

  • change
  • select2-opening
  • select2-open
  • select2-close
  • select2-highlight
  • select2-selecting
  • select2-removed
  • select2-loaded
  • select2-focus

The names are self-explanatory. For example, select2-focus fires when you give focus to the control.

How to create text file and insert data to that file on Android

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Difference between two dates in MySQL

SELECT TIMESTAMPDIFF(SECOND,'2018-01-19 14:17:15','2018-01-20 14:17:15');

Second approach

SELECT ( DATEDIFF('1993-02-20','1993-02-19')*( 24*60*60) )AS 'seccond';

CURRENT_TIME() --this will return current Date
DATEDIFF('','') --this function will return  DAYS and in 1 day there are 24hh 60mm 60sec

What does on_delete do on Django models?

As mentioned earlier, CASCADE will delete the record that has a foreign key and references another object that was deleted. So for example if you have a real estate website and have a Property that references a City

class City(models.Model):
    # define model fields for a city

class Property(models.Model):
    city = models.ForeignKey(City, on_delete = models.CASCADE)
    # define model fields for a property

and now when the City is deleted from the database, all associated Properties (eg. real estate located in that city) will also be deleted from the database

Now I also want to mention the merit of other options, such as SET_NULL or SET_DEFAULT or even DO_NOTHING. Basically, from the administration perspective, you want to "delete" those records. But you don't really want them to disappear. For many reasons. Someone might have deleted it accidentally, or for auditing and monitoring. And plain reporting. So it can be a way to "disconnect" the property from a City. Again, it will depend on how your application is written.

For example, some applications have a field "deleted" which is 0 or 1. And all their searches and list views etc, anything that can appear in reports or anywhere the user can access it from the front end, exclude anything that is deleted == 1. However, if you create a custom report or a custom query to pull down a list of records that were deleted and even more so to see when it was last modified (another field) and by whom (i.e. who deleted it and when)..that is very advantageous from the executive standpoint.

And don't forget that you can revert accidental deletions as simple as deleted = 0 for those records.

My point is, if there is a functionality, there is always a reason behind it. Not always a good reason. But a reason. And often a good one too.

How does java do modulus calculations with negative numbers?

According to section 15.17.3 of the JLS, "The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0)."

Hope that helps.

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

Changing MongoDB data store directory

If installed via apt-get in Ubuntu 12.04, don't forget to chown -R mongodb:nogroup /path/to/new/directory. Also, change the configuration at /etc/mongodb.conf.

As a reminder, the mongodb-10gen package is now started via upstart, so the config script is in /etc/init/mongodb.conf

I just went through this, hope googlers find it useful :)

Open multiple Eclipse workspaces on the Mac

A more convenient way:

  1. Create an executable script as mentioned above:

    #!/bin/sh

    cd /Applications/Adobe\ Flash\ Builder\ 4.6

    open -n Adobe\ Flash\ Builder\ 4.6.app

  2. In you current instance of Flashbuilder or Eclipse, add a new external tool configuration. This is the button next to the debug/run/profile buttons on your toolbar. In that dialog, click on "Program" and add a new one. Give it the name you want and in the "Location" field, put the path to the script from step 1:

    /Users/username/bin/flashbuilder

  3. You can stop at step 2, but I prefer adding a custom icon to the toolbar. I use a the Quick Launch plugin to do that:

    http://sourceforge.net/projects/quicklaunch/files/

  4. After adding the plugin, go to "Run"->"Organize Quick Lauches" and add the external tool config from step 2. Then you can configure the icon for it.

  5. After you save that, you'll see the icon in your toolbar. Now you can just click it every time you want a new Flashbuilder/Eclipse instance.

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

@theczechsensation's solution is already half way there.

For those who like to exclude noisy log messages and keep the log to their app only this is the solution:

New Logcat Filter Settings

Add your exclusions to Log Tag like this: ^(?!(eglCodecCommon|tagToExclude))

Add your package name or prefix to Package Name: com.mycompany.

This way it is possible to filter for as many strings you like and keep the log to your package.

Strip Leading and Trailing Spaces From Java String

trim() is your choice, but if you want to use replace method -- which might be more flexiable, you can try the following:

String stripppedString = myString.replaceAll("(^ )|( $)", "");

Difference between "managed" and "unmanaged"

Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).

http://en.wikipedia.org/wiki/Managed_code

http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

How do I localize the jQuery UI Datepicker?

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src=">/js/datepicker-fr.js"></script>
<script>
jQuery(function() {
jQuery( "#datepicker" ).datepicker({minDate: 0 , dateFormat: 'mm/dd/yy'});
});

</script>

<script type="text/javascript">
$(document).ready(function(){
$('#datepicker').datepicker($.datepicker.regional['fr']);
});
</script>

Autoreload of modules in IPython

As mentioned above, you need the autoreload extension. If you want it to automatically start every time you launch ipython, you need to add it to the ipython_config.py startup file:

It may be necessary to generate one first:

ipython profile create

Then include these lines in ~/.ipython/profile_default/ipython_config.py:

c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

As well as an optional warning in case you need to take advantage of compiled Python code in .pyc files:

c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in ipython_config.py to improve performance." ')

edit: the above works with version 0.12.1 and 0.13

What is the maximum length of a URL in different browsers?

The HTTP 1.1 specification says:

URIs in HTTP can be represented in absolute form or relative to some
known base URI [11], depending upon the context of their use. The two
forms are differentiated by the fact that absolute URIs always begin
with a scheme name followed by a colon. For definitive information on
URL syntax and semantics, see "Uniform Resource Identifiers (URI): Generic Syntax and Semantics," RFC 2396 [42] (which replaces RFCs 1738 [4] and RFC 1808 [11]). This specification adopts the definitions of "URI-reference", "absoluteURI", "relativeURI", "port",
"host","abs_path", "rel_path", and "authority" from that
specification.

The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs.*
A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.

As mentioned by @Brian, the HTTP clients (e.g. browsers) may have their own limits, and HTTP servers will have different limits.

How do I prevent a form from being resized by the user?

You can remove the UI to control this with:

frmYour.MinimizeBox = False
frmYour.MaximizeBox = False

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

set Environment variable ANDROID_DAILY_OVERRIDE to same value Example - b9471da4f76e0d1a88d41a072922b1e0c257745c

this works for me.

How do I output lists as a table in Jupyter notebook?

I recently used prettytable for rendering a nice ASCII table. It's similar to the postgres CLI output.

import pandas as pd
from prettytable import PrettyTable

data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(data, columns=['one', 'two', 'three'])

def generate_ascii_table(df):
    x = PrettyTable()
    x.field_names = df.columns.tolist()
    for row in df.values:
        x.add_row(row)
    print(x)
    return x

generate_ascii_table(df)

Output:

+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
|  1  |  2  |   3   |
|  4  |  5  |   6   |
|  7  |  8  |   9   |
+-----+-----+-------+

Properties file in python (similar to Java Properties)

I have created a python module that is almost similar to the Properties class of Java ( Actually it is like the PropertyPlaceholderConfigurer in spring which lets you use ${variable-reference} to refer to already defined property )

EDIT : You may install this package by running the command(currently tested for python 3).
pip install property

The project is hosted on GitHub

Example : ( Detailed documentation can be found here )

Let's say you have the following properties defined in my_file.properties file

foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge

Code to load the above properties

from properties.p import Property

prop = Property()
# Simply load it into a dictionary
dic_prop = prop.load_property_files('my_file.properties')

Convert an image to grayscale

"I want a Bitmap d, that is grayscale. I do see a consructor that includes System.Drawing.Imaging.PixelFormat, but I don't understand how to use that."

Here is how to do this

Bitmap grayScaleBP = new 
         System.Drawing.Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);

EDIT: To convert to grayscale

             Bitmap c = new Bitmap("fromFile");
             Bitmap d;
             int x, y;

             // Loop through the images pixels to reset color.
             for (x = 0; x < c.Width; x++)
             {
                 for (y = 0; y < c.Height; y++)
                 {
                     Color pixelColor = c.GetPixel(x, y);
                     Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
                     c.SetPixel(x, y, newColor); // Now greyscale
                 }
             }
            d = c;   // d is grayscale version of c  

Faster Version from switchonthecode follow link for full analysis:

public static Bitmap MakeGrayscale3(Bitmap original)
{
   //create a blank bitmap the same size as original
   Bitmap newBitmap = new Bitmap(original.Width, original.Height);

   //get a graphics object from the new image
   using(Graphics g = Graphics.FromImage(newBitmap)){

       //create the grayscale ColorMatrix
       ColorMatrix colorMatrix = new ColorMatrix(
          new float[][] 
          {
             new float[] {.3f, .3f, .3f, 0, 0},
             new float[] {.59f, .59f, .59f, 0, 0},
             new float[] {.11f, .11f, .11f, 0, 0},
             new float[] {0, 0, 0, 1, 0},
             new float[] {0, 0, 0, 0, 1}
          });

       //create some image attributes
       using(ImageAttributes attributes = new ImageAttributes()){

           //set the color matrix attribute
           attributes.SetColorMatrix(colorMatrix);

           //draw the original image on the new image
           //using the grayscale color matrix
           g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                       0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
       }
   }
   return newBitmap;
}

Removing multiple keys from a dictionary safely

Using dict.pop:

d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
    d.pop(k, None)

How do I create a round cornered UILabel on the iPhone?

In Monotouch / Xamarin.iOS I solved the same problem like this:

UILabel exampleLabel = new UILabel(new CGRect(0, 0, 100, 50))
        {
            Text = "Hello Monotouch red label"
        };
        exampleLabel.Layer.MasksToBounds = true;
        exampleLabel.Layer.CornerRadius = 8;
        exampleLabel.Layer.BorderColor = UIColor.Red.CGColor;
        exampleLabel.Layer.BorderWidth = 2;

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

Space between two rows in a table?

A too late answer :)

If you apply float to tr elements, you can space between two rows with margin attribute.

table tr{
float: left
width: 100%;
}

tr.classname {
margin-bottom:5px;
}

Android SharedPreferences in Fragment

use requiredactivity in fragment kotlin

 val sharedPreferences = requireActivity().getSharedPreferences(loginmasuk.LOGIN_DATA, Context.MODE_PRIVATE)

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

How to find all occurrences of an element in a list

While not a solution for lists directly, numpy really shines for this sort of thing:

import numpy as np
values = np.array([1,2,3,1,2,4,5,6,3,2,1])
searchval = 3
ii = np.where(values == searchval)[0]

returns:

ii ==>array([2, 8])

This can be significantly faster for lists (arrays) with a large number of elements vs some of the other solutions.

What is difference between Errors and Exceptions?

An Error "indicates serious problems that a reasonable application should not try to catch."

while

An Exception "indicates conditions that a reasonable application might want to catch."

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

Visual Studio popup: "the operation could not be completed"

Restarting Visual Studio solved my problem :)

Integer value in TextView

If you want it to display on your layout you should

For example:

activity_layout.XML file

    <TextView
        android:id="@+id/example_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

On the activity.java file

    final TextView textView = findViewById(R.id.example_tv);
    textView.setText(Integer.toString(yourNumberHere));

In the first line on the XML file you can see:

android:id="@+id/example_tv"

That's where you get the id to change in the .java file for the findViewById(R.id.example_tv)

Hope I made myself clear, I just went with this explanation because a lot of times people seem to know the ".setText()" method, they just can't change the text in the "UI".


EDIT Since this is a fairly old answer, and Kotlin is the preferred language for Android development, here's its counterpart.

With the same XML layout:

You can either use the findViewbyId() or use Kotlin synthetic properties:

findViewById<TextView>(R.id.example_tv).text = yourNumberHere.toString()

// Or

example_tv?.text = yourNumberHere.toString()

The toString() is from Kotlin's Any object (comparable to the Java Object):

The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.

Unable to find valid certification path to requested target - error even after cert imported

Check if the file $JAVA_HOME/lib/security/cacerts exists! In my case it was not a file but a link to /etc/ssl/certs/java/cacerts and also this was a link to itself (WHAT???) so due to it JVM can't find the file.

Solution: Copy the real cacerts file (you can do it from another JDK) to /etc/ssl/certs/java/ directory and it'll solve your problem :)

Adding an arbitrary line to a matplotlib plot in ipython notebook

Rather than abusing plot or annotate, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")

# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)

plt.gca().add_collection(lc)

plt.show()

Figure with two lines plotted via LineCollection

It takes a list of lines [l1, l2, ...], where each line is a sequence of N coordinates (N can be more than two).

The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values, in which case the value for the ith line is values[i % M].

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Git merge reports "Already up-to-date" though there is a difference

If merging branch A into branch B reports "Already up to date", reverse is not always true. It is true only if branch B is descendant of branch A, otherwise branch B simply can have changes that aren't in A.

Example:

  1. You create branches A and B off master
  2. You make some changes in master and merge these changes only into branch B (not updating or forgetting to update branch A).
  3. You make some changes in branch A and merge A to B.

At this point merging A to B reports "Already up to date" but the branches are different because branch B has updates from master while branch A does not.

Cannot connect to the Docker daemon on macOS

On a supported Mac, run:

brew install --cask docker

Then launch the Docker app. Click next. It will ask for privileged access. Confirm. A whale icon should appear in the top bar. Click it and wait for "Docker is running" to appear.

You should be able to run docker commands now:

docker ps

Because docker is a system-level package, you cannot install it using brew install, and must use --cask instead.

Note: This solution only works for Macs whose CPUs support virtualization, which may not include old Macs.

How to format JSON in notepad++

The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.

Measuring the distance between two coordinates in PHP

I found this code which is giving me reliable results.

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
      return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
      return $miles;
  }
}

results :

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

Initialization of an ArrayList in one line

(Should be a comment, but too long, so new reply). As others have mentioned, the Arrays.asList method is fixed size, but that's not the only issue with it. It also doesn't handle inheritance very well. For instance, suppose you have the following:

class A{}
class B extends A{}

public List<A> getAList(){
    return Arrays.asList(new B());
}

The above results in a compiler error, because List<B>(which is what is returned by Arrays.asList) is not a subclass of List<A>, even though you can add Objects of type B to a List<A> object. To get around this, you need to do something like:

new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))

This is probably the best way to go about doing this, esp. if you need an unbounded list or need to use inheritance.

Remove a parameter to the URL with JavaScript

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

The var alteredURL will be the output you desire.

Hope it helps!

How is the AND/OR operator represented as in Regular Expressions?

use
if in vim:

:s/{\|}/"/g

will replace { and } on " so {lol} becomes "lol"

Passing properties by reference in C#

without duplicating the property

void Main()
{
    var client = new Client();
    NullSafeSet("test", s => client.Name = s);
    Debug.Assert(person.Name == "test");

    NullSafeSet("", s => client.Name = s);
    Debug.Assert(person.Name == "test");

    NullSafeSet(null, s => client.Name = s);
    Debug.Assert(person.Name == "test");
}

void NullSafeSet(string value, Action<string> setter)
{
    if (!string.IsNullOrEmpty(value))
    {
        setter(value);
    }
}

How to capitalize the first letter of word in a string using Java?

Actually, you will get the best performance if you avoid + operator and use concat() in this case. It is the best option for merging just 2 strings (not so good for many strings though). In that case the code would look like this:

String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));

How to get HttpContext.Current in ASP.NET Core?

There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)

app.Use(async (httpContext, next) =>
{
    CallContext.LogicalSetData("CurrentContextKey", httpContext);
    try
    {
        await next();
    }
    finally
    {
        CallContext.FreeNamedDataSlot("CurrentContextKey");
    }
});

And when you need it you can get it with :

HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;

I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine

How to find longest string in the table column data

Instead of SELECT max(len(CR)) AS Max_Length_String FROM table1

Use

SELECT (CR) FROM table1

WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

Starting of Tomcat failed from Netbeans

It affects at least NetBeans versions 7.4 through 8.0.2. It was first reported from version 8.0 and fixed in NetBeans 8.1. It would have had the problem for any tomcat version (confirmed for versions 7.0.56 through 8.0.28).

Specifics are described as Netbeans bug #248182.

This problem is also related to postings mentioning the following error output:

'127.0.0.1*' is not recognized as an internal or external command, operable program or batch file.

For a tomcat installed from the zip file, I fixed it by changing the catalina.bat file in the tomcat bin directory.

Find the bellow configuration in your catalina.bat file.

:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

And change it as in below by removing the double quotes:

:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%

:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%

Now save your changes, and start your tomcat from within NetBeans.

Breaking up long strings on multiple lines in Ruby without stripping newlines

I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

ngFor with index as value in attribute

The other answers are correct but you can omit the [attr.data-index] altogether and just use

<ul>
    <li *ngFor="let item of items; let i = index">{{i + 1}}</li>
</ul

How to implement a Boolean search with multiple columns in pandas

Easiest way to do this

if this helpful hit up arrow! Tahnks!!

students = [ ('jack1', 'Apples1' , 341) ,
             ('Riti1', 'Mangos1'  , 311) ,
             ('Aadi1', 'Grapes1' , 301) ,
             ('Sonia1', 'Apples1', 321) ,
             ('Lucy1', 'Mangos1'  , 331) ,
             ('Mike1', 'Apples1' , 351),
              ('Mik', 'Apples1' , np.nan)
              ]
#Create a DataFrame object
df = pd.DataFrame(students, columns = ['Name1' , 'Product1', 'Sale1']) 
print(df)


    Name1 Product1  Sale1
0   jack1  Apples1    341
1   Riti1  Mangos1    311
2   Aadi1  Grapes1    301
3  Sonia1  Apples1    321
4   Lucy1  Mangos1    331
5   Mike1  Apples1    351
6     Mik  Apples1    NaN

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’,
subset = df[df['Product1'] == 'Apples1']
print(subset)

 Name1 Product1  Sale1
0   jack1  Apples1    341
3  Sonia1  Apples1    321
5   Mike1  Apples1    351
6     Mik  Apples1    NA

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’, AND notnull value in Sale

subsetx= df[(df['Product1'] == "Apples1")  & (df['Sale1'].notnull())]
print(subsetx)
    Name1   Product1    Sale1
0   jack1   Apples1      341
3   Sonia1  Apples1      321
5   Mike1   Apples1      351

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’, AND Sale = 351

subsetx= df[(df['Product1'] == "Apples1")  & (df['Sale1'] == 351)]
print(subsetx)

   Name1 Product1  Sale1
5  Mike1  Apples1    351

# Another example
subsetData = df[df['Product1'].isin(['Mangos1', 'Grapes1']) ]
print(subsetData)

Name1 Product1  Sale1
1  Riti1  Mangos1    311
2  Aadi1  Grapes1    301
4  Lucy1  Mangos1    331

Here is the Original link I found this. I edit it a little bit -- https://thispointer.com/python-pandas-select-rows-in-dataframe-by-conditions-on-multiple-columns/

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

How to cache Google map tiles for offline usage?

update:

I found the terms of use from Google Map:

Section 10.5

No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.

It means we can cache for limited time actually

Apache server keeps crashing, "caught SIGTERM, shutting down"

Have you asked your provider to investigate? I assume this is not a dedicated server,

On the face of it, this seems like a security exception and somone is trying to exploit it / or there is a process running at a set time which is causing this, can you think of anything that runs on the server every 2 days? Logging tools?

SIGTERM is the signal sent to a process to request its termination. The symbolic constant for SIGTERM is defined in the header file signal.h. Symbolic signal names are used because signal numbers can vary across platforms, however on the vast majority of systems, SIGTERM is signal #15.

Text size and different android screen sizes

As @espinchi mentioned from 3.2 (API level 13) size groups are deprecated. Screen size ranges are the favored approach going forward.

How do I put text on ProgressBar?

I have written a no blinking/flickering TextProgressBar

You can find the source code here: https://github.com/ukushu/TextProgressBar

enter image description here

WARNING: It's a little bit buggy! But still, I think it's better than another answers here. As I have no time for fixes, if you will do sth with them, please send me update by some way:) Thanks.

Samples:

enter image description here enter image description here no blinking/flickering TextProgressBar

no blinking/flickering TextProgressBar enter image description here enter image description here

Convert iterator to pointer?

Vector is a template class and it is not safe to convert the contents of a class to a pointer : You cannot inherit the vector class to add this new functionality. and changing the function parameter is actually a better idea. Jst create another vector of int vector temp_foo (foo.begin[X],foo.end()); and pass this vector to you functions

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

In my case.. following steps resolved:

There was a column value which was set to "Update" - replaced it with Edit (non sql keyword) There was a space in one of the column names (removed the extra space or trim)

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

Split a vector into chunks

I needed the same function and have read the previous solutions, however i also needed to have the unbalanced chunk to be at the end i.e if i have 10 elements to split them into vectors of 3 each, then my result should have vectors with 3,3,4 elements respectively. So i used the following (i left the code unoptimised for readability, otherwise no need to have many variables):

chunk <- function(x,n){
  numOfVectors <- floor(length(x)/n)
  elementsPerVector <- c(rep(n,numOfVectors-1),n+length(x) %% n)
  elemDistPerVector <- rep(1:numOfVectors,elementsPerVector)
  split(x,factor(elemDistPerVector))
}
set.seed(1)
x <- rnorm(10)
n <- 3
chunk(x,n)
$`1`
[1] -0.6264538  0.1836433 -0.8356286

$`2`
[1]  1.5952808  0.3295078 -0.8204684

$`3`
[1]  0.4874291  0.7383247  0.5757814 -0.3053884

git rm - fatal: pathspec did not match any files

Step 1

Add the file name(s) to your .gitignore file.

Step 2

git filter-branch --force --index-filter \
    'git rm -r --cached --ignore-unmatch YOURFILE' \
    --prune-empty --tag-name-filter cat -- --all

Step 3

git push -f origin branch

A big thank you to @mu.

How to Multi-thread an Operation Within a Loop in Python

First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.

This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.


Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing and concurrent.futures libraries both wraps up most of the details for you.

The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures, 4 lines with multiprocessing.)

If you're using 2.6-2.7 or 3.0-3.1, futures isn't built in, but you can install it from PyPI (pip install futures).


Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map), so let's do that first:

def try_my_operation(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

Putting it all together:

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)

If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper from the itertools recipes, which you can copy and paste into your code, or get from the more-itertools project on PyPI):

def try_multiple_operations(items):
    for item in items:
        try:
            api.my_operation(item)
        except:
            print('error with item')

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group) 
           for group in grouper(5, items)]
concurrent.futures.wait(futures)

Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.

So, how do you use threads instead of processes? Just change ProcessPoolExecutor to ThreadPoolExecutor.

If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.


Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?

Yes. In fact, there are two different ways to do it.

First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.

Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.

If you don't know which is appropriate for your program, usually it's the first.

Copy all values from fields in one class to another through reflection

    public <T1 extends Object, T2 extends Object> void copy(T1 origEntity, T2 destEntity) {
        DozerBeanMapper mapper = new DozerBeanMapper();
        mapper.map(origEntity,destEntity);
    }

 <dependency>
            <groupId>net.sf.dozer</groupId>
            <artifactId>dozer</artifactId>
            <version>5.4.0</version>
        </dependency>

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

jQuery plugin with emulate natural scrolling for Internet Explorer

  $.fn.mousewheelStopPropagation = function(options) {
    options = $.extend({
        // defaults
        wheelstop: null // Function
        }, options);

    // Compatibilities
    var isMsIE = ('Microsoft Internet Explorer' === navigator.appName);
    var docElt = document.documentElement,
        mousewheelEventName = 'mousewheel';
    if('onmousewheel' in docElt) {
        mousewheelEventName = 'mousewheel';
    } else if('onwheel' in docElt) {
        mousewheelEventName = 'wheel';
    } else if('DOMMouseScroll' in docElt) {
        mousewheelEventName = 'DOMMouseScroll';
    }
    if(!mousewheelEventName) { return this; }

    function mousewheelPrevent(event) {
        event.preventDefault();
        event.stopPropagation();
        if('function' === typeof options.wheelstop) {
            options.wheelstop(event);
        }
    }

    return this.each(function() {
        var _this = this,
            $this = $(_this);
        $this.on(mousewheelEventName, function(event) {
            var origiEvent = event.originalEvent;
            var scrollTop = _this.scrollTop,
                scrollMax = _this.scrollHeight - $this.outerHeight(),
                delta = -origiEvent.wheelDelta;
            if(isNaN(delta)) {
                delta = origiEvent.deltaY;
            }
            var scrollUp = delta < 0;
            if((scrollUp && scrollTop <= 0) || (!scrollUp && scrollTop >= scrollMax)) {
                mousewheelPrevent(event);
            } else if(isMsIE) {
                // Fix Internet Explorer and emulate natural scrolling
                var animOpt = { duration:200, easing:'linear' };
                if(scrollUp && -delta > scrollTop) {
                    $this.stop(true).animate({ scrollTop:0 }, animOpt);
                    mousewheelPrevent(event);
                } else if(!scrollUp && delta > scrollMax - scrollTop) {
                    $this.stop(true).animate({ scrollTop:scrollMax }, animOpt);
                    mousewheelPrevent(event);
                }
            }
        });
    });
};

https://github.com/basselin/jquery-mousewheel-stop-propagation/blob/master/mousewheelStopPropagation.js

Use CSS to automatically add 'required field' asterisk to form inputs

This example puts an asterisk symbol in front of a label to denote that particular input as a required field. I set the CSS properties using % and em to makesure my webpage is responsive. You could use px or other absolute units if you want to.

_x000D_
_x000D_
#name {_x000D_
   display: inline-block;_x000D_
   margin-left: 40%;_x000D_
   font-size:25px;_x000D_
    _x000D_
}_x000D_
.nameinput{_x000D_
   margin-left: 10px;_x000D_
   font-size:90%;_x000D_
   width: 17em;_x000D_
   _x000D_
}_x000D_
_x000D_
.nameinput::placeholder {_x000D_
  font-size: 0.7em;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
#name p{_x000D_
   margin:0;_x000D_
   border:0;_x000D_
   padding:0;_x000D_
   display:inline-block;_x000D_
   font-size: 40%;_x000D_
   vertical-align: super;_x000D_
}
_x000D_
<label id="name" value="name">_x000D_
<p>*</p> _x000D_
Name:  <input class="nameinput" type="text" placeholder="Enter your name" required>_x000D_
</label>
_x000D_
_x000D_
_x000D_

Clone private git repo with dockerfile

There's no need to fiddle around with ssh configurations. Use a configuration file (not a Dockerfile) that contains environment variables, and have a shell script update your docker file at runtime. You keep tokens out of your Dockerfiles and you can clone over https (no need to generate or pass around ssh keys).

Go to Settings > Personal Access Tokens

  • Generate a personal access token with repo scope enabled.
  • Clone like this: git clone https://[email protected]/user-or-org/repo

Some commenters have noted that if you use a shared Dockerfile, this could expose your access key to other people on your project. While this may or may not be a concern for your specific use case, here are some ways you can deal with that:

  • Use a shell script to accept arguments which could contain your key as a variable. Replace a variable in your Dockerfile with sed or similar, i.e. calling the script with sh rundocker.sh MYTOKEN=foo which would replace on https://{{MY_TOKEN}}@github.com/user-or-org/repo. Note that you could also use a configuration file (in .yml or whatever format you want) to do the same thing but with environment variables.
  • Create a github user (and generate an access token for) for that project only

Java BigDecimal: Round to the nearest whole value

You want

round(new MathContext(0));  // or perhaps another math context with rounding mode HALF_UP

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

What is the difference between UNION and UNION ALL?

Suppose that you have two table Teacher & Student

Both have 4 Column with different Name like this

Teacher - ID(int), Name(varchar(50)), Address(varchar(50)), PositionID(varchar(50))

enter image description here

Student- ID(int), Name(varchar(50)), Email(varchar(50)), PositionID(int)

enter image description here

You can apply UNION or UNION ALL for those two table which have same number of columns. But they have different name or data type.

When you apply UNION operation on 2 tables, it neglects all duplicate entries(all columns value of row in a table is same of another table). Like this

SELECT * FROM Student
UNION
SELECT * FROM Teacher

the result will be

enter image description here

When you apply UNION ALL operation on 2 tables, it returns all entries with duplicate(if there is any difference between any column value of a row in 2 tables). Like this

SELECT * FROM Student
UNION ALL
SELECT * FROM Teacher

Output enter image description here

Performance:

Obviously UNION ALL performance is better that UNION as they do additional task to remove the duplicate values. You can check that from Execution Estimated Time by press ctrl+L at MSSQL

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

I had the exact same issue. The cause could be different but in my case, after trying several different things like changing the connection string on the Data Source setup, I found that this was the infamous 'double hop' issue (more info here).

To solve the problem, the following two options are available (as per one of the responses from the hyperlink):

  1.   Change the Report Server service to run under a domain user account, and register a SPN for the account.
    
  2.   Map Built-in accounts HTTP SPN to a Host SPN.
    

Using option 1, you need to select 'Windows' credentials instead of database credentials to overcome the double hop that happens while authentication.

windows credentials

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

How to install Selenium WebDriver on Mac OS

Mac already has Python and a package manager called easy_install, so open Terminal and type

sudo easy_install selenium

Add and remove attribute with jquery

Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

The solution is to cache a reference to the element:

$(document).ready(function(){
    // This reference remains available to the following functions
    // even when the ID is removed.
    var page_navigation = $("#page_navigation1");

    $("#add").click(function(){
        page_navigation.attr("id","page_navigation1");
    });     

    $("#remove").click(function(){
        page_navigation.removeAttr("id");
    });     
});

Is it possible to import a whole directory in sass using @import?

I create a file named __partials__.scss in the same directory of partials

|- __partials__.scss
|- /partials
   |- __header__.scss
   |- __viewport__.scss
   |- ....

In __partials__.scss, I wrote these:

@import "partials/header";
@import "partials/viewport";
@import "partials/footer";
@import "partials/forms";
....

So, when I want import the whole partials, just write @import "partials". If I want import any of them, I can also write @import "partials/header".

Remove Null Value from String array in java

Those are zero-length strings, not null. But if you want to remove them:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

Convert data.frame column format from character to factor

If you want to change all character variables in your data.frame to factors after you've already loaded your data, you can do it like this, to a data.frame called dat:

character_vars <- lapply(dat, class) == "character"
dat[, character_vars] <- lapply(dat[, character_vars], as.factor)

This creates a vector identifying which columns are of class character, then applies as.factor to those columns.

Sample data:

dat <- data.frame(var1 = c("a", "b"),
                  var2 = c("hi", "low"),
                  var3 = c(0, 0.1),
                  stringsAsFactors = FALSE
                  )

How to update an "array of objects" with Firestore?

Consider John Doe a document rather than a collection

Give it a collection of things and thingsSharedWithOthers

Then you can map and query John Doe's shared things in that parallel thingsSharedWithOthers collection.

proprietary: "John Doe"(a document)

things(collection of John's things documents)

thingsSharedWithOthers(collection of John's things being shared with others):
[thingId]:
    {who: "[email protected]", when:timestamp}
    {who: "[email protected]", when:timestamp}

then set thingsSharedWithOthers

firebase.firestore()
.collection('thingsSharedWithOthers')
.set(
{ [thingId]:{ who: "[email protected]", when: new Date() } },
{ merge: true }
)

How do you install GLUT and OpenGL in Visual Studio 2012?

OpenGL should be present already - it will probably be Freeglut / GLUT that is missing.

GLUT is very dated now and not actively supported - so you should certainly be using Freeglut instead. You won't have to change your code at all, and a few additional features become available.

You'll find pre-packaged sets of files from here: http://freeglut.sourceforge.net/index.php#download If you don't see the "lib" folder, it's because you didn't download the pre-packaged set. "Martin Payne's Windows binaries" is posted at above link and works on Windows 8.1 with Visual Studio 2013 at the time of this writing.

When you download these you'll find that the Freeglut folder has three subfolders: - bin folder: this contains the dll files for runtime - include: the header files for compilation - lib: contains library files for compilation/linking

Installation instructions usually suggest moving these files into the visual studio folder and the Windows system folder: It is best to avoid doing this as it makes your project less portable, and makes it much more difficult if you ever need to change which version of the library you are using (old projects might suddenly stop working, etc.)

Instead (apologies for any inconsistencies, I'm basing these instructions on VS2010)... - put the freeglut folder somewhere else, e.g. C:\dev - Open your project in Visual Studio - Open project properties - There should be a tab for VC++ Directories, here you should add the appropriate include and lib folders, e.g.: C:\dev\freeglut\include and C:\dev\freeglut\lib - (Almost) Final step is to ensure that the opengl lib file is actually linked during compilation. Still in project properties, expand the linker menu, and open the input tab. For Additional Dependencies add opengl32.lib (you would assume that this would be linked automatically just by adding the include GL/gl.h to your project, but for some reason this doesn't seem to be the case)

At this stage your project should compile OK. To actually run it, you also need to copy the freeglut.dll files into your project folder

Finding duplicate rows in SQL Server

select orgname, count(*) as dupes, id 
from organizations
where orgname in (
    select orgname
    from organizations
    group by orgname
    having (count(*) > 1)
)
group by orgname, id

c# razor url parameter from view

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

Counting null and non-null values in a single query

if its mysql, you can try something like this.

select 
   (select count(*) from TABLENAME WHERE a = 'null') as total_null, 
   (select count(*) from TABLENAME WHERE a != 'null') as total_not_null
FROM TABLENAME

bool to int conversion

There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.

Concatenate two char* strings in a C program

strcat attempts to append the second parameter to the first. This won't work since you are assigning implicitly sized constant strings.

If all you want to do is print two strings out

printf("%s%s",str1,str2);

Would do.

You could do something like

char *str1 = calloc(sizeof("SSSS")+sizeof("KKKK")+1,sizeof *str1);
strcpy(str1,"SSSS");
strcat(str1,str2);

to create a concatenated string; however strongly consider using strncat/strncpy instead. And read the man pages carefully for the above. (oh and don't forget to free str1 at the end).

pip: no module named _internal

For completeness, I just encountered this problem with "Ubuntu latest" ... v18.04 ... and fixed it in this way:

python3 -m pip install --upgrade pip

(Notice that it was necessary to specify python3 since this references Python 3.6.9. The python command on the same system references Python 2.7.17. Since this is apparently a system-wide installation it encountered a ["not sudo" ...] permission error, but it didn't matter because it was the wrong thing to do anyway. I was encountering the problem with pip3.)

How can I find where I will be redirected using cURL?

Lot's of regex here, despite the fact i really like them this way might be more stable to me:

$resultCurl=curl_exec($curl); //get curl result
//Optional line if you want to store the http status code
$headerHttpCode=curl_getinfo($curl,CURLINFO_HTTP_CODE);

//let's use dom and xpath
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($resultCurl, LIBXML_HTML_NODEFDTD);
libxml_use_internal_errors(false);
$xpath = new \DOMXPath($dom);
$head=$xpath->query("/html/body/p/a/@href");

$newUrl=$head[0]->nodeValue;

The location part is a link in the HTML sent by apache. So Xpath is perfect to recover it.

How to determine whether a substring is in a different string

foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
    # do something

(By the way - try to not name a variable string, since there's a Python standard library with the same name. You might confuse people if you do that in a large project, so avoiding collisions like that is a good habit to get into.)

bower command not found

This turned out to NOT be a bower problem, though it showed up for me with bower.

It seems to be a node-which problem. If a file is in the path, but has the setuid/setgid bit set, which will not find it.

Here is a files with the s bit set: (unix 'which' will find it with no problems).

ls -al /usr/local/bin -rwxrwsr-- 110 root nmt 5535636 Jul 17 2012 git

Here is a node-which attempt:

> which.sync('git')
Error: not found: git

I change the permissions (chomd 755 git). Now node-which can find it.

> which.sync('git')
'/usr/local/bin/git'

Hope this helps.

Switch in Laravel 5 - Blade

Updated 2020 Answer

Since Laravel 5.5 the @switch is built into the Blade. Use it as shown below.

@switch($login_error)
    @case(1)
        <span> `E-mail` input is empty!</span>
        @break

    @case(2)
        <span>`Password` input is empty!</span>
        @break

    @default
        <span>Something went wrong, please try again</span>
@endswitch

Older Answer

Unfortunately Laravel Blade does not have switch statement. You can use Laravel if else approach or use use plain PHP switch. You can use plain PHP in blade templates like in any other PHP application. Starting from Laravel 5.2 and up use @php statement.

Option 1:

@if ($login_error == 1)
    `E-mail` input is empty!
@elseif ($login_error == 2)
    `Password` input is empty!
@endif

How to align content of a div to the bottom

The modern way to do it would be using flexbox. See the example below. You don't even need to wrap Some text... into any HTML tag, since text directly contained in a flex container is wrapped in an anonymous flex item.

_x000D_
_x000D_
header {_x000D_
  border: 1px solid blue;_x000D_
  height: 150px;_x000D_
  display: flex;                   /* defines flexbox */_x000D_
  flex-direction: column;          /* top to bottom */_x000D_
  justify-content: space-between;  /* first item at start, last at end */_x000D_
}_x000D_
h1 {_x000D_
  margin: 0;_x000D_
}
_x000D_
<header>_x000D_
  <h1>Header title</h1>_x000D_
  Some text aligns to the bottom_x000D_
</header>
_x000D_
_x000D_
_x000D_

If there is only some text and you want to align vertically to the bottom of the container.

_x000D_
_x000D_
section {_x000D_
  border: 1px solid blue;_x000D_
  height: 150px;_x000D_
  display: flex;                   /* defines flexbox */_x000D_
  align-items: flex-end;           /* bottom of the box */_x000D_
}
_x000D_
<section>Some text aligns to the bottom</section>
_x000D_
_x000D_
_x000D_

Custom format for time command

From the man page for time:

  1. There may be a shell built-in called time, avoid this by specifying /usr/bin/time
  2. You can provide a format string and one of the format options is elapsed time - e.g. %E

    /usr/bin/time -f'%E' $CMD

Example:

$ /usr/bin/time -f'%E' ls /tmp/mako/
res.py  res.pyc
0:00.01

Assigning strings to arrays of characters

Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

There is another solution if above didn't help, add:

noload => res_pjsip.so to /etc/asterisk/modules.conf

Bootstrap 3 Align Text To Bottom of Div

You can do this:

CSS:

#container {
    height:175px;
}

#container h3{
    position:absolute;
    bottom:0;
    left:0;
}

Then in HTML:

<div class="row">
    <div class="col-sm-6">
        <img src="//placehold.it/600x300" alt="Logo" />
    </div>
    <div id="container" class="col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

EDIT: add the <

How to get everything after last slash in a URL?

One more (idio(ma)tic) way:

URL.split("/")[-1]

How to convert R Markdown to PDF?

If you don't want to install anything you can output html. Then open the html file - it should open in a browser window, then right click to print. In the print window, select "save as pdf" in the bottom right hand corner if you're on a Mac. Voila!

How to easily resize/optimize an image size with iOS?

I developed an ultimate solution for image scaling in Swift.

You can use it to resize image to fill, aspect fill or aspect fit specified size.

You can align image to center or any of four edges and four corners.

And also you can trim extra space which is added if aspect ratios of original image and target size are not equal.

enum UIImageAlignment {
    case Center, Left, Top, Right, Bottom, TopLeft, BottomRight, BottomLeft, TopRight
}

enum UIImageScaleMode {
    case Fill,
    AspectFill,
    AspectFit(UIImageAlignment)
}

extension UIImage {
    func scaleImage(width width: CGFloat? = nil, height: CGFloat? = nil, scaleMode: UIImageScaleMode = .AspectFit(.Center), trim: Bool = false) -> UIImage {
        let preWidthScale = width.map { $0 / size.width }
        let preHeightScale = height.map { $0 / size.height }
        var widthScale = preWidthScale ?? preHeightScale ?? 1
        var heightScale = preHeightScale ?? widthScale
        switch scaleMode {
        case .AspectFit(_):
            let scale = min(widthScale, heightScale)
            widthScale = scale
            heightScale = scale
        case .AspectFill:
            let scale = max(widthScale, heightScale)
            widthScale = scale
            heightScale = scale
        default:
            break
        }
        let newWidth = size.width * widthScale
        let newHeight = size.height * heightScale
        let canvasWidth = trim ? newWidth : (width ?? newWidth)
        let canvasHeight = trim ? newHeight : (height ?? newHeight)
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(canvasWidth, canvasHeight), false, 0)

        var originX: CGFloat = 0
        var originY: CGFloat = 0
        switch scaleMode {
        case .AspectFit(let alignment):
            switch alignment {
            case .Center:
                originX = (canvasWidth - newWidth) / 2
                originY = (canvasHeight - newHeight) / 2
            case .Top:
                originX = (canvasWidth - newWidth) / 2
            case .Left:
                originY = (canvasHeight - newHeight) / 2
            case .Bottom:
                originX = (canvasWidth - newWidth) / 2
                originY = canvasHeight - newHeight
            case .Right:
                originX = canvasWidth - newWidth
                originY = (canvasHeight - newHeight) / 2
            case .TopLeft:
                break
            case .TopRight:
                originX = canvasWidth - newWidth
            case .BottomLeft:
                originY = canvasHeight - newHeight
            case .BottomRight:
                originX = canvasWidth - newWidth
                originY = canvasHeight - newHeight
            }
        default:
            break
        }
        self.drawInRect(CGRectMake(originX, originY, newWidth, newHeight))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

There are examples of applying this solution below.

Gray rectangle is target site image will be resized to. Blue circles in light blue rectangle is the image (I used circles because it's easy to see when it's scaled without preserving aspect). Light orange color marks areas that will be trimmed if you pass trim: true.

Aspect fit before and after scaling:

Aspect fit 1 (before) Aspect fit 1 (after)

Another example of aspect fit:

Aspect fit 2 (before) Aspect fit 2 (after)

Aspect fit with top alignment:

Aspect fit 3 (before) Aspect fit 3 (after)

Aspect fill:

Aspect fill (before) Aspect fill (after)

Fill:

Fill (before) Fill (after)

I used upscaling in my examples because it's simpler to demonstrate but solution also works for downscaling as in question.

For JPEG compression you should use this :

let compressionQuality: CGFloat = 0.75 // adjust to change JPEG quality
if let data = UIImageJPEGRepresentation(image, compressionQuality) {
  // ...
}

You can check out my gist with Xcode playground.

Remove row lines in twitter bootstrap

In Bootstrap 3 I've added a table-no-border class

.table-no-border>thead>tr>th, 
.table-no-border>tbody>tr>th, 
.table-no-border>tfoot>tr>th, 
.table-no-border>thead>tr>td, 
.table-no-border>tbody>tr>td, 
.table-no-border>tfoot>tr>td {
  border-top: none; 
}

Why is division in Ruby returning an integer instead of decimal value?

It’s doing integer division. You can use to_f to force things into floating-point mode:

9.to_f / 5  #=> 1.8
9 / 5.to_f  #=> 1.8

This also works if your values are variables instead of literals. Converting one value to a float is sufficient to coerce the whole expression to floating point arithmetic.

Make an HTTP request with android

The most simple way is using the Android lib called Volley

Volley offers the following benefits:

Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.

You can send a http/https request as simple as this:

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="http://www.yourapi.com";
        JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (null != response) {
                         try {
                             //handle your response
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                    }
                }
            }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);

In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.

How do I return the SQL data types from my query?

This will give you everything column property related.

SELECT * INTO TMP1
FROM ( SELECT TOP 1 /* rest of your query expression here */ );

SELECT o.name AS obj_name, TYPE_NAME(c.user_type_id) AS type_name, c.*  
FROM sys.objects AS o   
JOIN sys.columns AS c  ON o.object_id = c.object_id  
WHERE o.name = 'TMP1';

DROP TABLE TMP1;

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

One of the problems that can cause this is when you forget to put the / character in the WebServlet annotation @WebServlet("/example") @WebServlet("example") I hope it works, it worked for me.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Get JavaScript object from array of objects by value of property

OK, there are few ways to do that, but let's start with the simplest one and latest approach to do this, this function is called find().

Just be careful when you using find to as even IE11 dosn't support it, so it needs to be transpiled...

so you have this object as you said:

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

and you can write a function and get it like this:

function filterValue(obj, key, value) {
  return obj.find(function(v){ return v[key] === value});
}

and use the function like this:

filterValue(jsObjects, "b", 6); //{a: 5, b: 6}

Also in ES6 for even shortened version:

const filterValue = (obj, key, value)=> obj.find(v => v[key] === value);

This method only return the first value which match..., for better result and browser support, you can use filter:

const filterValue = (obj, key, value)=> obj.filter(v => v[key] === value);

and we will return [{a: 5, b: 6}]...

This method will return an array instead...

You simpley use for loop as well, create a function like this:

function filteredArray(arr, key, value) {
  const newArray = [];
  for(i=0, l=arr.length; i<l; i++) {
    if(arr[i][key] === value) {
      newArray.push(arr[i]);
    }
  }
 return newArray;
}

and call it like this:

filteredArray(jsObjects, "b", 6); //[{a: 5, b: 6}]

What does the "+" (plus sign) CSS selector mean?

See adjacent selectors on W3.org.

In this case, the selector means that the style applies only to paragraphs directly following another paragraph.

A plain p selector would apply the style to every paragraph in the page.


This will only work on IE7 or above. In IE6, the style will not be applied to any elements. This also goes for the > combinator, by the way.

See also Microsoft's overview for CSS compatibility in Internet Explorer.

Get scroll position using jquery

Use scrollTop() to get or set the scroll position.

How to expand 'select' option width after the user wants to select an option

I fixed my problem with the following code:

_x000D_
_x000D_
<div style="width: 180px; overflow: hidden;">_x000D_
   <select style="width: auto;" name="abc" id="10">_x000D_
     <option value="-1">AAAAAAAAAAA</option>_x000D_
     <option value="123">123</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!

How to suspend/resume a process in Windows?

You can't do it from the command line, you have to write some code (I assume you're not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).

Hard Way

First get all the threads of a given process then call the SuspendThread function to stop each one (and ResumeThread to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.

void suspend(DWORD processId)
{
    HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    THREADENTRY32 threadEntry; 
    threadEntry.dwSize = sizeof(THREADENTRY32);

    Thread32First(hThreadSnapshot, &threadEntry);

    do
    {
        if (threadEntry.th32OwnerProcessID == processId)
        {
            HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
                threadEntry.th32ThreadID);

            SuspendThread(hThread);
            CloseHandle(hThread);
        }
    } while (Thread32Next(hThreadSnapshot, &threadEntry));

    CloseHandle(hThreadSnapshot);
}

Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it's easy to cause a dead-lock because of suspend/resume order. For single threaded applications it's prolix but it works.

Undocumented way

Starting from Windows XP there is the NtSuspendProcess but it's undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).

typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);

void suspend(DWORD processId)
{
    HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId));

    NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(
        GetModuleHandle("ntdll"), "NtSuspendProcess");

    pfnNtSuspendProcess(processHandle);
    CloseHandle(processHandle);
}

"Debugger" Way

To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess function. It'll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop.

This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you'll make a command line application you'll need to keep its instance running to keep the process suspended (or it'll be terminated). See the Remarks section on MSDN for details.

void suspend(DWORD processId)
{
    DebugActiveProcess(processId);
}

From Command Line

As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:

Invoke-WindowsApi "kernel32" ([bool]) "DebugActiveProcess" @([int]) @(process_id_here)

Of course if you need it often you can make an alias for that.

When to encode space to plus (+) or %20?

What's the difference: See other answers.

When use + instead of %20? Use + if, for some reason, you want to make the URL query string (?.....) or hash fragment (#....) more readable. Example: You can actually read this:

https://www.google.se/#q=google+doesn%27t+encode+:+and+uses+%2B+instead+of+spaces (%2B = +)

But the following is a lot harder to read: (at least to me)

https://www.google.se/#q=google%20doesn%27t%20oops%20:%20%20this%20text%20%2B%20is%20different%20spaces

I would think + is unlikely to break anything, since Google uses + (see the 1st link above) and they've probably thought about this. I'm going to use + myself just because readable + Google thinks it's OK.

Using SELECT result in another SELECT

What you are looking for is a query with WITH clause, if your dbms supports it. Then

WITH NewScores AS (
    SELECT * 
    FROM Score  
    WHERE InsertedDate >= DATEADD(mm, -3, GETDATE())
)
SELECT 
<and the rest of your query>
;

Note that there is no ; in the first half. HTH.

Java Serializable Object to Byte Array

The best way to do it is to use SerializationUtils from Apache Commons Lang.

To serialize:

byte[] data = SerializationUtils.serialize(yourObject);

To deserialize:

YourObject yourObject = SerializationUtils.deserialize(data)

As mentioned, this requires Commons Lang library. It can be imported using Gradle:

compile 'org.apache.commons:commons-lang3:3.5'

Maven:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Jar file

And more ways mentioned here

Alternatively, the whole collection can be imported. Refer this link

Android - shadow on text?

You can do both in code and XML. Only 4 basic things to be set.

  1. shadow color
  2. Shadow Dx - it specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right
  3. shadow Dy - it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.
  4. shadow radius - specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. Else otherwise.

e.g.

    android:shadowColor="@color/text_shadow_color"
    android:shadowDx="-2"
    android:shadowDy="2"
    android:shadowRadius="0.01"

This draws a prominent shadow on left-lower side of text. In code, you can add something like this;

    TextView item = new TextView(getApplicationContext());
    item.setText(R.string.text);
    item.setTextColor(getResources().getColor(R.color.general_text_color));
    item.setShadowLayer(0.01f, -2, 2,   getResources().getColor(R.color.text_shadow_color));

Java Desktop application: SWT vs. Swing

Interesting question. I don't know SWT too well to brag about it (unlike Swing and AWT) but here's the comparison done on SWT/Swing/AWT.

http://www.developer.com/java/other/article.php/10936_2179061_2/Swing-and-SWT-A-Tale-of-Two-Java-GUI-Libraries.htm

And here's the site where you can get tutorial on basically anything on SWT (http://www.java2s.com/Tutorial/Java/0280__SWT/Catalog0280__SWT.htm)

Hope you make a right decision (if there are right decisions in coding)... :-)

Pandas DataFrame Groupby two columns and get counts

Inserting data into a pandas dataframe and providing column name.

import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df)   #printing dataframe.

This is our printed data:

enter image description here

For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.

Like this:

df['COUNTER'] =1       #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)

OUTPUT:

enter image description here

Converting .NET DateTime to JSON

the conversion from 1970,1,1 needs the double rounded to zero decimal places i thinks

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);

on the client side i use

new Date(+data.replace(/\D/g, ''));

Can I install Python 3.x and 2.x on the same Windows computer?

I'm using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

Name them pythonX.Y.bat and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to pythonX.bat. (E.g. copy python2.6.bat python2.bat.) Then you can use python2 file.py from anywhere.

However, this doesn't help or even affect the Windows file association situation. For that you'll need a launcher program that reads the #! line, and then associate that with .py and .pyw files.

must appear in the GROUP BY clause or be used in an aggregate function

The problem with specifying non-grouped and non-aggregate fields in group by selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min and max are exceptions).

However, there is a workaround: make the required field aggregated as well. In posgres, this should work:

SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;

Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

ensure you have...

Trusted_Connection=false;

in your connection String

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

How to fill a datatable with List<T>

Try this

static DataTable ConvertToDatatable(List<Item> list)
{
    DataTable dt = new DataTable();

    dt.Columns.Add("Name");
    dt.Columns.Add("Price");
    dt.Columns.Add("URL");
    foreach (var item in list)
    {
        var row = dt.NewRow();

        row["Name"] = item.Name;
        row["Price"] = Convert.ToString(item.Price);
        row["URL"] = item.URL;

        dt.Rows.Add(row);
    }

    return dt;
}

How to add "active" class to Html.ActionLink in ASP.NET MVC

I created an HtmlHelper extension that adds an ActiveActionLink method for those of you who want to add the "active" class to the link itself rather than the <li> surrounding the link.


public static class LinkExtensions
{
    public static MvcHtmlString ActiveActionLink(this HtmlHelper html, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
    {
        return ActiveActionLink(html, linkText, actionName, controllerName, new RouteValueDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString ActiveActionLink(this HtmlHelper html, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
    {
        const string activeClassName = "active";

        var routeData = html.ViewContext.RouteData;

        var routeAction = (string)routeData.Values["action"];
        var routeController = (string)routeData.Values["controller"];

        var active = controllerName.Equals(routeController) && actionName.Equals(routeAction);

        if (active)
        {
            var @class = (string)htmlAttributes["class"];

            htmlAttributes["class"] = string.IsNullOrEmpty(@class)
                ? activeClassName
                : @class + " active";
        }

        var link = html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);

        return link;
    }
}

Usage is as follows:

@Html.ActiveActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-item nav-link" })

Accessing elements by type in javascript

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');

Which characters need to be escaped when using Bash?

I noticed that bash automatically escapes some characters when using auto-complete.

For example, if you have a directory named dir:A, bash will auto-complete to dir\:A

Using this, I runned some experiments using characters of the ASCII table and derived the following lists:

Characters that bash escapes on auto-complete: (includes space)

 !"$&'()*,:;<=>?@[\]^`{|}

Characters that bash does not escape:

#%+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~

(I excluded /, as it cannot be used in directory names)

How to set up Automapper in ASP.NET Core

In my Startup.cs (Core 2.2, Automapper 8.1.1)

services.AddAutoMapper(new Type[] { typeof(DAL.MapperProfile) });            

In my data access project

namespace DAL
{
    public class MapperProfile : Profile
    {
        // place holder for AddAutoMapper (to bring in the DAL assembly)
    }
}

In my model definition

namespace DAL.Models
{
    public class PositionProfile : Profile
    {
        public PositionProfile()
        {
            CreateMap<Position, PositionDto_v1>();
        }
    }

    public class Position
    {
        ...
    }

Java character array initializer

Instead of above way u can achieve the solution simply by following method..

public static void main(String args[]) {
    String ini = "Hi there";
    for (int i = 0; i < ini.length(); i++) {
        System.out.print(" " + ini.charAt(i));
    }
}

Set initial value in datepicker with jquery?

Use setDate

.datepicker( "setDate" , date )

Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

How to generate unique IDs for form labels in React?

I create a uniqueId generator module (Typescript):

const uniqueId = ((): ((prefix: string) => string) => {
  let counter = 0;
  return (prefix: string): string => `${prefix}${++counter}`;
})();

export default uniqueId;

And use top module to generate unique ids:

import React, { FC, ReactElement } from 'react'
import uniqueId from '../../modules/uniqueId';

const Component: FC = (): ReactElement => {
  const [inputId] = useState(uniqueId('input-'));
  return (
    <label htmlFor={inputId}>
      <span>text</span>
      <input id={inputId} type="text" />
    </label>
  );
};     

How to choose multiple files using File Upload Control?

        aspx code

            <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
            <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />
            <hr />
            <asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />


    Code Behind:

protected void UploadMultipleFiles(object sender, EventArgs e)
{
     foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
     {
          string fileName = Path.GetFileName(postedFile.FileName);
          postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
     }
     lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}

How to check for a Null value in VB.NET

This is the exact answer. Try this code:

If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

Normal arguments vs. keyword arguments

I was looking for an example that had default kwargs using type annotation:

def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
     return ' '.join([a, b, c, str(kwargs)])

example:

>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}

echo key and value of an array without and with loop

Without a loop, just for the kicks of it...


You can either convert the array to a non-associative one, by doing:

$page = array_values($page);

And then acessing each element by it's zero-based index:

echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'

Or you can use a slightly more complicated version:

$value = array_slice($page, 0, 1);

echo key($value); // Home
echo current($value); // index.html

$value = array_slice($page, 1, 1);

echo key($value); // Service
echo current($value); // services.html

pod install -bash: pod: command not found

This solution worked for me. Make sure to not miss the last command (export PATH=$PATH:$HOME/Software/ruby/bin).

See This.

Div Height in Percentage

There is the semicolon missing (;) after the "50%"

but you should also notice that the percentage of your div is connected to the div that contains it.

for instance:

<div id="wrapper">
  <div class="container">
   adsf
  </div>
</div>

#wrapper {
  height:100px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.

if you have:

adsf

#wrapper {
  height:400px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

then you .container will be 200px. 50% of the wrapper.

So you may want to look at the divs "wrapping" your ".container"...

Error 500: Premature end of script headers

The "Premature end of script headers" error message is probably the most loathed and common error message you'll find. What the error actually means, is that the script stopped for whatever reason before it returned any output to the web server. A common cause of this for script writers is to fail to set a content type before printing output code. In Perl for example, before printing any HTML it is necessary to tell the Perl script to set the content type to text/html, this is done by sending a header, like so:

print "Content-type: text/html\n\n";

(source; http://htmlfixit.com/cgi-tutes/tutorial_Common_Web_dev_error_messages_and_what_they_mean.php#premature

How to auto-size an iFrame?

My solution, (using jquery):

<iframe id="Iframe1" class="tabFrame" width="100%" height="100%" scrolling="no" src="http://samedomain" frameborder="0" >
</iframe>  
<script type="text/javascript">
    $(function () {

        $('.tabFrame').load(function () {
            var iframeContentWindow = this.contentWindow;
            var height = iframeContentWindow.$(document).height();
            this.style.height = height + 'px';
        });
    });
</script>

How do I rename the extension for a bunch of files?

The command mmv seems to do this task very efficiently on a huge number of files (tens of thousands in a second). For example, to rename all .xml files to .html files, use this:

mmv ";*.xml" "#1#2.html"

the ; will match the path, the * will match the filename, and these are referred to as #1 and #2 in the replacement name.

Answers based on exec or pipes were either too slow or failed on a very large number of files.

How do I activate a specific workbook and a specific sheet?

The code that worked for me is:

ThisWorkbook.Sheets("sheetName").Activate

Looping over arrays, printing both index and value

Simple one line trick for dumping array

I've added one value with spaces:

foo=()
foo[12]="bar"
foo[42]="foo bar baz"
foo[35]="baz"

I, for quickly dump arrays or associative arrays I use

This one line command:

paste <(printf "%s\n" "${!foo[@]}") <(printf "%s\n" "${foo[@]}")

Will render:

12  bar
35  baz
42  foo bar baz

Explained

  • printf "%s\n" "${!foo[@]}" will print all keys separated by a newline,
  • printf "%s\n" "${foo[@]}" will print all values separated by a newline,
  • paste <(cmd1) <(cmd2) will merge output of cmd1 and cmd2 line by line.

Tunning

This could be tunned by -d switch:

paste -d : <(printf "%s\n" "${!foo[@]}") <(printf "%s\n" "${foo[@]}")
12:bar
35:baz
42:foo bar baz

or even:

paste -d = <(printf "foo[%s]\n" "${!foo[@]}") <(printf "'%s'\n" "${foo[@]}")
foo[12]='bar'
foo[35]='baz'
foo[42]='foo bar baz'

Associative array will work same:

declare -A bar=([foo]=snoopy [bar]=nice [baz]=cool [foo bar]='Hello world!')
paste -d = <(printf "bar[%s]\n" "${!bar[@]}") <(printf '"%s"\n' "${bar[@]}")
bar[foo bar]="Hello world!"
bar[foo]="snoopy"
bar[bar]="nice"
bar[baz]="cool"

Issue with newlines or special chars

Unfortunely, there is at least one condition making this not work anymore: when variable do contain newline:

foo[17]=$'There is one\nnewline'

Command paste will merge line-by-line, so output will become wrong:

paste -d = <(printf "foo[%s]\n" "${!foo[@]}") <(printf "'%s'\n" "${foo[@]}")
foo[12]='bar'
foo[17]='There is one
foo[35]=newline'
foo[42]='baz'
='foo bar baz'

For this work, you could use %q instead of %s in second printf command (and whipe quoting):

paste -d = <(printf "foo[%s]\n" "${!foo[@]}") <(printf "%q\n" "${foo[@]}")

Will render perfect:

foo[12]=bar
foo[17]=$'There is one\nnewline'
foo[35]=baz
foo[42]=foo\ bar\ baz

From man bash:

          %q     causes  printf  to output the corresponding argument in a
                 format that can be reused as shell input.

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

GitHub relative link in Markdown file

You can link to file, but not to folders, and keep in mind that, Github will add /blob/master/ before your relative link(and folders lacks that part so they cannot be linked, neither with HTML <a> tags or Markdown link).

So, if we have a file in myrepo/src/Test.java, it will have a url like:

https://github.com/WesternGun/myrepo/blob/master/src/Test.java

And to link it in the readme file, we can use:

[This is a link](src/Test.java)

or: <a href="src/Test.java">This is a link</a>.

(I guess, master represents the master branch and it differs when the file is in another branch.)

Sequelize.js delete query?

  1. the best way to delete a record is to find it firstly (if exist in data base in the same time you want to delete it)
  2. watch this code
const StudentSequelize = require("../models/studientSequelize");
const StudentWork = StudentSequelize.Student;

const id = req.params.id;
    StudentWork.findByPk(id) // here i fetch result by ID sequelize V. 5
    .then( resultToDelete=>{
        resultToDelete.destroy(id); // when i find the result i deleted it by destroy function
    })
    .then( resultAfterDestroy=>{
        console.log("Deleted :",resultAfterDestroy);
    })
    .catch(err=> console.log(err));

Default instance name of SQL Server Express

in my case the right server name was the name of my computer. for example John-PC, or somth

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

How can I get date in application run by node.js?

You do that as you would in a browser:

_x000D_
_x000D_
    var datetime = new Date();_x000D_
    console.log(datetime);
_x000D_
_x000D_
_x000D_

How to build query string with Javascript

These answers are very helpful, but i want to add another answer, that may help you build full URL. This can help you concat base url, path, hash and parameters.

var url = buildUrl('http://mywebsite.com', {
        path: 'about',
        hash: 'contact',
        queryParams: {
            'var1': 'value',
            'var2': 'value2',
            'arr[]' : 'foo'
        }
    });
    console.log(url);

You can download via npm https://www.npmjs.com/package/build-url

Demo:

_x000D_
_x000D_
;(function () {_x000D_
  'use strict';_x000D_
_x000D_
  var root = this;_x000D_
  var previousBuildUrl = root.buildUrl;_x000D_
_x000D_
  var buildUrl = function (url, options) {_x000D_
    var queryString = [];_x000D_
    var key;_x000D_
    var builtUrl;_x000D_
    var caseChange; _x000D_
    _x000D_
    // 'lowerCase' parameter default = false,  _x000D_
    if (options && options.lowerCase) {_x000D_
        caseChange = !!options.lowerCase;_x000D_
    } else {_x000D_
        caseChange = false;_x000D_
    }_x000D_
_x000D_
    if (url === null) {_x000D_
      builtUrl = '';_x000D_
    } else if (typeof(url) === 'object') {_x000D_
      builtUrl = '';_x000D_
      options = url;_x000D_
    } else {_x000D_
      builtUrl = url;_x000D_
    }_x000D_
_x000D_
    if(builtUrl && builtUrl[builtUrl.length - 1] === '/') {_x000D_
      builtUrl = builtUrl.slice(0, -1);_x000D_
    } _x000D_
_x000D_
    if (options) {_x000D_
      if (options.path) {_x000D_
          var localVar = String(options.path).trim(); _x000D_
          if (caseChange) {_x000D_
            localVar = localVar.toLowerCase();_x000D_
          }_x000D_
          if (localVar.indexOf('/') === 0) {_x000D_
              builtUrl += localVar;_x000D_
          } else {_x000D_
            builtUrl += '/' + localVar;_x000D_
          }_x000D_
      }_x000D_
_x000D_
      if (options.queryParams) {_x000D_
        for (key in options.queryParams) {_x000D_
          if (options.queryParams.hasOwnProperty(key) && options.queryParams[key] !== void 0) {_x000D_
            var encodedParam;_x000D_
            if (options.disableCSV && Array.isArray(options.queryParams[key]) && options.queryParams[key].length) {_x000D_
              for(var i = 0; i < options.queryParams[key].length; i++) {_x000D_
                encodedParam = encodeURIComponent(String(options.queryParams[key][i]).trim());_x000D_
                queryString.push(key + '=' + encodedParam);_x000D_
              }_x000D_
            } else {              _x000D_
              if (caseChange) {_x000D_
                encodedParam = encodeURIComponent(String(options.queryParams[key]).trim().toLowerCase());_x000D_
              }_x000D_
              else {_x000D_
                encodedParam = encodeURIComponent(String(options.queryParams[key]).trim());_x000D_
              }_x000D_
              queryString.push(key + '=' + encodedParam);_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
        builtUrl += '?' + queryString.join('&');_x000D_
      }_x000D_
_x000D_
      if (options.hash) {_x000D_
        if(caseChange)_x000D_
            builtUrl += '#' + String(options.hash).trim().toLowerCase();_x000D_
        else_x000D_
            builtUrl += '#' + String(options.hash).trim();_x000D_
      }_x000D_
    } _x000D_
    return builtUrl;_x000D_
  };_x000D_
_x000D_
  buildUrl.noConflict = function () {_x000D_
    root.buildUrl = previousBuildUrl;_x000D_
    return buildUrl;_x000D_
  };_x000D_
_x000D_
  if (typeof(exports) !== 'undefined') {_x000D_
    if (typeof(module) !== 'undefined' && module.exports) {_x000D_
      exports = module.exports = buildUrl;_x000D_
    }_x000D_
    exports.buildUrl = buildUrl;_x000D_
  } else {_x000D_
    root.buildUrl = buildUrl;_x000D_
  }_x000D_
}).call(this);_x000D_
_x000D_
_x000D_
var url = buildUrl('http://mywebsite.com', {_x000D_
  path: 'about',_x000D_
  hash: 'contact',_x000D_
  queryParams: {_x000D_
   'var1': 'value',_x000D_
   'var2': 'value2',_x000D_
   'arr[]' : 'foo'_x000D_
  }_x000D_
 });_x000D_
 console.log(url);
_x000D_
_x000D_
_x000D_

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

You don't need to learn JPA. You can use my easy-criteria for JPA2 (https://sourceforge.net/projects/easy-criteria/files/). Here is the example

CriteriaComposer<Pet> petCriteria CriteriaComposer.from(Pet.class).
where(Pet_.type, EQUAL, "Cat").join(Pet_.owner).where(Ower_.name,EQUAL, "foo");

List<Pet> result = CriteriaProcessor.findAllEntiry(petCriteria);

OR

List<Tuple> result =  CriteriaProcessor.findAllTuple(petCriteria);

Read a zipped file as a pandas DataFrame

I think you want to open the ZipFile, which returns a file-like object, rather than read:

In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
BUSINESSIMPROVEMENTDISTRICT    3613  non-null values
dtypes: float64(4), int64(1), object(10)

Is there a foreach loop in Go?

Go has a foreach-like syntax. It supports arrays/slices, maps and channels.

Iterate over array or slice:

// index and value
for i, v := range slice {}

// index only
for i := range slice {}

// value only
for _, v := range slice {}

Iterate over a map:

// key and value
for key, value := range theMap {}

// key only
for key := range theMap {}

// value only
for _, value := range theMap {}

Iterate over a channel:

for v := range theChan {}

Iterating over a channel is equivalent to receiving from a channel until it is closed:

for {
    v, ok := <-theChan
    if !ok {
        break
    }
}

JPA OneToMany not deleting child

In addition to cletus' answer, JPA 2.0, final since december 2010, introduces an orphanRemoval attribute on @OneToMany annotations. For more details see this blog entry.

Note that since the spec is relatively new, not all JPA 1 provider have a final JPA 2 implementation. For example, the Hibernate 3.5.0-Beta-2 release does not yet support this attribute.

Is there a better way to compare dictionary values

Uhm, you are describing dict1 == dict2 ( check if boths dicts are equal )

But what your code does is all( dict1[k]==dict2[k] for k in dict1 ) ( check if all entries in dict1 are equal to those in dict2 )

Case insensitive 'Contains(string)'

public static class StringExtension
{
    #region Public Methods

    public static bool ExContains(this string fullText, string value)
    {
        return ExIndexOf(fullText, value) > -1;
    }

    public static bool ExEquals(this string text, string textToCompare)
    {
        return text.Equals(textToCompare, StringComparison.OrdinalIgnoreCase);
    }

    public static bool ExHasAllEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index]) == false) return false;
        return true;
    }

    public static bool ExHasEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index])) return true;
        return false;
    }

    public static bool ExHasNoEquals(this string text, params string[] textArgs)
    {
        return ExHasEquals(text, textArgs) == false;
    }

    public static bool ExHasNotAllEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index])) return false;
        return true;
    }

    /// <summary>
    /// Reports the zero-based index of the first occurrence of the specified string
    /// in the current System.String object using StringComparison.InvariantCultureIgnoreCase.
    /// A parameter specifies the type of search to use for the specified string.
    /// </summary>
    /// <param name="fullText">
    /// The string to search inside.
    /// </param>
    /// <param name="value">
    /// The string to seek.
    /// </param>
    /// <returns>
    /// The index position of the value parameter if that string is found, or -1 if it
    /// is not. If value is System.String.Empty, the return value is 0.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    /// fullText or value is null.
    /// </exception>
    public static int ExIndexOf(this string fullText, string value)
    {
        return fullText.IndexOf(value, StringComparison.OrdinalIgnoreCase);
    }

    public static bool ExNotEquals(this string text, string textToCompare)
    {
        return ExEquals(text, textToCompare) == false;
    }

    #endregion Public Methods
}

How to pass optional parameters while omitting some other optional parameters?

As specified in the documentation, use undefined:

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter? : number);
}

class X {
    error(message: string, title?: string, autoHideAfter?: number) {
        console.log(message, title, autoHideAfter);
    }
}

new X().error("hi there", undefined, 1000);

Playground link.

Where does Vagrant download its .box files to?

@Luke Peterson: There's a simpler way to get .box file.

Just go to https://atlas.hashicorp.com/boxes/search, search for the box you'd like to download. Notice the URL of the box, e.g:

https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1

Then you can download this box using URL like this:

https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box

I tried and successfully download all the boxes I need. Hope that help.

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

How to calculate a time difference in C++

if you are using c++11, here is a simple wrapper (see this gist):

#include <iostream>
#include <chrono>

class Timer
{
public:
    Timer() : beg_(clock_::now()) {}
    void reset() { beg_ = clock_::now(); }
    double elapsed() const { 
        return std::chrono::duration_cast<second_>
            (clock_::now() - beg_).count(); }

private:
    typedef std::chrono::high_resolution_clock clock_;
    typedef std::chrono::duration<double, std::ratio<1> > second_;
    std::chrono::time_point<clock_> beg_;
};

Or for c++03 on *nix:

#include <iostream>
#include <ctime>

class Timer
{
public:
    Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }

    double elapsed() {
        clock_gettime(CLOCK_REALTIME, &end_);
        return end_.tv_sec - beg_.tv_sec +
            (end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
    }

    void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }

private:
    timespec beg_, end_;
};

Example of usage:

int main()
{
    Timer tmr;
    double t = tmr.elapsed();
    std::cout << t << std::endl;

    tmr.reset();
    t = tmr.elapsed();
    std::cout << t << std::endl;
    return 0;
}

The source was not found, but some or all event logs could not be searched

I recently experienced the error, and none of the solutions worked for me. What resolved the error for me was adding the Application pool user to the Power Users group in computer management. I couldn't use the Administrator group due to a company policy.

JavaFX and OpenJDK

Also answering this question:

Where can I get pre-built JavaFX libraries for OpenJDK (Windows)

On Linux its not really a problem, but on Windows its not that easy, especially if you want to distribute the JRE.

You can actually use OpenJFX with OpenJDK 8 on windows, you just have to assemble it yourself:

Download the OpenJDK from here: https://github.com/AdoptOpenJDK/openjdk8-releases/releases/tag/jdk8u172-b11

Download OpenJFX from here: https://github.com/SkyLandTW/OpenJFX-binary-windows/releases/tag/v8u172-b11

copy all the files from the OpenFX zip on top of the JDK, voila, you have an OpenJDK with JavaFX.

Update:

Fortunately from Azul there is now a OpenJDK+OpenJFX build which can be downloaded at their community page: https://www.azul.com/downloads/zulu-community/?&version=java-8-lts&os=windows&package=jdk-fx

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

syntaxerror: unexpected character after line continuation character in python

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Best way to read a large file into a byte array in C#?

I might argue that the answer here generally is "don't". Unless you absolutely need all the data at once, consider using a Stream-based API (or some variant of reader / iterator). That is especially important when you have multiple parallel operations (as suggested by the question) to minimise system load and maximise throughput.

For example, if you are streaming data to a caller:

Stream dest = ...
using(Stream source = File.OpenRead(path)) {
    byte[] buffer = new byte[2048];
    int bytesRead;
    while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
        dest.Write(buffer, 0, bytesRead);
    }
}

Java unsupported major minor version 52.0

Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.

In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.

Try recompiling your code with Java 1.7 or upgrade your Java Plugin.

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

Select a random sample of results from a query result

Suppose you are trying to select exactly 1,000 random rows from a table called my_table. This is one way to do it:

select
    *
from
    (
        select
            row_number() over(order by dbms_random.value) as random_id,
            x.*
        from
            my_table x
    )
where
    random_id <= 1000
;

This is a slight deviation from the answer posted by @Quassnoi. They both have the same costs and execution times. The only difference is that you can select the random number used to fetch the sample.

Exporting PDF with jspdf not rendering CSS

To remove black background only add background-color: white; to the style of

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Since bootstrap 4 will be out soon I thought I would share a function that supports it (xl is now a thing) and performs minimal jQuery to get the job done.

/**
 * Get the Bootstrap device size
 * @returns {string|boolean} xs|sm|md|lg|xl on success, otherwise false if Bootstrap is not working or installed
 */
function findBootstrapEnvironment() {
    var environments = ['xs', 'sm', 'md', 'lg', 'xl'];
    var $el = $('<span />');
    $el.appendTo($('body'));
    for (var i = environments.length - 1; i >= 0; i--) {
        var env = environments[i];
        $el.addClass('hidden-'+env);
        if ($el.is(':hidden')) {
            $el.remove();
            return env;
        }
    }
    $el.remove();
    return false;
}

How do I put two increment statements in a C++ 'for' loop?

for (int i = 0; i != 5; ++i, ++j) 
    do_something(i, j);