Programs & Examples On #Jsr305

(Dormant JSR) Annotations for Software Defect Detection

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

This can be because of following reason:

  1. one of the jar files inside project was using an older version of google play services.

  2. use multiDexEnabled true in defaultconfig

  3. Be specific with classes you add in dependencies. like

    compile 'com.google.android.gms:play-services-maps:8.4.0'

Not like compile 'com.google.android.gms:play-services:+'

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

Those who are getting same error in Android 3.0.1,can resolve it by simply update the versions of compileSdkVersion and targetSdkVersion to 27 and also Implement com.android.support:appcompat-v7:27.1.1' in dependencies.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

Read .csv file in C

With fscanf read the file until you encounter ';' or \n, then you can just skip it with fscang(f, "%*c").

int main()
{
    char str[128];
    int result;
    FILE* f = fopen("test.txt", "r");
    ...
    
    do {
        result = fscanf(f, "%127[^;\n]", str);
        
        if(result == 0)
        {
            result = fscanf(f, "%*c");
        }
        else
        {
            //whatever you want to do with your value
            printf("%s\n", str);
        }
        
    } while(result != EOF);

    return 0;
}

Object of class mysqli_result could not be converted to string in

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}

How do I convert a TimeSpan to a formatted string?

According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:

dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"

How to get a list of properties with a given attribute?

If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:

public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
  var atts = provider.GetCustomAttributes(typeof(T), true);
  return atts.Length > 0;
}

which you can use like typeof(Foo).HasAttribute<BarAttribute>();

Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:

ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()

Index of Currently Selected Row in DataGridView

I modified @JayRiggs' answer, and this works. You need the if because sometimes the SelectedRows may be empty, so the index operation will throw a exception.

if (yourDGV.SelectedRows.Count>0){
    int index = yourDGV.SelectedRows[0].Index;
}

How to handle calendar TimeZones using Java?

You can solve it with Joda Time:

Date utcDate = new Date(timezoneFrom.convertLocalToUTC(date.getTime(), false));
Date localDate = new Date(timezoneTo.convertUTCToLocal(utcDate.getTime()));

Java 8:

LocalDateTime localDateTime = LocalDateTime.parse("2007-12-03T10:15:30");
ZonedDateTime fromDateTime = localDateTime.atZone(
    ZoneId.of("America/Toronto"));
ZonedDateTime toDateTime = fromDateTime.withZoneSameInstant(
    ZoneId.of("Canada/Newfoundland"));

how to upload a file to my server using html

On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.

Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.

How to find path of active app.config file?

Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

Yet another way using just bash and grep:

For a single file 'test.txt':

  grep -q Dansk test.txt && grep -q Norsk test.txt && grep -l Svenska test.txt

Will print test.txt iff the file contains all three (in any combination). The first two greps don't print anything (-q) and the last only prints the file if the other two have passed.

If you want to do it for every file in the directory:

   for f in *; do grep -q Dansk $f && grep -q Norsk $f && grep -l Svenska $f; done

How to export non-exportable private key from store

You're right, no API at all that I'm aware to export PrivateKey marked as non-exportable. But if you patch (in memory) normal APIs, you can use the normal way to export :)

There is a new version of mimikatz that also support CNG Export (Windows Vista / 7 / 2008 ...)

  1. download (and launch with administrative privileges) : http://blog.gentilkiwi.com/mimikatz (trunk version or last version)

Run it and enter the following commands in its prompt:

  1. privilege::debug (unless you already have it or target only CryptoApi)
  2. crypto::patchcng (nt 6) and/or crypto::patchcapi (nt 5 & 6)
  3. crypto::exportCertificates and/or crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE

The exported .pfx files are password protected with the password "mimikatz"

How can I remove an element from a list, with lodash?

Just use vanilla JS. You can use splice to remove the element:

obj.subTopics.splice(1, 1);

Demo

Capture the Screen into a Bitmap

If using the .NET 2.0 (or later) framework you can use the CopyFromScreen() method detailed here:

http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html

//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                               Screen.PrimaryScreen.Bounds.Height,
                               PixelFormat.Format32bppArgb);

// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                            Screen.PrimaryScreen.Bounds.Y,
                            0,
                            0,
                            Screen.PrimaryScreen.Bounds.Size,
                            CopyPixelOperation.SourceCopy);

// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);

setting request headers in selenium

For those people using Python, you may consider using Selenium Wire, which can set request headers, as well as provide you with the ability to inspect requests and responses.

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver (or Chrome)
driver = webdriver.Firefox()

# Create a request interceptor
def interceptor(request):
    del request.headers['Referer']  # Delete the header first
    request.headers['Referer'] = 'some_referer'

# Set the interceptor on the driver
driver.request_interceptor = interceptor

# All requests will now use 'some_referer' for the referer
driver.get('https://mysite')

How can I echo the whole content of a .html file in PHP?

You should use readfile():

readfile("/path/to/file");

This will read the file and send it to the browser in one command. This is essentially the same as:

echo file_get_contents("/path/to/file");

except that file_get_contents() may cause the script to crash for large files, while readfile() won't.

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

Reset select value to default

$("#reset").on("click", function () {
    $('#my_select').prop('selectedIndex',0);
});

How to resolve "local edit, incoming delete upon update" message

So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case

open link in iframe

I had this problem in a project this morning. Make sure you specify the base tag in the head section.

It should be like this:

<head>
<base target="name_of_iframe">
</head>

That way when you click a link on the page it will open up inside of the iframe by default.

Hope that helped.

How do I get ruby to print a full backtrace instead of a truncated one?

IRB has a setting for this awful "feature", which you can customize.

Create a file called ~/.irbrc that includes the following line:

IRB.conf[:BACK_TRACE_LIMIT] = 100

This will allow you to see 100 stack frames in irb, at least. I haven't been able to find an equivalent setting for the non-interactive runtime.

Detailed information about IRB customization can be found in the Pickaxe book.

constant pointer vs pointer on a constant value

char * const a;

*a is writable, but a is not; in other words, you can modify the value pointed to by a, but you cannot modify a itself. a is a constant pointer to char.

const char * a; 

a is writable, but *a is not; in other words, you can modify a (pointing it to a new location), but you cannot modify the value pointed to by a.

Note that this is identical to

char const * a;

In this case, a is a pointer to a const char.

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

Why does the arrow (->) operator in C exist?

I'll interpret your question as two questions: 1) why -> even exists, and 2) why . does not automatically dereference the pointer. Answers to both questions have historical roots.

Why does -> even exist?

In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator -> had very exclusive meaning, not synonymous with * and . combination

The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare

struct S {
  int a;
  int b;
};

and name a would stand for offset 0, while name b would stand for offset 2 (assuming int type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare

struct X {
  int a;
  int x;
};

and that would be OK, since the name a would consistently stand for offset 0. But this additional declaration

struct Y {
  int b;
  int a;
};

would be formally invalid, since it attempted to "redefine" a as offset 2 and b as offset 0.

And this is where the -> operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these

int i = 5;
i->b = 42;  /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */

The first assignment was interpreted by the compiler as "take address 5, add offset 2 to it and assign 42 to the int value at the resultant address". I.e. the above would assign 42 to int value at address 7. Note that this use of -> did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).

This sort of trickery was not possible with * and . combination. You could not do

(*i).b = 42;

since *i is already an invalid expression. The * operator, since it is separate from ., imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the -> operator, which is independent from the type of the left-hand operand.

As Keith noted in the comments, this difference between -> and *+. combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1 be of pointer type, the expression E1->MOS is exactly equivalent to (*E1).MOS

Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of -> operator became fully identical to the functionality of * and . combination.

Why can't . dereference the pointer automatically?

Again, in CRM version of the language the left operand of the . operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->, as explained above). Note that CRM did not require the left operand of . to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this

struct S { int a, b; };
struct T { float x, y, z; };

struct T c;
c.b = 55;

In this case the compiler would write 55 into an int value positioned at byte-offset 2 in the continuous memory block known as c, even though type struct T had no field named b. The compiler would not care about the actual type of c at all. All it cared about is that c was an lvalue: some sort of writable memory block.

Now note that if you did this

S *s;
...
s.b = 42;

the code would be considered valid (since s is also an lvalue) and the compiler would simply attempt to write data into the pointer s itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.

I.e. in that version of the language your proposed idea about overloading operator . for pointer types would not work: operator . already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.

Of course, this weird functionality is not a very strong reason against introducing overloaded . operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.

(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)

Center form submit buttons HTML / CSS

/* here is what works for me - set up as a class */

.button {
    text-align: center;
    display: block;
    margin: 0 auto;
}

/* you can set padding and width to whatever works best */

Running AMP (apache mysql php) on Android

I think this is what you're looking for: PAW Server from http://paw-android.fun2code.de/

hope it works

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

When should you use constexpr capability in C++11?

From what I've read, the need for constexpr comes from an issue in metaprogramming. Trait classes may have constants represented as functions, think: numeric_limits::max(). With constexpr, those types of functions can be used in metaprogramming, or as array bounds, etc etc.

Another example off of the top of my head would be that for class interfaces, you may want derived types define their own constants for some operation.

Edit:

After poking around on SO, it looks like others have come up with some examples of what might be possible with constexprs.

Formatting floats without trailing zeros

You can achieve that in most pythonic way like that:

python3:

"{:0.0f}".format(num)

Visual Studio displaying errors even if projects build

Unload & reload the project fixed this problem.

jQuery window scroll event does not fire up

In my case you should put the function in $(document).ready

$(document).ready(function () {
    $('div#page').on('scroll', function () {
     ...
    });
});

How to list all `env` properties within jenkins pipeline job?

I suppose that you needed that in form of a script, but if someone else just want to have a look through the Jenkins GUI, that list can be found by selecting the "Environment Variables" section in contextual left menu of every build Select project => Select build => Environment Variables

enter image description here

How to call a button click event from another method

you can call the button_click event by passing..

private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}

private void ChildNode_Click(object sender, RoutedEventArgs args)
{
   SubGraphButton_Click(sender, args);
}

Also without passing..

private void SubGraphButton_Click(object sender, EventArgs args)
{
}

private void Some_Method() //this method is called
{
   SubGraphButton_Click(new object(), new EventArgs());
}

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}

How to return part of string before a certain character?

In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_

Rearrange columns using cut

Just been working on something very similar, I am not an expert but I thought I would share the commands I have used. I had a multi column csv which I only required 4 columns out of and then I needed to reorder them.

My file was pipe '|' delimited but that can be swapped out.

LC_ALL=C cut -d$'|' -f1,2,3,8,10 ./file/location.txt | sed -E "s/(.*)\|(.*)\|(.*)\|(.*)\|(.*)/\3\|\5\|\1\|\2\|\4/" > ./newcsv.csv

Admittedly it is really rough and ready but it can be tweaked to suit!

ASP.NET Web Application Message Box

As others already pointed out, a message box will be clientside Javascript. So the problem then is how to force a clientside JS message box from the server side. A simple solution is to include this in the HTML:

<script>
    var data = '<%= JsData %>';
    alert(data);
</script>

and to fill this data from the server side code-behind:

public partial class PageName : Page
{
    protected string JsData = "your message";

Note that the string value should be a Javascript string, i.e. be a one-liner, but it may contain escaped newlines as \n.

Now you can use all your Javascript or JQuery skills and tricks to do whatever you want with that message text on the clientside, such as display a simple alert(), as shown in the above code sample, or sophisticated message box or message banner.

(Note that popups are sometimes frowned upon and blocked)

Note also that, due to the HTTP protocol, the message can only be shown in response to an HTTP request that the user sends to the server. Unlike WinForm apps, the web server cannot push a message to the client whenever it sees fit.

If you want to show the message only once, and not after the user refreshes the page with F5, you could set and read a cookie with javascript code. In any case, the nice point with this method is that it is an easy way to get data from the server to the javascript on the client, and that you can use all javascript features to accomplish anything you like.

Using jQuery to center a DIV on the screen

I like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)

Running Node.js in apache?

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

Calculate text width with JavaScript

The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.

function textWidth(text, fontProp) {
    var tag = document.createElement("div");
    tag.style.position = "absolute";
    tag.style.left = "-999em";
    tag.style.whiteSpace = "nowrap";
    tag.style.font = fontProp;
    tag.innerHTML = text;

    document.body.appendChild(tag);

    var result = tag.clientWidth;

    document.body.removeChild(tag);

    return result;
}

Usage:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

In Python, how do I determine if an object is iterable?

def is_iterable(x):
    try:
        0 in x
    except TypeError:
        return False
    else:
        return True

This will say yes to all manner of iterable objects, but it will say no to strings in Python 2. (That's what I want for example when a recursive function could take a string or a container of strings. In that situation, asking forgiveness may lead to obfuscode, and it's better to ask permission first.)

import numpy

class Yes:
    def __iter__(self):
        yield 1;
        yield 2;
        yield 3;

class No:
    pass

class Nope:
    def __iter__(self):
        return 'nonsense'

assert is_iterable(Yes())
assert is_iterable(range(3))
assert is_iterable((1,2,3))   # tuple
assert is_iterable([1,2,3])   # list
assert is_iterable({1,2,3})   # set
assert is_iterable({1:'one', 2:'two', 3:'three'})   # dictionary
assert is_iterable(numpy.array([1,2,3]))
assert is_iterable(bytearray("not really a string", 'utf-8'))

assert not is_iterable(No())
assert not is_iterable(Nope())
assert not is_iterable("string")
assert not is_iterable(42)
assert not is_iterable(True)
assert not is_iterable(None)

Many other strategies here will say yes to strings. Use them if that's what you want.

import collections
import numpy

assert isinstance("string", collections.Iterable)
assert isinstance("string", collections.Sequence)
assert numpy.iterable("string")
assert iter("string")
assert hasattr("string", '__getitem__')

Note: is_iterable() will say yes to strings of type bytes and bytearray.

  • bytes objects in Python 3 are iterable True == is_iterable(b"string") == is_iterable("string".encode('utf-8')) There is no such type in Python 2.
  • bytearray objects in Python 2 and 3 are iterable True == is_iterable(bytearray(b"abc"))

The O.P. hasattr(x, '__iter__') approach will say yes to strings in Python 3 and no in Python 2 (no matter whether '' or b'' or u''). Thanks to @LuisMasuelli for noticing it will also let you down on a buggy __iter__.

How do you clear a stringstream variable?

It's a conceptual problem.

Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Private Sub ListView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.Click
        Dim tt As String
        tt = ListView1.SelectedItems.Item(0).SubItems(1).Text
        TextBox1.Text = tt.ToString
End Sub

The representation of if-elseif-else in EL using JSF

The following code the easiest way:

 <h:outputLabel value="value = 10" rendered="#{row == 10}" /> 
 <h:outputLabel value="value = 15" rendered="#{row == 15}" /> 
 <h:outputLabel value="value xyz" rendered="#{row != 15 and row != 10}" /> 

Link for EL expression syntax. http://developers.sun.com/docs/jscreator/help/jsp-jsfel/jsf_expression_language_intro.html#syntax

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

Default values and initialization in Java

I wrote following function to return a default representation 0 or false of a primitive or Number:

/**
 * Retrieves the default value 0 / false for any primitive representative or
 * {@link Number} type.
 *
 * @param type
 *
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T getDefault(final Class<T> type)
{
    if (type.equals(Long.class) || type.equals(Long.TYPE))
        return (T) new Long(0);
    else if (type.equals(Integer.class) || type.equals(Integer.TYPE))
        return (T) new Integer(0);
    else if (type.equals(Double.class) || type.equals(Double.TYPE))
        return (T) new Double(0);
    else if (type.equals(Float.class) || type.equals(Float.TYPE))
        return (T) new Float(0);
    else if (type.equals(Short.class) || type.equals(Short.TYPE))
        return (T) new Short((short) 0);
    else if (type.equals(Byte.class) || type.equals(Byte.TYPE))
        return (T) new Byte((byte) 0);
    else if (type.equals(Character.class) || type.equals(Character.TYPE))
        return (T) new Character((char) 0);
    else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
        return (T) new Boolean(false);
    else if (type.equals(BigDecimal.class))
        return (T) BigDecimal.ZERO;
    else if (type.equals(BigInteger.class))
        return (T) BigInteger.ZERO;
    else if (type.equals(AtomicInteger.class))
        return (T) new AtomicInteger();
    else if (type.equals(AtomicLong.class))
        return (T) new AtomicLong();
    else if (type.equals(DoubleAdder.class))
        return (T) new DoubleAdder();
    else
        return null;
}

I use it in hibernate ORM projection queries when the underlying SQL query returns null instead of 0.

/**
 * Retrieves the unique result or zero, <code>false</code> if it is
 * <code>null</code> and represents a number
 *
 * @param criteria
 *
 * @return zero if result is <code>null</code>
 */
public static <T> T getUniqueResultDefault(final Class<T> type, final Criteria criteria)
{
    final T result = (T) criteria.uniqueResult();

    if (result != null)
        return result;
    else
        return Utils.getDefault(type);
}

One of the many unnecessary complex things about Java making it unintuitive to use. Why instance variables are initialized with default 0 but local are not is not logical. Similar why enums dont have built in flag support and many more options. Java lambda is a nightmare compared to C# and not allowing class extension methods is also a big problem.

Java ecosystem comes up with excuses why its not possible but me as the user / developer i dont care about their excuses. I want easy approach and if they dont fix those things they will loose big in the future since C# and other languages are not waiting to make life of developers more simple. Its just sad to see the decline in the last 10 years since i work daily with Java.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

I like to use: ArgumentException, ArgumentNullException, and ArgumentOutOfRangeException.

There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:

  • InvalidOperationException – The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote his answer up as well.
  • NotSupportedException – The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.

The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.

I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. “Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”. When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.

Thanks to STW (ex Yoooder) again for the comments.


In response to your followup, I would throw an ArgumentOutOfRangeException. Look at what MSDN says about this exception:

ArgumentOutOfRangeException is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference (Nothing in Visual Basic) and does not contain a valid value.

So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say ArgumentOutOfRangeException, another developer might say ArgumentException. Make it easy and document the behavior.

Mongoose: Get full list of users

This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);

    server.get('/usersList', (req, res) => 
        User.find({}, (err, users) => 
            res.send(users.reduce((userMap, item) => {
                userMap[item.id] = item
                return userMap
            }, {}));
        );
    );

cheers!

Cannot use Server.MapPath

Try adding System.Web as a reference to your project.

How can I decrypt MySQL passwords

Hashing is a one-way process but using a password-list you can regenerate the hashes and compare to the stored hash to 'crack' the password.

This site https://crackstation.net/ attempts to do this for you - run through passwords lists and tell you the cleartext password based on your hash.

Is there a Java equivalent or methodology for the typedef keyword in C++?

Really, the only use of typedef that carries over to Javaland is aliasing- that is, giving the same class multiple names. That is, you've got a class "A" and you want "B" to refer to the same thing. In C++, you'd be doing "typedef B A;"

Unfortunately, they just don't support it. However, if you control all the types involved you CAN pull a nasty hack at the library level- you either extend B from A or have B implement A.

conditional Updating a list using LINQ

How about

(from k in myList
 where k.id > 35
 select k).ToList().ForEach(k => k.Name = "Banana");

Simple two column html layout without using tables

This code not only allows you to add two columns, it allows you to add as many coloumns as you want and align them left or right, change colors, add links etc. Check out the Fiddle link also

Fiddle Link : http://jsfiddle.net/eguFN/

<div class="menu">
                <ul class="menuUl">
                    <li class="menuli"><a href="#">Cadastro</a></li>
                    <li class="menuli"><a href="#">Funcionamento</a></li>
                    <li class="menuli"><a href="#">Regulamento</a></li>
                    <li class="menuli"><a href="#">Contato</a></li>
                </ul>
</div>

Css is as follows

.menu {
font-family:arial;
color:#000000;
font-size:12px;
text-align: left;
margin-top:35px;
}

.menu a{
color:#000000
}

.menuUl {
  list-style: none outside none;
  height: 34px;
}

.menuUl > li {
  display:inline-block;
  line-height: 33px;
  margin-right: 45px;

}

Python - Convert a bytes array into JSON format

Your bytes object is almost JSON, but it's using single quotes instead of double quotes, and it needs to be a string. So one way to fix it is to decode the bytes to str and replace the quotes. Another option is to use ast.literal_eval; see below for details. If you want to print the result or save it to a file as valid JSON you can load the JSON to a Python list and then dump it out. Eg,

import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

# Decode UTF-8 bytes to Unicode, and convert single quotes 
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)

# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)

output

[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "LogoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - - 
[
    {
        "Classe": [
            "Email addresses",
            "Passwords"
        ],
        "CreationDate": "2012-05-05",
        "Date": "2016-05-21T21:35:40Z",
        "Link": "http://some_link.com",
        "LogoType": "png",
        "Ref": 164611595
    }
]

As Antti Haapala mentions in the comments, we can use ast.literal_eval to convert my_bytes_value to a Python list, once we've decoded it to a string.

from ast import literal_eval
import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)

s = json.dumps(data, indent=4, sort_keys=True)
print(s)

Generally, this problem arises because someone has saved data by printing its Python repr instead of using the json module to create proper JSON data. If it's possible, it's better to fix that problem so that proper JSON data is created in the first place.

How to add a browser tab icon (favicon) for a website?

For Chrome to display the page icon (favicon), you need to check your website from a hosting server or you can use local host while developing and testing your website on your PC.

PreparedStatement with Statement.RETURN_GENERATED_KEYS

private void alarmEventInsert(DriveDetail driveDetail, String vehicleRegNo, int organizationId) {

    final String ALARM_EVENT_INS_SQL = "INSERT INTO alarm_event (event_code,param1,param2,org_id,created_time) VALUES (?,?,?,?,?)";
    CachedConnection conn = JDatabaseManager.getConnection();
    PreparedStatement ps = null;
    ResultSet generatedKeys = null;
    try {
        ps = conn.prepareStatement(ALARM_EVENT_INS_SQL, ps.RETURN_GENERATED_KEYS);
        ps.setInt(1, driveDetail.getEventCode());
        ps.setString(2, vehicleRegNo);
        ps.setString(3, null);
        ps.setInt(4, organizationId);
        ps.setString(5, driveDetail.getCreateTime());
        ps.execute();
        generatedKeys = ps.getGeneratedKeys();
        if (generatedKeys.next()) {
            driveDetail.setStopDuration(generatedKeys.getInt(1));
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("Error inserting into alarm_event : {}", e
                .getMessage());
        logger.info(ps.toString());
    } finally {
        if (ps != null) {
            try {

                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                logger.error("Error closing prepared statements : {}", e
                        .getMessage());
            }
        }
    }
    JDatabaseManager.freeConnection(conn);
}

Get url without querystring

You can use System.Uri

Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = String.Format("{0}{1}{2}{3}", url.Scheme, 
    Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);

Or you can use substring

string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));

EDIT: Modifying the first solution to reflect brillyfresh's suggestion in the comments.

Server is already running in Rails

On Windows Rails 5.2, delete this file

c:/Sites/<your_folder>/tmp/pids/server.pid

and run

rails s

again.

How to make System.out.println() shorter

For Intellij IDEA type sout and press Tab.

For Eclipse type syso and press Ctrl+Space.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

If you are using 64-bit COM components in a web application on IIS, make sure the application pool is set to not allow 32 bit applications (Enable 32-Bit Applications: false in advanced settings)

How can I create Min stl priority_queue?

The third template parameter for priority_queue is the comparator. Set it to use greater.

e.g.

std::priority_queue<int, std::vector<int>, std::greater<int> > max_queue;

You'll need #include <functional> for std::greater.

Get size of an Iterable in Java

This is perhaps a bit late, but may help someone. I come across similar issue with Iterable in my codebase and solution was to use for each without explicitly calling values.iterator();.

int size = 0;
for(T value : values) {
   size++;
}

Comparing date part only without comparing time in JavaScript

Just use toDateString() on both dates. toDateString doesn't include the time, so for 2 times on the same date, the values will be equal, as demonstrated below.

var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true

Obviously some of the timezone concerns expressed elsewhere on this question are valid, but in many scenarios, those are not relevant.

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

How do I clear all options in a dropdown box?

var select =$('#selectbox').val();

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

There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config

_x000D_
_x000D_
{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
}
_x000D_
_x000D_
_x000D_

, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside

_x000D_
_x000D_
declare module '*.jpg';
declare module '*.png';
_x000D_
_x000D_
_x000D_

,then restart dev-server. After these steps we can import and use images like in code bellow

_x000D_
_x000D_
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';

const HelloWorld = () => (
  <>
    <h1 className="main">React TypeScript Starter</h1>
        <img src={image} alt="some example image" />
  </>
);
export default HelloWorld;
_x000D_
_x000D_
_x000D_

Works in typescript and also in javacript,just change extension from .ts to .js

Cheers.

Docker-Compose can't connect to Docker Daemon

I found this and it seemed to fix my issue.

GitHub Fix Docker Daemon Crash

I changed the content of my docker-compose-deps.yml file as seen in the link. Then I ran docker-compose -f docker-compose-deps.yml up -d. Then I changed it back and it worked for some reason. I didn't have to continue the steps in the link I provided, but the first two steps fixed the issue for me.

What are some uses of template template parameters?

Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like:

template<typename T>
static inline std::ostream& operator<<(std::ostream& out, std::list<T> const& v)
{
    out << '[';
    if (!v.empty()) {
        for (typename std::list<T>::const_iterator i = v.begin(); ;) {
            out << *i;
            if (++i == v.end())
                break;
            out << ", ";
        }
    }
    out << ']';
    return out;
}

Then you'd figure out that code for vector is just the same, for forward_list is the same, actually, even for multitude of map types it's still just the same. Those template classes don't have anything in common except for meta-interface/protocol, and using template template parameter allows to capture the commonality in all of them. Before proceeding to write a template though, it's worth to check a reference to recall that sequence containers accept 2 template arguments - for value type and allocator. While allocator is defaulted, we still should account for its existence in our template operator<<:

template<template <typename, typename> class Container, class V, class A>
std::ostream& operator<<(std::ostream& out, Container<V, A> const& v)
...

Voila, that will work automagically for all present and future sequence containers adhering to the standard protocol. To add maps to the mix, it would take a peek at reference to note that they accept 4 template params, so we'd need another version of the operator<< above with 4-arg template template param. We'd also see that std:pair tries to be rendered with 2-arg operator<< for sequence types we defined previously, so we would provide a specialization just for std::pair.

Btw, with C+11 which allows variadic templates (and thus should allow variadic template template args), it would be possible to have single operator<< to rule them all. For example:

#include <iostream>
#include <vector>
#include <deque>
#include <list>

template<typename T, template<class,class...> class C, class... Args>
std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
{
    os << __PRETTY_FUNCTION__ << '\n';
    for (auto const& obj : objs)
        os << obj << ' ';
    return os;
}

int main()
{
    std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
    std::cout << vf << '\n';

    std::list<char> lc { 'a', 'b', 'c', 'd' };
    std::cout << lc << '\n';

    std::deque<int> di { 1, 2, 3, 4 };
    std::cout << di << '\n';

    return 0;
}

Output

std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = float, C = vector, Args = <std::__1::allocator<float>>]
1.1 2.2 3.3 4.4 
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = char, C = list, Args = <std::__1::allocator<char>>]
a b c d 
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = int, C = deque, Args = <std::__1::allocator<int>>]
1 2 3 4 

Server.Mappath in C# classlibrary

You can get the base path by using the following code and append your needed path with that.

string  path = System.AppDomain.CurrentDomain.BaseDirectory;

Calling Oracle stored procedure from C#?

In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:

using System.Data.OracleClient;

There are some system requirements here that you should verify are OK in your scenario.

Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

How to minify php page html output?

Turn on gzip if you want to do it properly. You can also just do something like this:

$this->output = preg_replace(
    array(
        '/ {2,}/',
        '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
    ),
    array(
        ' ',
        ''
    ),
    $this->output
);

This removes about 30% of the page size by turning your html into one line, no tabs, no new lines, no comments. Mileage may vary

Overriding !important style

https://jsfiddle.net/xk6Ut/256/

One option to override CSS class in JavaScript is using an ID for the style element so that we can update the CSS class

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

..

   var cssText = '.testDIV{ height:' + height + 'px !important; }';
    writeStyles('styles_js', cssText)

How to paste yanked text into the Vim command line

If you have two values yanked into two different registers (for example register a and register b) then you can simply set a variable c and do the operation on it.

For example, :set c = str2float(@a) + str2float(@b) and then you can paste the content of c anywhere.

For example whilst in INSERT mode, CTRL + R then type = to enter into the expression register and just type c after equal sign and hit ENTER. Done you should now have the total of a and b registers.

All these can be recorded in a macro and repeated over!

The str2float function is used if you are working with floats, if you don't, you will get integers instead.

I am not sure if this is idiomatic but it worked for my case where I needed to add 2 numbers in a row and repeat it for 500 more lines.

How do I make a delay in Java?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

Find methods calls in Eclipse project

Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.

How can I see the raw SQL queries Django is running?

I developed an extension for this purpose, so you can easily put a decorator on your view function and see how many queries are executed.

To install:

$ pip install django-print-sql

To use as context manager:

from django_print_sql import print_sql

# set `count_only` to `True` will print the number of executed SQL statements only
with print_sql(count_only=False):

  # write the code you want to analyze in here,
  # e.g. some complex foreign key lookup,
  # or analyzing a DRF serializer's performance

  for user in User.objects.all()[:10]:
      user.groups.first()

To use as decorator:

from django_print_sql import print_sql_decorator


@print_sql_decorator(count_only=False)  # this works on class-based views as well
def get(request):
    # your view code here

Github: https://github.com/rabbit-aaron/django-print-sql

Run text file as commands in Bash

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn

How to display an activity indicator with text on iOS 8 with Swift?

For activity indicator, its better you create one custom class.

Instead of creating UIActivityIndicator in each UIViewController.Subclass UIView and use from any UIViewController.

Updated for Swift 5.0:

import UIKit
import Foundation
class ProgressIndicator: UIView {

var indicatorColor:UIColor
var loadingViewColor:UIColor
var loadingMessage:String
var messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()

init(inview:UIView,loadingViewColor:UIColor,indicatorColor:UIColor,msg:String){

    self.indicatorColor = indicatorColor
    self.loadingViewColor = loadingViewColor
    self.loadingMessage = msg
    super.init(frame: CGRect(x: inview.frame.midX - 90, y: inview.frame.midY - 250 , width: 180, height: 50))
    initalizeCustomIndicator()

}
convenience init(inview:UIView) {

    self.init(inview: inview,loadingViewColor: UIColor.brown,indicatorColor:UIColor.black, msg: "Loading..")
}
convenience init(inview:UIView,messsage:String) {

    self.init(inview: inview,loadingViewColor: UIColor.brown,indicatorColor:UIColor.black, msg: messsage)
}

required init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")
}

func initalizeCustomIndicator(){

    messageFrame.frame = self.bounds
    activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.medium)
    activityIndicator.tintColor = indicatorColor
    activityIndicator.hidesWhenStopped = true
    activityIndicator.frame = CGRect(x: self.bounds.origin.x + 6, y: 0, width: 20, height: 50)
    print(activityIndicator.frame)
    let strLabel = UILabel(frame:CGRect(x: self.bounds.origin.x + 30, y: 0, width: self.bounds.width - (self.bounds.origin.x + 30) , height: 50))
    strLabel.text = loadingMessage
    strLabel.adjustsFontSizeToFitWidth = true
    strLabel.textColor = UIColor.white
    messageFrame.layer.cornerRadius = 15
    messageFrame.backgroundColor = loadingViewColor
    messageFrame.alpha = 0.8
    messageFrame.addSubview(activityIndicator)
    messageFrame.addSubview(strLabel)


}

func  start(){
    //check if view is already there or not..if again started
    if !self.subviews.contains(messageFrame){

        activityIndicator.startAnimating()
        self.addSubview(messageFrame)

    }
}

func stop(){

    if self.subviews.contains(messageFrame){

        activityIndicator.stopAnimating()
        messageFrame.removeFromSuperview()

    }
}
}

Put this class in your project and then call from any ViewController as

var indicator:ProgressIndicator?
override func viewDidLoad() {
    super.viewDidLoad()

    //indicator = ProgressIndicator(inview: self.view,messsage: "Hello from Nepal..")
    //self.view.addSubview(indicator!)
    //OR
    indicator = ProgressIndicator(inview:self.view,loadingViewColor: UIColor.grayColor(), indicatorColor: UIColor.blackColor(), msg: "Landing within minutes,Please hold tight..")
    self.view.addSubview(indicator!)

}

@IBAction func startBtn(sender: AnyObject) {
    indicator!.start()
}


@IBAction func stopBtn(sender: AnyObject) {
    indicator!.stop()
}

Remove the last chars of the Java String variable

import org.apache.commons.lang3.StringUtils;

// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

What is the difference between a static and const variable?

static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the same name and no name conflicts.

const is just constant, meaning can't be modified.

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

Maybe your model not linked when migration process is ongoing. Try to import it in file urls.py from models import your_file

how to make div click-able?

Give it an ID like "something", then:

var something = document.getElementById('something');

something.style.cursor = 'pointer';
something.onclick = function() {
    // do something...
};

Changing the background color (as per your updated question):

something.onmouseover = function() {
    this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
    this.style.backgroundColor = '';
};

How can I extract a predetermined range of lines from a text file on Unix?

cat dump.txt | head -16224 | tail -258

should do the trick. The downside of this approach is that you need to do the arithmetic to determine the argument for tail and to account for whether you want the 'between' to include the ending line or not.

Convert normal date to unix timestamp

var datestr = '2012.08.10';
var timestamp = (new Date(datestr.split(".").join("-")).getTime())/1000;

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:

SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;

Omitting the parenthesis was solving it for me.

SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;

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

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

Facebook API "This app is in development mode"

in your app dashboard check status to on facebook change develope mode to live

Include another HTML file in a HTML file

Based on the answer of https://stackoverflow.com/a/31837264/4360308 I've implemented this functionality with Nodejs (+ express + cheerio) as follows:

HTML (index.html)

<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>

JS

function includeComponents($) {
    $('.include').each(function () {
        var file = 'view/html/component/' + $(this).data('include') + '.html';
        var dataComp = fs.readFileSync(file);
        var htmlComp = dataComp.toString();
        if ($(this).data('method') == "replace") {
            $(this).replaceWith(htmlComp);
        } else if ($(this).data('method') == "append") {
            $(this).append(htmlComp);
        }
    })
}

function foo(){
    fs.readFile('./view/html/index.html', function (err, data) {
        if (err) throw err;
        var html = data.toString();
        var $ = cheerio.load(html);
        includeComponents($);
        ...
    }
}

append -> includes the content into the div

replace -> replaces the div

you could easily add more behaviours following the same design

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

Checking if a key exists in a JavaScript object?

ES6 solution

using Array#some and Object.keys. It will return true if given key exists in the object or false if it doesn't.

_x000D_
_x000D_
var obj = {foo: 'one', bar: 'two'};_x000D_
    _x000D_
function isKeyInObject(obj, key) {_x000D_
    var res = Object.keys(obj).some(v => v == key);_x000D_
    console.log(res);_x000D_
}_x000D_
_x000D_
isKeyInObject(obj, 'foo');_x000D_
isKeyInObject(obj, 'something');
_x000D_
_x000D_
_x000D_

One-line example.

_x000D_
_x000D_
console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo'));
_x000D_
_x000D_
_x000D_

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

Use defaultValue and onChange like this

const [myValue, setMyValue] = useState('');

<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
                    
       <option>Option 1</option>
       <option>Option 2</option>
       <option>Option 3</option>

</select>

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

Instagram API - How can I retrieve the list of people a user is following on Instagram

I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.

You need to use browser console from instagram.com tab to make it works.

let username = 'USERNAME'
let followers = [], followings = []
try {
  let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)

  res = await res.json()
  let userId = res.graphql.user.id

  let after = null, has_next = true
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_followed_by.page_info.has_next_page
      after = res.data.user.edge_followed_by.page_info.end_cursor
      followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followers', followers)

  has_next = true
  after = null
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_follow.page_info.has_next_page
      after = res.data.user.edge_follow.page_info.end_cursor
      followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followings', followings)
} catch (err) {
  console.log('Invalid username')
}

Detect Close windows event by jQuery

You can use:

$(window).unload(function() {
    //do something
}

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

$(window).on("beforeunload", function() { 
    return confirm("Do you really want to close?"); 
})

Source Browser window close event

In Python, how do I create a string of n characters in one line of code?

To simply repeat the same letter 10 times:

string_val = "x" * 10  # gives you "xxxxxxxxxx"

And if you want something more complex, like n random lowercase letters, it's still only one line of code (not counting the import statements and defining n):

from random import choice
from string import ascii_lowercase
n = 10

string_val = "".join(choice(ascii_lowercase) for i in range(n))

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

How can I tell when a MySQL table was last updated?

i made a column by name : update-at in phpMyAdmin and got the current time from Date() method in my code (nodejs) . with every change in table this column hold the time of changes.

An invalid XML character (Unicode: 0xc) was found

For people who are reading byte array into String and trying to convert to object with JAXB, you can add "iso-8859-1" encoding by creating String from byte array like this:

String JAXBallowedString= new String(byte[] input, "iso-8859-1");

This would replace the conflicting byte to single-byte encoding which JAXB can handle. Obviously this solution is only to parse the xml.

rake assets:precompile RAILS_ENV=production not working as required

I had this problem today. I fixed it being being explict about my require

gem 'uglifier', '>= 1.0.3', require: 'uglifier'

I had mine still in the assets group.

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

How do I get a list of folders and sub folders without the files?

dir /ad /b /s will give the required answer.

mysql query result into php array

I think you wanted to do this:

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

Or maybe store id as key too

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

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

"query function not defined for Select2 undefined error"

I got the same error. I have been using select2-3.5.2

This was my code which had error

    $('#carstatus-select').select2().val([1,2])

Below code fixed the issue.

    $('#carstatus-select').val([1,2]);

What is difference between mutable and immutable String in java

Case 1:

String str = "Good";
str = str + " Morning";

In the above code you create 3 String Objects.

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.


Case 2:

StringBuffer str = new StringBuffer("Good"); 
str.append(" Morning");

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

What is the correct JSON content type?

Always try to remember these three content types even though there are many content types. as you may have to use these more frequently.

  • Content-Type: application/json
  • Content-Type: application/xml
  • Content-Type: text/html

find all subsets that sum to a particular value

I used Dynamic Programming & Memoization to find count of subsets from a set having a particular total. The code below code is in java. Have included the comments to explain the code intentions -

package com.company.dynamicProgramming;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class FindSumInSubSet {

    public static void main(String...args){

        int[] arr = {3, 2, 4, 6, 10};
        int total = 16;
        // Challenge is to find the subsets of numbers total 6 in above super set (represented as array)
        // In general - Write a code to count subset of elements totalling m(6 above) in given set of n(9 as array size above) elements

        Map<Entry, Integer> memoMap = new HashMap<>();

        Entry entry = new Entry(total, arr.length-1);

        int count = countSubSetForSum(arr, entry, memoMap);
        System.out.format("In set of %d elements, the number of subsets having total=%d is %d %n", arr.length,total, count);
    }


    static int countSubSetForSum(int[] arr, Entry entry, Map<Entry, Integer> memoMap){

        int total = entry.getTotal();
        int i = entry.getI();

        if (total == 0){             // means element was equal in previous recursion
            return 1;
        }else if(total < 0){         // means element was less in previous recursion i.e. not equal
            return 0;
        }else if (i < 0){            // means arr was finished previous recursion
            return 0;
        }else if (arr[i] > total){   // means element is greater than total
                                     // i.e. leave that element and look further sets excluding this element
            return getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);

        }else{                       // means element is less than total i.e. 2 possibilities :
                                     // 1st - look further sets including this element
                                     // 2nd - look further sets excluding this element
            return getCountForIthAndTotal(arr, new Entry( total-arr[i], i-1), memoMap) +
                    getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);
        }
    }


    static int getCountForIthAndTotal(int[] arr, Entry entry, Map<Entry, Integer> memoMap){
        if (memoMap.containsKey(entry)){     //look up in has table if we already calculated particular total for ith subset..
            return memoMap.get(entry);       //This is nothing but using memoization that reduce the entire below code i.e. further recursion -
        }else {
            int count = countSubSetForSum(arr, entry, memoMap);  //Recursion
            memoMap.put(entry, count); //Build memoization
            return count;
        }
    }


    //Just Data Structure for Key in HashMap (memoMaP)... intent to include particular total for ith element's subset.
    static class Entry {
        int total;
        int i;

        public Entry(int total, int i) {
            this.total = total;
            this.i = i;
        }

        public int getTotal() {
            return total;
        }

        public int getI() {
            return i;
        }


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Entry entry = (Entry) o;
            return total == entry.total &&
                    i == entry.i;
        }

        @Override
        public int hashCode() {
            return Objects.hash(total, i);
        }
    }

}

When i ran this the out put is :

In set of 5 elements, the number of subsets having total=16 is 2 
Process finished with exit code 0

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

Check Postgres access for a user

For all users on a specific database, do the following:

# psql
\c your_database
select grantee, table_catalog, privilege_type, table_schema, table_name from information_schema.table_privileges order by grantee, table_schema, table_name;

How to select multiple files with <input type="file">?

New answer:

In HTML5 you can add the multiple attribute to select more than 1 file.

<input type="file" name="filefield" multiple="multiple">

Old answer:

You can only select 1 file per <input type="file" />. If you want to send multiple files you will have to use multiple input tags or use Flash or Silverlight.

regex with space and letters only?

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

How to get href value using jQuery?

If your html link is like this:

<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

Then you can access the href in jquery as given below (there is no need to use "a" in href for this)

$(".linkClass").on("click",accesshref);

function accesshref()
 {
 var url = $(".linkClass").attr("href");
 //OR
 var url = $(this).attr("href");
}

How to do a redirect to another route with react-router?

How to do a redirect to another route with react-router?

For example, when a user clicks a link <Link to="/" />Click to route</Link> react-router will look for / and you can use Redirect to and send the user somewhere else like the login route.

From the docs for ReactRouterTraining:

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

to: string, The URL to redirect to.

<Redirect to="/somewhere/else"/>

to: object, A location to redirect to.

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>

How can I scroll a div to be visible in ReactJS?

Another example which uses function in ref rather than string

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items:[], index: 0 };
    this._nodes = new Map();

    this.handleAdd = this.handleAdd.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
   }

  handleAdd() {
    let startNumber = 0;
    if (this.state.items.length) {
      startNumber = this.state.items[this.state.items.length - 1];
    }

    let newItems = this.state.items.splice(0);
    for (let i = startNumber; i < startNumber + 100; i++) {
      newItems.push(i);
    }

    this.setState({ items: newItems });
  }

  handleRemove() {
    this.setState({ items: this.state.items.slice(1) });
  }

  handleShow(i) {
    this.setState({index: i});
    const node = this._nodes.get(i);
    console.log(this._nodes);
    if (node) {
      ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
    }
  }

  render() {
    return(
      <div>
        <ul>{this.state.items.map((item, i) => (<Item key={i} ref={(element) => this._nodes.set(i, element)}>{item}</Item>))}</ul>
        <button onClick={this.handleShow.bind(this, 0)}>0</button>
        <button onClick={this.handleShow.bind(this, 50)}>50</button>
        <button onClick={this.handleShow.bind(this, 99)}>99</button>
        <button onClick={this.handleAdd}>Add</button>
        <button onClick={this.handleRemove}>Remove</button>
        {this.state.index}
      </div>
    );
  }
}

class Item extends React.Component
{
  render() {
    return (<li ref={ element => this.listItem = element }>
      {this.props.children}
    </li>);
  }
}

Demo: https://codepen.io/anon/pen/XpqJVe

Python PDF library

There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.

How to escape JSON string?

String.Format("X", c);

That just outputs: X

Try this instead:

string t = ((int)c).ToString("X");

sb.Append("\\u" + t.PadLeft(4, '0'));

Convert array of integers to comma-separated string

You can have a pair of extension methods to make this task easier:

public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
    return lst.ToDelimitedString(p => p, separator);
}

public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, 
                                             string separator = ", ")
{
    return string.Join(separator, lst.Select(selector));
}

So now just:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();

is it possible to evenly distribute buttons across the width of an android linearlayout

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Tom"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="24sp" 
        android:layout_weight="3"/>

    <TextView
        android:text="Tim"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="24sp"
        android:layout_weight="3"/>

    <TextView
        android:text="Todd"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="24sp" 
        android:layout_weight="3"/>

</LinearLayout>

In circle, Tom, Tim, and Todd get assumed to be 3 centimeters. If you want it to be touch down screen, put it as Tom and Tim getting assumed to be 1 centimeter, which means they combine virtual but its 2D plane is at the bottom. This is displayed on screen.

Add IIS 7 AppPool Identities as SQL Server Logons

This may be what you are looking for...

http://technet.microsoft.com/en-us/library/cc730708%28WS.10%29.aspx

I would also advise longer term to consider a limited rights domain user, what you are trying works fine in a silo machine scenario but you are going to have to make changes if you move to another machine for the DB server.

How to POST JSON data with Python Requests?

It turns out I was missing the header information. The following works:

url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

How do you round UP a number in Python?

I think you are confusing the working mechanisms between int() and round().

int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.

round(2.5) = 3
int(2.5) = 2

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

The solution provided by Emanuele worked for me. I could see the report when I accessed it directly from the server but when I used a ReportViewer control on my aspx page, I was unable to see the report. Upon inspecting the rendered HTML, I found a div by the id "ReportViewerGeneral_ctl09" (ReportViewerGeneral is the server id of the report viewer control) which had it's overflow property set to auto.

<div id="ReportViewerGeneral_ctl09" style="height: 100%; width: 100%; overflow: auto; position: relative; ">...</div>

I used the procedure explained by Emanuele to change this to visible as follows:

function pageLoad() {
    var element = document.getElementById("ReportViewerGeneral_ctl09");

    if (element) {
        element.style.overflow = "visible";
    }
}

Fastest way of finding differences between two files in unix?

This will work fast:

Case 1 - File2 = File1 + extra text appended.

grep -Fxvf File2.txt File1.txt >> File3.txt

File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines

How to echo in PHP, HTML tags

You need to escape the " so that PHP doesn't recognise them as part of your PHP code. You do this by using the \ escape character.

So, your code would look like this:

echo
    "<div>
        <h3><a href=\"#\">First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
    </div>
    <div>"

How to get the selected date of a MonthCalendar control in C#

For those who are still trying, this link helped me out, too; it just puts it all together:

http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx

private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);

//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;

//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}

Laravel redirect back to original destination after login

For Laravel 5.5 and probably 5.4

In App\Http\Middleware\RedirectIfAuthenticated change redirect('/home') to redirect()->intended('/home') in the handle function:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect()->intended('/home');
    }

    return $next($request);
}

in App\Http\Controllers\Auth\LoginController create the showLoginForm() function as follows:

public function showLoginForm()
{
    if(!session()->has('url.intended'))
    {
        session(['url.intended' => url()->previous()]);
    }
    return view('auth.login');
}

This way if there was an intent for another page it will redirect there otherwise it will redirect home.

How to convert an int to string in C?

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

How to delete all data from solr and hbase

If you need to clean out all data, it might be faster to recreate collection, e.g.

solrctl --zk localhost:2181/solr collection --delete <collectionName>
solrctl --zk localhost:2181/solr collection --create <collectionName> -s 1

Create web service proxy in Visual Studio from a WSDL file

save the file on your disk and then use the following as URL:

file://your_path/your_file.wsdl

How to convert a pymongo.cursor.Cursor into a dict?

Easy

import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
array = list(col.find())

print array

There you go

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

I found it, I was trying to compile my app which is using facebook sdk. I was made that like augst 2016. When I try to open it today i got same error. I had that line in my gradle " compile 'com.facebook.android:facebook-android-sdk:4.+' " and I went https://developers.facebook.com/docs/android/change-log-4x this page and i found the sdk version while i was running this app succesfully and it was 4.14.1 then I changed that line to " compile 'com.facebook.android:facebook-android-sdk:4.14.1' " and it worked.

Output data with no column headings using PowerShell

First we grab the command output, then wrap it and select one of its properties. There is only one and its "Name" which is what we want. So we select the groups property with ".name" then output it.

to text file

 (Get-ADGroupMember 'Domain Admins' |Select name).name | out-file Admins1.txt

to csv

(Get-ADGroupMember 'Domain Admins' |Select name).name | export-csv -notypeinformation "Admins1.csv"

When are static variables initialized?

Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

Currently some people are facing the same issue because of using 12.0.0 version of AdMob lib.

Update it to 12.0.1. This should fix it. You can read more here

Finding last occurrence of substring in string, replacing that

You can use the function below which replaces the first occurrence of the word from right.

def replace_from_right(text: str, original_text: str, new_text: str) -> str:
    """ Replace first occurrence of original_text by new_text. """
    return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

A trick that works is to position box #2 with position: absolute instead of position: relative. We usually put a position: relative on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:

And here is the full code with this change:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">

            /* Positioning */
            #box1 { overflow: hidden }
            #box2 { position: absolute }
            #box3 { position: absolute; top: 10px }

            /* Styling */
            #box1 { background: #efe; padding: 5px; width: 125px }
            #box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
            #box3 { background: #eef; padding: 2px; width: 75px; height: 150px }

        </style>
    </head>
    <body>
        <br/><br/><br/>
        <div id="box1">
            <div id="box2">
                <div id="box3"/>
            </div>
        </div>
    </body>
</html>

How can I break from a try/catch block without throwing an exception in Java

The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:

public void someMethod() {
    try {
        ...
        if (condition)
            return;
        ...
    } catch (SomeException e) {
        ...
    }
}

If the code involves lots of local variables, you may also consider using a break from a labeled block, as suggested by Stephen C:

label: try {
    ...
    if (condition)
        break label;
    ...
} catch (SomeException e) {
    ...
}

Javascript change font color

Consider changing your markup to this:

<span id="someId">onlineff</span>

Then you can use this script:

var x = document.getElementById('someId');
x.style.color = '#00FF00';

see it here: http://jsfiddle.net/2ANmM/

How do I update a Python package?

pip install -U $(pip list --outdated | awk 'NR>2 {print $1}')

Regex Match all characters between two strings

Lazy Quantifier Needed

Resurrecting this question because the regex in the accepted answer doesn't seem quite correct to me. Why? Because

(?<=This is)(.*)(?=sentence)

will match my first sentence. This is my second in This is my first sentence. This is my second sentence.

See demo.

You need a lazy quantifier between the two lookarounds. Adding a ? makes the star lazy.

This matches what you want:

(?<=This is).*?(?=sentence)

See demo. I removed the capture group, which was not needed.

DOTALL Mode to Match Across Line Breaks

Note that in the demo the "dot matches line breaks mode" (a.k.a.) dot-all is set (see how to turn on DOTALL in various languages). In many regex flavors, you can set it with the online modifier (?s), turning the expression into:

(?s)(?<=This is).*?(?=sentence)

Reference

how to get curl to output only http response body (json) and no other headers etc

#!/bin/bash

req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

Select specific row from mysql table

SQL tables are not ordered by default, and asking for the n-th row from a non ordered set of rows has no meaning as it could potentially return a different row each time unless you specify an ORDER BY:

select * from customer order by id where row_number() = 3

(sometimes MySQL tables are shown with an internal order but you cannot rely on this behaviour). Then you can use LIMIT offset, row_count, with a 0-based offset so row number 3 becomes offset 2:

select * from customer order by id
limit 2, 1

or you can use LIMIT row_count OFFSET offset:

select * from customer order by id
limit 1 offset 2

Storyboard - refer to ViewController in AppDelegate

Have a look at the documentation for -[UIStoryboard instantiateViewControllerWithIdentifier:]. This allows you to instantiate a view controller from your storyboard using the identifier that you set in the IB Attributes Inspector:

enter image description here

EDITED to add example code:

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                         bundle: nil];

MyViewController *controller = (MyViewController*)[mainStoryboard 
                    instantiateViewControllerWithIdentifier: @"<Controller ID>"];

What does 'wb' mean in this code, using Python?

That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

Object of class stdClass could not be converted to string

In General to get rid of

Object of class stdClass could not be converted to string.

try to use echo '<pre>'; print_r($sql_query); for my SQL Query got the result as

stdClass Object
(
    [num_rows] => 1
    [row] => Array
        (
            [option_id] => 2
            [type] => select
            [sort_order] => 0
        )

    [rows] => Array
        (
            [0] => Array
                (
                    [option_id] => 2
                    [type] => select
                    [sort_order] => 0
                )

        )

)

In order to acces there are different methods E.g.: num_rows, row, rows

echo $query2->row['option_id'];

Will give the result as 2

How to parse unix timestamp to time.Time

According to the go documentation, Unix returns a local time.

Unix returns the local Time corresponding to the given Unix time

This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.

To do so, I adapted the snippet to make it return a time in UTC:

i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
    panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())

This prints on my machine (in CEST)

2014-07-16 20:55:46 +0000 UTC

How to migrate GIT repository from one server to a new one

You can use git-copy to duplicate the repo with all histories.

git copy http://a.com/old.git http://a.com/new.git

Using Jasmine to spy on a function without an object

If you are defining your function:

function test() {};

Then, this is equivalent to:

window.test = function() {}  /* (in the browser) */

So spyOn(window, 'test') should work.

If that is not, you should also be able to:

test = jasmine.createSpy();

If none of those are working, something else is going on with your setup.

I don't think your fakeElement technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.

Python executable not finding libpython shared library

I had the same problem and I solved it this way:

If you know where libpython resides at, I supposed it would be /usr/local/lib/libpython2.7.so.1.0 in your case, you can just create a symbolic link to it:

sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0

Then try running ldd again and see if it worked.

How to change CSS using jQuery?

You can do either:

$("h1").css("background-color", "yellow");

Or:

$("h1").css({backgroundColor: "yellow"});

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

How to get screen width without (minus) scrollbar?

I experienced a similar problem and doing width:100%; solved it for me. I came to this solution after trying an answer in this question and realizing that the very nature of an <iframe> will make these javascript measurement tools inaccurate without using some complex function. Doing 100% is a simple way to take care of it in an iframe. I don't know about your issue since I'm not sure of what HTML elements you are manipulating.

How to enable multidexing with the new Android Multidex support library

Here is an up-to-date approach as of October 2020, with Android X. This comes from Android's documentation, "Enable multidex for apps with over 64K methods."

For minSdk >= 21

You do not need to do anything. All of these devices use the Android RunTime (ART) VM, which supports multidex natively.

For minSdk < 21

In your module-level build.gradle, ensure that the following configurations are populated:

android {
    defaultConfig {
        multiDexEnabled true
    }
}

dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
}

You need to install explicit multidex support. The documentation includes three methods to do so, and you have to pick one.

For example, in your src/main/AndroidManifest.xml, you can declare MultiDexApplication as the application:name:

<manifest package="com.your.package"
          xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:name="androidx.multidex.MultiDexApplication" />
</manifest>

ArrayList: how does the size increase?

From JDK source code, I found below code

int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);

Make DateTimePicker work as TimePicker only in WinForms

...or alternatively if you only want to show a portion of the time value use "Custom":

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

Reading NFC Tags with iPhone 6 / iOS 8

From digging into the iOS 8 docs that are available as of Sept 9th 3:30pm there is no mention of developer access to the NFC controller to perform any NFC operations; that includes reading tags, writing tags, pairing, payments, tag emulation... Given its an NXP controller the hardware has the capability to perform these features. They did mention a 3rd party app for the watch that allowed a hotel guest to open their room door with NFC. This is a classic use case for NFC and gives some indication that the NFC controller will be open to developers at some point. Remember, the watch is not supposed to be released until Q1 2015. So for now I'd say it's closed but will be open soon. Given the 'newness' of contactless payments for the general US consumer and the recent security breaches its not surprising Apple wants to keep this closed for a while.

Disclosure: Im the CEO of GoToTags, an NFC company with obvious vested interest in Apple opening up NFC to developers.

--- Correction & Update ---

The hotel app actually uses Bluetooth, not NFC. NFC is still often used for door unlocking, just not in this one example. NFC could be used if the watch has an open NFC controller.

I do know that Apple is aware of all of this and is discussing this with their top developers and stakeholders. There has already been massive negative push back on the lack of support for reading tags. As often the case in the past, I expect Apple to eventually open this up to developers for non-payment related functionality (reading tags, pairing). I do not think Apple will ever allow other wallets though. File sharing will likely be left to AirDrop as well.

--- Update on March 23rd 2016 ---

I am continually asked for updates about this topic, often with people referencing this post. With Apple releasing the iPhone SE, many are again asking why Apple has not supported tag reading yet. In summary Apple is more focused on Apple Pay succeeding than the other use cases for NFC for now. Apple could make a lot of money from Apple Pay, and has less to make from the other uses for NFC. Apple will likely open up NFC tag reading when they feel that consumer trust and security with NFC and Apple Pay is such that it wont put Apple Pay at risk. Further information here.

--- Update on May 24th 2017 ---

A developer in Greece has hacked the iPhone 6s to get it to read NFC tags via the NFC private frameworks; more info & video. While this isn't a long term solution, it provides some guidance on some outstanding question: Is there enough power in the iPhone's NFC controller to power an NFC tag? Looks like the answer is yes. From initial testing the range is a few cm, which isn't too bad. It might also be the power is tunable; this is being investigated at this time. The implications of this are significant. If the older model phones do have enough RF power for tag reading/writing, then when Apple does open up the SDK it means there will be 100Ms of iPhones that can read NFC tags, vs the case where only the new iPhones could.

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

How does MySQL process ORDER BY and LIMIT in a query?

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

All details on: http://dev.mysql.com/doc/refman/5.0/en/select.html

How to install Android Studio on Ubuntu?

add a repository,

sudo apt-add-repository ppa:maarten-fonville/android-studio
sudo apt-get update

Then install using the command below:

sudo apt-get install android-studio

Including a css file in a blade template?

include the css file into your blade template in laravel

  1. move css file into public->css folder in your laravel project.
  2. use <link rel="stylesheet" href="{{ asset('css/filename') }}">

so css is applied in a blade.php file.

Difference between using Throwable and Exception in a try catch

Thowable catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop() method. So by catching Throwable you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError and InternalError or StackOverflowError.

Catching Throwable is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.

C++ Loop through Map

Try the following

for ( const auto &p : table )
{
   std::cout << p.first << '\t' << p.second << std::endl;
} 

The same can be written using an ordinary for loop

for ( auto it = table.begin(); it != table.end(); ++it  )
{
   std::cout << it->first << '\t' << it->second << std::endl;
} 

Take into account that value_type for std::map is defined the following way

typedef pair<const Key, T> value_type

Thus in my example p is a const reference to the value_type where Key is std::string and T is int

Also it would be better if the function would be declared as

void output( const map<string, int> &table );

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

React Native android build failed. SDK location not found

This worked for me .

I am taking Stephen Grider's React Native on Udemy and one of the students posted this in Lecture 50. Pasted verbatim in the command line (w/o '$' of course).

$ export "ANDROID_HOME=/usr/local/opt/android-sdk" >~/.bash_profile

Centering image and text in R Markdown for a PDF report

none of the answers worked but this

\newcommand{\bcenter}{\begin{center}}
\newcommand{\ecenter}{\end{center}}

but then the following problem is that it works for only one figure and then will not for any other figures.

I just started learning R I knew it was going to be difficult but what's worst is that there is little to no info that I can refer to.

ReactJS - How to use comments?

To summarize, JSX doesn't support comments, either html-like or js-like:

<div>
    /* This will be rendered as text */
    // as well as this
    <!-- While this will cause compilation failure -->
</div>

and the only way to add comments "in" JSX is actually to escape into JS and comment in there:

<div>
    {/* This won't be rendered */}
    {// just be sure that your closing bracket is out of comment
    }
</div>

if you don't want to make some nonsense like

<div style={{display:'none'}}>
    actually, there are other stupid ways to add "comments"
    but cluttering your DOM is not a good idea
</div>

Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.

What are some good Python ORM solutions?

SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode.

Why can't I have abstract static methods in C#?

We actually override static methods (in delphi), it's a bit ugly, but it works just fine for our needs.

We use it so the classes can have a list of their available objects without the class instance, for example, we have a method that looks like this:

class function AvailableObjects: string; override;
begin
  Result := 'Object1, Object2';
end; 

It's ugly but necessary, this way we can instantiate just what is needed, instead of having all the classes instantianted just to search for the available objects.

This was a simple example, but the application itself is a client-server application which has all the classes available in just one server, and multiple different clients which might not need everything the server has and will never need an object instance.

So this is much easier to maintain than having one different server application for each client.

Hope the example was clear.

How to set value in @Html.TextBoxFor in Razor syntax?

I tried replacing value with Value and it worked out. It has set the value in input tag now.

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

How to move certain commits to be based on another branch in git?

The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto but is easier for the eyes :)

git cherry-pick quickfix1..quickfix2

JavaScript .replace only replaces first Match

From w3schools

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Would be better to use a regex here then:

textTitle.replace(/ /g, '%20');

Bash: infinite sleep (infinite blocking)

tail does not block

As always: For everything there is an answer which is short, easy to understand, easy to follow and completely wrong. Here tail -f /dev/null falls into this category ;)

If you look at it with strace tail -f /dev/null you will notice, that this solution is far from blocking! It's probably even worse than the sleep solution in the question, as it uses (under Linux) precious resources like the inotify system. Also other processes which write to /dev/null make tail loop. (On my Ubuntu64 16.10 this adds several 10 syscalls per second on an already busy system.)

The question was for a blocking command

Unfortunately, there is no such thing ..

Read: I do not know any way to archive this with the shell directly.

Everything (even sleep infinity) can be interrupted by some signal. So if you want to be really sure it does not exceptionally return, it must run in a loop, like you already did for your sleep. Please note, that (on Linux) /bin/sleep apparently is capped at 24 days (have a look at strace sleep infinity), hence the best you can do probably is:

while :; do sleep 2073600; done

(Note that I believe sleep loops internally for higher values than 24 days, but this means: It is not blocking, it is very slowly looping. So why not move this loop to the outside?)

.. but you can come quite near with an unnamed fifo

You can create something which really blocks as long as there are no signals send to the process. Following uses bash 4, 2 PIDs and 1 fifo:

bash -c 'coproc { exec >&-; read; }; eval exec "${COPROC[0]}<&-"; wait'

You can check that this really blocks with strace if you like:

strace -ff bash -c '..see above..'

How this was constructed

read blocks if there is no input data (see some other answers). However, the tty (aka. stdin) usually is not a good source, as it is closed when the user logs out. Also it might steal some input from the tty. Not nice.

To make read block, we need to wait for something like a fifo which will never return anything. In bash 4 there is a command which can exactly provide us with such a fifo: coproc. If we also wait the blocking read (which is our coproc), we are done. Sadly this needs to keep open two PIDs and a fifo.

Variant with a named fifo

If you do not bother using a named fifo, you can do this as follows:

mkfifo "$HOME/.pause.fifo" 2>/dev/null; read <"$HOME/.pause.fifo"

Not using a loop on the read is a bit sloppy, but you can reuse this fifo as often as you like and make the reads terminat using touch "$HOME/.pause.fifo" (if there are more than a single read waiting, all are terminated at once).

Or use the Linux pause() syscall

For the infinite blocking there is a Linux kernel call, called pause(), which does what we want: Wait forever (until a signal arrives). However there is no userspace program for this (yet).

C

Create such a program is easy. Here is a snippet to create a very small Linux program called pause which pauses indefinitely (needs diet, gcc etc.):

printf '#include <unistd.h>\nint main(){for(;;)pause();}' > pause.c;
diet -Os cc pause.c -o pause;
strip -s pause;
ls -al pause

python

If you do not want to compile something yourself, but you have python installed, you can use this under Linux:

python -c 'while 1: import ctypes; ctypes.CDLL(None).pause()'

(Note: Use exec python -c ... to replace the current shell, this frees one PID. The solution can be improved with some IO redirection as well, freeing unused FDs. This is up to you.)

How this works (I think): ctypes.CDLL(None) loads the standard C library and runs the pause() function in it within some additional loop. Less efficient than the C version, but works.

My recommendation for you:

Stay at the looping sleep. It's easy to understand, very portable, and blocks most of the time.

ReactJS - Get Height of an element

For those who are interested in using react hooks, this might help you get started.

import React, { useState, useEffect, useRef } from 'react'

export default () => {
  const [height, setHeight] = useState(0)
  const ref = useRef(null)

  useEffect(() => {
    setHeight(ref.current.clientHeight)
  })

  return (
    <div ref={ref}>
      {height}
    </div>
  )
}

Is it possible to declare a variable in Gradle usable in Java?

Here are two ways to pass value from Gradle to use in Java;

Generate Java Constants

android {
    buildTypes {
        debug {
            buildConfigField "int", "FOO", "42"
            buildConfigField "String", "FOO_STRING", "\"foo\""
            buildConfigField "boolean", "LOG", "true"
        }

        release {
            buildConfigField "int", "FOO", "52"
            buildConfigField "String", "FOO_STRING", "\"bar\""
            buildConfigField "boolean", "LOG", "false"
        }
    }
}

You can access them with BuildConfig.FOO

Generate Android resources

android {
    buildTypes {
        debug{
            resValue "string", "app_name", "My App Name Debug"
        }
        release {
            resValue "string", "app_name", "My App Name"
        }
    }
}

You can access them in the usual way with @string/app_name or R.string.app_name

Remove white space below image

If you would like to preserve the image as inline you can put vertical-align: top or vertical-align: bottom on it. By default it is aligned on the baseline hence the few pixels beneath it.

iOS download and save image inside app

If you are using AFNetworking library to download image and that images are using in UITableview then You can use below code in cellForRowAtIndexPath

 [self setImageWithURL:user.user_ProfilePicturePath toControl:cell.imgView]; 
 
-(void)setImageWithURL:(NSURL*)url toControl:(id)ctrl
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        if (image) {
            if([ctrl isKindOfClass:[UIButton class]])
            {
                UIButton btn =(UIButton)ctrl;
                [btn setBackgroundImage:image forState:UIControlStateNormal];
            }
            else
            {
                UIImageView imgView = (UIImageView)ctrl;
                imgView.image = image;
            }

} } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { NSLog(@"No Image"); }]; [operation start];}

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
{
    public string ItemType { get; set; }

    public string this[string propertyName]
    {
        set
        {
            switch (propertyName)
            {
                case "itemType":
                    ItemType = value;
                    break;
                    // etc
            }   
        }
    }
}

Alternatively, as others have mentioned, use reflection.

PySpark 2.0 The size or shape of a DataFrame

print((df.count(), len(df.columns)))

is easier for smaller datasets.

However if the dataset is huge, an alternative approach would be to use pandas and arrows to convert the dataframe to pandas df and call shape

spark.conf.set("spark.sql.execution.arrow.enabled", "true")
spark.conf.set("spark.sql.crossJoin.enabled", "true")
print(df.toPandas().shape)

Creating a zero-filled pandas data frame

You can try this:

d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)

WPF MVVM: How to close a window

Simple approach is close window on saveComand Implementation. Use below code to close window.

Application.Current.Windows[1].Close();

It will close the child window.

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

Can I redirect the stdout in python into some sort of string buffer?

In Python3.6, the StringIO and cStringIO modules are gone, you should use io.StringIO instead.So you should do this like the first answer:

import sys
from io import StringIO

old_stdout = sys.stdout
old_stderr = sys.stderr
my_stdout = sys.stdout = StringIO()
my_stderr = sys.stderr = StringIO()

# blah blah lots of code ...

sys.stdout = self.old_stdout
sys.stderr = self.old_stderr

// if you want to see the value of redirect output, be sure the std output is turn back
print(my_stdout.getvalue())
print(my_stderr.getvalue())

my_stdout.close()
my_stderr.close()

How to pass argument to Makefile from command line?

Few years later, want to suggest just for this: https://github.com/casey/just

action v1 v2=default:
    @echo 'take action on {{v1}} and {{v2}}...'

Align div with fixed position on the right side

You can use two imbricated div. But you need a fixed width for your content, that's the only limitation.

<div style='float:right; width: 180px;'>
 <div style='position: fixed'>
   <!-- Your content -->
 </div>
</div>

How to print the current Stack Trace in .NET without any exception?

An alternative to System.Diagnostics.StackTrace is to use System.Environment.StackTrace which returns a string-representation of the stacktrace.

Another useful option is to use the $CALLER and $CALLSTACK debugging variables in Visual Studio since this can be enabled run-time without rebuilding the application.

Scripting SQL Server permissions

YOU CAN ALSO DOWNLOAD THE CODE IN THE BELOW LINK AND SEE HOW IT WORKS

https://gallery.technet.microsoft.com/Extract-Database-dfa53d5a

THIS IS HOW YOU WILL SEE THE OUTPUT OF THIS QUERY

set nocount off

IF OBJECT_ID(N'tempdb..##temp1') IS NOT NULL
     DROP TABLE ##temp1

create table ##temp1(query varchar(1000))

insert into ##temp1 
select 'use '+db_name() +';'

insert into ##temp1 
select 'go'

/*creating database roles*/
insert into ##temp1
                    select 'if DATABASE_PRINCIPAL_ID('''+name+''')  is null 
                    exec sp_addrole '''+name+''''  from sysusers
where issqlrole = 1 and (sid is not null and sid <> 0x0)

/*creating application roles*/
insert into ##temp1
                    select 'if DATABASE_PRINCIPAL_ID('+char(39)+name+char(39)+')
                    is null CREATE APPLICATION ROLE ['+name+'] WITH DEFAULT_SCHEMA = ['+
                    default_schema_name+'], Password='+char(39)+'Pass$w0rd123'+char(39)+' ;'
 from sys.database_principals
where type_desc='APPLICATION_ROLE'

insert into ##temp1 
                     select  
                                case  
                                          when state_desc='GRANT_WITH_GRANT_OPTION' 
                                                       then
                                                                substring (state_desc,0,6)+' '+permission_name+' to '+'['+USER_NAME(grantee_principal_id)+']'+' WITH GRANT OPTION ;'

                                                         else 
                                                                  state_desc+' '+permission_name+' to '+'['+USER_NAME(grantee_principal_id)+']'+' ;'
                    END
from sys.database_permissions 
where class=0 and USER_NAME(grantee_principal_id) not in ('dbo','guest','sys','information_schema')

insert into ##temp1 
                    select 
                               case 
                                         when state_desc='GRANT_WITH_GRANT_OPTION' 
                                                   then
                                                             substring (state_desc,0,6)+' '+permission_name+' on '+OBJECT_SCHEMA_NAME(major_id)+'.['+OBJECT_NAME(major_id)
                                                             +'] to '+'['+USER_NAME(grantee_principal_id)+']'+' with grant option ;'
                                                     else 
                                                              state_desc+' '+permission_name+' on '+OBJECT_SCHEMA_NAME(major_id)+'.['+OBJECT_NAME(major_id)
                                                              +'] to '+'['+USER_NAME(grantee_principal_id)+']'+' ;'
                                  end
from sys.database_permissions where class=1 and USER_NAME(grantee_principal_id) not in ('public');


 insert into ##temp1 
                      select 
                                 case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION' 
                                                     then
                                                              substring (state_desc,0,6)+' '+permission_name+' ON schema::['+sa.name+
                                                               '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                                       else
                                                               state_desc+' '+permission_name+' ON schema::['+sa.name+
                                                               '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                       COLLATE LATIN1_General_CI_AS  
                                      end
from sys.database_permissions dp inner join sys.schemas sa on
 sa.schema_id = dp.major_id where dp.class=3

 insert into ##temp1 
                     select 
                                 case 
                                            when state_desc='GRANT_WITH_GRANT_OPTION'
                                             then
                                                    substring (state_desc,0,6)+' '+permission_name+' ON APPLICATION  ROLE::['+sa.name+
                                                     '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                             else
                                                      state_desc+' '+permission_name+' ON  APPLICATION ROLE::['+sa.name+
                                                      '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                      COLLATE LATIN1_General_CI_AS  
                         end
from sys.database_permissions dp inner join sys.database_principals  sa on
 sa.principal_id = dp.major_id where dp.class=4 and sa.type='A'

 insert into ##temp1 
                      select 
                                 case 
                                          when state_desc='GRANT_WITH_GRANT_OPTION' 
                                           then
                                                  substring (state_desc,0,6)+' '+permission_name+' ON   ROLE::['+sa.name+
                                                  '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                           else
                                                   state_desc+' '+permission_name+' ON   ROLE::['+sa.name+
                                                    '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                     COLLATE LATIN1_General_CI_AS  
                                           end
 from sys.database_permissions dp inner join
sys.database_principals  sa on sa.principal_id = dp.major_id 
 where dp.class=4 and sa.type='R'

 insert into ##temp1 
                      select 
                                  case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION' 
                                                       then
                                                               substring (state_desc,0,6)+' '+permission_name+' ON ASSEMBLY::['+sa.name+
                                                                '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                                        else
                                                                state_desc+' '+permission_name+' ON ASSEMBLY::['+sa.name+
                                                                 '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                                 COLLATE LATIN1_General_CI_AS  
                                       end
 from sys.database_permissions dp inner join sys.assemblies sa on
 sa.assembly_id = dp.major_id 
 where dp.class=5

 insert into ##temp1
                     select 
                                 case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION' 
                                            then
                                                    substring (state_desc,0,6)+'  '+permission_name+' ON type::['
                                                    +SCHEMA_NAME(schema_id)+'].['+sa.name+
                                                    '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                            else
                                                    state_desc+' '+permission_name+' ON type::['
                                                    +SCHEMA_NAME(schema_id)+'].['+sa.name+
                                                     '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                     COLLATE LATIN1_General_CI_AS  
                                              end
 from sys.database_permissions dp inner join sys.types sa on
 sa.user_type_id = dp.major_id 
 where dp.class=6


 insert into ##temp1
                      select 
                                 case 
                                          when state_desc='GRANT_WITH_GRANT_OPTION' 
                                           then
                                                     substring (state_desc,0,6)+'  '+permission_name+' ON  XML SCHEMA COLLECTION::['+
                                                     SCHEMA_NAME(SCHEMA_ID)+'].['+sa.name+'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                            else
                                                     state_desc+' '+permission_name+' ON  XML SCHEMA COLLECTION::['+
                                                     SCHEMA_NAME(SCHEMA_ID)+'].['+sa.name+'] to ['+user_name(dp.grantee_principal_id)+'];'
                                                     COLLATE LATIN1_General_CI_AS  
                                   end
 from sys.database_permissions dp inner join sys.xml_schema_collections sa on
 sa.xml_collection_id = dp.major_id 
 where dp.class=10



insert into ##temp1
                    select
                               case 
                                         when state_desc='GRANT_WITH_GRANT_OPTION' 
                                          then
                                                   substring (state_desc,0,6)+'  '+permission_name+' ON message type::['+sa.name+
                                                    '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                           else
                                                    state_desc+' '+permission_name+' ON message type::['+sa.name+
                                                    '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                     COLLATE LATIN1_General_CI_AS  
                                             end
 from sys.database_permissions dp inner join sys.service_message_types sa on
 sa.message_type_id = dp.major_id 
 where dp.class=15


 insert into ##temp1
                      select 
                                  case 
                                            when state_desc='GRANT_WITH_GRANT_OPTION' 
                                              then
                                                       substring (state_desc,0,6)+'  '+permission_name+' ON contract::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                                else
                                                         state_desc+' '+permission_name+' ON contract::['+sa.name+
                                                         '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                         COLLATE LATIN1_General_CI_AS  
                                   end
 from sys.database_permissions dp inner join sys.service_contracts sa on
 sa.service_contract_id = dp.major_id 
 where dp.class=16



  insert into ##temp1
                      select 
                                 case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION' 
                                            then
                                                      substring (state_desc,0,6)+'  '+permission_name+' ON SERVICE::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                              else
                                                       state_desc+'  '+permission_name+' ON SERVICE::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                        COLLATE LATIN1_General_CI_AS  
                                    end
 from sys.database_permissions dp inner join sys.services sa on
 sa.service_id = dp.major_id 
 where dp.class=17


 insert into ##temp1 
                      select 
                                   case 
                                              when state_desc='GRANT_WITH_GRANT_OPTION'
                                               then
                                                          substring (state_desc,0,6)+'  '+permission_name+' ON REMOTE SERVICE BINDING::['+sa.name+
                                                          '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                                 else
                                                          state_desc+' '+permission_name+' ON REMOTE SERVICE BINDING::['+sa.name+
                                                           '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                          COLLATE LATIN1_General_CI_AS  
                                      end
 from sys.database_permissions dp inner join sys.remote_service_bindings sa on
 sa.remote_service_binding_id = dp.major_id 
 where dp.class=18

 insert into ##temp1
                      select
                                  case 
                                            when state_desc='GRANT_WITH_GRANT_OPTION'
                                              then
                                                        substring (state_desc,0,6)+'  '+permission_name+' ON route::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                                else
                                                          state_desc+' '+permission_name+' ON route::['+sa.name+
                                                          '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                         COLLATE LATIN1_General_CI_AS  
                                      end
 from sys.database_permissions dp inner join sys.routes sa on
 sa.route_id = dp.major_id 
 where dp.class=19

 insert into ##temp1 
                      select 
                                 case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION' 
                                            then
                                                     substring (state_desc,0,6)+'  '+permission_name+' ON FULLTEXT CATALOG::['+sa.name+
                                                      '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                             else
                                                       state_desc+' '+permission_name+' ON FULLTEXT CATALOG::['+sa.name+
                                                       '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                        COLLATE LATIN1_General_CI_AS  
                                       end
 from sys.database_permissions dp inner join sys.fulltext_catalogs sa on
 sa.fulltext_catalog_id = dp.major_id 
 where dp.class=23

  insert into ##temp1 
                      select 
                                 case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION'
                                            then
                                                        substring (state_desc,0,6)+'  '+permission_name+' ON SYMMETRIC KEY::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                             else
                                                        state_desc+' '+permission_name+' ON SYMMETRIC KEY::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                        COLLATE LATIN1_General_CI_AS  
                                             end
 from sys.database_permissions dp inner join sys.symmetric_keys sa on
 sa.symmetric_key_id = dp.major_id 
 where dp.class=24

 insert into ##temp1 
                      select 
                                  case 
                                           when state_desc='GRANT_WITH_GRANT_OPTION' 
                                             then
                                                       substring (state_desc,0,6)+'  '+permission_name+' ON certificate::['+sa.name+
                                                        '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                               else
                                                          state_desc+' '+permission_name+' ON certificate::['+sa.name+
                                                          '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                           COLLATE LATIN1_General_CI_AS  
                                   end
 from sys.database_permissions dp inner join sys.certificates sa on
 sa.certificate_id = dp.major_id 
 where dp.class=25


 insert into ##temp1 
                     select 
                                 case 
                                          when state_desc='GRANT_WITH_GRANT_OPTION' 
                                          then
                                                     substring (state_desc,0,6)+'  '+permission_name+' ON ASYMMETRIC KEY::['+sa.name+
                                                     '] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
                                             else
                                                      state_desc+' '+permission_name+' ON ASYMMETRIC KEY::['+sa.name+
                                                       '] to ['+user_name(dp.grantee_principal_id)+'] ;'
                                                       COLLATE LATIN1_General_CI_AS  
                        end
 from sys.database_permissions dp inner join sys.asymmetric_keys sa on
 sa.asymmetric_key_id = dp.major_id 
 where dp.class=26

insert into ##temp1 
                     select  'exec sp_addrolemember ''' +p.NAME+''','+'['+m.NAME+']'+' ;'
FROM sys.database_role_members rm
JOIN sys.database_principals p
ON rm.role_principal_id = p.principal_id
JOIN sys.database_principals m
ON rm.member_principal_id = m.principal_id
where m.name not like 'dbo';






select *  from ##temp1  

How to turn on/off MySQL strict mode in localhost (xampp)?

on Debian 10 I start mysql from ./opt/lampp/xampp start

I do strace ./opt/lampp/sbin/mysqld and see that my.cnf is there:

stat("/opt/lampp/etc/my.cnf", {st_mode=S_IFREG|0644, st_size=5050, ...}) = 0
openat(AT_FDCWD, "/opt/lampp/etc/my.cnf", O_RDONLY|O_CLOEXEC) = 3

hence, I add sql_mode config to /opt/lampp/etc/my.cnf instead of /etc/mysql/my.cnf

CSS3 selector :first-of-type with class name?

This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.

However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :

:not(.myclass1) + .myclass1

Full working code example:

_x000D_
_x000D_
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
  <div>This text should appear as normal</div>_x000D_
  <p>This text should be blue.</p>_x000D_
  <p class="myclass1">This text should appear red.</p>_x000D_
  <p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_