Programs & Examples On #Mdb2

A database abstraction layer for PHP.

Assigning the return value of new by reference is deprecated

In PHP5 this idiom is deprecated

$obj_md =& new MDB2();

You sure you've not missed an ampersand in your sample code? That would generate the warning you state, but it is not required and can be removed.

To see why this idiom was used in PHP4, see this manual page (note that PHP4 is long dead and this link is to an archived version of the relevant page)

How To Check If A Key in **kwargs Exists?

One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

import sys

def myfunc(**kwargs):
    args = {'country':'England','town':'London',
            'currency':'Pound', 'language':'English'}

    diff = set(kwargs.keys()) - set(args.keys())
    if diff:
        print("Invalid args:",tuple(diff),file=sys.stderr)
        return

    args.update(kwargs)            
    print(args)

The defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.

Fill Combobox from database

void Fillcombobox()
{

    con.Open();
    cmd = new SqlCommand("select ID From Employees",con);
    Sdr = cmd.ExecuteReader();
    while (Sdr.Read())
    {
        for (int i = 0; i < Sdr.FieldCount; i++)
        {
           comboID.Items.Add( Sdr.GetString(i));

        }
    }
    Sdr.Close();
    con.Close();

}

Better/Faster to Loop through set or list?

set is what you want, so you should use set. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)! Code defensively. Worry about what's faster when you determine that it is too slow.

range(min(mylist), max(mylist) + 1)  # <-- don't forget to add 1

Replace all elements of Python NumPy Array that are greater than some value

Since you actually want a different array which is arr where arr < 255, and 255 otherwise, this can be done simply:

result = np.minimum(arr, 255)

More generally, for a lower and/or upper bound:

result = np.clip(arr, 0, 255)

If you just want to access the values over 255, or something more complicated, @mtitan8's answer is more general, but np.clip and np.minimum (or np.maximum) are nicer and much faster for your case:

In [292]: timeit np.minimum(a, 255)
100000 loops, best of 3: 19.6 µs per loop

In [293]: %%timeit
   .....: c = np.copy(a)
   .....: c[a>255] = 255
   .....: 
10000 loops, best of 3: 86.6 µs per loop

If you want to do it in-place (i.e., modify arr instead of creating result) you can use the out parameter of np.minimum:

np.minimum(arr, 255, out=arr)

or

np.clip(arr, 0, 255, arr)

(the out= name is optional since the arguments in the same order as the function's definition.)

For in-place modification, the boolean indexing speeds up a lot (without having to make and then modify the copy separately), but is still not as fast as minimum:

In [328]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: np.minimum(a, 255, a)
   .....: 
100000 loops, best of 3: 303 µs per loop

In [329]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: a[a>255] = 255
   .....: 
100000 loops, best of 3: 356 µs per loop

For comparison, if you wanted to restrict your values with a minimum as well as a maximum, without clip you would have to do this twice, with something like

np.minimum(a, 255, a)
np.maximum(a, 0, a)

or,

a[a>255] = 255
a[a<0] = 0

Spaces in URLs?

A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses + instead of %20 for spaces).

But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20 is not a space (obviously) but it represents a space.

String replace a Backslash

s.replaceAll ("\\\\", "");

You need to mask a backslash in your source, and for regex, you need to mask it again, so for every backslash you need two, which ends in 4.

But

s = "http://www.example.com\\/value";

needs two backslashes in source as well.

Can two Java methods have same name with different return types?

Only, if they accept different parameters. If there are no parameters, then you must have different names.

int doSomething(String s);
String doSomething(int); // this is fine


int doSomething(String s);
String doSomething(String s); // this is not

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

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

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

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

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

check if command was successful in a batch file

You can use

if errorlevel 1 echo Unsuccessful

in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

Escaping ampersand in URL

If you can't use any libraries to encode the value, http://www.urlencoder.org/ or http://www.urlencode-urldecode.com/ or ...

Just enter your value "M&M", not the full URL ;-)

Fatal error: Call to undefined function mcrypt_encrypt()

You don't have the mcrypt library installed.

See http://www.php.net/manual/en/mcrypt.setup.php for more information.

If you are on shared hosting, you can ask your provider to install it.


In OSX you can easily install mcrypt via homebrew

brew install php54-mcrypt --without-homebrew-php

Then add this line to /etc/php.ini.

extension="/usr/local/Cellar/php54-mcrypt/5.4.24/mcrypt.so"

Binary Data in JSON String. Something better than Base64

While it is true that base64 has ~33% expansion rate, it is not necessarily true that processing overhead is significantly more than this: it really depends on JSON library/toolkit you are using. Encoding and decoding are simple straight-forward operations, and they can even be optimized wrt character encoding (as JSON only supports UTF-8/16/32) -- base64 characters are always single-byte for JSON String entries. For example on Java platform there are libraries that can do the job rather efficiently, so that overhead is mostly due to expanded size.

I agree with two earlier answers:

  • base64 is simple, commonly used standard, so it is unlikely to find something better specifically to use with JSON (base-85 is used by postscript etc; but benefits are at best marginal when you think about it)
  • compression before encoding (and after decoding) may make lots of sense, depending on data you use

Center a H1 tag inside a DIV

There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.

position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);

It works most of the time. I did have a problem where a div was in a div in a li. The list item had a height set and the outer divs made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.

Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then?

Select elements by attribute

if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

return in for loop or outside loop

The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

width:auto for <input> fields

"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."

No one actually answered the above part of the original poster's question.

Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/

As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.

To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/

The requested operation cannot be performed on a file with a user-mapped section open

I had the same issue. How I resolved it was:

  1. Open "Task Manager"
  2. End task "Explorer.exe"
  3. Click "File" --> Create new task -- Type in "explorer.exe" --> OK
  4. Clean my project and it works

How to get a URL parameter in Express?

This will work if your route looks like this: localhost:8888/p?tagid=1234

var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234

Otherwise use the following code if your route looks like this: localhost:8888/p/1234

var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234

How to scroll to an element in jQuery?

You can extend jQuery functionalities like this:

jQuery.fn.extend({
scrollToMe: function () {
    var x = jQuery(this).offset().top - 100;
    jQuery('html,body').animate({scrollTop: x}, 500);
}});

and then:

$('...').scrollToMe();

easy ;-)

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

Python: How to ignore an exception and proceed?

Generic answer

The standard "nop" in Python is the pass statement:

try:
    do_something()
except Exception:
    pass

Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.

Python 2

Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:

try:
    do_something()
except Exception:
    sys.exc_clear()

This clears the last thrown exception.

Python 3

In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.

Is it a bad practice to use break in a for loop?

Using break as well as continue in a for loop is perfectly fine.

It simplifies the code and improves its readability.

How to view DLL functions?

Use dotPeek by JetBrains.

https://www.jetbrains.com/decompiler/

dotPeek is a free tool based on ReSharper. It can reliably decompile any .NET assembly into C# or IL code.

Check if application is installed - Android

Since Android 11 (API level 30), most user-installed apps are not visible by default. In your manifest, you must statically declare which apps you are going to get info about, as in the following:

<manifest>
    <queries>
        <!-- Explicit apps you know in advance about: -->
        <package android:name="com.example.this.app"/>
        <package android:name="com.example.this.other.app"/>
    </queries>
    
    ...
</manifest>

Then, @RobinKanters' answer works:

private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
    try {
        packageManager.getPackageInfo(packageName, 0);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

// ...
// This will return true on Android 11 if the app is installed,
// since we declared it above in the manifest.
isPackageInstalled("com.example.this.app", pm); 
// This will return false on Android 11 even if the app is installed:
isPackageInstalled("another.random.app", pm); 

Learn more here:

What is the best method of handling currency/money?

Simple code for Ruby & Rails

<%= number_to_currency(1234567890.50) %>

OUT PUT => $1,234,567,890.50

Finish all previous activities

I guess I am late but there is simple and short answer. There is a finishAffinity() method in Activity that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.

For API 16+, use

finishAffinity();

For below 16, use

ActivityCompat.finishAffinity(YourActivity.this);

Hope it helps!

get string value from HashMap depending on key name

If you are storing keys/values as strings, then this will work:

HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");

The question is what gets populated in the HashMap (key & value)

How can I select rows with most recent timestamp for each key value?

This can de done in a relatively elegant way using SELECT DISTINCT, as follows:

SELECT DISTINCT ON (sensorID)
sensorID, timestamp, sensorField1, sensorField2 
FROM sensorTable
ORDER BY sensorID, timestamp DESC;

The above works for PostgreSQL (some more info here) but I think also other engines. In case it's not obvious, what this does is sort the table by sensor ID and timestamp (newest to oldest), and then returns the first row (i.e. latest timestamp) for each unique sensor ID.

In my use case I have ~10M readings from ~1K sensors, so trying to join the table with itself on a timestamp-based filter is very resource-intensive; the above takes a couple of seconds.

Difference between const reference and normal parameter

The first method passes n by value, i.e. a copy of n is sent to the function. The second one passes n by reference which basically means that a pointer to the n with which the function is called is sent to the function.

For integral types like int it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.

Creating JSON on the fly with JObject

There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.

In these cases you can do:

using Newtonsoft.Json.Linq;

JObject jsonObject =
     new JObject(
             new JProperty("Date", DateTime.Now),
             new JProperty("Album", "Me Against The World"),
             new JProperty("Year", "James 2Pac-King's blog."),
             new JProperty("Artist", "2Pac")
         )

More documentation here: http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm

htaccess "order" Deny, Allow, Deny

In apache2, linux configuration

Require all granted

ionic build Android | error: No installed build tools found. Please install the Android build tools

as the error says 'No installed build tools found' it means that

1 : It really really really did not found build tools

2 : To make him find build tools you need to define these paths correctly

PATH IS SAME FOR UBUNTU(.bashrc) AND MAC(.bash_profile)

export ANDROID_HOME=/Users/vijay/Software/android-sdk-macosx
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/tools
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/platform-tools

3 : IMPORTANT IMPORTANT as soon as you set environmental variables you need to reload evnironmental variables.

//For ubuntu
$source .bashrc 

//For macos
$source .bash_profile

4 : Then check in terminal

$printenv ANDROID_HOME
$printenv PATH

Note : if you did not find your changes in printenv then restart the pc and try again printenv PATH, printenv ANDROID_HOME .There is also command to reload environmental variables .

4 : then open terminal and write HALF TEXT '$and' and hit tab. On hitting tab you should see full '$android' name.this verifys all paths are correct

5 : write $android in terminal and hit enter

How to convert a string to JSON object in PHP

Try with json_encode().

And look again Valid JSON

Functional style of Java 8's Optional.ifPresent and if-not-Present?

You cannot call orElse after ifPresent, the reason is, orElse is called on an optiional but ifPresent returns void. So the best approach to achieve is ifPresentOrElse. It could be like this:

op.ifPresentOrElse( 
            (value) 
                -> { System.out.println( 
                         "Value is present, its: "
                         + value); }, 
            () 
                -> { System.out.println( 
                         "Value is empty"); }); 

Removing leading zeroes from a field in a SQL statement

select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20), 
    patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 
    20)), 20)

returns N0Z, that is, will get rid of leading zeroes and anything that comes before them.

jQuery move to anchor location on page load

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

Linq Query Group By and Selecting First Items

See LINQ: How to get the latest/last record with a group by clause

var firstItemsInGroup = from b in mainButtons
                 group b by b.category into g
select g.First();

I assume that mainButtons are already sorted correctly.

If you need to specify custom sort order, use OrderBy override with Comparer.

var firstsByCompareInGroups = from p in rows
        group p by p.ID into grp
        select grp.OrderBy(a => a, new CompareRows()).First();

See an example in my post "Select First Row In Group using Custom Comparer"

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

How to determine whether code is running in DEBUG / RELEASE build?

Not sure if I answered you question, maybe you could try these code:

#ifdef DEBUG
#define DLOG(xx, ...)  NSLog( \
    @"%s(%d): " \
    xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__ \  
    )
#else
#define DLOG(xx, ...)  ((void)0)
#endif 

file_get_contents behind a proxy?

To use file_get_contents() over/through a proxy that doesn't require authentication, something like this should do :

(I'm not able to test this one : my proxy requires an authentication)

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)

If you're getting that kind of error :

Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required

It means your proxy requires an authentication.

If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$auth = base64_encode('LOGIN:PASSWORD');

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
        'header'          => "Proxy-Authorization: Basic $auth",
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

And... The page should be displayed ;-)

MySQL Error 1215: Cannot add foreign key constraint

Wooo I just got it ! It was a mix of a lot of already posted answers (innoDB, unsigned, etc). One thing I didn't see here though is : if your FK is pointing on a PK, ensure the source column has a value that makes sense. For example, if the PK is a mediumint(8), make sure the source column also contains a mediumint(8). That was part of the problem for me.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

Here's how you can mock your FileConnection

Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
                                                           MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
              .Throws(new IOException());

Then instantiate your Transfer class and use the mock in your method call

Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);

Update:

First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

Since you are setting those properties using another dependency, I would write it like this:

public class Transfer
{
    public Transfer(IInternalConfig internalConfig)
    {
        source = internalConfig.GetFileConnection("source");
        destination = internalConfig.GetFileConnection("destination");
    }

    //you should consider making these private or protected fields
    public virtual IFileConnection source { get; set; }
    public virtual IFileConnection destination { get; set; }

    public virtual void GetFile(IFileConnection connection, 
        string remoteFilename, string localFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void PutFile(IFileConnection connection, 
        string localFilename, string remoteFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void TransferFiles(string sourceName, string destName)
    {
        var tempName = Path.GetTempFileName();
        GetFile(source, sourceName, tempName);
        PutFile(destination, tempName, destName);
    }
}

This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

Default argument values in JavaScript functions

function func(a, b)
{
  if (typeof a == 'undefined')
    a = 10;
  if (typeof b == 'undefined')
    b = 20;
  // do what you want ... for example
  alert(a + ',' + b);
}

in shorthand

function func(a, b)
{
  a = (typeof a == 'undefined')?10:a;
  b = (typeof b == 'undefined')?20:b;

  // do what you want ... for example
  alert(a + ',' + b);
}

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.Screenshot

Centering elements in jQuery Mobile

This works

HTML

<section id="wrapper">
    <div data-role="page">
    </div>
</section>

Css

#wrapper { 
    margin:0 auto;
    width:1239px;
    height:1022px;
    background:#ffffff;
    position:relative;
}

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

my solution is to use a timeout. Seems to work ok

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});

Sorting an array in C?

I'd like to make some changes: In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
   int int_a = * ( (int*) a );
   int int_b = * ( (int*) b );

   // an easy expression for comparing
   return (int_a > int_b) - (int_a < int_b);
}

qsort( a, 6, sizeof(int), compare )

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Running Windows 7, when I had this issue it was because I had hidden the .git folder. The permissions were fine, it was just hidden. Showing the folder resolved it.

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

Query based on multiple where clauses in Firebase

I've written a personal library that allows you to order by multiple values, with all the ordering done on the server.

Meet Querybase!

Querybase takes in a Firebase Database Reference and an array of fields you wish to index on. When you create new records it will automatically handle the generation of keys that allow for multiple querying. The caveat is that it only supports straight equivalence (no less than or greater than).

const databaseRef = firebase.database().ref().child('people');
const querybaseRef = querybase.ref(databaseRef, ['name', 'age', 'location']);

// Automatically handles composite keys
querybaseRef.push({ 
  name: 'David',
  age: 27,
  location: 'SF'
});

// Find records by multiple fields
// returns a Firebase Database ref
const queriedDbRef = querybaseRef
 .where({
   name: 'David',
   age: 27
 });

// Listen for realtime updates
queriedDbRef.on('value', snap => console.log(snap));

How to recover MySQL database from .myd, .myi, .frm files

For those that have Windows XP and have MySQL server 5.5 installed - the location for the database is C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.5\data, unless you changed the location within the MySql Workbench installation GUI.

Session 'app': Error Installing APK

My issue was solved by Clean --> ReBuild --> Run and in my case it was because i accidentally deleted the project folder and when i clicked ctrl+z to restore something wrong happened.

Including a groovy script in another groovy

Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:

File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();

How can I ping a server port with PHP?

I think the answer to this question pretty much sums up the problem with your question.

If what you want to do is find out whether a given host will accept TCP connections on port 80, you can do this:

$host = '193.33.186.70'; 
$port = 80; 
$waitTimeoutInSeconds = 1; 
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
   // It worked 
} else {
   // It didn't work 
} 
fclose($fp);

For anything other than TCP it will be more difficult (although since you specify 80, I guess you are looking for an active HTTP server, so TCP is what you want). TCP is sequenced and acknowledged, so you will implicitly receive a returned packet when a connection is successfully made. Most other transport protocols (commonly UDP, but others as well) do not behave in this manner, and datagrams will not be acknowledged unless the overlayed Application Layer protocol implements it.

The fact that you are asking this question in this manner tells me you have a fundamental gap in your knowledge on Transport Layer protocols. You should read up on ICMP and TCP, as well as the OSI Model.

Also, here's a slightly cleaner version to ping to hosts.

// Function to check response time
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}

Remove all occurrences of a value from a list?

Numpy approach and timings against a list/array with 1.000.000 elements:

Timings:

In [10]: a.shape
Out[10]: (1000000,)

In [13]: len(lst)
Out[13]: 1000000

In [18]: %timeit a[a != 2]
100 loops, best of 3: 2.94 ms per loop

In [19]: %timeit [x for x in lst if x != 2]
10 loops, best of 3: 79.7 ms per loop

Conclusion: numpy is 27 times faster (on my notebook) compared to list comprehension approach

PS if you want to convert your regular Python list lst to numpy array:

arr = np.array(lst)

Setup:

import numpy as np
a = np.random.randint(0, 1000, 10**6)

In [10]: a.shape
Out[10]: (1000000,)

In [12]: lst = a.tolist()

In [13]: len(lst)
Out[13]: 1000000

Check:

In [14]: a[a != 2].shape
Out[14]: (998949,)

In [15]: len([x for x in lst if x != 2])
Out[15]: 998949

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is the latest correct way that I know of how to check for IE and Edge:

if (/MSIE 10/i.test(navigator.userAgent)) {
   // This is internet explorer 10
   window.alert('isIE10');
}

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
    // This is internet explorer 9 or 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge\/\d./i.test(navigator.userAgent)){
   // This is Microsoft Edge
   window.alert('Microsoft Edge');
}

Note that you don't need the extra var isIE10 in your code because it does very specific checks now.

Also check out this page for the latest IE and Edge user agent strings because this answer may become outdated at some point: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

T-SQL: Opposite to string concatenation - how to split string into multiple records

I wrote this awhile back. It assumes the delimiter is a comma and that the individual values aren't bigger than 127 characters. It could be modified pretty easily.

It has the benefit of not being limited to 4,000 characters.

Good luck!

ALTER Function [dbo].[SplitStr] ( 
        @txt text 
) 
Returns @tmp Table 
        ( 
                value varchar(127)
        ) 
as 
BEGIN 
        declare @str varchar(8000) 
                , @Beg int 
                , @last int 
                , @size int 

        set @size=datalength(@txt) 
        set @Beg=1 


        set @str=substring(@txt,@Beg,8000) 
        IF len(@str)<8000 set @Beg=@size 
        ELSE BEGIN 
                set @last=charindex(',', reverse(@str)) 
                set @str=substring(@txt,@Beg,8000-@last) 
                set @Beg=@Beg+8000-@last+1 
        END 

        declare @workingString varchar(25) 
                , @stringindex int 



        while @Beg<=@size Begin 
                WHILE LEN(@str) > 0 BEGIN 
                        SELECT @StringIndex = CHARINDEX(',', @str) 

                        SELECT 
                                @workingString = CASE 
                                        WHEN @StringIndex > 0 THEN SUBSTRING(@str, 1, @StringIndex-1) 
                                        ELSE @str 
                                END 

                        INSERT INTO 
                                @tmp(value)
                        VALUES 
                                (cast(rtrim(ltrim(@workingString)) as varchar(127)))
                        SELECT @str = CASE 
                                WHEN CHARINDEX(',', @str) > 0 THEN SUBSTRING(@str, @StringIndex+1, LEN(@str)) 
                                ELSE '' 
                        END 
                END 
                set @str=substring(@txt,@Beg,8000) 

                if @Beg=@size set @Beg=@Beg+1 
                else IF len(@str)<8000 set @Beg=@size 
                ELSE BEGIN 
                        set @last=charindex(',', reverse(@str)) 
                        set @str=substring(@txt,@Beg,8000-@last) 
                        set @Beg=@Beg+8000-@last+1 

                END 
        END     

        return
END 

Kill all processes for a given user

What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?

My docker container has no internet

for me, using centos 7.4, it was not issue of /etc/resolve.conf, iptables, iptables nat rules nor docker itself. The issue is the host missing the package bridge-utils which docker require to build the bridge using command brctl. yum install -y bridge-utils and restart docker, solve the problem.

Declaring a custom android UI element using XML

You can include any layout file in other layout file as-

             <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="30dp" >

                <include
                    android:id="@+id/frnd_img_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_imagefile"/>

                <include
                    android:id="@+id/frnd_video_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_video_lay" />

                <ImageView
                    android:id="@+id/downloadbtn"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_centerInParent="true"
                    android:src="@drawable/plus"/>
            </RelativeLayout>

here the layout files in include tag are other .xml layout files in the same res folder.

correct quoting for cmd.exe for multiple arguments

Note the "" at the beginning and at the end!

Run a program and pass a Long Filename

cmd /c write.exe "c:\sample documents\sample.txt"

Spaces in Program Path

cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in Program Path + parameters

cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2

Spaces in Program Path + parameters with spaces

cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch Demo1 and then Launch Demo2

cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

CMD.exe (Command Shell)

Java AES and using my own Key

MD5, AES, no padding

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import static org.apache.commons.io.Charsets.UTF_8;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class PasswordUtils {

    private PasswordUtils() {}

    public static String encrypt(String text, String pass) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(ENCRYPT_MODE, key);

            byte[] encrypted = cipher.doFinal(text.getBytes(UTF_8));
            byte[] encoded = Base64.getEncoder().encode(encrypted);
            return new String(encoded, UTF_8);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Cannot encrypt", e);
        }
    }

    public static String decrypt(String text, String pass) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(DECRYPT_MODE, key);

            byte[] decoded = Base64.getDecoder().decode(text.getBytes(UTF_8));
            byte[] decrypted = cipher.doFinal(decoded);
            return new String(decrypted, UTF_8);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Cannot decrypt", e);
        }
    }
}

Use IntelliJ to generate class diagram

Now there is an official way to add "PlantUML integration" plugin to your JetBrains product.

Installation steps please refer: https://stackoverflow.com/a/53387418/5320704

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Like stated in other answers, create a Twitter app to get the token, key and secret. Using the code bellow, you can modify request parameters from one spot and avoid typos and similar errors (change $request array in returnTweet() function).

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function returnTweet(){
    $oauth_access_token         = "x";
    $oauth_access_token_secret  = "x";
    $consumer_key               = "x";
    $consumer_secret            = "x";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'budidino',
            'count'             => '3'
        );

    $oauth = array(
        'oauth_consumer_key'        => $consumer_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
        $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

    //  make request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);

    return json_decode($json, true);
}

and then just call returnTweet()

Editing specific line in text file in Python

you can use fileinput to do in place editing

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

How to change the datetime format in pandas

Below is the code worked for me, And we need to be very careful for format. Below link will be definitely useful for knowing your exiting format and changing into desired format(Follow strftime() and strptime() Format Codes on below link):

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.

data['date_new_format'] = pd.to_datetime(data['date_to_be_changed'] , format='%b-%y')

using lodash .groupBy. how to add your own keys for grouped output?

Isn't it this simple?

var result = _(data)
            .groupBy(x => x.color)
            .map((value, key) => ({color: key, users: value}))
            .value();

Get multiple elements by Id

An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".

What are my options for storing data when using React Native? (iOS and Android)

you can use sync storage that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.

import SyncStorage from 'sync-storage';

SyncStorage.set('foo', 'bar');
const result = SyncStorage.get('foo');
console.log(result); // 'bar'

Specify a Root Path of your HTML directory for script links?

Just start it with a slash? This means root. As long as you're testing on a web server (e.g. localhost) and not a file system (e.g. C:) then that should be all you need to do.

Waiting for background processes to finish before exiting script

You can use kill -0 for checking whether a particular pid is running or not.

Assuming, you have list of pid numbers in a file called pid in pwd

while true;
do 
    if [ -s pid ] ; then
        for pid in `cat pid`
        do  
            echo "Checking the $pid"
            kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
        done
    else
        echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
        break
    fi
done

Changing nav-bar color after scrolling?

this is a simple pure javascript

var myNav = document.getElementById('mynav');
window.onscroll = function () { 
    "use strict";
    if (document.body.scrollTop >= 200 ) {
        myNav.classList.add("nav-colored");
        myNav.classList.remove("nav-transparent");
    } 
    else {
        myNav.classList.add("nav-transparent");
        myNav.classList.remove("nav-colored");
    }
};

in some chrome versions there is bug with:

document.body.scrollTop

so you may add a condition like this:

 if (document.body.scrollTop >= 200 || document.documentElement.scrollTop >= 200 )

sure you must have 2 classes

.nav-colored { background-color:#000; }
.nav-transparent { background-color:transparent;}

Matplotlib - How to plot a high resolution graph?

At the end of your for() loop, you can use the savefig() function instead of plt.show() and set the name, dpi and format of your figure.

E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder ./ with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:

for fname in glob("./*.txt"):
    # Your previous code goes here
    [...]

    plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

How do I put an already-running process under nohup?

  1. ctrl + z - this will pause the job (not going to cancel!)
  2. bg - this will put the job in background and return in running process
  3. disown -a - this will cut all the attachment with job (so you can close the terminal and it will still run)

These simple steps will allow you to close the terminal while keeping process running.

It wont put on nohup (based on my understanding of your question, you don't need it here).

glm rotate usage in Opengl

GLM has good example of rotation : http://glm.g-truc.net/code.html

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
    glm::mat4(1.0f),
    glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
    ViewTranslate,
    Rotate.y,
    glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
    ViewRotateX,
    Rotate.x,
    glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
    glm::mat4(1.0f),
    glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));

Property [title] does not exist on this collection instance

A person might get this while working with factory functions, so I can confirm this is valid syntax:

$user = factory(User::class, 1)->create()->first();

You might see the collection instance error if you do something like:

$user = factory(User::class, 1)->create()->id;

so change it to:

$user = factory(User::class, 1)->create()->first()->id;

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I had the same problems, but using easy_install "module" solved the problem for me.

I am not sure why, but pip and easy_install use different install locations, and easy_install chose the right ones.

Edit: without re-checking but because of the comments; it seems that different (OSX and brew-installed) installations interfere with each other which is why they tools mentioned indeed point to different locations (since they belong to different installations). I understand that usually those tools from one install point to the same folder.

Efficiently test if a port is open on Linux?

Here's one that works for both Mac and Linux:

netstat -aln | awk '$6 == "LISTEN" && $4 ~ "[\\.\:]445$"'

How to execute mongo commands through shell scripts?

mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF

Date formatting in WPF datagrid

I know the accepted answer is quite old, but there is a way to control formatting with AutoGeneratColumns :

First create a function that will trigger when a column is generated :

<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>

Then check if the type of the column generated is a DateTime and just change its String format to "d" to remove the time part :

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if(YourColumn == typeof(DateTime))
            {
                e.Column.ClipboardContentBinding.StringFormat = "d";
            }
        }

Difference between app.use and app.get in express.js

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

  • GET /
  • PUT /foo
  • POST /foo/bar
  • etc.

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET /

And, the equivalent routing for your example of app.use() would actually be:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

(Update: Attempting to better demonstrate the differences.)

The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').

Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.

Examples:

  • For simple, static routes:

    app.get('/', function (req, res) {
      // ...
    });
    

    vs.

    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      // ...
    });
    
  • With multiple handlers for the same route:

    app.get('/', authorize('ADMIN'), function (req, res) {
      // ...
    });
    

    vs.

    const authorizeAdmin = authorize('ADMIN');
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      authorizeAdmin(req, res, function (err) {
        if (err) return next(err);
    
        // ...
      });
    });
    
  • With parameters:

    app.get('/item/:id', function (req, res) {
      let id = req.params.id;
      // ...
    });
    

    vs.

    const pathToRegExp = require('path-to-regexp');
    
    function prepareParams(matches, pathKeys, previousParams) {
      var params = previousParams || {};
    
      // TODO: support repeating keys...
      matches.slice(1).forEach(function (segment, index) {
        let { name } = pathKeys[index];
        params[name] = segment;
      });
    
      return params;
    }
    
    const itemIdKeys = [];
    const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET') return next();
    
      var urlMatch = itemIdPattern.exec(req.url);
      if (!urlMatch) return next();
    
      if (itemIdKeys && itemIdKeys.length)
        req.params = prepareParams(urlMatch, itemIdKeys, req.params);
    
      let id = req.params.id;
      // ...
    });
    

Note: Express' implementation of these features are contained in its Router, Layer, and Route.

How to ignore the first line of data when processing CSV data?

The new 'pandas' package might be more relevant than 'csv'. The code below will read a CSV file, by default interpreting the first line as the column header and find the minimum across columns.

import pandas as pd

data = pd.read_csv('all16.csv')
data.min()

Xcode 10, Command CodeSign failed with a nonzero exit code

It works for me by delete all the apple developer Certification in the keychain. and generate it in the Xcode.

How do you do a limit query in JPQL or HQL?

 // SQL: SELECT * FROM table LIMIT start, maxRows;

Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);

What's the difference between SortedList and SortedDictionary?

This is visual representation of how performances compare to each other.

Unable to add window -- token null is not valid; is your activity running?

PopupWindow can only be attached to an Activity. In your case you are trying to add PopupWindow to service which is not right.

To solve this problem you can use a blank and transparent Activity. On click of floating icon, launch the Activity and on onCreate of Activity show the PopupWindow.

On dismiss of PopupWindow, you can finish the transparent Activity. Hope this helps you.

Changing fonts in ggplot2

Another option is to use showtext package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.

# install.packages('showtext', dependencies = TRUE)
library(showtext)

Import some Google Fonts

# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

Load font from the current search path into showtext

# Check the current search path for fonts
font_paths()    
#> [1] "C:\\Windows\\Fonts"

# List available font files in the search path
font_files()    
#>   [1] "AcadEref.ttf"                                
#>   [2] "AGENCYB.TTF"                           
#> [428] "pala.ttf"                                    
#> [429] "palab.ttf"                                   
#> [430] "palabi.ttf"                                  
#> [431] "palai.ttf"

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")

font_families()
#> [1] "sans"         "serif"        "mono"         "wqy-microhei"
#> [5] "Montserrat"   "Roboto"       "Palatino"

## automatically use showtext for new devices
showtext_auto() 

Plot: need to open Windows graphics device as showtext does not work well with RStudio built-in graphics device

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()

myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"

library(ggplot2)

a <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text = element_text(size = 16, family = myFont1)) +
  annotate("text", 4, 30, label = 'Palatino Linotype',
           family = myFont3, size = 10) +
  annotate("text", 1, 11, label = 'Roboto', hjust = 0,
           family = myFont2, size = 10) 

## On-screen device
print(a) 

## Save to PNG 
ggsave("plot_showtext.png", plot = a, 
       type = 'cairo',
       width = 6, height = 6, dpi = 150)  

## Save to PDF
ggsave("plot_showtext.pdf", plot = a, 
       device = cairo_pdf,
       width = 6, height = 6, dpi = 150)  

## turn showtext off if no longer needed
showtext_auto(FALSE) 

Edit: another workaround to use showtext in RStudio. Run the following code at the beginning of the R session (source)

trace(grDevices::png, exit = quote({
    showtext::showtext_begin()
}), print = FALSE)

Edit 2: Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like

order: [[1, 'asc']]

with an empty table, there is no row idx 1 -> this exception ensures. This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.

My solution:

// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];

if(srcCol >= aoColumns.length) {
    continue;
}

// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;

Find object by its property in array of objects with AngularJS way

For complete M B answer, if you want to access to an specific attribute of this object already filtered from the array in your HTML, you will have to do it in this way:

{{ (myArray | filter : {'id':73})[0].name }}

So, in this case, it will print john in the HTML.

Regards!

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

How do I consume the JSON POST data in an Express application

For Express v4+

install body-parser from the npm.

$ npm install body-parser

https://www.npmjs.org/package/body-parser#installation

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next()
})

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How to get date and time from server

No need to use date_default_timezone_set for the whole script, just specify the timezone you want with a DateTime object:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->format("Y-m-d\TH:i:sO"); // something like "2015-02-11T06:16:47+0100" (ISO 8601)

Update a column value, replacing part of a string

First, have to check

SELECT * FROM university WHERE course_name LIKE '%&amp%'

Next, have to update

UPDATE university SET course_name = REPLACE(course_name, '&amp', '&') WHERE id = 1

Results: Engineering &amp Technology => Engineering & Technology

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Another way to do this is:

// inflate the layout
View myLayout = LayoutInflater.from(this).inflate(R.layout.MY_LAYOUT,null);

// load the text view
TextView myView = (TextView) myLayout.findViewById(R.id.MY_VIEW);

Strict Standards: Only variables should be assigned by reference PHP 5.4

You should remove the & (ampersand) symbol, so that line 4 will look like this:

$conn = ADONewConnection($config['db_type']);

This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0

Box-Shadow on the left side of the element only

box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);

The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.

The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.

reference: CSS Box Shadow Property

What are the aspect ratios for all Android phone and tablet devices?

In case anyone wanted more of a visual reference:

aspect_ratio_visual_reference

Decimal approximations reference table:

+----------------------------------------------------------------------------+
¦       aspect ratio       ¦     decimal approx.    ¦     decimal approx.    ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦         19.5 x 9         ¦        0.462...        ¦        2.167...        ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 9          ¦        0.474...        ¦         2.11...        ¦
¦--------------------------+------------------------+------------------------¦
¦        ~18.7 x 9         ¦        0.482...        ¦        2.074...        ¦
¦--------------------------+------------------------+------------------------¦    
¦         18.5 x 9         ¦        0.486...        ¦        2.056...        ¦
¦--------------------------+------------------------+------------------------¦
¦          18 x 9          ¦           0.5          ¦            2           ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 10         ¦        0.526...        ¦           1.9          ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 9          ¦         0.5625         ¦        1.778...        ¦
¦--------------------------+------------------------+------------------------¦
¦           5 x 3          ¦           0.6          ¦        1.667...        ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 10         ¦          0.625         ¦           1.6          ¦
¦--------------------------+------------------------+------------------------¦
¦           3 x 2          ¦        0.667...        ¦           1.5          ¦
¦--------------------------+------------------------+------------------------¦
¦           4 x 3          ¦          0.75          ¦        1.333...        ¦
+----------------------------------------------------------------------------+

Changelog:

  • May 2018: Added 56x27 === ~18.7x9 (Huawei P20), 19x9 (Nokia X6 2018) and 19.5x9 (LG G7 ThinQ)
  • May 2017: Added 19x10 (Essential Phone)
  • March 2017: Added 18.5x9 (Samsung Galaxy S8) and 18x9 (LG G6)

Copying an array of objects into another array in javascript

The key things here are

  1. The entries in the array are objects, and
  2. You don't want modifications to an object in one array to show up in the other array.

That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.

If the destination array doesn't exist yet...

...use map to create a new array, and copy the objects as you go:

const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);

...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):

const newArray = sourceArray.map(obj => ({...obj}));

That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.

Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:

_x000D_
_x000D_
function naiveDeepCopy(obj) {
    const newObj = {};
    for (const key of Object.getOwnPropertyNames(obj)) {
        const value = obj[key];
        if (value && typeof value === "object") {
            newObj[key] = {...value};
        } else {
            newObj[key] = value;
        }
    }
    return newObj;
}
const sourceArray = [
    {
        name: "joe",
        address: {
            line1: "1 Manor Road",
            line2: "Somewhere",
            city: "St Louis",
            state: "Missouri",
            country: "USA",
        },
    },
    {
        name: "mohammed",
        address: {
            line1: "1 Kings Road",
            city: "London",
            country: "UK",
        },
    },
    {
        name: "shu-yo",
    },
];
const newArray = sourceArray.map(naiveDeepCopy);
// Modify the first one and its sub-object
newArray[0].name = newArray[0].name.toLocaleUpperCase();
newArray[0].address.country = "United States of America";
console.log("Original:", sourceArray);
console.log("Copy:", newArray);
_x000D_
.as-console-wrapper {
    max-height: 100% !important;
}
_x000D_
_x000D_
_x000D_

If the destination array exists...

...and you want to append the contents of the source array to it, you can use push and a loop:

for (const obj of sourceArray) {
    destinationArray.push(copy(obj));
}

Sometimes people really want a "one liner," even if there's no particular reason for it. If you refer that, you could create a new array and then use spread notation to expand it into a single push call:

destinationArray.push(...sourceArray.map(obj => copy(obj)));

Why can't I use Docker CMD multiple times to run multiple services?

Even though CMD is written down in the Dockerfile, it really is runtime information. Just like EXPOSE, but contrary to e.g. RUN and ADD. By this, I mean that you can override it later, in an extending Dockerfile, or simple in your run command, which is what you are experiencing. At all times, there can be only one CMD.

If you want to run multiple services, I indeed would use supervisor. You can make a supervisor configuration file for each service, ADD these in a directory, and run the supervisor with supervisord -c /etc/supervisor to point to a supervisor configuration file which loads all your services and looks like

[supervisord]
nodaemon=true

[include]
files = /etc/supervisor/conf.d/*.conf

If you would like more details, I wrote a blog on this subject here: http://blog.trifork.com/2014/03/11/using-supervisor-with-docker-to-manage-processes-supporting-image-inheritance/

How to convert an Array to a Set in Java

For anyone solving for Android:

Kotlin Collections Solution

The asterisk * is the spread operator. It applies all elements in a collection individually, each passed in order to a vararg method parameter. It is equivalent to:

val myArray = arrayOf("data", "foo")
val mySet = setOf(*myArray)

// Equivalent to
val mySet = setOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*myArray, "bar", *myArray)

Passing no parameters setOf() results in an empty set.

In addition to setOf, you can also use any of these for a specific hash type:

hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

This is how to define the collection item type explicitly.

setOf<String>()
hashSetOf<MyClass>()

How can I make a div not larger than its contents?

This seems to work fine for me on all browsers. Example is an actual ad i use online and in newsletter. Just change the content of the div. It will adjust and shrinkwrap with the amount of padding you specify.

<div style="float:left; border: 3px ridge red; background: aqua; padding:12px">
    <font color=red size=4>Need to fix a birth certificate? Learn <a href="http://www.example.com">Photoshop in a Day</a>!
    </font>
</div>

Converting a datetime string to timestamp in Javascript

Seems like the problem is with the date format.

 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

How to remove underline from a link in HTML?

All the above-mentioned code did not work for me. When I dig into the problem I realize that it was not working because I'd placed the style after the href. When I placed the style before the href it was working as expected.

<a style="text-decoration:none" href="http://yoursite.com/">yoursite</a>

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

How do I remove a single breakpoint with GDB?

Try these (reference):

clear linenum
clear filename:linenum

Media Queries - In between two widths

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}

Build not visible in itunes connect

This was My Mistake:

I had a minor update in a Push Notification content part and I did not even touch my code.

But I thought I might have to re-upload it in order to reflect that change in the latest version.

And I did.

Tried to upload 3 Builds One by One.

But Not a single build has shown in the Test Flight Version.(Shocked)

Later I realized my mistake that just by updating APNS content part without even touching my code, I was trying to upload a new build and was expecting to reflect it in the Test Flight. (So stupid of me)

How to tell which commit a tag points to in Git?

Even though this is pretty old, I thought I would point out a cool feature I just found for listing tags with commits:

git log --decorate=full

It will show the branches which end/start at a commit, and the tags for commits.

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

Jquery get form field value

You have to use value attribute to get its value

<input type="text" name="FirstName" value="First Name" />

try -

var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

Get JSON Data from URL Using Android?

I feel your frustration.

Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.

That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.

(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)

protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
{
    @Override
    protected JSONObject doInBackground(Void... params)
    {

        String str="http://your.domain.here/yourSubMethod";
        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(str);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuffer.append(line);
            }

            return new JSONObject(stringBuffer.toString());
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(JSONObject response)
    {
        if(response != null)
        {
            try {
                Log.e("App", "Success: " + response.getString("yourJsonElement") );
            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }
        }
    }
}

This would be the json object it is targeted towards.

{
    "yourJsonElement":"Hi, I'm a string",
    "anotherElement":"Ohh, why didn't you pick me"
}

It is working on my end, hope this is helpful to someone else out there.

Output an Image in PHP

(Expanding on the accepted answer...)

I needed to:

  1. log views of a jpg image and an animated gif, and,
  2. ensure that the images are never cached (so every view is logged), and,
  3. also retain the original file extensions.

I accomplished this by creating a "secondary" .htaccess file in the sub-folder where the images are located.
The file contains only one line:

AddHandler application/x-httpd-lsphp .jpg .jpeg .gif

In the same folder, I placed the two 'original' image files (we'll call them orig.jpg and orig.gif), as well as two variations of the [simplified] script below (saved as myimage.jpg and myimage.gif)...

<?php 
  error_reporting(0); //hide errors (displaying one would break the image)

  //get user IP and the pseudo-image's URL
  if(isset($_SERVER['REMOTE_ADDR'])) {$ip =$_SERVER['REMOTE_ADDR'];}else{$ip= '(unknown)';}
  if(isset($_SERVER['REQUEST_URI'])) {$url=$_SERVER['REQUEST_URI'];}else{$url='(unknown)';}

  //log the visit
  require_once('connect.php');            //file with db connection info
  $conn = new mysqli($servername, $username, $password, $dbname);
  if (!$conn->connect_error) {         //if connected then save mySQL record
   $conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
     $conn->close();  //(datetime is auto-added to table with default of 'now')
  } 

  //display the image
  $imgfile='orig.jpg';                             // or 'orig.gif'
  header('Content-Type: image/jpeg');              // or 'image/gif'
  header('Content-Length: '.filesize($imgfile));
  header('Cache-Control: no-cache');
  readfile($imgfile);
?>

The images render (or animate) normally and can be called in any of the normal ways for images (like an <img> tag), and will save a record of the visiting IP, while invisible to the user.

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

Accessing a local website from another computer inside the local network in IIS 7

Find the local IP address of computer A and find the port that your website is running on. Then from computer B open a web browser and go to IP:port. Example: 192.168.1.5:80 if computer A's IP is 192.168.1.5 and your website is running on port 80

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

This solution shows a list of applications in a ListView dialog that resembles the chooser:

screenshot

It is up to you to:

  1. obtain the list of relevant application packages
  2. given a package name, invoke the relevant intent

The adapter class:

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ChooserArrayAdapter extends ArrayAdapter<String> {
    PackageManager mPm;
    int mTextViewResourceId;
    List<String> mPackages;

    public ChooserArrayAdapter(Context context, int resource, int textViewResourceId, List<String> packages) {
        super(context, resource, textViewResourceId, packages);
        mPm = context.getPackageManager();
        mTextViewResourceId = textViewResourceId;
        mPackages = packages;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String pkg = mPackages.get(position);
        View view = super.getView(position, convertView, parent);

        try {
            ApplicationInfo ai = mPm.getApplicationInfo(pkg, 0);

            CharSequence appName = mPm.getApplicationLabel(ai);
            Drawable appIcon = mPm.getApplicationIcon(pkg);

            TextView textView = (TextView) view.findViewById(mTextViewResourceId);
            textView.setText(appName);
            textView.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null);
            textView.setCompoundDrawablePadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return view;
    }

}

and its usage:

    void doXxxButton() {
        final List<String> packages = ...;
        if (packages.size() > 1) {
            ArrayAdapter<String> adapter = new ChooserArrayAdapter(MyActivity.this, android.R.layout.select_dialog_item, android.R.id.text1, packages);

            new AlertDialog.Builder(MyActivity.this)
            .setTitle(R.string.app_list_title)
            .setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item ) {
                    invokeApplication(packages.get(item));
                }
            })
            .show();
        } else if (packages.size() == 1) {
            invokeApplication(packages.get(0));
        }
    }

    void invokeApplication(String packageName) {
        // given a package name, create an intent and fill it with data
        ...
        startActivityForResult(intent, rq);
    }

offsetTop vs. jQuery.offset().top

Try this: parseInt(jQuery.offset().top, 10)

Pythonic way of checking if a condition holds for any element of a list

Python has a built in any() function for exactly this purpose.

Detect Click into Iframe using JavaScript

I ran into a situation where I had to track clicks on a social media button pulled in through an iframe. A new window would be opened when the button was clicked. Here was my solution:

var iframeClick = function () {
    var isOverIframe = false,
    windowLostBlur = function () {
        if (isOverIframe === true) {
            // DO STUFF
            isOverIframe = false;
        }
    };
    jQuery(window).focus();
    jQuery('#iframe').mouseenter(function(){
        isOverIframe = true;
        console.log(isOverIframe);
    });
    jQuery('#iframe').mouseleave(function(){
        isOverIframe = false;
        console.log(isOverIframe);
    });
    jQuery(window).blur(function () {
        windowLostBlur();
    });
};
iframeClick();

Truncating Text in PHP?

$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);

This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)

size of struct in C

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

What Are Some Good .NET Profilers?

I have found dotTrace Profiler by JetBrains to be an excellent profiling tool for .NET and their ASP.NET mode is quality.

C#: Looping through lines of multiline string

To update this ancient question for .NET 4, there is now a much neater way:

var lines = File.ReadAllLines(filename);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

How to check if a specific key is present in a hash or not?

Hash's key? method tells you whether a given key is present or not.

session.key?("user")

How do I parse JSON with Ruby on Rails?

You can try something like this:

def details_to_json
{
  :id                    => self.id, 
  :credit_period_type    => self.credit_period_type,
  :credit_payment_period => self.credit_payment_period,

 }.to_json
end

Where is the kibana error log? Is there a kibana error log?

In kibana 4.0.2 there is no --log-file option. If I start kibana as a service with systemctl start kibana I find log in /var/log/messages

MySQL integer field is returned as string in PHP

$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, TRUE);

Try this - worked for me.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to get time in milliseconds since the unix epoch in Javascript?

Date.now() returns a unix timestamp in milliseconds.

_x000D_
_x000D_
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
_x000D_
_x000D_

Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:

_x000D_
_x000D_
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
_x000D_
_x000D_

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

Difference between Destroy and Delete

A lot of answers already; wanted to jump on with a bit more.

docs:

For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

The delete verbage works differently for ActiveRecord::Association.has_many and ActiveRecord::Base. For the latter, delete will execute SQL DELETE and bypass all validations/callbacks. The former will be executed based on the :dependent option passed into the association. However, during testing, I found the following side effect where callbacks were only ran for delete and not delete_all

dependent: :destroy Example:

class Parent < ApplicationRecord
   has_many :children,
     before_remove: -> (_) { puts "before_remove callback" },
     dependent: :destroy
end

class Child < ApplicationRecord
   belongs_to :parent

   before_destroy -> { puts "before_destroy callback" }
end

> child.delete                            # Ran without callbacks
Child Destroy (99.6ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 21]]

> parent.children.delete(other_child)     # Ran with callbacks
before_remove callback
before_destroy callback
Child Destroy (0.4ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 22]]

> parent.children.delete_all              # Ran without callbacks
Child Destroy (1.0ms)  DELETE FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 1]]

Re-enabling window.alert in Chrome

In Chrome Browser go to setting , clear browsing history and then reload the page

What does asterisk * mean in Python?

I only have one thing to add that wasn't clear from the other answers (for completeness's sake).

You may also use the stars when calling the function. For example, say you have code like this:

>>> def foo(*args):
...     print(args)
...
>>> l = [1,2,3,4,5]

You can pass the list l into foo like so...

>>> foo(*l)
(1, 2, 3, 4, 5)

You can do the same for dictionaries...

>>> def foo(**argd):
...     print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}

Reload activity in Android

This is what I do to reload the activity after changing returning from a preference change.

@Override
protected void onResume() {

   super.onResume();
   this.onCreate(null);
}

This essentially causes the activity to redraw itself.

Updated: A better way to do this is to call the recreate() method. This will cause the activity to be recreated.

Just get column names from hive table

use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt

where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

$cd ~
$ls

Understanding .get() method in Python

I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections library exists to fulfill these purposes.

from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
    letter_counter[letter] += 1

>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.

As for the dict.get(a_key, default_value), there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.

What is "String args[]"? parameter in main method Java

try this:

System.getProperties().getProperty("sun.java.command", 
    System.getProperties().getProperty("sun.rt.javaCommand"));

Convert php array to Javascript

It can be done in a safer way.

If your PHP array contains special characters, you need to use rawurlencode() in PHP and then use decodeURIComponent() in JS to escape those. And parse the JSON to native js. Try this:

var data = JSON.parse(
        decodeURIComponent(
            "<?=rawurlencode(json_encode($data));?>"
        )
    );

console.log(data);

Group by month and year in MySQL

Use

GROUP BY year, month DESC";

Instead of

GROUP BY MONTH(t.summaryDateTime) DESC";

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

How to get a path to a resource in a Java JAR file

In my case, I have used a URL object instead Path.

File

File file = new File("my_path");
URL url = file.toURI().toURL();

Resource in classpath using classloader

URL url = MyClass.class.getClassLoader().getResource("resource_name")

When I need to read the content, I can use the following code:

InputStream stream = url.openStream();

And you can access the content using an InputStream.

Node.js - Maximum call stack size exceeded

You should wrap your recursive function call into a

  • setTimeout,
  • setImmediate or
  • process.nextTick

function to give node.js the chance to clear the stack. If you don't do that and there are many loops without any real async function call or if you do not wait for the callback, your RangeError: Maximum call stack size exceeded will be inevitable.

There are many articles concerning "Potential Async Loop". Here is one.

Now some more example code:

// ANTI-PATTERN
// THIS WILL CRASH

var condition = false, // potential means "maybe never"
    max = 1000000;

function potAsyncLoop( i, resume ) {
    if( i < max ) {
        if( condition ) { 
            someAsyncFunc( function( err, result ) { 
                potAsyncLoop( i+1, callback );
            });
        } else {
            // this will crash after some rounds with
            // "stack exceed", because control is never given back
            // to the browser 
            // -> no GC and browser "dead" ... "VERY BAD"
            potAsyncLoop( i+1, resume ); 
        }
    } else {
        resume();
    }
}
potAsyncLoop( 0, function() {
    // code after the loop
    ...
});

This is right:

var condition = false, // potential means "maybe never"
    max = 1000000;

function potAsyncLoop( i, resume ) {
    if( i < max ) {
        if( condition ) { 
            someAsyncFunc( function( err, result ) { 
                potAsyncLoop( i+1, callback );
            });
        } else {
            // Now the browser gets the chance to clear the stack
            // after every round by getting the control back.
            // Afterwards the loop continues
            setTimeout( function() {
                potAsyncLoop( i+1, resume ); 
            }, 0 );
        }
    } else {
        resume();
    }
}
potAsyncLoop( 0, function() {
    // code after the loop
    ...
});

Now your loop may become too slow, because we loose a little time (one browser roundtrip) per round. But you do not have to call setTimeout in every round. Normally it is o.k. to do it every 1000th time. But this may differ depending on your stack size:

var condition = false, // potential means "maybe never"
    max = 1000000;

function potAsyncLoop( i, resume ) {
    if( i < max ) {
        if( condition ) { 
            someAsyncFunc( function( err, result ) { 
                potAsyncLoop( i+1, callback );
            });
        } else {
            if( i % 1000 === 0 ) {
                setTimeout( function() {
                    potAsyncLoop( i+1, resume ); 
                }, 0 );
            } else {
                potAsyncLoop( i+1, resume ); 
            }
        }
    } else {
        resume();
    }
}
potAsyncLoop( 0, function() {
    // code after the loop
    ...
});

What is correct media query for IPad Pro?

/* Landscape*/

@media only screen and (min-device-width: 1366px) and (max-device-height: 1024px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: landscape)  {}

/* Portrait*/
@media only screen and (min-device-width: 1024px) and (max-device-height: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: portrait)  {}

Portrait medias query for iPad Pro should be fine as it is.

Landscape media query for iPad Pro (min-device-width) should be 1366px and (max device-height) should be 1024px.

Hope this helps.

User Get-ADUser to list all properties and export to .csv

Query all users and filter by the list from your text file:

$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
    Where-Object { $Users -contains $_.SamAccountName } |
    Select-Object DisplayName, Office |
    Export-Csv 'C:\path\to\your.csv' -NoType

Get-ADUser -Filter '*' returns all AD user accounts. This stream of user objects is then piped into a Where-Object filter, which checks for each object if its SamAccountName property is contained in the user list from your input file ($Users). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.

You can further optimize the code by replacing the -contains operator with hashtable lookups:

$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }

Get-ADUser -Filter '*' -Properties DisplayName,Office |
    Where-Object { $Users.ContainsKey($_.SamAccountName) } |
    Select-Object DisplayName, Office |
    Export-Csv 'C:\path\to\your.csv' -NoType

Get the value of checked checkbox?

in plain javascript:

function test() {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
    }
}
function selectOnlyOne(current_clicked) {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        cboxes[i].checked = (cboxes[i] == current);
    }
}

How to restart remote MySQL server running on Ubuntu linux?

What worked for me on an Amazon EC2 server was:

sudo service mysqld restart

Use JavaScript to place cursor at end of text in text input element

input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}

Changing Underline color

A pseudo element works best.

a, a:hover {
  position: relative;
  text-decoration: none;
}
a:after {
  content: '';
  display: block;
  position: absolute;
  height: 0;
  top:90%;
  left: 0;
  right: 0;
  border-bottom: solid 1px red;
}

See jsfiddle.

You don't need any extra elements, you can position it as close or far as you want from the text (border-bottom is kinda far for my liking), there aren't any extra colors that show up if your link is over a different colored background (like with the box-shadow trick), and it works in all browsers (text-decoration-color only supports Firefox as of yet).

Possible downside: The link can't be position:static, but that's probably not a problem the vast majority of the time. Just set it to relative and all is good.

Responsive css background images

Try using background-size but using TWO ARGUMENTS One for the width and the other one for the height

background-image:url('../images/bg.png'); 
background-repeat:no-repeat;
background-size: 100% 100%; // Here the first argument will be the width 
// and the second will be the height.
background-position:center;

How to get first and last element in an array in java?

I think there is only one intuitive solution and it is:

int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);

Output:

First: 1
Last: 5

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

Java Long primitive type maximum limit

It will overflow and wrap around to Long.MIN_VALUE.

Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

class Program
{
    static void Main(string[] args)
    {
        a a1 = new b();  
        a1.print();  
    }
}
class a
{
    public a()
    {
        Console.WriteLine("base class object initiated");
    }
    public void print()
    {
        Console.WriteLine("base");
    }
}
class b:a
{
    public b()
    {
        Console.WriteLine("child class object");
    }
    public void print1()
    {
        Console.WriteLine("derived");
    }
}

}

when we create a child class object,the base class object is auto initiated so base class reference variable can point to child class object.

but not vice versa because a child class reference variable can not point to base class object because no child class object is created.

and also notice that base class reference variable can only call base class member.

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Just wrap the float, boolean, int or similar in an NSNumber.

For structs, I don't know of a handy solution, but you could make a separate ObjC class that owns such a struct.

Adding IN clause List to a JPA Query

When using IN with a collection-valued parameter you don't need (...):

@NamedQuery(name = "EventLog.viewDatesInclude", 
    query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND " 
    + "el.timeMark <= :dateTo AND " 
    + "el.name IN :inclList") 

Slidedown and slideup layout with animation

This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.

keycode and charcode

Handling key events consistently is not at all easy.

Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress event. Do not try to get character codes for keyup and keydown events.

Secondly, you get different sets of values in a keypress event to what you get in a keyup or keydown event.

I recommend this page as a useful resource. As a summary:

If you're interested in detecting a user typing a character, use the keypress event. IE bizarrely only stores the character code in keyCode while all other browsers store it in which. Some (but not all) browsers also store it in charCode and/or keyCode. An example keypress handler:

function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
}

If you're interested in detecting a non-printable key (such as a cursor key), use the keydown event. Here keyCode is always the property to use. Note that keyup events have the same properties.

function(evt) {
  evt = evt || window.event;
  var keyCode = evt.keyCode;

  // Check for left arrow key
  if (keyCode == 37) {
    alert("Left arrow");
  }
}

Purpose of installing Twitter Bootstrap through npm?

If you NPM those modules you can serve them using static redirect.

First install the packages:

npm install jquery
npm install bootstrap

Then on the server.js:

var express = require('express');
var app = express();

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

Then, finally, at the .html:

<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.

Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.

Create parameterized VIEW in SQL Server 2008

no. You can use UDF in which you can pass parameters.

How to get selected option using Selenium WebDriver with Java

Completing the answer:

String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();

Assert.assertEquals("Please select any option...", selectedOption);

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

another alternative to determine orientation, based on comparison of the width/height:

var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
     orientation = 'landscape';
} 

You use it on "resize" event:

window.addEventListener("resize", function() { ... });

How to impose maxlength on textArea in HTML using JavaScript

Also add the following event to deal with pasting into the textarea:

...

txts[i].onkeyup = function() {
  ...
}

txts[i].paste = function() {
  var len = parseInt(this.getAttribute("maxlength"), 10);

  if (this.value.length + window.clipboardData.getData("Text").length > len) {
    alert('Maximum length exceeded: ' + len);
    this.value = this.value.substr(0, len);
    return false;
  }
}

...

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Add the annotation

@JsonManagedReference

For example:

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "autorizacoes_usuario", joinColumns = { @JoinColumn(name = "fk_usuario") }, inverseJoinColumns = { @JoinColumn(name = "fk_autorizacoes") })
@JsonManagedReference
public List<AutorizacoesUsuario> getAutorizacoes() {
    return this.autorizacoes;
}

What does "xmlns" in XML mean?

xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:

<config xmlns:rnc="URI1" xmlns:bsc="URI2">
  <rnc:node>
      <rnc:rncId>5</rnc:rncId>
  </rnc:node>

  <bsc:node>
      <bsc:cId>5</bsc:cId>
  </bsc:node>
</config>

Two different node elements in one xml file. Without namespaces this file would not be valid.

Error "package android.support.v7.app does not exist"

Switching to AndroidX helped me: import androidx.appcompat.app.AppCompatActivity;

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Excel 2010 driver is 64 bit, while the default SSMS import export wizard is 32 therefore the error message.

You can import using the Import Export Data (64 bit) tool. ("C:\Program Files\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe") notice the path is not Program Files x86.

Naming convention - underscore in C++ and C# variables

As far as the C and C++ languages are concerned there is no special meaning to an underscore in the name (beginning, middle or end). It's just a valid variable name character. The "conventions" come from coding practices within a coding community.

As already indicated by various examples above, _ in the beginning may mean private or protected members of a class in C++.

Let me just give some history that may be fun trivia. In UNIX if you have a core C library function and a kernel back-end where you want to expose the kernel function to user space as well the _ is stuck in front of the function stub that calls the kernel function directly without doing anything else. The most famous and familiar example of this is exit() vs _exit() under BSD and SysV type kernels: There, exit() does user-space stuff before calling the kernel's exit service, whereas _exit just maps to the kernel's exit service.

So _ was used for "local" stuff in this case local being machine-local. Typically _functions() were not portable. In that you should not expect same behaviour across various platforms.

Now as for _ in variable names, such as

int _foo;

Well psychologically, an _ is an odd thing to have to type in the beginning. So if you want to create a variable name that would have a lesser chance of a clash with something else, ESPECIALLY when dealing with pre-processor substitutions you want consider uses of _.

My basic advice would be to always follow the convention of your coding community, so that you can collaborate more effectively.

How to capitalize first letter of each word, like a 2-word city?

There's a good answer here:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

or in ES6:

var text = "foo bar loo zoo moo";
text = text.toLowerCase()
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

How to check if a table is locked in sql server

Better yet, consider sp_getapplock which is designed for this. Or use SET LOCK_TIMEOUT

Otherwise, you'd have to do something with sys.dm_tran_locks which I'd use only for DBA stuff: not for user defined concurrency.

Java SSL: how to disable hostname verification

It should be possible to create custom java agent that overrides default HostnameVerifier:

import javax.net.ssl.*;
import java.lang.instrument.Instrumentation;

public class LenientHostnameVerifierAgent {
    public static void premain(String args, Instrumentation inst) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }
}

Then just add -javaagent:LenientHostnameVerifierAgent.jar to program's java startup arguments.

How to setup Main class in manifest file in jar produced by NetBeans project

Don't hesitate but look into your project files after you have built your project for the first time. Look for a manifest file and choose open with notepad.

Add the line:

Main-Class: package.myMainClassName

Where package is your package and myClassName is the class with the main(String[] args) method.

How to get the focused element with jQuery?

How is it noone has mentioned..

document.activeElement.id

I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}

Forbidden You don't have permission to access /wp-login.php on this server

I had this same problem, and after temporarily deleting all my .htaccess files, then trying to modify them as suggested, and making sure all my files and folder permissions were set to 777, I still couldn't get it to work. I don't know why I couldn't access the file, but I was able to create a new file and access it no problem. So what I did was create a new file in /wp-admin/ called temp.php and pasted all the code from install.php into it. This allowed me to access the file. The only other thing I had to do was edit the code so that the form submitted to temp.php instead of install.php. After that, I could finish the install and everything worked.

<form id="setup" method="post" action="temp.php?step=2">

How to pause a YouTube player when hiding the iframe?

You can stop the video by calling the stopVideo() method on the YouTube player instance before hiding the div e.g.

player.stopVideo()

For more details see here: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls

What is the difference between 'protected' and 'protected internal'?

This table shows the difference. protected internal is the same as protected, except it also allows access from other classes in the same assembly.

Comparison of C# modifiers

Create an empty object in JavaScript with {} or new Object()?

These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.

How to get the real path of Java application at runtime?

It is better to save files into a sub-directory of user.home than wherever the app. might reside.

Sun went to considerable effort to ensure that applets and apps. launched using Java Web Start cannot determine the apps. real path. This change broke many apps. I would not be surprised if the changes are extended to other apps.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Convert JsonNode into POJO

String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
    new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);

If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)

mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);

Simple calculations for working with lat/lon and km distance?

Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:

func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
        let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
        let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
        let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax

        let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
        let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
        return CLLocation(latitude: lat, longitude: lng)
    }

In this function to convert distance I use following formulas:

latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

Remove

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency> 

slf4j-log4j12 is the log4j binding for slf4j you dont need to add another log4j dependency.

Added
Provide the log4j configuration in log4j.properties and add it to your class path. There are sample configurations here

or you can change your binding to

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>

if you are configuring slf4j due to some dependencies requiring it.

What is the meaning of curly braces?

In Python, curly braces are used to define a dictionary.

a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3

In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.

for entry in entries:
     code....

There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.

from __future__ import braces

Getting values from JSON using Python

Using Python to extract a value from the provided Json

Working sample:-

import json
import sys

//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

//dumps the json object into an element
json_str = json.dumps(data)

//load the json to a string
resp = json.loads(json_str)

//print the resp
print (resp)

//extract an element in the response
print (resp['test1'])

Setting default value in select drop-down using Angularjs

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

This would get you desired result Dude :) Cheers