Programs & Examples On #Mapstraction

Mapstraction is a common API that abstracts various JavaScript mapping APIs.

How to convert a python numpy array to an RGB image with Opencv 2.4?

The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50

import cv2 as cv
import numpy as np

black_screen = np.zeros([50,50,3])

black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()

How to clear a data grid view

refresh the datagridview and refresh the datatable

dataGridView1.Refresh();
datatable.Clear();

CSS selectors ul li a {...} vs ul > li > a {...}

ul > li > a selects only the direct children. In this case only the first level <a> of the first level <li> inside the <ul> will be selected.

ul li a on the other hand will select ALL <a>-s in ALL <li>-s in the unordered list

Example of ul > li

_x000D_
_x000D_
ul > li.bg {_x000D_
  background: red;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="bg">affected</li>_x000D_
  <li class="bg">affected</li>    _x000D_
  <li>_x000D_
    <ol>_x000D_
      <li class="bg">NOT affected</li>_x000D_
      <li class="bg">NOT affected</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

if you'd be using ul li - ALL of the li-s would be affected

UPDATE The order of more to less efficient CSS selectors goes thus:

  • ID, e.g.#header
  • Class, e.g. .promo
  • Type, e.g. div
  • Adjacent sibling, e.g. h2 + p
  • Child, e.g. li > ul
  • Descendant, e.g. ul a
  • Universal, i.e. *
  • Attribute, e.g. [type="text"]
  • Pseudo-classes/-elements, e.g. a:hover

So your better bet is to use the children selector instead of just descendant. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.

Why can't decimal numbers be represented exactly in binary?

The problem is that you do not really know whether the number actually is exactly 61.0 . Consider this:


float a = 60;
float b = 0.1;
float c = a + b * 10;

What is the value of c? It is not exactly 61, because b is not really .1 because .1 does not have an exact binary representation.

Event on a disabled input

suggestion here looks like a good candidate for this question as well

Performing click event on a disabled element? Javascript jQuery

jQuery('input#submit').click(function(e) {
    if ( something ) {        
        return false;
    } 
});

Maven command to determine which settings.xml file Maven is using

The M2_HOME environment variable for the global one. See Settings Reference:

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:

  • The Maven install: $M2_HOME/conf/settings.xml
  • A user's install: ${user.home}/.m2/settings.xml

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Change the project theme in Android Studio?

Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles

Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.enter image description here

Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

  • Theme.Holo for a "dark" theme.
  • Theme.Holo.Light for a "light" theme.

When using the Support Library, you must instead use the Theme.AppCompat themes:

  • Theme.AppCompat for the "dark" theme.
  • Theme.AppCompat.Light for the "light" theme.
  • Theme.AppCompat.Light.DarkActionBar for the light theme with a dark action bar.

Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x

How to empty a char array?

You can use the following instruction:

strcpy_s(members, "");

ActionController::UnknownFormat

You can also modify your config/routes.rb file like:

 get 'ajax/:action', to: 'ajax#:action', :defaults => { :format => 'json' }

Which will default the format to json. It is working fine for me in Rails 4.

Or if you want to go even further and you are using namespaces, you can cut down the duplicates:

namespace :api, defaults: {format: 'json'} do
   #your controller routes here ...
end

with the above everything under /api will be formatted as json by default.

In a URL, should spaces be encoded using %20 or +?

This confusion is because URL is still 'broken' to this day

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+   
|      Part     |      Data         |   
+---------------+-------------------+   
|  Scheme       | http              |   
|  Host address | www.google.com    |   
+---------------+-------------------+  

If we look at a more complex URL such as "https://bob:[email protected]:8080/file;p=1?q=2#third" we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host address     | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file               |
|  Path parameters  | p=1                 |
|  Query parameters | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

The reserved characters are different for each part

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts: "http://example.com/blue+light%20blue?blue%2Blight+blue". From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

What this boils down to is

you should have %20 before the ? and + after

Source

Redirect to Action by parameter mvc

This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.

public static void RegisterRoutes(RouteCollection routes)
{
    //adding the {id} and setting is as optional so that you do not need to use it for every action
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Now you should be able to redirect to your controller the way you have set it up.

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index","ProductImageManager", new { id });

    //if the action is in the same controller, you can omit the controller:
    //RedirectToAction("Index", new { id });
}

In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter

return RedirectToAction("Index", new RouteValueDictionary( 
    new { controller = "ProductImageManager", action = "Index", id = id } ) 
);

If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index). See this so question for more information.

Controlling a USB power supply (on/off) with Linux

I have found these solutions that at least work for properly configured Terminus FE 1.1 USB hub chip:

1.To turn off power on all USB ports of a hub, you may unbind the hub from kernel using:

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/unbind

to turn power back on - you may bind it back using

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/bind

2.Switching power at each port individually is trickier: I was able to use hubpower to control each port - but it comes with a downside: hubpower first disconnects the usbdevfs wich causes all of the USB devices to disconect from system, at least on ubuntu:

usb_ioctl.ioctl_code = USBDEVFS_DISCONNECT;
rc = ioctl(fd, USBDEVFS_IOCTL, &usb_ioctl);

With this ioctl disabled I was able to switch off individual port power without detaching all devices - but the power goes back on immediately (probably due to kernel seeing an uninitialized device) which causes USB device just to do a "cold restart" which is what I generally wanted to do. My patched hubpower is here

Creating an index on a table variable

It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386

Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.

The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.

To avoid name clashes, something like this usually works:

declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);

This insures the name is always unique even between simultaneous executions of the same procedure.

Access item in a list of lists

You can use itertools.cycle:

>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0])   # lis[0] is [10,13,17]
36

Here the generator expression inside sum would return something like this:

>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]

You can also use zip here:

>>> cyc = cycle((-1, 1))
>>> [x*y for x, y  in zip(lis[0], cyc)]
[-10, 13, -17]

How do I perform a Perl substitution on a string while keeping the original?

The statement:

(my $newstring = $oldstring) =~ s/foo/bar/g;

Which is equivalent to:

my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

Alternatively, as of Perl 5.13.2 you can use /r to do a non destructive substitution:

use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;

Is using 'var' to declare variables optional?

Consider this question asked at StackOverflow today:

Simple Javascript question

A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.

What's the problem with the code?
The code only works the first time the user clicks the button.

What's the solution?
Add the var keyword before the variable name.

Minimum Hardware requirements for Android development

Its of no use even if you increase your RAM size because I tried it too. I am using P4 3.00GHz processor and 3 GB RAM(changed from 1 GB to 3GB), But even the Hello world application never turned up.

Its preferable to upgrade your system.

How does JavaScript .prototype work?

Consider the following keyValueStore object :

var keyValueStore = (function() {
    var count = 0;
    var kvs = function() {
        count++;
        this.data = {};
        this.get = function(key) { return this.data[key]; };
        this.set = function(key, value) { this.data[key] = value; };
        this.delete = function(key) { delete this.data[key]; };
        this.getLength = function() {
            var l = 0;
            for (p in this.data) l++;
            return l;
        }
    };

    return  { // Singleton public properties
        'create' : function() { return new kvs(); },
        'count' : function() { return count; }
    };
})();

I can create a new instance of this object by doing this :

kvs = keyValueStore.create();

Each instance of this object would have the following public properties :

  • data
  • get
  • set
  • delete
  • getLength

Now, suppose we create 100 instances of this keyValueStore object. Even though get, set, delete, getLength will do the exact same thing for each of these 100 instances, every instance has its own copy of this function.

Now, imagine if you could have just a single get, set, delete and getLength copy, and each instance would reference that same function. This would be better for performance and require less memory.

That's where prototypes come in. A prototype is a "blueprint" of properties that is inherited but not copied by instances. So this means that it exists only once in memory for all instances of an object and is shared by all of those instances.

Now, consider the keyValueStore object again. I could rewrite it like this :

var keyValueStore = (function() {
    var count = 0;
    var kvs = function() {
        count++;
        this.data = {};
    };

    kvs.prototype = {
        'get' : function(key) { return this.data[key]; },
        'set' : function(key, value) { this.data[key] = value; },
        'delete' : function(key) { delete this.data[key]; },
        'getLength' : function() {
            var l = 0;
            for (p in this.data) l++;
            return l;
        }
    };

    return  {
        'create' : function() { return new kvs(); },
        'count' : function() { return count; }
    };
})();

This does EXACTLY the same as the previous version of the keyValueStore object, except that all of its methods are now put in a prototype. What this means, is that all of the 100 instances now share these four methods instead of each having their own copy.

Xcode Objective-C | iOS: delay function / NSTimer help?

I would like to add a bit the answer by Avner Barr. When using int64, it appears that when we surpass the 1.0 value, the function seems to delay differently. So I think at this point, we should use NSTimeInterval.

So, the final code is:

NSTimeInterval delayInSeconds = 0.05;

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

//do your tasks here

});

How do I make a transparent border with CSS?

hey this is the best solution I ever experienced.. this is CSS3

use following property to your div or anywhere you wanna put border trasparent

e.g.

div_class { 
 border: 10px solid #999;
 background-clip: padding-box; /* Firefox 4+, Opera, for IE9+, Chrome */
}

this will work..

Jquery .on('scroll') not firing the event while scrolling

I know that this is quite old thing, but I solved issue like that: I had parent and child element was scrollable.

   if ($('#parent > *').length == 0 ){
        var wait = setInterval(function() {
            if($('#parent > *').length != 0 ) {
                $('#parent .child').bind('scroll',function() {
                  //do staff
                });
                clearInterval(wait);
            },1000);
        }

The issue I had is that I didn't know when the child is loaded to DOM, but I kept checking for it every second.

NOTE:this is useful if it happens soon but not right after document load, otherwise it will use clients computing power for no reason.

jQuery Set Select Index

you can set selectoption variable value dynamically as well as option will be selected.You can try following code

code:

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

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML CODE:

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

How to switch activity without animation in Android?

Here is a one-liner solution that works for as low as minSdkVersion 14 which you should insert in you res/styles.xml:

<item name="android:windowAnimationStyle">@null</item>

like so:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        ...
        <item name="android:windowAnimationStyle">@null</item>
    </style>
    ...
</resources>

Cheers!

How to turn on front flash light programmatically in Android?

In Marshmallow and above, CameraManager's `setTorchMode()' seems to be the answer. This works for me:

 final CameraManager mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
 CameraManager.TorchCallback torchCallback = new CameraManager.TorchCallback() {
     @Override
     public void onTorchModeUnavailable(String cameraId) {
         super.onTorchModeUnavailable(cameraId);
     }

     @Override
     public void onTorchModeChanged(String cameraId, boolean enabled) {
         super.onTorchModeChanged(cameraId, enabled);
         boolean currentTorchState = enabled;
         try {
             mCameraManager.setTorchMode(cameraId, !currentTorchState);
         } catch (CameraAccessException e){}



     }
 };

 mCameraManager.registerTorchCallback(torchCallback, null);//fires onTorchModeChanged upon register
 mCameraManager.unregisterTorchCallback(torchCallback);

Connect to mysql in a docker container from the host

For conversion,you can create ~/.my.cnf file in host:

[Mysql]
user=root
password=yourpass
host=127.0.0.1
port=3306

Then next time just run mysql for mysql client to open connection.

Replace Both Double and Single Quotes in Javascript String

You don't need to escape it inside. You can use the | character to delimit searches.

"\"foo\"\'bar\'".replace(/("|')/g, "")

Java serialization - java.io.InvalidClassException local class incompatible

@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver program on all your old classes. put these serialVersionUID values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID on all Serializable classes)

if the new versions are not serial compatible, then you need to do some magic with a custom readObject implementation (you would only need a custom writeObject if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.

Of course, even if the new class is serial compatible, you may still want a custom readObject implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).

Find unused code

FXCop is a code analyzer... It does much more than find unused code. I used FXCop for a while, and was so lost in its recommendations that I uninstalled it.

I think NDepend looks like a more likely candidate.

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

how to create 100% vertical line in css

There are at least two ways to solve this.

Solution 1:

If you are okay with using an absolutely positioned element, you can use the top and bottom properties instead of height. By setting both top and bottom to 0 you force the element into taking up full height.

#menu
{
    position: absolute;
    border-right: 1px solid black;
    top: 0;
    bottom: 0;
}?

Demo

Solution 2:

Another way would be to force the HTML and BODY elements into a 100% height, to give room for a menu with 100% height:

body, html { height: 100%; }
#menu
{
    border-right: 1px solid black;
    height: 100%;
}?

Demo

Inner join with count() on three tables

select pe_name,count( distinct b.ord_id),count(c.item_id) 
 from people  a, order1 as b ,item as c
 where a.pe_id=b.pe_id and
b.ord_id=c.order_id   group by a.pe_id,pe_name

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I just had to solve the same problem: json-encoding an entity ("User") having a One-To-Many Bidirectional Association to another Entity ("Location").

I tried several things and I think now I found the best acceptable solution. The idea was to use the same code as written by David, but somehow intercept the infinite recursion by telling the Normalizer to stop at some point.

I did not want to implement a custom normalizer, as this GetSetMethodNormalizer is a nice approach in my opinion (based on reflection etc.). So I've decided to subclass it, which is not trivial at first sight, because the method to say if to include a property (isGetMethod) is private.

But, one could override the normalize method, so I intercepted at this point, by simply unsetting the property that references "Location" - so the inifinite loop is interrupted.

In code it looks like this:

class GetSetMethodNormalizer extends \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer {

    public function normalize($object, $format = null)
    {
        // if the object is a User, unset location for normalization, without touching the original object
        if($object instanceof \Leonex\MoveBundle\Entity\User) {
            $object = clone $object;
            $object->setLocations(new \Doctrine\Common\Collections\ArrayCollection());
        }

        return parent::normalize($object, $format);
    }

} 

PHPExcel auto size column width

Here a more flexible variant based on @Mark Baker post:

foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
        $phpExcelObject->getActiveSheet()
                ->getColumnDimension($col)
                ->setAutoSize(true);
    } 

Hope this helps ;)

Currency format for display

Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.

You can use it with either String.Format or the overloaded ToString method for a numeric type.

For example:

double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("da-DK")));

// The example displays the following output on a system whose
// current culture is English (United States):
//       $12,345.68
//       $12,345.679
//       kr 12.345,679

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

Perform .join on value in array of objects

I've also come across using the reduce method, this is what it looks like:

[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
].reduce(function (a, b) {return (a.name || a) + ", " + b.name})

The (a.name || a) is so the first element is treated correctly, but the rest (where a is a string, and so a.name is undefined) isn't treated as an object.

Edit: I've now refactored it further to this:

x.reduce(function(a, b) {return a + ["", ", "][+!!a.length] + b.name;}, "");

which I believe is cleaner as a is always a string, b is always an object (due to the use of the optional initialValue parameter in reduce)

Edit 6 months later: Oh what was I thinking. "cleaner". I've angered the code Gods.

Python Loop: List Index Out of Range

  1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
    Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a's items like that: a[i]. This won't give any errors.

  1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

  1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

This does the job in only one line.

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

How to know if two arrays have the same values

I have another way based on the accepted answer.

function compareArrays(array1, array2) {

    if (
        !Array.isArray(array1)
        || !Array.isArray(array2)
        || array1.length !== array2.length
    ) return false;

    var first = array1.sort().map(value => (String(value))).join();
    var second = array2.sort().map(value => (String(value))).join();

    return first == second ? true : false;
}

How to connect Bitbucket to Jenkins properly

I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.

Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.

How do I use a regular expression to match any string, but at least 3 characters?

You could try with simple 3 dots. refer to the code in perl below

$a =~ m /.../ #where $a is your string

Waiting until the task finishes

In Swift 3, there is no need for completion handler when DispatchQueue finishes one task. Furthermore you can achieve your goal in different ways

One way is this:

    var a: Int?

    let queue = DispatchQueue(label: "com.app.queue")
    queue.sync {

        for  i in 0..<10 {

            print("??" , i)
            a = i
        }
    }

    print("After Queue \(a)")

It will wait until the loop finishes but in this case your main thread will block.

You can also do the same thing like this:

    let myGroup = DispatchGroup()
    myGroup.enter()
    //// Do your task

    myGroup.leave() //// When your task completes
     myGroup.notify(queue: DispatchQueue.main) {

        ////// do your remaining work
    }

One last thing: If you want to use completionHandler when your task completes using DispatchQueue, you can use DispatchWorkItem.

Here is an example how to use DispatchWorkItem:

let workItem = DispatchWorkItem {
    // Do something
}

let queue = DispatchQueue.global()
queue.async {
    workItem.perform()
}
workItem.notify(queue: DispatchQueue.main) {
    // Here you can notify you Main thread
}

How can I make a DateTimePicker display an empty string?

The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.

dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;


dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;

the value changed event function

        void Dtp_ValueChanged(object sender, EventArgs e)
        {
            if(((DateTimePicker)sender).ShowCheckBox==true)
            {
                if(((DateTimePicker)sender).Checked==false)
                {
                    ((DateTimePicker)sender).CustomFormat = " ";
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
                }
                else
                {
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
                }
            }
            else
            {
                ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
            }
        }

When unchecked enter image description here

When checked enter image description here

How to get an Array with jQuery, multiple <input> with the same name

Q:How to access name array text field

<input type="text" id="task" name="task[]" />

Answer - Using Input name array :

$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()

Get path of executable

There is no cross platform way that I know.

For Linux: readlink /proc/self/exe

Windows: GetModuleFileName

Detect If Browser Tab Has Focus

Cross Browser jQuery Solution! Raw available at GitHub

Fun & Easy to Use!

The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:

  • onblur|.blur/onfocus|.focus "duplicate" calls
  • window losing focus through selection of alternate app, like word
    • This tends to be undesirable simply because, if you have a bank page open, and it's onblur event tells it to mask the page, then if you open calculator, you can't see the page anymore!
  • Not triggering on page load

Use is as simple as: Scroll Down to 'Run Snippet'

$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
});

//  OR Pass False boolean, and it will not trigger on load,
//  Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
}, false);

//  OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
//  (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
    blur: function(event) {
        console.log("Blur\t\t", event);
    },
    focus: function(event) {
        console.log("Focus\t\t", event);
    }
});

//  OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
    console.log("Blur\t\t", event);
},
function(event) {
    console.log("Focus\t\t", event);
});

_x000D_
_x000D_
/*    Begin Plugin    */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/*    End Plugin      */_x000D_
_x000D_
// Simple example_x000D_
$(function() {_x000D_
 $.winFocus(function(event, isVisible) {_x000D_
  $('td tbody').empty();_x000D_
  $.each(event, function(i) {_x000D_
   $('td tbody').append(_x000D_
    $('<tr />').append(_x000D_
     $('<th />', { text: i }),_x000D_
     $('<td />', { text: this.toString() })_x000D_
    )_x000D_
   )_x000D_
  });_x000D_
  if (isVisible) _x000D_
   $("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
    $('body').addClass('visible');_x000D_
    $(this).stop().text('TRUE').fadeIn('slow');_x000D_
   });_x000D_
  else {_x000D_
   $('body').removeClass('visible');_x000D_
   $("#isVisible").text('FALSE');_x000D_
  }_x000D_
 });_x000D_
})
_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th><p>Is Visible?</p></th>_x000D_
        <td><p id="isVisible">TRUE</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="2">_x000D_
            <table>_x000D_
                <thead>_x000D_
                    <tr>_x000D_
                        <th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_
                    </tr>_x000D_
                </thead>_x000D_
                <tbody></tbody>_x000D_
            </table>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

No module named Image

Did you setup PIL module? Link

You can try to reinstall it on your computer.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

If none of the solutions work for you, the handling the post-autoload-dump event returned with error code 1 error can also be caused by using Composer 2 instead of Composer 1. That can happen when you run the install command manually in something like a Dockerfile, and it installs newest. Just modify your command to install the last 1.x.x stable version with the --1 option:

curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --1

Or, specify a certain version with --version=x.x.x:

curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --version=1.10.17

It might be good to also delete your vendor directory and composer.lock file so that nothing stale interferes with the version downgrade, before calling composer install as usual.

Understanding Bootstrap's clearfix class

.clearfix is defined in less/mixins.less. Right above its definition is a comment with a link to this article:

A new micro clearfix hack

The article explains how it all works.

UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):

This “micro clearfix” generates pseudo-elements and sets their display to table. This creates an anonymous table-cell and a new block formatting context that means the :before pseudo-element prevents top-margin collapse. The :after pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.

Including the :before selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:

  • It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g., overflow:hidden

  • It ensures visual consistency with IE 6/7 when zoom:1 is applied.

N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.

The use of content:" " (note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if the contenteditable attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to use font:0/0 a.

Legacy Firefox

Firefox < 3.5 will benefit from using Thierry’s method with the addition of visibility:hidden to hide the inserted character. This is because legacy versions of Firefox need content:"." to avoid extra space appearing between the body and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)

Alternative float-containment methods that create a new block formatting context, such as applying overflow:hidden or display:inline-block to the container element, will also avoid this behaviour in legacy versions of Firefox.

HTML text input field with currency symbol

Since you can't do ::before with content: '$' on inputs and adding an absolutely positioned element adds extra html - I like do to a background SVG inline css.

It goes something like this:

input {
    width: 85px;
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='16px' width='85px'><text x='2' y='13' fill='gray' font-size='12' font-family='arial'>$</text></svg>");
    padding-left: 12px;
}

It outputs the following:

svg dollar sign background css

Note: the code must all be on a single line. Support is pretty good in modern browsers, but be sure to test.

ASP.Net MVC - Read File from HttpPostedFileBase without save

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

Get webpage contents with Python?

You can use urlib2 and parse the HTML yourself.

Or try Beautiful Soup to do some of the parsing for you.

How to specify HTTP error code?

Old question, but still coming up on Google. In the current version of Express (3.4.0), you can alter res.statusCode before calling next(err):

res.statusCode = 404;
next(new Error('File not found'));

Margin on child element moves parent element

Using top instead of margin-top is another possible solution, if appropriate.

Open JQuery Datepicker by clicking on an image w/ no input field

Having a hidden input field leads to problems with datepicker dialog positioning (dialog is horizontally centered). You could alter the dialog's margin, but there's a better way.

Just create an input field and "hide" it by setting it's opacity to 0 and making it 1px wide. Also position it near (or under) the button, or where ever you want the datepicker to appear.

Then attach the datepicker to the "hidden" input field and show it when user presses the button.

HTML:

<button id="date-button">Show Calendar</button>
<input type="text" name="date-field" id="date-field" value="">

CSS:

#date-button {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    height 30px;
}

#date-field {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 1px;
    height: 32px; // height of the button + a little margin
    opacity: 0;
}

JS:

$(function() {
   $('#date-field').datepicker();

   $('#date-button').on('click', function() {
      $('#date-field').datepicker('show');
   });
});

Note: not tested with all browsers.

How to set entire application in portrait mode only?

Use:

android:screenOrientation="portrait" 

Just write this line in your application's manifest file in each activity which you want to show in portrait mode only.

Select mySQL based only on month and year

The logic will be:

SELECT * FROM objects WHERE Date LIKE '$_POST[period]-%';

The LIKE operator will select all rows that start with $_POST['period'] followed by dash and the day of the mont

http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html - Some additional information

How to get the type of T from a member of a generic class or method?

That's work for me. Where myList is some unknown kind of list.

IEnumerable myEnum = myList as IEnumerable;
Type entryType = myEnum.AsQueryable().ElementType;

Is it possible to set a number to NaN or infinity?

When using Python 2.4, try

inf = float("9e999")
nan = inf - inf

I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999") fixed it. Don't use inf = 9e999, you need convert it from string. -inf gives the -Infinity.

How to import a csv file into MySQL workbench?

At the moment it is not possible to import a CSV (using MySQL Workbench) in all platforms, nor is advised if said file does not reside in the same host as the MySQL server host.

However, you can use mysqlimport.

Example:

mysqlimport --local --compress --user=username --password --host=hostname \
--fields-terminated-by=',' Acme sales.part_*

In this example mysqlimport is instructed to load all of the files named "sales" with an extension starting with "part_". This is a convenient way to load all of the files created in the "split" example. Use the --compress option to minimize network traffic. The --fields-terminated-by=',' option is used for CSV files and the --local option specifies that the incoming data is located on the client. Without the --local option, MySQL will look for the data on the database host, so always specify the --local option.

There is useful information on the subject in AWS RDS documentation.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Getting DOM elements by classname

Update: Xpath version of *[@class~='my-class'] css selector

So after my comment below in response to hakre's comment, I got curious and looked into the code behind Zend_Dom_Query. It looks like the above selector is compiled to the following xpath (untested):

[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]

So the PHP would be:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

Basically, all we do here is normalize the class attribute so that even a single class is bounded by spaces, and the complete class list is bounded in spaces. Then append the class we are searching for with a space. This way we are effectively looking for and find only instances of my-class .


Use an xpath selector?

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

If it is only ever one type of element you can replace the * with the particular tagname.

If you need to do a lot of this with very complex selector I would recommend Zend_Dom_Query which supports CSS selector syntax (a la jQuery):

$finder = new Zend_Dom_Query($html);
$classname = 'my-class';
$nodes = $finder->query("*[class~=\"$classname\"]");

Slidedown and slideup layout with animation

I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.

Refer to the link for more details: https://github.com/mancj/SlideUp-Android

To set up the library(copied from the ReadMe portion of its Github page on request):

Get SlideUp library

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" } // or google() in AS 3.0
  }
}

Add the dependency (in the Module gradle)

dependencies {
    compile 'com.github.mancj:SlideUp-Android:2.2.1'
    compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
    compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}

To add the SlideUp into your project, follow these three simple steps:

Step 1:

create any type of layout

<LinearLayout
  android:id="@+id/slideView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

Step 2:

Find that view in your activity/fragment

View slideView = findViewById(R.id.slideView);

Step 3:

Create a SlideUp object and pass in your view

slideUp = new SlideUpBuilder(slideView)
                .withStartState(SlideUp.State.HIDDEN)
                .withStartGravity(Gravity.BOTTOM)

                //.withSlideFromOtherView(anotherView)
                //.withGesturesEnabled()
                //.withHideSoftInputWhenDisplayed()
                //.withInterpolator()
                //.withAutoSlideDuration()
                //.withLoggingEnabled()
                //.withTouchableAreaPx()
                //.withTouchableAreaDp()
                //.withListeners()
                //.withSavedState()
                .build();

You may also refer to the sample project on the link. I found it quite useful.

Opening PDF String in new window with javascript

I realize this is a pretty old question, but I had the same thing come up today and came up with the following solution:

doSomethingToRequestData().then(function(downloadedFile) {
  // create a download anchor tag
  var downloadLink      = document.createElement('a');
  downloadLink.target   = '_blank';
  downloadLink.download = 'name_to_give_saved_file.pdf';

  // convert downloaded data to a Blob
  var blob = new Blob([downloadedFile.data], { type: 'application/pdf' });

  // create an object URL from the Blob
  var URL = window.URL || window.webkitURL;
  var downloadUrl = URL.createObjectURL(blob);

  // set object URL as the anchor's href
  downloadLink.href = downloadUrl;

  // append the anchor to document body
  document.body.appendChild(downloadLink);

  // fire a click event on the anchor
  downloadLink.click();

  // cleanup: remove element and revoke object URL
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(downloadUrl);
});

How to run vbs as administrator from vbs?

`My vbs file path :

D:\QTP Practice\Driver\Testany.vbs'

objShell = CreateObject("Shell.Application")

objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1

set x=createobject("wscript.shell")

wscript.sleep(2000)

x.sendkeys "CD\"&"{ENTER}"&"cd D:"&"{ENTER}"&"cd "&"QTP Practice\Driver"&"{ENTER}"&"Testany.vbs"&"{ENTER}"

--from google search and some tuning, working for me

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

MySQLDump one INSERT statement for each data row

Use:

mysqldump --extended-insert=FALSE 

Be aware that multiple inserts will be slower than one big insert.

How do I bottom-align grid elements in bootstrap fluid layout

Here's also an angularjs directive to implement this functionality

    pullDown: function() {
      return {
        restrict: 'A',
        link: function ($scope, iElement, iAttrs) {
          var $parent = iElement.parent();
          var $parentHeight = $parent.height();
          var height = iElement.height();

          iElement.css('margin-top', $parentHeight - height);
        }
      };
    }

Validate phone number using javascript

Here's how I do it.

_x000D_
_x000D_
function validate(phone) {_x000D_
  const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  console.log(regex.test(phone))_x000D_
}_x000D_
_x000D_
validate('1234567890')     // true_x000D_
validate(1234567890)       // true_x000D_
validate('(078)789-8908')  // true_x000D_
validate('123-345-3456')   // true
_x000D_
_x000D_
_x000D_

High Quality Image Scaling Library

Try This basic code snippet:

private static Bitmap ResizeBitmap(Bitmap srcbmp, int width, int height )
{
    Bitmap newimage = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(newimage))
           g.DrawImage(srcbmp, 0, 0, width, height);
    return newimage;
}

Disable button in jQuery

There are two things here, and the highest voted answer is technically correct as per the OPs question.

Briefly summarized as:

$("some sort of selector").prop("disabled", true | false);

However should you be using jQuery UI (I know the OP wasn't but some people arriving here might be) then while this will disable the buttons click event it wont make the button appear disabled as per the UI styling.

If you are using a jQuery UI styled button then it should be enabled / disabled via:

$("some sort of selector").button("enable" | "disable");

http://api.jqueryui.com/button/#method-disable

Android webview slow

Adding this android:hardwareAccelerated="true" in the manifest was the only thing that significantly improved the performance for me

More info here: http://developer.android.com/guide/topics/manifest/application-element.html#hwaccel

How to make URL/Phone-clickable UILabel?

Use UITextView instead of UILabel and it has a property to convert your text to hyperlink

Swift code:

yourTextView.editable = false
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.PhoneNumber
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.Link

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}
          ],
          testRcd:'value'   
};

How to validate phone number using PHP?

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....

Take a look at this similar question to get some ideas.

Then there is E.164 which is a numbering standard recommendation from ITU-T

How do I redirect output to a variable in shell?

read hash < <(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)

This technique uses Bash's "process substitution" not to be confused with "command substitution".

Here are a few good references:

Entity framework code-first null foreign key

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

This really saved my day.

I have written a extension method based on Zach's answer, also I have extended it to use the encoding as a parameter, allowing for different encodings beside from UTF-8 to be used, and I wrapped the MemoryStream in a 'using' statement.

public static class XmlHelperExtentions
{
    /// <summary>
    /// Loads a string through .Load() instead of .LoadXml()
    /// This prevents character encoding problems.
    /// </summary>
    /// <param name="xmlDocument"></param>
    /// <param name="xmlString"></param>
    public static void LoadString(this XmlDocument xmlDocument, string xmlString, Encoding encoding = null) {

        if (encoding == null) {
            encoding = Encoding.UTF8;
        }

        // Encode the XML string in a byte array
        byte[] encodedString = encoding.GetBytes(xmlString);

        // Put the byte array into a stream and rewind it to the beginning
        using (var ms = new MemoryStream(encodedString)) {
            ms.Flush();
            ms.Position = 0;

            // Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
            xmlDocument.Load(ms);
        }
    }
}

How does the SQL injection from the "Bobby Tables" XKCD comic work?

A single quote is the start and end of a string. A semicolon is the end of a statement. So if they were doing a select like this:

Select *
From Students
Where (Name = '<NameGetsInsertedHere>')

The SQL would become:

Select *
From Students
Where (Name = 'Robert'); DROP TABLE STUDENTS; --')
--             ^-------------------------------^

On some systems, the select would get ran first followed by the drop statement! The message is: DONT EMBED VALUES INTO YOUR SQL. Instead use parameters!

How to determine an object's class?

You can use:

Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object

HTH. But I think most of the time it is no good practice to use that for control flow or something similar...

Add new item in existing array in c#.net

All proposed answers do the same as what they say they'd like to avoid, creating a new array and adding a new entry in it only with lost more overhead. LINQ is not magic, list of T is an array with a buffer space with some extra space as to avoid resizing the inner array when items are added.

All the abstractions have to solve the same issue, create an array with no empty slots that hold all values and return them.

If you need the flexibility an can create a large enough list that you can use to pass then do that. else use an array and share that thread-safe object. Also, the new Span helps to share data without having to copy the lists around.

To answer the question:

Array.Resize(ref myArray, myArray.Length + 1);
data[myArray.Length - 1] = Value;

How to show code but hide output in RMarkdown?

For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)

How to start mongodb shell?

You were in the correct folder if you got the ./mongod working! You now need to open another terminal, go to the same folder and type ./mongo the first terminal window serves as your server, the second is where you enter your commands!

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

How to Validate Google reCaptcha on Form Submit

var googleResponse = jQuery('#g-recaptcha-response').val();
if (!googleResponse) {
    $('<p style="color:red !important" class=error-captcha"><span class="glyphicon glyphicon-remove " ></span> Please fill up the captcha.</p>" ').insertAfter("#html_element");
    return false;
} else {            
    return true;
}

Put this in a function. Call this function on submit... #html_element is my empty div.

Get the directory from a file path in java (android)

You could also use FilenameUtils from Apache. It provides you at least the following features for the example C:\dev\project\file.txt:

  • the prefix - C:\
  • the path - dev\project\
  • the full path - C:\dev\project\
  • the name - file.txt
  • the base name - file
  • the extension - txt

C# Timer or Thread.Sleep

It's important to understand that your code will sleep for 50 seconds between ending one loop, and starting the next...

A timer will call your loop every 50 seconds, which isn't exactly the same.

They're both valid, but a timer is probably what you're looking for here.

What is the easiest way to parse an INI File in C++?

If you need a cross-platform solution, try Boost's Program Options library.

How to pass object from one component to another in Angular 2?

From component

_x000D_
_x000D_
import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
    import { HttpClient } from '@angular/common/http';_x000D_
    import { dataService } from "src/app/service/data.service";_x000D_
    @Component( {_x000D_
        selector: 'app-sideWidget',_x000D_
        templateUrl: './sideWidget.html',_x000D_
        styleUrls: ['./linked-widget.component.css']_x000D_
    } )_x000D_
    export class sideWidget{_x000D_
    TableColumnNames: object[];_x000D_
    SelectedtableName: string = "patient";_x000D_
    constructor( private LWTableColumnNames: dataService ) { _x000D_
       _x000D_
    }_x000D_
    _x000D_
    ngOnInit() {_x000D_
        this.http.post( 'getColumns', this.SelectedtableName )_x000D_
            .subscribe(_x000D_
            ( data: object[] ) => {_x000D_
                this.TableColumnNames = data;_x000D_
     this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
            } );_x000D_
    _x000D_
    }    _x000D_
    }
_x000D_
_x000D_
_x000D_

DataService

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
_x000D_
@Injectable()_x000D_
export class dataService {_x000D_
    refLWTableColumnNames: object;//creating an object for the data_x000D_
}
_x000D_
_x000D_
_x000D_

To Component

_x000D_
_x000D_
import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
_x000D_
@Component( {_x000D_
    selector: 'app-linked-widget',_x000D_
    templateUrl: './linked-widget.component.html',_x000D_
    styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
_x000D_
    constructor(private LWTableColumnNames: dataService) { }_x000D_
_x000D_
    ngOnInit() {_x000D_
    console.log(this.LWTableColumnNames.refLWTableColumnNames);_x000D_
    }_x000D_
    createTable(){_x000D_
        console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Django: List field in model?

It's quite an old topic, but since it is returned when searching for "django list field" I'll share the custom django list field code I modified to work with Python 3 and Django 2. It supports the admin interface now and not uses eval (which is a huge security breach in Prashant Gaur's code).

from django.db import models
from typing import Iterable

class ListField(models.TextField):
    """
    A custom Django field to represent lists as comma separated strings
    """

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['token'] = self.token
        return name, path, args, kwargs

    def to_python(self, value):

        class SubList(list):
            def __init__(self, token, *args):
                self.token = token
                super().__init__(*args)

            def __str__(self):
                return self.token.join(self)

        if isinstance(value, list):
            return value
        if value is None:
            return SubList(self.token)
        return SubList(self.token, value.split(self.token))

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        if not value:
            return
        assert(isinstance(value, Iterable))
        return self.token.join(value)

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)

Using Razor within JavaScript

None of the previous solutions work correctly... I have tried all the ways, but it did not give me the expected result... At last I found that there are some errors in the code... And the full code is given below.

<script type="text/javascript">

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(23.00, 90.00),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    @foreach (var item in Model)
    {
        <text>
            var markerlatLng = new google.maps.LatLng(@(item.LATITUDE), @(item.LONGITUDE));
            var title = '@(item.EMP_ID)';
            var description = '@(item.TIME)';
            var contentString = '<h3>' + "Employee " +title+ " was here at "+description+ '</h3>' + '<p>'+" "+ '</p>'

            var infowindow = new google.maps.InfoWindow({
                // content: contentString
            });

            var marker = new google.maps.Marker({
                position: markerlatLng,
                title: title,
                map: map,
                draggable: false,
                content: contentString
            });

            google.maps.event.addListener(marker, 'click', (function (marker) {
                return function () {
                    infowindow.setContent(marker.content);
                    infowindow.open(map, marker);
                }
            })(marker));
        </text>
    }
</script>

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How to set caret(cursor) position in contenteditable element (div)?

I refactored @Liam's answer. I put it in a class with static methods, I made its functions receive an element instead of an #id, and some other small tweaks.

This code is particularly good for fixing the cursor in a rich text box that you might be making with <div contenteditable="true">. I was stuck on this for several days before arriving at the below code.

edit: His answer and this answer have a bug involving hitting enter. Since enter doesn't count as a character, the cursor position gets messed up after hitting enter. If I am able to fix the code, I will update my answer.

edit2: Save yourself a lot of headaches and make sure your <div contenteditable=true> is display: inline-block. This fixes some bugs related to Chrome putting <div> instead of <br> when you press enter.

How To Use

let richText = document.getElementById('rich-text');
let offset = Cursor.getCurrentCursorPosition(richText);
// do stuff to the innerHTML, such as adding/removing <span> tags
Cursor.setCurrentCursorPosition(offset, richText);
richText.focus();

Code

// Credit to Liam (Stack Overflow)
// https://stackoverflow.com/a/41034697/3480193
class Cursor {
    static getCurrentCursorPosition(parentElement) {
        var selection = window.getSelection(),
            charCount = -1,
            node;
        
        if (selection.focusNode) {
            if (Cursor._isChildOf(selection.focusNode, parentElement)) {
                node = selection.focusNode; 
                charCount = selection.focusOffset;
                
                while (node) {
                    if (node === parentElement) {
                        break;
                    }

                    if (node.previousSibling) {
                        node = node.previousSibling;
                        charCount += node.textContent.length;
                    } else {
                        node = node.parentNode;
                        if (node === null) {
                            break;
                        }
                    }
                }
            }
        }
        
        return charCount;
    }
    
    static setCurrentCursorPosition(chars, element) {
        if (chars >= 0) {
            var selection = window.getSelection();
            
            let range = Cursor._createRange(element, { count: chars });

            if (range) {
                range.collapse(false);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
    }
    
    static _createRange(node, chars, range) {
        if (!range) {
            range = document.createRange()
            range.selectNode(node);
            range.setStart(node, 0);
        }

        if (chars.count === 0) {
            range.setEnd(node, chars.count);
        } else if (node && chars.count >0) {
            if (node.nodeType === Node.TEXT_NODE) {
                if (node.textContent.length < chars.count) {
                    chars.count -= node.textContent.length;
                } else {
                    range.setEnd(node, chars.count);
                    chars.count = 0;
                }
            } else {
                for (var lp = 0; lp < node.childNodes.length; lp++) {
                    range = Cursor._createRange(node.childNodes[lp], chars, range);

                    if (chars.count === 0) {
                    break;
                    }
                }
            }
        } 

        return range;
    }
    
    static _isChildOf(node, parentElement) {
        while (node !== null) {
            if (node === parentElement) {
                return true;
            }
            node = node.parentNode;
        }

        return false;
    }
}

Add a column with a default value to an existing table in SQL Server

ALTER TABLE <table name> 
ADD <new column name> <data type> NOT NULL
GO
ALTER TABLE <table name> 
ADD CONSTRAINT <constraint name> DEFAULT <default value> FOR <new column name>
GO

automatically execute an Excel macro on a cell change

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 
       Macro
    End If

How to make google spreadsheet refresh itself every 1 minute?

If you're on the New Google Sheets, this is all you need to do, according to the docs:

change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.

This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.

If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:

=GoogleClock()

EDIT to include old and new Google Sheets and change to =GoogleClock().

How to count how many values per level in a given factor?

We can use summary on factor column:

summary(myDF$factorColumn)

This project references NuGet package(s) that are missing on this computer

Removed below lines in .csproj file

<Import Project="$(SolutionDir)\.nuget\NuGet.targets" 
Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
 <ErrorText>This project references NuGet package(s) that are missing on this computer. 
 Enable NuGet Package Restore to download them.  For more information, see 
 http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" 
Text="$([System.String]::Format('$(ErrorText)', 
'$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

Connecting to MySQL from Android with JDBC

Do you want to keep your database on mobile? Use sqlite instead of mysql.

If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.

How to install JQ on Mac by command-line?

For most it is a breeze, however like you I had a difficult time installing jq

The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/

However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system

What worked for me was removing all previous installs then pip install jq

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

Round button with text and icon in flutter

You can achieve that by using a FlatButton that contains a Column (for showing a text below the icon) or a Row (for text next to the icon), and then having an Icon Widget and a Text widget as children.

Here's an example:

class MyPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) =>
      Scaffold(
        appBar: AppBar(
          title: Text("Hello world"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                onPressed: () => {},
                color: Colors.orange,
                padding: EdgeInsets.all(10.0),
                child: Column( // Replace with a Row for horizontal icon + text
                  children: <Widget>[
                    Icon(Icons.add),
                    Text("Add")
                  ],
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => {},
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      );
}

This will produce the following:

Result

How to pass arguments within docker-compose?

Now docker-compose supports variable substitution.

Compose uses the variable values from the shell environment in which docker-compose is run. For example, suppose the shell contains POSTGRES_VERSION=9.3 and you supply this configuration in your docker-compose.yml file:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

Should I use Vagrant or Docker for creating an isolated environment?

If your purpose is the isolation, I think Docker is what you want.

Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on VirtualBox (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.

Docker on the other hand uses kernel cgroup and namespacing via LXC. It means that you are using the same kernel as the host and the same file system. You can use Dockerfile with the docker build command in order to handle the provisioning and configuration of your container. You have an example at docs.docker.com on how to make your Dockerfile; it is very intuitive.

The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.

Using the "start" command with parameters passed to the started program

Instead of a batch file, you can create a shortcut on the desktop.

Set the target to:

"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch

and you're all set. Since you're not starting up a command prompt to launch it, there will be no DOS Box.

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

How can I sanitize user input with PHP?

Never trust user data.

function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

The trim() function removes whitespace and other predefined characters from both sides of a string.

The stripslashes() function removes backslashes

The htmlspecialchars() function converts some predefined characters to HTML entities.

The predefined characters are:

& (ampersand) becomes &amp;
" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;

Comparing results with today's date?

This worked for me:

SELECT * FROM table where date(column_date) = curdate()

Erase the current printed console line

Usually when you have a '\r' at the end of the string, only carriage return is printed without any newline. If you have the following:

printf("fooooo\r");
printf("bar");

the output will be:

barooo

One thing I can suggest (maybe a workaround) is to have a NULL terminated fixed size string that is initialized to all space characters, ending in a '\r' (every time before printing), and then use strcpy to copy your string into it (without the newline), so every subsequent print will overwrite the previous string. Something like this:

char str[MAX_LENGTH];        
// init str to all spaces, NULL terminated with character as '\r'
strcpy(str, my_string);       // copy my_string into str
str[strlen(my_string)] = ' '; // erase null termination char
str[MAX_LENGTH - 1] = '\r';
printf(str);

You can do error checking so that my_string is always atleast one less in length than str, but you get the basic idea.

Paritition array into N chunks with Numpy

Not quite an answer, but a long comment with nice formatting of code to the other (correct) answers. If you try the following, you will see that what you are getting are views of the original array, not copies, and that was not the case for the accepted answer in the question you link. Be aware of the possible side effects!

>>> x = np.arange(9.0)
>>> a,b,c = np.split(x, 3)
>>> a
array([ 0.,  1.,  2.])
>>> a[1] = 8
>>> a
array([ 0.,  8.,  2.])
>>> x
array([ 0.,  8.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])
>>> def chunks(l, n):
...     """ Yield successive n-sized chunks from l.
...     """
...     for i in xrange(0, len(l), n):
...         yield l[i:i+n]
... 
>>> l = range(9)
>>> a,b,c = chunks(l, 3)
>>> a
[0, 1, 2]
>>> a[1] = 8
>>> a
[0, 8, 2]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8]

When to use MongoDB or other document oriented database systems?

I would say use an RDBMS if you need complex transactions. Otherwise I would go with MongoDB - more flexible to work with and you know it can scale when you need to. (I'm biased though - I work on the MongoDB project)

how to remove the first two columns in a file using shell (awk, sed, whatever)

perl:

perl -lane 'print join(' ',@F[2..$#F])' File

awk:

awk '{$1=$2=""}1' File

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

Using the passwd command from within a shell script

You can use the expect utility to drive all programs that read from a tty (as opposed to stdin, which is what passwd does). Expect comes with ready to run examples for all sorts of interactive problems, like passwd entry.

How can I add an item to a ListBox in C# and WinForms?

If you just want to add a string to it, the simple answer is:

ListBox.Items.Add("some text");

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How to check if current thread is not main thread

You can check

if(Looper.myLooper() == Looper.getMainLooper()) {
   // You are on mainThread 
}else{
// you are on non-ui thread
}

Send value of submit button when form gets posted

Like the others said, you probably missunderstood the idea of a unique id. All I have to add is, that I do not like the idea of using "value" as the identifying property here, as it may change over time (i.e. if you want to provide multiple languages).

<input id='submit_tea'    type='submit' name = 'submit_tea'    value = 'Tea' />
<input id='submit_coffee' type='submit' name = 'submit_coffee' value = 'Coffee' />

and in your php script

if( array_key_exists( 'submit_tea', $_POST ) )
{
  // handle tea
}
if( array_key_exists( 'submit_coffee', $_POST ) )
{
  // handle coffee
}

Additionally, you can add something like if( 'POST' == $_SERVER[ 'REQUEST_METHOD' ] ) if you want to check if data was acctually posted.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I have resolved the issue by adding below code snippet into node.js file.

app.get("/*", function (request, response) {
    console.log('Unknown API called');
    response.redirect('/#' + request.url);
});

Note : when we refresh the page, it will look for the API instead of Angular page (Because of no # tag in URL.) . Using the above code, I am redirecting to the url with #

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
    )
  )

SID_LIST_abc =
  (SID_LIST =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)
    )
  )

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Tools > Manage Add-ons, right click "Name" header and enable the "In Folder" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click "remove".

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

How to access your website through LAN in ASP.NET

If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.

Binding IIS Express to an IP Address

JavaScript: function returning an object

The latest way to do this with ES2016 JavaScript

let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
    name,
    totalScore,
    gamesPlayed
})

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Is there a .NET/C# wrapper for SQLite?

Microsoft.Data.Sqlite

Microsoft now provides Microsoft.Data.Sqlite as a first-party SQLite solution for .NET, which is provided as part of ASP.NET Core. The license is the Apache License, Version 2.0.

* Disclaimer: I have not actually tried using this myself yet, but there is some documentation provided on Microsoft Docs here for using it with .NET Core and UWP.

How to send a model in jQuery $.ajax() post request to MVC controller method

you can create a variable and send to ajax.

var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

Had the same issue. I am running the selenium script on Google cloud VM.

options.addArguments("--headless");

The above line resolved my issue. I removed the other optional arguments. I think the rest lines of code mentioned in other answers did not have any effect on resolving the issue on the cloud VM.

Can I use a case/switch statement with two variables?

If the action of each combination is static, you could build a two-dimensional array:

var data = [
  [1,2,3,4,5],
  [6,7,8,9,10],
  [11,12,13,14,15],
  [16,17,18,19,20],
  [21,22,23,24,25]
];

The numbers in above example can be anything, such as string, array, etc. Fetching the value is now a one-liner (assuming sliders have a value range of [0,5):

var info = data[firstSliderValue][secondSliderValue];

Python: Find in list

Definition and Usage

the count() method returns the number of elements with the specified value.

Syntax

list.count(value)

example:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

Question's example:

item = someSortOfSelection()

if myList.count(item) >= 1 :

    doMySpecialFunction(item)

Simplest way to merge ES6 Maps/Sets?

merge to Map

 let merge = {...map1,...map2};

Can I set an unlimited length for maxJsonLength in web.config?

I solved the problem adding this code:

String confString = HttpContext.Current.Request.ApplicationPath.ToString();
Configuration conf = WebConfigurationManager.OpenWebConfiguration(confString);
ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
section.MaxJsonLength = 6553600;
conf.Save();

What to gitignore from the .idea folder?

I just want to present a more recent alternative. There is an online tool that generates .gitignore files based on operating systems, IDEs and programming languages that you might be using.

gitignore.io


EDIT Disclaimer: Do not copy this file, copy the file generated by the website instead, they do a good job on keeping it updated. This is just an example.

The file generated for IntelliJ contains the following

# Created by https://www.gitignore.io/api/intellij

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;
}

How to pip or easy_install tkinter on Windows

If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment

Installing and Running MongoDB on OSX

Assuming you have created the data/db directory under bin after install.

  1. Start a terminal for your mongo server
  2. Go to <mongodb-install-directory>/bin directory
  3. Run the command

    ./mongod

  4. Start a terminal for your mongo shell

  5. Go to <mongodb-install-directory>/bin directory
  6. Run the command (make sure you put the name of the database)

    ./mongo test

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

iterate through a map in javascript

I'd use standard javascript:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

Note the different ways of treating objects and arrays.

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

How to force a view refresh without having it trigger automatically from an observable?

You can't call something on the entire viewModel, but on an individual observable you can call myObservable.valueHasMutated() to notify subscribers that they should re-evaluate. This is generally not necessary in KO, as you mentioned.

Deep copy of a dict in python

How about:

import copy
d = { ... }
d2 = copy.deepcopy(d)

Python 2 or 3:

Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = copy.deepcopy(my_dict)
>>> my_dict['a'][2] = 7
>>> my_copy['a'][2]
3
>>>

CSS transition fade in

I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS

div {
  opacity:0;
  transition:opacity 1s linear;*
}
div.SomeClass {
  opacity:1;
}

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

Open S3 object as a string with Boto3

This isn't in the boto3 documentation. This worked for me:

object.get()["Body"].read()

object being an s3 object: http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

fixing this on an ionic app, simply add

<preference name="loadUrlTimeoutValue" value="700000" />

to your config.xml file immediately after this line

<platform name="android">

How to downgrade to older version of Gradle

I did following steps to downgrade Gradle back to the original version:

  • I deleted content of '.gradle/caches' folder in user home directory (windows).
  • I deleted content of '.gradle' folder in my project root.
  • I checked that Gradle version is properly set in 'Project' option of 'Project Structure' in Android Studio.
  • I selected 'Use default gradle wrapper' option in 'Settings' in Android Studio, just search for gradle key word to find it.

Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.

the thing you have to do is to change your insertion query as below

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I     thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

ALTER TABLE to add a composite primary key

You may simply want a UNIQUE CONSTRAINT. Especially if you already have a surrogate key. (example of an already existing surrogate key would be a single column that is an AUTO_INCREMENT )

Below is the sql code for a Unique Constraint

ALTER TABLE `MyDatabase`.`Provider`
    ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (person,place,thing)
;

How do I compare two columns for equality in SQL Server?

What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.

CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult

should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How can I tell when HttpClient has timed out?

I found that the best way to determine if the service call has timed out is to use a cancellation token and not the HttpClient's timeout property:

var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);

And then handle the CancellationException during the service call...

catch(TaskCanceledException)
{
    if(!cts.Token.IsCancellationRequested)
    {
        // Timed Out
    }
    else
    {
        // Cancelled for some other reason
    }
}

Of course if the timeout occurs on the service side of things, that should be able to handled by a WebException.

How to redirect to a different domain using NGINX?

I'm using this code for my sites

server {
        listen 80;
        listen 443;
        server_name  .domain.com;

        return 301 $scheme://newdomain.com$request_uri;
}

List of lists into numpy array

I had a list of lists of equal length. Even then Ignacio Vazquez-Abrams's answer didn't work out for me. I got a 1-D numpy array whose elements are lists. If you faced the same problem, you can use the below method

Use numpy.vstack

import numpy as np

np_array = np.empty((0,4), dtype='float')
for i in range(10)
     row_data = ...   # get row_data as list
     np_array = np.vstack((np_array, np.array(row_data)))

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

How to check undefined in Typescript

Late to the story but I think some details are overlooked?

if you use

if (uemail !== undefined) {
  //some function
}

You are, technically, comparing variable uemail with variable undefined and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefined may actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

To be correct one would have to declare a constant of type undefined for example:

const _undefined: undefined

and then test by:

if (uemail === _undefined) {
  //some function
}

This test will return true as uemail now equals both value & type of _undefined as _undefined is now properly declared to be of type undefined.

Another way would be

if (typeof(uemail) === 'undefined') {
  //some function
}

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.

Copy and Paste a set range in the next empty row

The reason the code isn't working is because lastrow is measured from whatever sheet is currently active, and "A:A500" (or other number) is not a valid range reference.

Private Sub CommandButton1_Click()
    Dim lastrow As Long

    lastrow = Sheets("Summary Info").Range("A65536").End(xlUp).Row    ' or + 1
    Range("A3:E3").Copy Destination:=Sheets("Summary Info").Range("A" & lastrow)
End Sub

How to scroll to the bottom of a UITableView on the iPhone before the view appears

The accepted answer didn't work with my table (thousands of rows, dynamic loading) but the code below works:

- (void)scrollToBottom:(id)sender {
    if ([self.sections count] > 0) {
        NSInteger idx = [self.sections count] - 1;
        CGRect sectionRect = [self.tableView rectForSection:idx];
        sectionRect.size.height = self.tableView.frame.size.height;
        [self.tableView scrollRectToVisible:sectionRect animated:NO];
    }
}

Java equivalent of unsigned long long?

No, there isn't. The designers of Java are on record as saying they didn't like unsigned ints. Use a BigInteger instead. See this question for details.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

Here's a fix to invoketheshell's buggy code (which currently appears as the accepted answer):

def performance_measure(y_actual, y_hat):
    TP = 0
    FP = 0
    TN = 0
    FN = 0

    for i in range(len(y_hat)): 
        if y_actual[i] == y_hat[i]==1:
            TP += 1
        if y_hat[i] == 1 and y_actual[i] == 0:
            FP += 1
        if y_hat[i] == y_actual[i] == 0:
            TN +=1
        if y_hat[i] == 0 and y_actual[i] == 1:
            FN +=1

    return(TP, FP, TN, FN)

Height equal to dynamic width (CSS fluid layout)

Simple and neet : use vw units for a responsive height/width according to the viewport width.

vw : 1/100th of the width of the viewport. (Source MDN)

DEMO

HTML:

<div></div>

CSS for a 1:1 aspect ratio:

div{
    width:80vw;
    height:80vw; /* same as width */
}

Table to calculate height according to the desired aspect ratio and width of element.

   aspect ratio  |  multiply width by
    -----------------------------------
         1:1      |         1
         1:3      |         3
         4:3      |        0.75
        16:9      |       0.5625

This technique allows you to :

  • insert any content inside the element without using position:absolute;
  • no unecessary HTML markup (only one element)
  • adapt the elements aspect ratio according to the height of the viewport using vh units
  • you can make a responsive square or other aspect ratio that alway fits in viewport according to the height and width of the viewport (see this answer : Responsive square according to width and height of viewport or this demo)

These units are supported by IE9+ see canIuse for more info

jQuery validation: change default error message

Another possible solution is to loop over the fields, adding the same error message to each field.

$('.required').each(function(index) {
  $(this).rules("add", {
    messages: {
      required: "Custom error message."
   }
  });
});

PHP how to get the base domain/url?

/**
 * Suppose, you are browsing in your localhost 
 * http://localhost/myproject/index.php?id=8
 */
function getBaseUrl() 
{
    // output: /myproject/index.php
    $currentPath = $_SERVER['PHP_SELF']; 

    // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
    $pathInfo = pathinfo($currentPath); 

    // output: localhost
    $hostName = $_SERVER['HTTP_HOST']; 

    // output: http://
    $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';

    // return: http://localhost/myproject/
    return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
}

Passing parameters to a JDBC PreparedStatement

You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:

statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);

There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

Your response must return some sort of Response object. You can't just return an object.

So change it to something like:

return Response::json($promotion);

or my favorite using the helper function:

return response()->json($promotion);

If returning a response doesn't work it may be some sort of encoding issue. See this article: The Response content must be a string or object implementing __toString(), \"boolean\" given."

Check if a specific tab page is selected (active)

For whatever reason the above would not work for me. This is what did:

if (tabControl.SelectedTab.Name == "tabName" )
{
     .. do stuff
}

where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

I have tried the following command and they work well.

bzip2 -t file.bz2
gunzip -t file.gz

However, we can found these two command are time-consuming. Maybe we need some more quick way to determine the intact of the compress files.

How to Detect Browser Window /Tab Close Event?

to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :

_x000D_
_x000D_
<script>_x000D_
    function endSession() {_x000D_
         // Browser or Broswer tab is closed_x000D_
         // Write code here_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Convert number to varchar in SQL with formatting

Here's an alternative following the last answer

declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')

This will work on any number and by varying the length of the str() function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.

How to remove an app with active device admin enabled on Android?

You could also create a new DevicePolicyManager and then use removeAdmin(adminReceiver) from an onClickListener of a button in your app

//set the onClickListener here
{
   ComponentName devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
   DevicePolicyManager dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
   dpm.removeActiveAdmin(devAdminReceiver);
}

And then you can uninstall

Is there a way to link someone to a YouTube Video in HD 1080p quality?

No, this is not working. And it's not just for you, in case you spent the last hour trying to find an answer for having your embeded videos open in HD.

Question: Oh, but how do you know this is not working anymore and there is no other alternative to make embeded videos open in a different quality?

Answer: Just went to Google's official documentation regarding Youtube's player parameters and there is not a single parameter that allows you to change its quality.

Also, hd=1 doesn't work either. More info here.

Apparently Youtube analyses the width and height of the user's window (or iframe) and automatically sets the quality based on this.

UPDATE:

As of 10 of April of 2018 it still doesn't work (see my comment on the accepted answer for more details).

What I can see from comments is that it MAY work sometimes, but some others it doesn't. The accepted answer states that "it measures the network speed and the screen and player sizes". So, by that, we can understand that I CANNOT force HD as YouTube will still do whatever it wants in case of low network speed/screen resolution. From my perspective everyone saying it works just have false positives on their hands and on the occasion they tested it worked for some random reason not related to the vq parameter. If it was a valid parameter, Google would document it somewhere, and vq isn't documented anywhere.

How to get the latest record in each group using GROUP BY?

Try this

SELECT * FROM messages where id in (SELECT max(id) FROM messages GROUP BY from_id ) order by id desc

Singletons vs. Application Context in Android?

Consider both at the same time:

  • having singleton objects as static instances inside the classes.
  • having a common class (Context) that returns the singleton instances for all the singelton objects in your application, which has the advantage that the method names in Context will be meaningful for example: context.getLoggedinUser() instead of User.getInstance().

Furthermore, I suggest that you expand your Context to include not only access to singleton objects but some functionalities that need to be accessed globally, like for example: context.logOffUser(), context.readSavedData(), etc. Probably renaming the Context to Facade would make sense then.

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

How to detect my browser version and operating system using JavaScript?

I'm sad to say: We are sh*t out of luck on this one.

I'd like to refer you to the author of WhichBrowser: Everybody lies.

Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:

hims056's fiddle

Hariharan's fiddle

or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.

Take your code, for example:

<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>

Chrome says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

IE says:

Browser CodeName: Mozilla

Browser Name: Netscape

Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

Cookies Enabled: true

Platform: Win32

User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko

At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET or Media Center :P), and then match it against the rv: at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

In PrimeFaces 3.0, that style get applied on the generated inner <div> of the table cell, not on the <td> as you (and I) would expect. The following example should work out for you:

<p:dataTable styleClass="myTable">

with

.myTable td:nth-child(1) {
    width: 20px;
}

In PrimeFaces 3.5 and above, it should work exactly the way you coded and expected.

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

Docker and securing passwords

My approach seems to work, but is probably naive. Tell me why it is wrong.

ARGs set during docker build are exposed by the history subcommand, so no go there. However, when running a container, environment variables given in the run command are available to the container, but are not part of the image.

So, in the Dockerfile, do setup that does not involve secret data. Set a CMD of something like /root/finish.sh. In the run command, use environmental variables to send secret data into the container. finish.sh uses the variables essentially to finish build tasks.

To make managing the secret data easier, put it into a file that is loaded by docker run with the --env-file switch. Of course, keep the file secret. .gitignore and such.

For me, finish.sh runs a Python program. It checks to make sure it hasn't run before, then finishes the setup (e.g., copies the database name into Django's settings.py).

Class method differences in Python: bound, unbound and static

method_two won't work because you're defining a member function but not telling it what the function is a member of. If you execute the last line you'll get:

>>> a_test.method_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)

If you're defining member functions for a class the first argument must always be 'self'.

Real-world examples of recursion

The last real world example I have is a pretty frivolous, but it demonstrates how recursion 'just fits' sometimes.

I was using the Chain of Responsibility pattern,so a Handler object either handles a request itself, or delegates it down the chain. It's useful to log the construction of the chain:

public String getChainString() {
    cs = this.getClass().toString();
    if(this.delegate != null) {
        cs += "->" + delegate.getChainString();
    }
    return cs;
}

You could argue that this isn't the purest recursion, because although the method calls "itself", it is in a different instance each time it's called.

Failed to open/create the internal network Vagrant on Windows10

You can try disabling the "VirtualBox NDIS6 Bridged Networking Driver" on all but your actual physical network adapter(s) before attempting to create the VirtualBox host-only adapter again.

See this answer.

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

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes

Source: w3.org


So, this CSS works, although styling the color is not possible in every browser:

option:checked { color: red; }

An example of this in action, hiding the currently selected item from the drop down list.

_x000D_
_x000D_
option:checked { display:none; }
_x000D_
<select>_x000D_
    <option>A</option>_x000D_
    <option>B</option>_x000D_
    <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


To style the currently selected option in the closed dropdown as well, you could try reversing the logic:

select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */

Should import statements always be at the top of a module?

Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.

Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.

If you have to load heavyweight modules at unexpected times, it probably makes more sense to load them dynamically with the __import__ function, and be sure to catch ImportError exceptions, and handle them in a reasonable manner.

SQL Server 2008- Get table constraints

I used the following query to retrieve the information of constraints in the SQL Server 2012, and works perfectly. I hope it would be useful for you.

SELECT 
    tab.name AS [Table]
    ,tab.id AS [Table Id]
    ,constr.name AS [Constraint Name]
    ,constr.xtype AS [Constraint Type]
    ,CASE constr.xtype WHEN 'PK' THEN 'Primary Key' WHEN 'UQ' THEN 'Unique' ELSE '' END AS [Constraint Name]
    ,i.index_id AS [Index ID]
    ,ic.column_id AS [Column ID]
    ,clmns.name AS [Column Name]
    ,clmns.max_length AS [Column Max Length]
    ,clmns.precision AS [Column Precision]
    ,CASE WHEN clmns.is_nullable = 0 THEN 'NO' ELSE 'YES' END AS [Column Nullable]
    ,CASE WHEN clmns.is_identity = 0 THEN 'NO' ELSE 'YES' END AS [Column IS IDENTITY]
FROM SysObjects AS tab
INNER JOIN SysObjects AS constr ON(constr.parent_obj = tab.id AND constr.type = 'K')
INNER JOIN sys.indexes AS i ON( (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tab.id) AND i.name = constr.name )
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) 
                                    AND (ic.index_id=CAST(i.index_id AS int) 
                                    AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE tab.xtype = 'U'
ORDER BY tab.name

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I killed myself for 3 days trying every possible combination to try to get this to work -- I finally tried making a DSA key instead and it worked.

Try DSA instead of RSA if it's not working for you.

(I'm using Ubuntu 11.10, ruby 1.8.7, heroku 2.15.1)

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

Converting of Uri to String

STRING TO URI.

Uri uri=Uri.parse("YourString");

URI TO STRING

Uri uri;
String andro=uri.toString();

happy coding :)

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

How to delete a column from a table in MySQL

To delete column use this,

ALTER TABLE `tbl_Country` DROP `your_col`

Remove a specific string from an array of string

Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.

Filter Linq EXCEPT on properties

public static class ExceptByProperty
{
    public static List<T> ExceptBYProperty<T, TProperty>(this List<T> list, List<T> list2, Expression<Func<T, TProperty>> propertyLambda)
    {
        Type type = typeof(T);

        MemberExpression member = propertyLambda.Body as MemberExpression;

        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));
        Func<T, TProperty> func = propertyLambda.Compile();
        var ids = list2.Select<T, TProperty>(x => func(x)).ToArray();
        return list.Where(i => !ids.Contains(((TProperty)propInfo.GetValue(i, null)))).ToList();
    }
}

public class testClass
{
    public int ID { get; set; }
    public string Name { get; set; }
}

For Test this:

        List<testClass> a = new List<testClass>();
        List<testClass> b = new List<testClass>();
        a.Add(new testClass() { ID = 1 });
        a.Add(new testClass() { ID = 2 });
        a.Add(new testClass() { ID = 3 });
        a.Add(new testClass() { ID = 4 });
        a.Add(new testClass() { ID = 5 });

        b.Add(new testClass() { ID = 3 });
        b.Add(new testClass() { ID = 5 });
        a.Select<testClass, int>(x => x.ID);

        var items = a.ExceptBYProperty(b, u => u.ID);

How do you disable browser Autocomplete on web form field / input tag?

There are many answers but most of them are hacks or some kind of workaround.

There are three cases here.

Case I: If this is your standard login form. Turning it off by any means is probably bad. Think hard if you really need to do it. Users are accustomed to browsers remembering and storing the passwords. You shouldn't change that standard behaviour in most cases.

In case you still want to do it, see Case III

Case II: When this is not your regular login form but name or id attribute of inputs is not "like" email, login, username, user_name, password.

Use

<input type="text" name="yoda" autocomplete="off">

Case III: When this is not your regular login form but name or id attribute of inputs is "like" email, login, username, user_name, password.

For example: login, abc_login, password, some_password, password_field.

All browsers come with password management features offering to remember them OR suggesting stronger passwords. That's how they do it.

However, suppose you are an admin of a site and can create users and set their passwords. In this case you wouldn't want browsers to offer these features.

In such cases, autocomplete="off" will not work. Use autocomplete="new-password"

<input type="text" name="yoda" autocomplete="new-password">

Helpful Link:

  1. https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion