Programs & Examples On #Jquery ui autocomplete

Autocomplete widget from jQuery-ui which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

How to use source: function()... and AJAX in JQuery UI autocomplete

$("#subject_name").autocomplete({
  source: function(request, response) {
    $.ajax({
      url: "api/listBasicsubject",
      dataType: "json",
      type: "post",
      data: {
        search: request.term
      },
      success: function(data) {

        if (!data.length) {
          var result = [{
            label: 'Subject not found',
            value: response.term
          }];
          response(result);
        } else {
          //response(data.data);
          response($.map(data.data, function(item) {
            return {
              label: item.subject_name,
              value: item.subject_id
            }
          }));
        }
      }
    });
  },
  change: function(event, ui) {
    if (ui.item == null) {
      $("#subject_name").val("");
      $("#subject_code").val("");
      $("#subject_name").focus();
    }
  },

  minLength: 0,
  classes: {
    "ui-autocomplete": "auto_compl-cat"
  },

  focus: function(event, ui) {
    event.preventDefault();
    // $("#subject_name").val(ui.item.label);

    $("#subject_name").val(ui.item.label);

  },

  select: function(event, ui) {
    if (ui.item.label == "Subject not found") {

      $("#subject_name").val('');
      $("#subject_code").val('');
      event.preventDefault();
      return false;
    }
    //console.log( "Selected: " + ui.item.label + " aka " + ui.item.value);
    $("#subject_name").val(ui.item.label);
    $("#subject_code").val(ui.item.value);
    return false;
  }
});

Styling JQuery UI Autocomplete

Bootstrap styling for jQuery UI Autocomplete

    .ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;   
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
}

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
}

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
}

jQuery UI autocomplete with item and id

I do not think that there is need to hack around the value and label properties, use hidden input fields or to suppress events. You may add your own custom property to each Autocomplete object and then read that property value later.

Here is an example.

$(#yourInputTextBox).autocomplete({
    source: function(request, response) {
        // Do something with request.term (what was keyed in by the user).
        // It could be an AJAX call or some search from local data.
        // To keep this part short, I will do some search from local data.
        // Let's assume we get some results immediately, where
        // results is an array containing objects with some id and name.
        var results = yourSearchClass.search(request.term);

        // Populate the array that will be passed to the response callback.
        var autocompleteObjects = [];
        for (var i = 0; i < results.length; i++) {
            var object = {
                // Used by jQuery Autocomplete to show
                // autocomplete suggestions as well as
                // the text in yourInputTextBox upon selection.
                // Assign them to a value that you want the user to see.
                value: results[i].name;
                label: results[i].name;

                // Put our own custom id here.
                // If you want to, you can even put the result object.
                id: results[i].id;
            };

            autocompleteObjects.push(object);
        }

        // Invoke the response callback.
        response(autocompleteObjects);
    },
    select: function(event, ui) {
        // Retrieve your id here and do something with it.
        console.log(ui.item.id);
    }
});

The documentation mentions you have to pass in an array of objects with label and value properties. However, you may certainly pass in objects with more than these two properties and read them later.

Here is the relevant part I am referring to.

Array: An array can be used for local data. There are two supported formats: An array of strings: [ "Choice1", "Choice2" ] An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ] The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

How to get jQuery dropdown value onchange event

Try like this

 $("#drop").change(function () {
        var end = this.value;
        var firstDropVal = $('#pick').val();
    });

jQuery UI autocomplete with JSON

I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}

Limit results in jQuery UI Autocomplete

You can set the minlength option to some big value or you can do it by css like this,

.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}

twitter bootstrap typeahead ajax example

One can make calls by using Bootstrap. The current version does not has any source update issues Trouble updating Bootstrap's typeahead data-source with post response , i.e. the source of bootstrap once updated can be again modified.

Please refer to below for an example:

jQuery('#help').typeahead({
    source : function(query, process) {
        jQuery.ajax({
            url : "urltobefetched",
            type : 'GET',
            data : {
                "query" : query
            },
            dataType : 'json',
            success : function(json) {
                process(json);
            }
        });
    },
    minLength : 1,
});

Difference between null and empty ("") Java String

The empty string is distinct from a null reference in that in an object-oriented programming language a null reference to a string type doesn't point to a string object and will cause an error were one to try to perform any operation on it. The empty string is still a string upon which string operations may be attempted.

From the wikipedia article on empty string.

Issue pushing new code in Github

I use the Branches options, and then right click on the "remote/origin" folder and then click on "delete branches from remote", see the image below:

the image

creating array without declaring the size - java

Once the array size is fixed while running the program ,it's size can't be changed further. So better go for ArrayList while dealing with dynamic arrays.

git pull remote branch cannot find remote ref

check your branch on your repo. maybe someone delete it.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

Make sure that the folder name does not contain .c extension. When I removed the .c extension in my folder name it worked automatically.

python plot normal distribution

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()

gass distro, mean is 0 variance 1

Why can't Python import Image from PIL?

I had the same error. Here was my workflow. I first installed PIL (not Pillow) using

pip install --no-index -f https://dist.plone.org/thirdparty/ -U PIL

Then I found Pillow and installed it using

pip install Pillow

What fixed my issues was uninstalling both and reinstalling Pillow

pip uninstall PIL
pip uninstall Pillow
pip install Pillow

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

The code below works for me:

private pricecheckEntities _context = new pricecheckEntities();

...

private void resetpcheckedtoFalse()
{
    try
    {
        foreach (var product in _context.products)
        {
            product.pchecked = false;
            _context.products.Attach(product);
            _context.Entry(product).State = EntityState.Modified;
        }
        _context.SaveChanges();
    }
    catch (Exception extofException)
    {
        MessageBox.Show(extofException.ToString());

    }
    productsDataGrid.Items.Refresh();
}

Setting timezone in Python

Be aware that running

import os
os.system("tzutil /s \"Central Standard Time\"");

will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:

>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()

which will only set in the current environment time (in Unix only)

Difference between / and /* in servlet mapping url pattern

Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.

false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:

<servlet-mapping>
    <servlet-name>viewServlet</servlet-name>
    <url-pattern>/perfix/*</url-pattern>
</servlet-mapping>

the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething

@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
    @RequestMapping(value = "/doSomething", method = RequestMethod.GET) 
    @ResponseBody
    public String doSomething(HttpServletRequest request) {
        ....
    }
}

It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base @RequestingMapping.

How to install older version of node.js on Windows?

Go here and find the version you want to install and then download the correct msi file and run the installer. You cannot install node by running this command, also the error you receive is stating that npm is not on your path which suggests machine doesn't currently have node installed on it

Is there a way to represent a directory tree in a Github README.md?

Not directly, no. You'd have to hand create it and put it in yourself. Assuming you are using a *nix box locally and are using utf, then tree will generate it nicely (I believe that is what generated the example you used above).

Assuming you mean the readme.md as the documentation target, then I think the only way you could automate it would be a git pre-commit hook that ran tree and embedded it into your readme file. You'd want to do a diff to make sure you only updated the readme if the output changed.

Otoh if you are maintaining seperate docs via github pages, then what you could do, is switch to using jekyll (or another generator) locally and pushing the static pages yourself. Then you could potentially implement the changes you want either as a plugin / shell script* / manual changes (if they won't vary much), or use the same method as above.

*If you integrate it into a commit hook, you can avoid adding any extra steps to changing your pages.

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

This problem happens when you install the JDK by _uncompressing_ it instead of _executing_ it.

By example:

unzip jdk-6u45-linux-x64.bin  (wrong)

sh ./jdk-6u45-linux-x64.bin   (right)

In the first scenario, the runtime libraries, as rt.jar, don't get automatically uncompresessed (thus, you can find the rt.pack files, etc. instead of the .jar ones).

Java compiler level does not match the version of the installed Java project facet

If using eclipse,

Under.settings click on org.eclipse.wst.common.project.facet.core.xml

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <installed facet="java" version="1.7"/>
</faceted-project>

Change the version to the correct version.

Mysql - delete from multiple tables with one query

Normally you can't DELETE from multiple tables at once, unless you'll use JOINs as shown in other answers.

However if all yours tables starts with certain name, then this query will generate query which would do that task:

SELECT CONCAT('DELETE FROM ', GROUP_CONCAT(TABLE_NAME SEPARATOR ' WHERE user_id=123;DELETE FROM ') , 'FROM table1;' ) AS statement FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%'

then pipe it (in shell) into mysql command for execution.

For example it'll generate something like:

DELETE FROM table1 WHERE user_id=123;
DELETE FROM table2 WHERE user_id=123;
DELETE FROM table3 WHERE user_id=123;

More shell oriented example would be:

echo "SHOW TABLES LIKE 'table%'" | mysql | tail -n +2 | xargs -L1 -I% echo "DELETE FROM % WHERE user_id=123;" | mysql -v

If you want to use only MySQL for that, you can think of more advanced query, such as this:

SET @TABLES = (SELECT GROUP_CONCAT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%');
PREPARE drop_statement FROM 'DELETE FROM @tables';
EXECUTE drop_statement USING @TABLES;
DEALLOCATE PREPARE drop_statement;

The above example is based on: MySQL – Delete/Drop all tables with specific prefix.

RegEx - Match Numbers of Variable Length

You can specify how many times you want the previous item to match by using {min,max}.

{[0-9]{1,3}:[0-9]{1,3}}

Also, you can use \d for digits instead of [0-9] for most regex flavors:

{\d{1,3}:\d{1,3}}

You may also want to consider escaping the outer { and }, just to make it clear that they are not part of a repetition definition.

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

PHP if not statements

I think this is the best and easiest way to do it:

if (!(isset($action) && ($action == "add" || $action == "delete")))

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

How do I auto size a UIScrollView to fit its content

The size depends on the content loaded inside of it, and the clipping options. If its a textview, then it also depends on the wrapping, how many lines of text, the font size, and so on and on. Nearly impossible for you to compute yourself. The good news is, it is computed after the view is loaded and in the viewWillAppear. Before that, it's all unknown and and content size will be the same as frame size. But, in the viewWillAppear method and after (such as the viewDidAppear) the content size will be the actual.

How to get child process from parent process

I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.

function getcpid() {
    cpids=`pgrep -P $1|xargs`
#    echo "cpids=$cpids"
    for cpid in $cpids;
    do
        echo "$cpid"
        getcpid $cpid
    done
}

getcpid $1

How do you run a script on login in *nix?

The script ~/.bash_profile is run on login.

Should operator<< be implemented as a friend or as a member function?

If possible, as non-member and non-friend functions.

As described by Herb Sutter and Scott Meyers, prefer non-friend non-member functions to member functions, to help increase encapsulation.

In some cases, like C++ streams, you won't have the choice and must use non-member functions.

But still, it does not mean you have to make these functions friends of your classes: These functions can still acess your class through your class accessors. If you succeed in writting those functions this way, then you won.

About operator << and >> prototypes

I believe the examples you gave in your question are wrong. For example;

ostream & operator<<(ostream &os) {
    return os << paragraph;
}

I can't even start to think how this method could work in a stream.

Here are the two ways to implement the << and >> operators.

Let's say you want to use a stream-like object of type T.

And that you want to extract/insert from/into T the relevant data of your object of type Paragraph.

Generic operator << and >> function prototypes

The first being as functions:

// T << Paragraph
T & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// T >> Paragraph
T & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)
{
   // do the extraction of p_oParagraph
   return p_oInputStream ;
}

Generic operator << and >> method prototypes

The second being as methods:

// T << Paragraph
T & T::operator << (const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return *this ;
}

// T >> Paragraph
T & T::operator >> (const Paragraph & p_oParagraph)
{
   // do the extraction of p_oParagraph
   return *this ;
}

Note that to use this notation, you must extend T's class declaration. For STL objects, this is not possible (you are not supposed to modify them...).

And what if T is a C++ stream?

Here are the prototypes of the same << and >> operators for C++ streams.

For generic basic_istream and basic_ostream

Note that is case of streams, as you can't modify the C++ stream, you must implement the functions. Which means something like:

// OUTPUT << Paragraph
template <typename charT, typename traits>
std::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// INPUT >> Paragraph
template <typename charT, typename traits>
std::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)
{
   // do the extract of p_oParagraph
   return p_oInputStream ;
}

For char istream and ostream

The following code will work only for char-based streams.

// OUTPUT << A
std::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// INPUT >> A
std::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)
{
   // do the extract of p_oParagraph
   return p_oInputStream ;
}

Rhys Ulerich commented about the fact the char-based code is but a "specialization" of the generic code above it. Of course, Rhys is right: I don't recommend the use of the char-based example. It is only given here because it's simpler to read. As it is only viable if you only work with char-based streams, you should avoid it on platforms where wchar_t code is common (i.e. on Windows).

Hope this will help.

python and sys.argv

In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:

sys.stderr.write("Usage: " + sys.argv[0])

or

sys.stderr.write("Usage: %s" % sys.argv[0])

Also, you may want to consider using the following syntax of print (for Python earlier than 3.x):

print >>sys.stderr, "Usage:", sys.argv[0]

Using print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.

In Python 3.x, you would use the print function:

print("Usage:", sys.argv[0], file=sys.stderr)

Finally, in Python 2.6 and later you can use .format:

print >>sys.stderr, "Usage: {0}".format(sys.argv[0])

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Setting up a cron job in Windows

If you don't want to use Scheduled Tasks you can use the Windows Subsystem for Linux which will allow you to use cron jobs like on Linux.

To make sure cron is actually running you can type service cron status from within the Linux terminal. If it isn't currently running then type service cron start and you should be good to go.

MVC4 input field placeholder

The correct solution to get the Prompt value in a non-templated control context is:

@Html.TextBoxFor(model => model.Email, 
    new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)

This will also not double-escape the watermark text.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How to update primary key

When you find it necessary to update a primary key value as well as all matching foreign keys, then the entire design needs to be fixed.

It is tricky to cascade all the necessary foreign keys changes. It is a best practice to never update the primary key, and if you find it necessary, you should use a Surrogate Primary Key, which is a key not derived from application data. As a result its value is unrelated to the business logic and never needs to change (and should be invisible to the end user). You can then update and display some other column.

for example:

BadUserTable
UserID     varchar(20) primary key --user last name
other columns...

when you create many tables that have a FK to UserID, to track everything that the user has worked on, but that user then gets married and wants a ID to match their new last name, you are out of luck.

GoodUserTable
UserID    int identity(1,1) primary key
UserLogin varchar(20) 
other columns....

you now FK the Surrogate Primary Key to all the other tables, and display UserLogin when necessary, allow them to login using that value, and when they need to change it, you change it in one column of one row only.

Disable future dates in jQuery UI Datepicker

$(function() { $("#datepicker").datepicker({  maxDate: '0'}); });

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

Show current assembly instruction in GDB

Setting the following option:

set  disassemble-next-line on
show disassemble-next-line

Will give you results that look like this:

(gdb) stepi
0x000002ce in ResetISR () at startup_gcc.c:245
245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
=> 0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
   0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0
(gdb) stepi
0x000002d0  245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
   0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
=> 0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0

How do you divide each element in a list by an int?

>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]

What is the simplest C# function to parse a JSON string into an object?

I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.

Return a `struct` from a function in C

As far as I can remember, the first versions of C only allowed to return a value that could fit into a processor register, which means that you could only return a pointer to a struct. The same restriction applied to function arguments.

More recent versions allow to pass around larger data objects like structs. I think this feature was already common during the eighties or early nineties.

Arrays, however, can still be passed and returned only as pointers.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Inserting data into a MySQL table using VB.NET

You need to open the connection first:

 SQLConnection.Open();

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

For SQL server 2000:

     INSERT INTO t1 (ID, NAME)
      SELECT valueid, valuename
      WHERE  NOT EXISTS
               (SELECT 0
                FROM   t1 as t2
                WHERE  t2.ID = valueid AND t2.name = valuename)

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

LINQ query on a DataTable

Using LINQ to manipulate data in DataSet/DataTable

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

YYYY-MM-DD format date in shell script

You can do something like this:

$ date +'%Y-%m-%d'

Angular2 disable button

 <button [disabled]="this.model.IsConnected() == false"
              [ngClass]="setStyles()"
              class="action-button action-button-selected button-send"
              (click)= "this.Send()">
          SEND
        </button>

.ts code

setStyles() 
{
    let styles = {

    'action-button-disabled': this.model.IsConnected() == false  
  };
  return styles;
}

How do I get a file's directory using the File object?

File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
    dir=filePath.getAbsolutePath();
}
else
{
    dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}

How do you make an element "flash" in jQuery

After 5 years... (And no additional plugin needed)

This one "pulses" it to the color you want (e.g. white) by putting a div background color behind it, and then fading the object out and in again.

HTML object (e.g. button):

<div style="background: #fff;">
  <input type="submit" class="element" value="Whatever" />
</div>

jQuery (vanilla, no other plugins):

$('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); });

element - class name

first number in fadeTo() - milliseconds for the transition

second number in fadeTo() - opacity of the object after fade/unfade

You may check this out in the lower right corner of this webpage: https://single.majlovesreg.one/v1/

Edit (willsteel) no duplicated selector by using $(this) and tweaked values to acutally perform a flash (as the OP requested).

How to find a value in an array and remove it by using PHP array functions?

<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>

How to go from Blob to ArrayBuffer

The Response API consumes a (immutable) Blob from which the data can be retrieved in several ways. The OP only asked for ArrayBuffer, and here's a demonstration of it.

var blob = GetABlobSomehow();

// NOTE: you will need to wrap this up in a async block first.
/* Use the await keyword to wait for the Promise to resolve */
await new Response(blob).arrayBuffer();   //=> <ArrayBuffer>

alternatively you could use this:

new Response(blob).arrayBuffer()
.then(/* <function> */);

Note: This API isn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)

PHP read and write JSON from file

You need to make the decode function return an array by passing in the true parameter.

json_decode(file_get_contents($file),true);

How to search a Git repository by commit message?

first to list the commits use

git log --oneline

then find the SHA of the commit (Message), then I used

 git log --stat 8zad24d

(8zad24d) is the SHA assosiated with the commit you are intrested in (the first couples sha example (8zad24d) you can select 4 char or 6 or 8 or the entire sha) to find the right info

Pandas How to filter a Series

Another way is to first convert to a DataFrame and use the query method (assuming you have numexpr installed):

import pandas as pd

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

s = pd.Series(test)
s.to_frame(name='x').query("x != 1")

How to delete parent element using jQuery

You could also use this:

$(this)[0].parentNode.remove();

How to decode jwt token in javascript without using a library?

you can use pure javascript atob() function to decode token into a string:

atob(token.split('.')[1]);

or parse directly it into a json object:

JSON.parse(atob(token.split('.')[1]));

read about atob() and btoa() built-in javascript functions Base64 encoding and decoding - Web APIs | MDN.

Laravel 5 route not defined, while it is?

In my case the solution was simple:

I have defined the route at the very start of the route.php file.

After moving the named route to the bottom, my app finally saw it. It means that somehow the route was defined too early.

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

See the documentation for the print function: print()

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

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

ListenForClients is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main. When two instances of the TcpListener try to listen on the same port, you get that error.

Python sys.argv lists and indexes

So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?

import sys
def main():
  if len(sys.argv) >= 2:
    fname = sys.argv[1]
    lname = sys.argv[2]
  else:
    name = 'World'
  print 'Hello', fname, lname
if __name__ == '__main__':
  main()

Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?

Edit 2: Got it figured out:

import sys
def main():
  if len(sys.argv) >= 2:
    name = sys.argv[1] + " " + sys.argv[2]
  else:
    name = 'World'
  print 'Hello', name
if __name__ == '__main__':
  main()

Function to Calculate a CRC16 Checksum

There are several different varieties of CRC-16. See wiki page.

Every of those will return different results from the same input.

So you must carefully select correct one for your program.

How to set base url for rest in spring boot?

I might be a bit late, BUT... I believe it is the best solution. Set it up in your application.yml (or analogical config file):

spring:
    data:
        rest:
            basePath: /api

As I can remember that's it - all of your repositories will be exposed beneath this URI.

Truncating a table in a stored procedure

You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.

You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.

1) Execute immediate

2) DBMS_SQL package

3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);

Hope this answers your question with explanation.

how to access master page control from content page

It Works

To find master page controls on Child page

Label lbl_UserName = this.Master.FindControl("lbl_UserName") as Label;                    
lbl_UserName.Text = txtUsr.Text;

How do I get current scope dom-element in AngularJS controller?

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

It worked only after removing the eclipse folder and all related folders like .p2, .eclipse (in my case they are at different location where I have saved eclipse installer) etc. and after re-downloading the eclipse, it worked.

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 is that the requested resource has been assigned a new permanent URI and any future references to this resource should be done using one of the returned URIs.

302 is that the requested resource resides temporarily under a different URI.

Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.

This response is only cachable if indicated by a Cache-Control or Expires header field.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Let’s assume, your old app.module.ts may look similar to this :

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }

Now import FormsModule in your app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }

http://jsconfig.com/solution-cant-bind-ngmodel-since-isnt-known-property-input/

adding 30 minutes to datetime php/mysql

Dominc has the right idea, but put the calculation on the other side of the expression.

SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)

This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.

Calculating how many days are between two dates in DB2?

Wouldn't it just be:

SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';

That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.

If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.

Reading numbers from a text file into an array in C

Loop with %c to read the stream character by character instead of %d.

In C - check if a char exists in a char array

The less well-known but extremely useful (and standard since C89 — meaning 'forever') functions in the C library provide the information in a single call. Actually, there are multiple functions — an embarrassment of riches. The relevant ones for this are:

7.21.5.3 The strcspn function

Synopsis

#include <string.h>
size_t strcspn(const char *s1, const char *s2);

Description

The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.

Returns

The strcspn function returns the length of the segment.

7.21.5.4 The strpbrk function

Synopsis

#include <string.h>
char *strpbrk(const char *s1, const char *s2);

Description

The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.

Returns

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.

The question asks about 'for each char in string ... if it is in list of invalid chars'.

With these functions, you can write:

size_t len = strlen(test);
size_t spn = strcspn(test, "invald");

if (spn != len) { ...there's a problem... }

Or:

if (strpbrk(test, "invald") != 0) { ...there's a problem... }

Which is better depends on what else you want to do. There is also the related strspn() function which is sometimes useful (whitelist instead of blacklist).

How to append text to a text file in C++?

You could also do it like this

#include <fstream>

int main(){   
std::ofstream ost {outputfile, std::ios_base::app};

ost.open(outputfile);
ost << "something you want to add to your outputfile";
ost.close();
return 0;
}

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

Import Google Play Services library in Android Studio

After hours of having the same problem, notice that if your jar is on the libs folder will cause problem once you set it upon the "Dependencies ", so i just comment the file tree dependencies and keep the one using

dependencies

//compile fileTree(dir: 'libs', include: ['*.jar'])  <-------- commented one 
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.android.support:appcompat-v7:22.2.1'

and the problem was solved.

How can I de-install a Perl module installed via `cpan`?

As a general rule, there is not a specific 'uninstall' mechanism that comes with CPAN modules. But you might try make uninstall in the original directory the module unpacked into (this is often under /root/.cpan or ~/.cpan), as some packages do contain this directive in their install script. (However, since you've installed modules into a local (non-root) library directory, you also have the option of blowing away this entire directory and reinstalling everything else that you want to keep.)

A lot of the time you can simply get away with removing the A/B.pm file (for the A::B module) from your perllib -- that will at least render the module unusable. Most modules also contain a list of files to be installed (called a "manifest"), so if you can find that, you'll know which files you can delete.

However, none of these approaches will address any modules that were installed as dependencies. There's no good (automated) way of knowing if something else is dependent on that module, so you'll have to uninstall it manually as well once you're sure.

The difficulty in uninstalling modules is one reason why many Perl developers are moving towards using a revision control system to keep track of installations -- e.g. see the article by brian d foy as a supplement to his upcoming book that discusses using git for package management.

Replace line break characters with <br /> in ASP.NET MVC Razor view

Applying the DRY principle to Omar's solution, here's an HTML Helper extension:

using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace System.Web.Mvc.Html {
    public static class MyHtmlHelpers {
        public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
            return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
        }
    }
}

Usage (with improved regex):

@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.


My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

How to create permanent PowerShell Aliases

This is a little bit fancy... but it works:

Step 1: Create a Powershell Profile:

FILE: install_profile.ps1
# THIS SCRIPT BLOWS AWAY YOUR DEFAULT POWERSHELL PROFILE SCRIPT
#   AND INSTALLS A POINTER TO A GLOBAL POWERSHELL PROFILE

$ErrorActionPreference = "Stop"

function print ([string]$msg)
{
    Write-Host -ForegroundColor Green $msg
}

print ""

# User's Powershell Profile
$psdir  = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"

print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null

# this is your auto-generated powershell profile to be installed
$content = @(
    "",
    ". ~/Documents/tools/profile.ps1",
    ""
)

print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)

print ""

# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted

Step 2: then in tools ~/Documents/tools/profile.ps1:

function Do-ActualThing {
    # do actual thing
}

Set-Alias MyAlias Do-ActualThing

Step 3:

$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1

Build and Install unsigned apk on device without the development server?

After you follow the first response, you can run your app using

react-native run-android --variant=debug

And your app will run without need for the packager

Difference between jQuery’s .hide() and setting CSS to display: none

See there is no difference if you use basic hide method. But jquery provides various hide method which give effects to the element. Refer below link for detailed explanation: Effects for Hide in Jquery

SQL Error: ORA-01861: literal does not match format string 01861

ORA-01861: literal does not match format string

This happens because you have tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.

You can overcome this issue by carrying out following alteration.

TO_DATE('1989-12-09','YYYY-MM-DD')

As a general rule, if you are using the TO_DATE function, TO_TIMESTAMP function, TO_CHAR function, and similar functions, make sure that the literal that you provide matches the format string that you've specified

Django values_list vs values

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

How to run crontab job every week on Sunday

10 * * * Sun

Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12 
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday. 

How to get name of dataframe column in pyspark?

I found the answer is very very simple...

// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();

The variable "theNameOftheCol" is "colName"

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

C fopen vs open

Unless you're part of the 0.1% of applications where using open is an actual performance benefit, there really is no good reason not to use fopen. As far as fdopen is concerned, if you aren't playing with file descriptors, you don't need that call.

Stick with fopen and its family of methods (fwrite, fread, fprintf, et al) and you'll be very satisfied. Just as importantly, other programmers will be satisfied with your code.

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

The justify-self and justify-items properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content property.

Reference: Box alignment in CSS Grid Layout

port 8080 is already in use and no process using 8080 has been listed

PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn which will show the process names (but must be run under an administrator account).

Having said that, I would expect the find "8080" to find it...

Another thing to do is just visit http://localhost:8080 - on that port, chances are it's a web server of some description.

How to assign a value to a TensorFlow variable?

You can also assign a new value to a tf.Variable without adding an operation to the graph: tf.Variable.load(value, session). This function can also save you adding placeholders when assigning a value from outside the graph and it is useful in case the graph is finalized.

import tensorflow as tf
x = tf.Variable(0)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(x))  # Prints 0.
x.load(1, sess)
print(sess.run(x))  # Prints 1.

Update: This is depricated in TF2 as eager execution is default and graphs are no longer exposed in the user-facing API.

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

You can first read the whole content of file into a String.

FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
    fileInputStream=new FileInputStream(filename);
    int i;
    while((i=fileInputStream.read())!=-1)
    {
        stringBuffer.append((char)i);
    }
    data = stringBuffer.toString();
}
catch(Exception e){
        LoggerUtil.printStackTrace(e);
}
finally{
    if(fileInputStream!=null){  
        fileInputStream.close();
    }
}

Now You will have the whole content into String ( data variable ).

JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);

After that you can use jsonArray as you want.

jquery json to string?

I use

$.param(jsonObj)

which gets me the string.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Phone Number Validation MVC

Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:

$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

Convert HTML + CSS to PDF

Darryl Hein's mention above of TCPDF is likely a great idea. Nicola Asuni's code is pretty handy and powerful. The only killer is if you ever plan on merging PDF files with your generated PDF it doesn't have those features. You would have to create the PDF and then merge it using something like PDFTK by Sid Steward (www.pdflabs.com/tools/pdftk-the-pdf-toolkit/).

Delete all rows in a table based on another table

Referencing MSDN T-SQL DELETE (Example D):

DELETE FROM Table1
FROM Tabel1 t1
   INNER JOIN Table2 t2 on t1.ID = t2.ID

How to grey out a button?

The most easy solution is to set color filter to the background image of a button as I saw here

You can do as follow:

if ('need to set button disable')
    button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
else
    button.getBackground().setColorFilter(null);

Hope I helped someone...

How do I get the path and name of the file that is currently executing?

I wrote a function which take into account eclipse debugger and unittest. It return the folder of the first script you launch. You can optionally specify the __file__ var, but the main thing is that you don't have to share this variable across all your calling hierarchy.

Maybe you can handle others stack particular cases I didn't see, but for me it's ok.

import inspect, os
def getRootDirectory(_file_=None):
    """
    Get the directory of the root execution file
    Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing
    For eclipse user with unittest or debugger, the function search for the correct folder in the stack
    You can pass __file__ (with 4 underscores) if you want the caller directory
    """
    # If we don't have the __file__ :
    if _file_ is None:
        # We get the last :
        rootFile = inspect.stack()[-1][1]
        folder = os.path.abspath(rootFile)
        # If we use unittest :
        if ("/pysrc" in folder) & ("org.python.pydev" in folder):
            previous = None
            # We search from left to right the case.py :
            for el in inspect.stack():
                currentFile = os.path.abspath(el[1])
                if ("unittest/case.py" in currentFile) | ("org.python.pydev" in currentFile):
                    break
                previous = currentFile
            folder = previous
        # We return the folder :
        return os.path.dirname(folder)
    else:
        # We return the folder according to specified __file__ :
        return os.path.dirname(os.path.realpath(_file_))

Reload parent window from child window

parent.location.reload();

This should work.

Code formatting shortcuts in Android Studio for Operation Systems

It's Ctrl + Alt + L for Windows. For a complete list of keyboard shortcuts please take a look at the user manual: https://developer.android.com/studio/intro/keyboard-shortcuts.html

how do you increase the height of an html textbox

If you want multiple lines consider this:

<textarea rows="2"></textarea>

Specify rows as needed.

How to find NSDocumentDirectory in Swift?

Xcode 8.2.1 • Swift 3.0.2

let documentDirectoryURL =  try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

Xcode 7.1.1 • Swift 2.1

let documentDirectoryURL =  try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

Create excel ranges using column numbers in vba?

Here is a condensed replacement for the ConvertToLetter function that in theory should work for all possible positive integers. For example, 1412 produces "BBH" as the result.

Public Function ColumnNumToStr(ColNum As Integer) As String
Dim Value As Integer
Dim Rtn As String
    Rtn = ""
    Value = ColNum - 1
    While Value > 25
        Rtn = Chr(65 + (Value Mod 26)) & Rtn
        Value = Fix(Value / 26) - 1
    Wend
    Rtn = Chr(65 + Value) & Rtn
    ColumnNumToStr = Rtn
End Function

How to test an Oracle Stored Procedure with RefCursor return type?

Something like

create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
  open p_rc
   for select 1 col1
         from dual;
end;
/

variable rc refcursor;
exec my_proc( :rc );
print rc;

will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.

Setting environment variables for accessing in PHP when using Apache

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in "/etc/apache2/envvars" location.

Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go

Activity has leaked window that was originally added

Dismiss the dialog when activity destroy

@Override
protected void onDestroy()
{
    super.onDestroy();
    if (pDialog!=null && pDialog.isShowing()){
        pDialog.dismiss();
    }
}

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

Use cell's color as condition in if statement (function)

Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).

In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".

inject bean reference into a Quartz job in Spring?

A solution from Hary https://stackoverflow.com/a/37797575/4252764 works very well. It's simpler, doesn't need so many special factory beans, and support multiple triggers and jobs. Would just add that Quartz job can be made to be generic, with specific jobs implemented as regular Spring beans.

public interface BeanJob {
  void executeBeanJob();
}

public class GenericJob implements Job {

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap dataMap = context.getMergedJobDataMap();
    ((BeanJob)dataMap.get("beanJob")).executeBeanJob();    
  }

}

@Component
public class RealJob implements BeanJob {
  private SomeService service;

  @Autowired
  public RealJob(SomeService service) {
    this.service = service;
  }

  @Override
  public void executeBeanJob() {
      //do do job with service
  }

}

flow 2 columns of text automatically with CSS

Below I have created both a static and dynamic approach at columnizing paragraphs. The code is pretty much self-documented.

Foreward

Below, you will find the following methods for creating columns:

  1. Static (2-columns)
  2. Dynamic w/ JavaScript + CSS (n-columns)
  3. Dynamic w/ JavaScript + CSS3 (n-columns)

Static (2-columns)

This is a simple 2 column layout. Based on Glennular's 1st answer.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    var columns = 2;_x000D_
    var size = $("#data > p").size();_x000D_
    var half = size / columns;_x000D_
    $(".col50 > p").each(function (index) {_x000D_
        if (index >= half) {_x000D_
            $(this).appendTo(".col50:eq(1)");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
.col50 {_x000D_
    display: inline-block;_x000D_
    vertical-align: top;_x000D_
    width: 48.2%;_x000D_
    margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="data" class="col50">_x000D_
    <!-- data Start -->_x000D_
    <p>This is paragraph 1. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 2. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 3. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 4. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 5. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 6. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 7. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 8. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 9. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 10. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 11. Lorem ipsum ...</p>_x000D_
    <!-- data End-->_x000D_
</div>_x000D_
<div class="col50"></div>
_x000D_
_x000D_
_x000D_

Dynamic w/ JavaScript + CSS (n-columns)

With this approach, I essentially detect if the block needs to be converted to columns. The format is col-{n}. n is the number of columns you want to create.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    splitByColumns('col-', 4);_x000D_
});_x000D_
_x000D_
function splitByColumns(prefix, gap) {_x000D_
    $('[class^="' + prefix + '"]').each(function(index, el) {_x000D_
        var me = $(this);_x000D_
        var count = me.attr("class").split(' ').filter(function(className) {_x000D_
            return className.indexOf(prefix) === 0;_x000D_
        }).reduce(function(result, value) {_x000D_
            return Math.max(parseInt(value.replace(prefix, '')), result);_x000D_
        }, 0);_x000D_
        var paragraphs = me.find('p').get();_x000D_
        me.empty(); // We now have a copy of the children, we can clear the element._x000D_
        var size = paragraphs.length;_x000D_
        var percent = 1 / count;_x000D_
        var width = (percent * 100 - (gap / count || percent)).toFixed(2) + '%';_x000D_
        var limit = Math.round(size / count);_x000D_
        var incr = 0;_x000D_
        var gutter = gap / 2 + 'px';_x000D_
        for (var col = 0; col < count; col++) {_x000D_
            var colDiv = $('<div>').addClass('col').css({ width: width });_x000D_
            var css = {};_x000D_
            if (col > -1 && col < count -1) css['margin-right'] = gutter;_x000D_
            if (col > 0 && col < count)     css['margin-left'] = gutter;_x000D_
            colDiv.css(css);_x000D_
            for (var line = 0; line < limit && incr < size; line++) {_x000D_
                colDiv.append(paragraphs[incr++]);_x000D_
            }_x000D_
            me.append(colDiv);_x000D_
        }_x000D_
    });_x000D_
}
_x000D_
.col {_x000D_
    display: inline-block;_x000D_
    vertical-align: top;_x000D_
    margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="data" class="col-6">_x000D_
    <!-- data Start -->_x000D_
    <p>This is paragraph 1. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 2. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 3. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 4. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 5. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 6. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 7. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 8. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 9. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 10. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 11. Lorem ipsum ...</p>_x000D_
    <!-- data End-->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dynamic w/ JavaScript + CSS3 (n-columns)

This has been derived from on Glennular's 2nd answer. It uses the column-count and column-gap CSS3 rules.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    splitByColumns('col-', '4px');_x000D_
});_x000D_
_x000D_
function splitByColumns(prefix, gap) {_x000D_
    var vendors = [ '', '-moz', '-webkit-' ];_x000D_
    var getColumnCount = function(el) {_x000D_
        return el.attr("class").split(' ').filter(function(className) {_x000D_
            return className.indexOf(prefix) === 0;_x000D_
        }).reduce(function(result, value) {_x000D_
            return Math.max(parseInt(value.replace(prefix, '')), result);_x000D_
        }, 0);_x000D_
    }_x000D_
    $('[class^="' + prefix + '"]').each(function(index, el) {_x000D_
        var me = $(this);_x000D_
        var count = getColumnCount(me);_x000D_
        var css = {};_x000D_
        $.each(vendors, function(idx, vendor) {_x000D_
            css[vendor + 'column-count'] = count;_x000D_
            css[vendor + 'column-gap'] = gap;_x000D_
        });_x000D_
        me.css(css);_x000D_
    });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="data" class="col-3">_x000D_
    <!-- data Start -->_x000D_
    <p>This is paragraph 1. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 2. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 3. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 4. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 5. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 6. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 7. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 8. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 9. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 10. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 11. Lorem ipsum ...</p>_x000D_
    <!-- data End-->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

How to get the last day of the month?

How about more simply:

import datetime
now = datetime.datetime.now()
datetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)

How can I install a previous version of Python 3 in macOS using homebrew?

To solve this with homebrew, you can temporarily backdate homebrew-core and set the HOMEBREW_NO_AUTO_UPDATE variable to hold it in place:

cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python

I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.

You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract command:

brew extract python tap_owner/tap_name --version=3.6.5

Getting String Value from Json Object Android

If you can use JSONObject library, you could just

    JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
    String result = ja.getJSONObject(0).getString("NeededString");

How can I debug a Perl script?

If using an interactive debugger is OK for you, you can try perldebug.

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

Left align and right align within div in Bootstrap

We can achieve by Bootstrap 4 Flexbox:

<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>

d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%

Example: JSFiddle

Can't install any packages in Node.js using "npm install"

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

System.MissingMethodException: Method not found?

In my case it was a folder with olders DLLs of the same name that those wich were referenced in my .csproj file although the path was explicitly given they were somehow included therefore the several versions of the same DLLs were in conflict.

PHP, display image with Header()

Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.

This isn't something you should rely on however. It's recommended you always use the correct MIME content.

Copy entire contents of a directory to another using php

// using exec

function rCopy($directory, $destination)
{

    $command = sprintf('cp -r %s/* %s', $directory, $destination);

    exec($command);

}

How do I add a user when I'm using Alpine as a base image?

The commands are adduser and addgroup.

Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker
ENV UID=12345
ENV GID=23456

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "$(pwd)" \
    --ingroup "$USER" \
    --no-create-home \
    --uid "$UID" \
    "$USER"

Note the following:

  • --disabled-password prevents prompt for a password
  • --gecos "" circumvents the prompt for "Full Name" etc. on Debian-based systems
  • --home "$(pwd)" sets the user's home to the WORKDIR. You may not want this.
  • --no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        --home DIR           Home directory
        --gecos GECOS        GECOS field
        --shell SHELL        Login shell
        --ingroup GRP        Group (by name)
        --system             Create a system user
        --disabled-password  Don't assign a password
        --no-create-home     Don't create home directory
        --uid UID            User id

One thing to note is that if --ingroup isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

        --gid GID  Group id
        --system   Create a system group

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

My entrypoint helper script can be found on GitHub.

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.

(At the time of writing I don't have documentation for my script. It's still on the todo list!!)

Using cURL with a username and password?

Use the -u flag to include a username, and curl will prompt for a password:

curl -u username http://example.com

You can also include the password in the command, but then your password will be visible in bash history:

curl -u username:password http://example.com

Pycharm: run only part of my Python file

You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:

enter image description here

After you've enabled, set a break-point to where you want it to:

enter image description here

After you're done setting the break-point:

enter image description here

Once that has been completed:

enter image description here

How to get a single value from FormGroup

You can get value like this

this.form.controls['your form control name'].value

Facebook page automatic "like" URL (for QR Code)

Have you tried using the fb:// protocol?

To have them like your page when they scan the qr code, it goes like this:

fb://page/(pageID)/addfan

If you need to get the pageID, replace "www" with "graph" in the Facebook url when you visit your page in a desktop browser and it will display the ID and other data.

Not only does this add them automatically, but it opens up the page in the FB app instead of the mobile browser.

As far as legality, I would assume as long as you put something like "Scan to like our page", you're in the clear. They know what they're getting into.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

If, after adding lines:

<property
name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>

hibernate.connection.zeroDateTimeBehavior=convertToNull

<connection-property
name="zeroDateTimeBehavior">convertToNull</connection-property>

continues to be an error:

Illegal DATETIME, DATE, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00 00:00:00' or '0000-00-00').

find lines:

1) resultSet.getTime("time"); // time = 00:00:00
2) resultSet.getTimestamp("timestamp"); // timestamp = 00000000000000
3) resultSet.getDate("date"); // date = 0000-00-00 00:00:00

replace with the following lines, respectively:

1) Time.valueOf(resultSet.getString("time"));
2) Timestamp.valueOf(resultSet.getString("timestamp"));
3) Date.valueOf(resultSet.getString("date"));

Do I cast the result of malloc?

The best thing to do when programming in C whenever it is possible:

  1. Make your program compile through a C compiler with all warnings turned on -Wall and fix all errors and warnings
  2. Make sure there are no variables declared as auto
  3. Then compile it using a C++ compiler with -Wall and -std=c++11. Fix all errors and warnings.
  4. Now compile using the C compiler again. Your program should now compile without any warning and contain fewer bugs.

This procedure lets you take advantage of C++ strict type checking, thus reducing the number of bugs. In particular, this procedure forces you to include stdlib.hor you will get

malloc was not declared within this scope

and also forces you to cast the result of malloc or you will get

invalid conversion from void* to T*

or what ever your target type is.

The only benefits from writing in C instead of C++ I can find are

  1. C has a well specified ABI
  2. C++ may generate more code [exceptions, RTTI, templates, runtime polymorphism]

Notice that the second cons should in the ideal case disappear when using the subset common to C together with the static polymorphic feature.

For those that finds C++ strict rules inconvenient, we can use the C++11 feature with inferred type

auto memblock=static_cast<T*>(malloc(n*sizeof(T))); //Mult may overflow...

Get Android Phone Model programmatically

Changed Idolons code a little. This will capitalize words when getting the device model.

public static String getDeviceName() {
    final String manufacturer = Build.MANUFACTURER, model = Build.MODEL;
    return model.startsWith(manufacturer) ? capitalizePhrase(model) : capitalizePhrase(manufacturer) + " " + model;
}

private static String capitalizePhrase(String s) {
    if (s == null || s.length() == 0)
        return s;
    else {
        StringBuilder phrase = new StringBuilder();
        boolean next = true;
        for (char c : s.toCharArray()) {
            if (next && Character.isLetter(c) || Character.isWhitespace(c))
                next = Character.isWhitespace(c = Character.toUpperCase(c));
            phrase.append(c);
        }
        return phrase.toString();
    }
}

How do you access the matched groups in a JavaScript regular expression?

As @cms said in ECMAScript (ECMA-262) you can use matchAll. It return an iterator and by putting it in [... ] (spread operator) it converts to an array.(this regex extract urls of file names)

_x000D_
_x000D_
let text = `<a href="http://myhost.com/myfile_01.mp4">File1</a> <a href="http://myhost.com/myfile_02.mp4">File2</a>`;

let fileUrls = [...text.matchAll(/href="(http\:\/\/[^"]+\.\w{3})\"/g)].map(r => r[1]);

console.log(fileUrls);
_x000D_
_x000D_
_x000D_

Find in Files: Search all code in Team Foundation Server

This search for a file link explains how to find a file. I did have to muck around with the advice to make it work.

  1. cd "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE"
  2. tf dir "$/*.sql" /recursive /server:http://mytfsserver:8080/tfs

In the case of the cd command, I performed the cd command because I was looking for the tf.exe file. It was easier to just start from that directory verses adding the whole path. Now that I understand how to make this work, I'd use the absolute path in quotes.

In case of the tf search, I started at the root of the server with $/ and I searched for all files that ended with sql i.e. *.sql. If you don't want to start at the root, then use "$/myproject/*.sql" instead.

Oh! This does not solve the search in file part of the question but my Google search brought me here to find files among other links.

I need an unordered list without any bullets

 <div class="custom-control custom-checkbox left">
    <ul class="list-unstyled">
        <li>
         <label class="btn btn-secondary text-left" style="width:100%;text-align:left;padding:2px;">
           <input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title
         </label>
        </li>
     </ul>
</div>

WAMP/XAMPP is responding very slow over localhost

I've just fixed such an issue on my laptop running windows 10. Suddenly wamp became super slow - a request to load a page was taking 2 minutes.

After trying numerous things, what it turned out to fix the problem was disabling windows defender. All worked like a charm after that.

p.s. I'd suggest you add your apache root dir to the exceptions list and not actually disable defender completely.

How to redraw DataTable with new data

Another alternative is

dtColumns[index].visible = false/true;

To show or hide any column.

Does GPS require Internet?

GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.

Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).

How do I display local image in markdown?

I've had problems with inserting images in R Markdown. If I do the entire URL: C:/Users/Me/Desktop/Project/images/image.png it tends to work. Otherwise, I have to put the markdown in either the same directory as the image or in an ancestor directory to it. It appears that the declared knitting directory is ignored when referencing images.

AngularJS - ng-if check string empty value

If by "empty" you mean undefined, it is the way ng-expressions are interpreted. Then, you could use :

<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>

QtCreator: No valid kits found

For QT 5.* if you face error at Kits, like No Valid Kits Found, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.

Just go to your OS Terminal and write sudo apt-get install qt5-default, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.

Update Jenkins from a war file

I use this groovy script to download new war file

import java.util.concurrent.atomic.AtomicInteger

class ThreadHelper{
    static done = false;
    static starttime = System.currentTimeMillis()
    static synchronized printx (message) {    printf ("%5s seconds: %20s",(System.currentTimeMillis()-starttime)/1000.0 , message); println("") }
    def download(address)
    {
    def filename = new File(System.getenv()['CI_HOME'] + '/' + address.tokenize("/")[-1])
    println(filename.getCanonicalPath())
    def file = new FileOutputStream(filename)
    def out = new BufferedOutputStream(file)
    out << new URL(address).openStream()
    out.close()
    done=true;
    }

}

println("executing from ... "+ new File(".").getCanonicalPath())

def counter = new AtomicInteger();
    th = Thread.start {
    while(!ThreadHelper.done) {
    sleep 1000
    counter.incrementAndGet()
    print '.'
    }
}

th2 = Thread.start { new ThreadHelper().download("http://mirrors.jenkins-ci.org/war/latest/jenkins.war") }
th.join()
th2.join()

ThreadHelper.printx('done')

And another script shutsdown tomcat - copies the war and restarts it

We host it on windows 2008 and tomcat, I use sc query, sc config, sc stop, sc start to manage windows services

    set warname=jenkins

if '%name%' == 'trak' set warname=trak

pushd .
if '%name%'=='' goto badname
if '%warname%'=='' goto badname

if '%ci_home%'=='' goto badcihome

REM =====================================================
REM stop windows service
sc stop %name%

REM sleep for 5 seconds see http:\\stackoverflow.com\questions\1672338\how-to-sleep-for-5-seconds-in-windowss-command-prompt-or-dos
ping 1.1.1.1 -n 1 -w 3000 > nul

rem replace forward slash with backward slash
set tomcat_dir=%ci_home:/=\%\instances\tomcat7-%name%

REM Create sub directory called bak-yymmdd-hhmmss
REM where yymmdd-hhmmss is a date-time stamp like 120601-142907

set hh=%time:~0,2%

REM Since there is no leading zero for times before 10 am, have to put in
REM a zero when this is run before 10 am.

if "%time:~0,1%"==" " set hh=0%hh:~1,1%

set yymmdd_hhmmss=%date:~12,2%%date:~4,2%%date:~7,2%-%hh%%time:~3,2%%time:~6,2%

set backupdir=bak-%yymmdd_hhmmss%

REM =====================================================
md %tomcat_dir%\logs\%backupdir%

cd %tomcat_dir%\logs

dir bak*
echo "nothing-to-log" >> force.log

REM move command will fail if there is nothing to move hence the force log statement above

call move *.* %backupdir%

REM =====================================================
rmdir %tomcat_dir%\webapps\%name% /q/s

echo f|xcopy %ci_home%\%warname%.war %tomcat_dir%\webapps\%name%.war /y

REM TODO===== something about jenkins plugins

REM =====================================================
cd "%tomcat_dir%\bin"
call catalina version

echo =====================================================
echo ====== removing %name%
call service remove %name%

echo =====================================================
echo ====== installing %name%
call service install %name%

echo on

REM setting service to start automatically, note that space before the word auto IS REQUIRED
sc config %name% start= auto

REM =====================================================
sc start %name%

popd

exit 0

goto done

:badname
echo 'name required - this will be used as windows service name as well'
pause
exit 1

:badcihome
echo 'CI home env var required - ci_home'
pause
exit 1

:done

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I was just having the same issue...

To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:

Manifest-Version: 1.0
... 
Bundle-ClassPath: lib/gson-1.6.jar,
 .
...

Or if you want to include all jar's in the folder:

Bundle-ClassPath: lib/

You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"

How do I check/uncheck all checkboxes with a button using jQuery?

Agreed with Richard Garside's short answer, but instead of using prop() in $(this).prop("checked") you can use native JS checked property of checkbox like,

_x000D_
_x000D_
$("#checkAll").change(function () {_x000D_
    $("input:checkbox").prop('checked', this.checked);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
    _x000D_
    <fieldset>_x000D_
        <legend>Loads of checkboxes</legend>_x000D_
        <p><label><input type="checkbox" /> Option 1</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 2</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 3</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 4</label></p>_x000D_
    </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Swift presentViewController

Solved the black screen by adding a navigation controller and setting the second view controller as rootVC.

let vc = ViewController()       
var navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Request-scoped beans can be autowired with the request object.

private @Autowired HttpServletRequest request;

Where is Android Studio layout preview?

In case you want docked mode, (it still visible while editing the xml file), and you, by mistake, clicked and unmarked docked mode. In order to get it back you have focus on preview and click Window > Active Tool Window > Docked Mode.

Read response headers from API response - Angular 5 + TypeScript

You should use the new HttpClient. You can find more information here.

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

How to grab substring before a specified character jQuery or JavaScript

You could use regex as this will give you the string if it matches the requirements. The code would be something like:

const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);

console.log(matchedResult[0]); // This will give you 1345 albany street.

So to break the code down. [1-9][0-9]* basically means the first number cannot be a zero and has to be a number between 1-9 and the next number can be any number from 0-9 and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [a-zA-Z] basically matches all capital letters to small letters and has to occur one or more times and this is repeated.

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

Split list into smaller lists (split in half)

While the answers above are more or less correct, you may run into trouble if the size of your array isn't divisible by 2, as the result of a / 2, a being odd, is a float in python 3.0, and in earlier version if you specify from __future__ import division at the beginning of your script. You are in any case better off going for integer division, i.e. a // 2, in order to get "forward" compatibility of your code.

PHP code to get selected text of a combo box

You can achive this with creating new array:

<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");

if (isset ($_POST['search'])) {
  $maker = mysql_real_escape_string($_POST['Make']);
  echo $array[$maker];
}
?>

bash: npm: command not found?

Just go into npm page and follow the instructions.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Since you are running it in servlet, you need to have the jar accessible by the servlet container. You either include the connector as part of your application war or put it as part of the servlet container's extended library and datasource management stuff, if it has one. The second part is totally depend on the container that you have.

opening html from google drive

Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)

-- use Get Link to get URL with id=... substring -- put uc instead of open in URL

jQuery: how do I animate a div rotation?

As of now you still can't animate rotations with jQuery, but you can with CSS3 animations, then simply add and remove the class with jQuery to make the animation occur.

JSFiddle demo


HTML

<img src="http://puu.sh/csDxF/2246d616d8.png" width="30" height="30"/>

CSS3

img {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
transition-duration:0.4s;
}

.rotate {
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
transition-duration:0.4s;
}

jQuery

$(document).ready(function() {
    $("img").mouseenter(function() {
        $(this).addClass("rotate");
    });
    $("img").mouseleave(function() {
        $(this).removeClass("rotate");
    });
});

T-SQL substring - separating first and last name

You could do this if firstname and surname are separated by space:

SELECT SUBSTRING(FirstAndSurnameCol, 0, CHARINDEX(' ', FirstAndSurnameCol)) Firstname,
SUBSTRING(FirstAndSurnameCol, CHARINDEX(' ', FirstAndSurnameCol)+1, LEN(FirstAndSurnameCol)) Surname FROM ...

iCheck check if checkbox is checked

this works for me... try it

_x000D_
_x000D_
// Check #x_x000D_
$( "#x" ).prop( "checked", true );_x000D_
 _x000D_
// Uncheck #x_x000D_
$( "#x" ).prop( "checked", false );
_x000D_
_x000D_
_x000D_

ImportError: No module named mysql.connector using Python2

Depending on your python version and how you installed it, it is possible that mysql connector isn't installed, you can install it with pip

To install mysql connector:

pip install mysql-connector-python

Print PDF directly from JavaScript

I used this function to download pdf stream from server.

function printPdf(url) {
        var iframe = document.createElement('iframe');
        // iframe.id = 'pdfIframe'
        iframe.className='pdfIframe'
        document.body.appendChild(iframe);
        iframe.style.display = 'none';
        iframe.onload = function () {
            setTimeout(function () {
                iframe.focus();
                iframe.contentWindow.print();
                URL.revokeObjectURL(url)
                // document.body.removeChild(iframe)
            }, 1);
        };
        iframe.src = url;
        // URL.revokeObjectURL(url)
    }

remove objects from array by object property

You can remove an item by one of its properties without using any 3rd party libs like this:

var removeIndex = array.map(item => item.id)
                       .indexOf("abc");

~removeIndex && array.splice(removeIndex, 1);

What is the difference between Serialization and Marshaling?

Think of them as synonyms, both have a producer that sends stuff over to a consumer... In the end fields of instances are written into a byte stream and the other end foes the reverse ands up with the same instances.

NB - java RMI also contains support for transporting classes that are missing from the recipient...

Is there an auto increment in sqlite?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.

The keyword AUTOINCREMENT can be used with INTEGER field only. Syntax:

The basic usage of AUTOINCREMENT keyword is as follows:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

For Example See Below: Consider COMPANY table to be created as follows:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now, insert following records into table TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

Now Select the record

SELECT *FROM TB_COMPANY_INFO
ID      NAME            AGE     ADDRESS             SALARY
1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

You may also consider stratified division into training and testing set. Startified division also generates training and testing set randomly but in such a way that original class proportions are preserved. This makes training and testing sets better reflect the properties of the original dataset.

import numpy as np  

def get_train_test_inds(y,train_proportion=0.7):
    '''Generates indices, making random stratified split into training set and testing sets
    with proportions train_proportion and (1-train_proportion) of initial sample.
    y is any iterable indicating classes of each observation in the sample.
    Initial proportions of classes inside training and 
    testing sets are preserved (stratified sampling).
    '''

    y=np.array(y)
    train_inds = np.zeros(len(y),dtype=bool)
    test_inds = np.zeros(len(y),dtype=bool)
    values = np.unique(y)
    for value in values:
        value_inds = np.nonzero(y==value)[0]
        np.random.shuffle(value_inds)
        n = int(train_proportion*len(value_inds))

        train_inds[value_inds[:n]]=True
        test_inds[value_inds[n:]]=True

    return train_inds,test_inds

y = np.array([1,1,2,2,3,3])
train_inds,test_inds = get_train_test_inds(y,train_proportion=0.5)
print y[train_inds]
print y[test_inds]

This code outputs:

[1 2 3]
[1 2 3]

What is the difference between WCF and WPF?

The quick answer is: Windows Presentation Foundation (WPF) is basically a way of displaying user interface. (see this)

Windows Communication Foundation (WCF) is a framework for creating service oriented applications. (see this)

As for which one you should use, it depends on your requirement. Usually an application written in WPF, ASP.NET..etc called the WCF service to do some processing at the server-side and the service returns the result to the application that called it.

How to disable Home and other system buttons in Android?

Just a guess, but I think with the SYSTEM_ALERT_WINDOW permission (displayed as "Draw over other apps", see here) it could be possible: display your app as a fullscreen, system alert type window. This way it will hide any other apps, even the homescreen so if you press Home, it won't really be disabled, just without any visible effect.

MX Player has this permission declared, and Facebook Messenger has it too for displaying "chat heads" over anything - so it might be the solution.

Update (added from my comments): Next, use SYSTEM_UI_FLAG_HIDE_NAVIGATION in conjunction with capturing touch events/using OnSystemUiVisibilityChangeListener to override the default behaviour (navbar appearing on touch). Also, since you said exit immersive gesture does not work, you could try setting SYSTEM_UI_FLAG_IMMERSIVE_STICKY too (with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION).

How to initialize log4j properly?

You can set up the log level by using setLevel().

The levels are useful to easily set the kind of informations you want the program to display.

For example:

Logger.getRootLogger().setLevel(Level.WARN); //will not show debug messages

The set of possible levels are:

TRACE,

DEBUG,

INFO,

WARN,

ERROR and

FATAL

According to Logging Services manual

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

POSTing JsonObject With HttpClient From Web API

With the new version of HttpClient and without the WebApi package it would be:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;

Or if you want it async:

var result = await client.PostAsync(url, content);

How to scale an Image in ImageView to keep the aspect ratio

If image quality decreases in: use

android:adjustViewBounds="true"

instead of

android:adjustViewBounds="true"
android:scaleType="fitXY"

Shell script to check if file exists

Wildcards aren't expanded inside quoted strings. And when wildcard is expanded, it's returned unchanged if there are no matches, it doesn't expand into an empty string. Try:

output="$(ls home/edward/bank1/fiche/Test* 2>/dev/null)"
if [ -n "$output" ]
then echo "Found one"
else echo "Found none"
fi

If the wildcard expanded to filenames, ls will list them on stdout; otherwise it will print an error on stderr, and nothing on stdout. The contents of stdout are assigned to output.

if [ -n "$output" ] tests whether $output contains anything.

Another way to write this would be:

if [ $(ls home/edward/bank1/fiche/Test* 2>/dev/null | wc -l) -gt 0 ]

How do you handle a "cannot instantiate abstract class" error in C++?

Provide implementation for any pure virtual functions that the class has.

Oracle - What TNS Names file am I using?

By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin directory on UNIX operating systems and in the ORACLE_HOME\network\admin directory on Windows operating systems. tnsnames.ora can also be stored the following locations:

The directory specified by the TNS_ADMIN environment variable (or registry value)

On UNIX operating systems, the global configuration directory. For example, on the Solaris Operating System, this directory is /var/opt/oracle

If you have multiple ORACLE_HOMES, be aware of which one you are using, as the location of the tnsnames.ora file can vary from one ORACLE_HOME to the next.

For the person who mentioned the TWO_TASK environment variable, that is used to set a default database service name to connect to (which could be a database on another server). The service name you set TWO_TASK to is then looked up in the tnsnames.ora file when you connect.

Correct way to read a text file into a buffer in C?

Have you considered mmap()? You can read from the file directly as if it were already in memory.

http://beej.us/guide/bgipc/output/html/multipage/mmap.html

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

Unable to start MySQL server

Go to MySQL installer and click Reconfigure (don't change any existing settings). This should start the server and you'll be off.

proper way to logout from a session in PHP

Personally, I do the following:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

When should iteritems() be used instead of items()?

You cannot use items instead iteritems in all places in Python. For example, the following code:

class C:
  def __init__(self, a):
    self.a = a
  def __iter__(self):
    return self.a.iteritems()

>>> c = C(dict(a=1, b=2, c=3))
>>> [v for v in c]
[('a', 1), ('c', 3), ('b', 2)]

will break if you use items:

class D:
  def __init__(self, a):
    self.a = a
  def __iter__(self):
    return self.a.items()

>>> d = D(dict(a=1, b=2, c=3))
>>> [v for v in d]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __iter__ returned non-iterator of type 'list'

The same is true for viewitems, which is available in Python 3.

Also, since items returns a copy of the dictionary’s list of (key, value) pairs, it is less efficient, unless you want to create a copy anyway.

In Python 2, it is best to use iteritems for iteration. The 2to3 tool can replace it with items if you ever decide to upgrade to Python 3.

UnicodeDecodeError when reading CSV file in Pandas with Python

In my case, a file has USC-2 LE BOM encoding, according to Notepad++. It is encoding="utf_16_le" for python.

Hope, it helps to find an answer a bit faster for someone.

Eclipse returns error message "Java was started but returned exit code = 1"

This work for me in eclipse js and eclipse php:

 -vm
 C:/java/jdk-11.0.1/bin/javaw.exe
 --launcher.appendVmargs
 -vmargs

Cannot create PoolableConnectionFactory

This is the actual cause of the problem:

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

You have a database communication link problem. Make sure that your application have network access to your database (and the firewall isn't blocking ports to your database).

java.lang.OutOfMemoryError: Java heap space

To avoid that exception, if you are using JUnit and Spring try adding this in every test class:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

HTML character codes for this ? or this ?

Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

Just a supplement here.

The following question is that what if I want more subplots in the figure?

As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2) to set a group of subplots with grid(2,2) in one figure object.

Then as we know, the fig, ax = plt.subplots() returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) firstly.

ValueError: not enough values to unpack (expected 4, got 2)

It raises a error, but no worry, because we now see that plt.subplots() actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.

So let's try this again:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

and check the type:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.

Hope this would be helpful for you.

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Loose coupling means that the degree of dependency between two components is very low.
Example: GSM SIM

Tight coupling means that the degree of dependency between two components is very high.
Example: CDMA Mobile

How do I check if a string contains another string in Swift?

Check if it contains 'Hello'

let s = "Hello World"

if s.rangeOfString("Hello") != nil {
    print("Yes it contains 'Hello'")
}

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

Pointers in JavaScript?

Late answer but I have come across a way of passing primitive values by reference by means of closures. It is rather complicated to create a pointer, but it works.

function ptr(get, set) {
    return { get: get, set: set };
}

function helloWorld(namePtr) {
    console.log(namePtr.get());
    namePtr.set('jack');
    console.log(namePtr.get())
}

var myName = 'joe';
var myNamePtr = ptr(
    function () { return myName; },
    function (value) { myName = value; }
);

helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack

In ES6, the code can be shortened to use lambda expressions:

var myName = 'joe';
var myNamePtr = ptr(=> myName, v => myName = v);

helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack

How can I convert a string with dot and comma into a float in Python

Just remove the , with replace():

float("123,456.908".replace(',',''))

How to hide a TemplateField column in a GridView

For Each dcfColumn As DataControlField In gvGridview.Columns
    If dcfColumn.HeaderText = "ColumnHeaderText" Then
        dcfColumn.Visible = false                    
    End If
Next

How to trigger a file download when clicking an HTML button or JavaScript

You can do it with "trick" with invisible iframe. When you set "src" to it, browser reacts as if you would click a link with the same "href". As opposite to solution with form, it enables you to embed additional logic, for example activating download after timeout, when some conditions are met etc.

It is also very silient, there's no blinking new window/tab like when using window.open.

HTML:

<iframe id="invisible" style="display:none;"></iframe>

Javascript:

function download() {
    var iframe = document.getElementById('invisible');
    iframe.src = "file.doc";
}

Using getline() with file input in C++

you should do as:

getline(name, sizeofname, '\n');
strtok(name, " ");

This will give you the "joht" in name then to get next token,

temp = strtok(NULL, " ");

temp will get "smith" in it. then you should use string concatination to append the temp at end of name. as:

strcat(name, temp);

(you may also append space first, to obtain a space in between).

Maven plugins can not be found in IntelliJ

None of the other answers worked for me. The solution that worked for me was to download the missing artifact manually via cmd:

mvn dependency:get -DrepoUrl=http://repo.maven.apache.org/maven2/ -Dartifact=ro.isdc.wro4j:wro4j-maven-plugin:1.8.0

After this change need to let know the Idea about new available artifacts. This can be done in "Settings > Maven > Repositories", select there your "Local" and simply click "Update".

Edit: the -DrepoUrl seems to be deprecated. -DremoteRepositories should be used instead. Source: Apache Maven Dependency Plugin – dependency:get.

How to read a text file from server using JavaScript?

I used Rafid's suggestion of using AJAX.

This worked for me:

var url = "http://www.example.com/file.json";

var jsonFile = new XMLHttpRequest();
    jsonFile.open("GET",url,true);
    jsonFile.send();

    jsonFile.onreadystatechange = function() {
        if (jsonFile.readyState== 4 && jsonFile.status == 200) {
            document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
        }
     }

I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2 so credit to them for everything.

I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)

Hope this helps!

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,

ggplot(data_country)+
  geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")

How to extract duration time from ffmpeg output?

If you want to retrieve the length (and possibly all other metadata) from your media file with ffmpeg by using a python script you could try this:

import subprocess
import json

input_file  = "< path to your input file here >"

metadata = subprocess.check_output(f"ffprobe -i {input_file} -v quiet -print_format json -show_format -hide_banner".split(" "))

metadata = json.loads(metadata)
print(f"Length of file is: {float(metadata['format']['duration'])}")
print(metadata)

Output:

Length of file is: 7579.977143

{
  "streams": [
    {
      "index": 0,
      "codec_name": "mp3",
      "codec_long_name": "MP3 (MPEG audio layer 3)",
      "codec_type": "audio",
      "codec_time_base": "1/44100",
      "codec_tag_string": "[0][0][0][0]",
      "codec_tag": "0x0000",
      "sample_fmt": "fltp",
      "sample_rate": "44100",
      "channels": 2,
      "channel_layout": "stereo",
      "bits_per_sample": 0,
      "r_frame_rate": "0/0",
      "avg_frame_rate": "0/0",
      "time_base": "1/14112000",
      "start_pts": 353600,
      "start_time": "0.025057",
      "duration_ts": 106968637440,
      "duration": "7579.977143",
      "bit_rate": "320000",
      ...
      ...

.setAttribute("disabled", false); changes editable attribute to false

A disabled element is, (self-explaining) disabled and thereby logically not editable, so:

set the disabled attribute [...] changes the editable attribute too

Is an intended and well-defined behaviour.

The real problem here seems to be you're trying to set disabled to false via setAttribute() which doesn't do what you're expecting. an element is disabled if the disabled-attribute is set, independent of it's value (so, disabled="true", disabled="disabled" and disabled="false" all do the same: the element gets disabled). you should instead remove the complete attribute:

element.removeAttribute("disabled");

or set that property directly:

element.disabled = false;

jQuery Ajax PUT with parameters

Use:

$.ajax({
    url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
        console.log(data);
    }
});

Always remember to use _METHOD=PUT.

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }