Programs & Examples On #Quicktime

QuickTime is an extensible proprietary multimedia framework developed by Apple Inc. A framework called qtkit can be used to develop multimedia applications on top of quicktime.

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

Adding a directory to the PATH environment variable in Windows

On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:\Program Files;C:\Winnt;C:\Winnt\System32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

Eclipse executable launcher error: Unable to locate companion shared library

I encountered this error with the Eclipse 4.10 installer. We had failed to complete the install correctly due to platform security settings and attempted to uninstall but had to do it by hand since no uninstaller was introduced during the failed install. We suspected this corrupted the end result - even after re-installing.

The solution was to use the JVM to launch Eclipse and bypass the launcher executable entirely. The following command successfully launches Eclipse 4.10 (some parameters will change based on the version of Eclipse):

%JDK190%\bin\javaw.exe -jar C:\<fully_qualified_path_to_eclipse>\Eclipse410\plugins\org.eclipse.equinox.launcher_1.5.200.v20180922-1751.jar -clean -showsplash

After using this command/shortcut to launch Eclipse we had no further errors with Eclipse itself but we weren't able to use the EXE launcher in the future. Even after a year of using this version, the launcher continues to display this same error.

To be clear, you'll have to modify your javaw.exe command to match your system specifications on MS Windows.

Leverage browser caching, how on apache or .htaccess?

I took my chance to provide full .htaccess code to pass on Google PageSpeed Insight:

  1. Enable compression
  2. Leverage browser caching
# Enable Compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
</IfModule>
<IfModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

# Leverage Browser Caching
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/html "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</IfModule>

There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.

optimized page score

HTML5 <video> element on Android

Roman's answer worked fine for me - or at least, it gave me what I was expecting. Opening the video in the phone's native application is exactly the same as what the iPhone does.

It's probably worth adjusting your viewpoint and expect video to be played fullscreen in its own application, and coding for that. It's frustrating that clicking the video isn't sufficient to get it playing in the same way as the iPhone does, but seeing as it only takes an onclick attribute to launch it, it's not the end of the world.

My advice, FWIW, is to use a poster image, and make it obvious that it will play the video. I'm working on a project at the moment that does precisely that, and the clients are happy with it - and also that they're getting the Android version of a web app for free, of course, because the contract was only for an iPhone web app.

Just for illustration, a working Android video tag is below. Nice and simple.

<video src="video/placeholder.m4v" poster="video/placeholder.jpg" onclick="this.play();"/>

H.264 file size for 1 hr of HD video

Around 4gb/hr is quite common.

Please explain the exec() function and its family

The exec(3,3p) functions replace the current process with another. That is, the current process stops, and another runs instead, taking over some of the resources the original program had.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};

Relevant documentation

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either

  1. Your code and/or network calls are way too slow (should be sub 100 ms for a good user experience)
  2. The assertions (tests) are failing and something is swallowing the errors before Mocha is able to act on them.

You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.

When external code swallows your errors

In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.

it('should not fail', function (done) { // Pass reference here!

  i_swallow_errors(function (err, result) {
    try { // boilerplate to be able to get the assert failures
      assert.ok(true);
      assert.equal(result, 'bar');
      done();
    } catch (error) {
      done(error);
    }
  });
});

This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:

it('should not fail', function (done) { // Pass reference here!
    i_swallow_errors(handleError(done, function (err, result) {
        assert.equal(result, 'bar');
    }));
});

// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
    try { 
        fn();
        done();
    } catch (error) {
        done(error);
    }
}

Speeding up network tests

Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this

describe('api tests normally involving network calls', function() {

    beforeEach: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    afterEach: function () {
        this.xhr.restore();
    }


    it("should fetch comments from server", function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
    });

});

See Sinon's nise docs for more info.

Function to calculate R2 (R-squared) in R

You can also use the summary for linear models:

summary(lm(obs ~ mod, data=df))$r.squared 

How to find out line-endings in a text file?

You can use vim -b filename to edit a file in binary mode, which will show ^M characters for carriage return and a new line is indicative of LF being present, indicating Windows CRLF line endings. By LF I mean \n and by CR I mean \r. Note that when you use the -b option the file will always be edited in UNIX mode by default as indicated by [unix] in the status line, meaning that if you add new lines they will end with LF, not CRLF. If you use normal vim without -b on a file with CRLF line endings, you should see [dos] shown in the status line and inserted lines will have CRLF as end of line. The vim documentation for fileformats setting explains the complexities.

Also, I don't have enough points to comment on the Notepad++ answer, but if you use Notepad++ on Windows, use the View / Show Symbol / Show End of Line menu to display CR and LF. In this case LF is shown whereas for vim the LF is indicated by a new line.

Most efficient way to increment a Map value in Java

Hope I'm understanding your question correctly, I'm coming to Java from Python so I can empathize with your struggle.

if you have

map.put(key, 1)

you would do

map.put(key, map.get(key) + 1)

Hope this helps!

MySQL - count total number of rows in php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

How to set the Android progressbar's height?

I guess the simplest solution would be:

mProgressBar.setScaleY(3f);

How to filter by IP address in Wireshark?

You can also limit the filter to only part of the ip address.

E.G. To filter 123.*.*.* you can use ip.addr == 123.0.0.0/8. Similar effects can be achieved with /16 and /24.

See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.

... the number after the slash represents the number of bits used to represent the network.

How do I run PHP code when a user clicks on a link?

This should work as well

<a href="#" onclick="callFunction();">Submit</a>

<script type="text/javascript">

function callFunction()
{
  <?php require("functions.php");  ?>
}
</script>

Thanks,

cowtipper

Big O, how do you calculate/approximate it?

While knowing how to figure out the Big O time for your particular problem is useful, knowing some general cases can go a long way in helping you make decisions in your algorithm.

Here are some of the most common cases, lifted from http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions:

O(1) - Determining if a number is even or odd; using a constant-size lookup table or hash table

O(logn) - Finding an item in a sorted array with a binary search

O(n) - Finding an item in an unsorted list; adding two n-digit numbers

O(n2) - Multiplying two n-digit numbers by a simple algorithm; adding two n×n matrices; bubble sort or insertion sort

O(n3) - Multiplying two n×n matrices by simple algorithm

O(cn) - Finding the (exact) solution to the traveling salesman problem using dynamic programming; determining if two logical statements are equivalent using brute force

O(n!) - Solving the traveling salesman problem via brute-force search

O(nn) - Often used instead of O(n!) to derive simpler formulas for asymptotic complexity

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Read user input inside a loop

You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:

{ cat notify-finished | while read line; do
    read -u 3 input
    echo "$input"
done; } 3<&0

BTW, if you really are using cat this way, replace it with a redirect and things become even easier:

while read line; do
    read -u 3 input
    echo "$input"
done 3<&0 <notify-finished

Or, you can swap stdin and unit 3 in that version -- read the file with unit 3, and just leave stdin alone:

while read line <&3; do
    # read & use stdin normally inside the loop
    read input
    echo "$input"
done 3<notify-finished

Can an XSLT insert the current date?

Do you have control over running the transformation? If so, you could pass in the current date to the XSL and use $current-date from inside your XSL. Below is how you declare the incoming parameter, but with knowing how you are running the transformation, I can't tell you how to pass in the value.

<xsl:param name="current-date" />

For example, from the bash script, use:

xsltproc --stringparam current-date `date +%Y-%m-%d` -o output.html path-to.xsl path-to.xml

Then, in the xsl you can use:

<xsl:value-of select="$current-date"/>

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

Getting View's coordinates relative to the root layout

No need to calculate it manually.

Just use getGlobalVisibleRect like so:

Rect myViewRect = new Rect();
myView.getGlobalVisibleRect(myViewRect);
float x = myViewRect.left;
float y = myViewRect.top;

Also note that for the centre coordinates, rather than something like:

...
float two = (float) 2
float cx = myViewRect.left + myView.getWidth() / two;
float cy = myViewRect.top + myView.getHeight() / two;

You can just do:

float cx = myViewRect.exactCenterX();
float cy = myViewRect.exactCenterY();

HTML5 Video Stop onClose

To save hours of coding time, use a jquery plug-in already optimized for embedded video iframes.

I spent a couple days trying to integrate Vimeo's moogaloop API with jquery tools unsuccessfully. See this list for a handful of easier options.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I had this error happen when I had 2 scripts I was running. I had:

  • A SQL*Plus session connected directly using a schema user account (account #1)
  • Another SQL*Plus session connected using a different schema user account (account #2), but connecting across a database link as the first account

I ran a table drop, then table creation as account #1. I ran a table update on account #2's session. Did not commit changes. Re-ran table drop/creation script as account #1. Got error on the drop table x command.

I solved it by running COMMIT; in the SQL*Plus session of account #2.

PDF Parsing Using Python - extracting formatted and plain texts

You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).

A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!

But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.

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

int main(){
    int i=0;
    int a=0;
    for(i;i<5;i++,a++){
        printf("%d %d\n",a,i);
    } 
}

How to sort Map values by key in Java?

List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
for (String str : map.keySet()) {
 list.add(str);
}
Collections.sort(list);
for (String str : list) {
 System.out.println(str);
}

PHP - SSL certificate error: unable to get local issuer certificate

I got the error like :

failed loading cafile stream: `C:\xamppPhp\apache\bin\curl-ca-bundle.crt`

I am using windows machine. So I followed the below steps.

1. I have downloaded .pem file from " https://curl.haxx.se/docs/caextract.html "

2. Then I kept the downloaded file inside  "C:/xamppPhp/apache/bin/" folder and renamed the same downloaded file to "curl-ca-bundle.crt".

3. I restarted XAMPP and cleared the cache.
4. It's done.

Hope it may help someone

How to perform a sum of an int[] array

int sum = 0;
for(int i = 0; i < A.length; i++){
  sum += A[i];
}

How to make a char string from a C macro's value?

#include <stdio.h>

#define QUOTEME(x) #x

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif

int main(void)
{
    puts(TEST_FUN_NAME);
    return 0;
}

Reference: Wikipedia's C preprocessor page

how to get right offset of an element? - jQuery

var $whatever        = $('#whatever');
var ending_right     = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

Reference: .outerWidth()

What is the easiest way to parse an INI file in Java?

I personally prefer Confucious.

It is nice, as it doesn't require any external dependencies, it's tiny - only 16K, and automatically loads your ini file on initialization. E.g.

Configurable config = Configuration.getInstance();  
String host = config.getStringValue("host");   
int port = config.getIntValue("port"); 
new Connection(host, port);

spring autowiring with unique beans: Spring expected single matching bean but found 2

The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .

When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'

You could do the following

  1. Remove @Component from your Service and depend on mapping via XML - Easiest

  2. Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.

  3. Use @Resource instead of @Autowired to pick the bean by its name .

     @Resource(name="suggestionService")
     private SuggestionService service;
    

or

    @Resource(name="SuggestionService")
    private SuggestionService service;

both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.

Update Fragment from ViewPager

A very simple yet effective solution to update your fragment views. Use setUserVisibleHint() method. It will be called upon when the fragment is about to be visible to user. There you can update our view (setText() or setVisibility() etc.)

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if(isVisibleToUser){
       //Write your code to be executed when it is visible to user
    }
}

It worked in my case. Hope it helps!

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Check the current number of connections to MongoDb

Alternatively you can check connection status by logging into Mongo Atlas and then navigating to your cluster.

enter image description here

Getting the length of two-dimensional array

Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):

    String row = "";
    int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
    for (int i=0; i<myArray.length; i++) {
        row+="\n";
        for (int j = 0; j<myArray[i].length; j++) {
            row += myArray[i][j] + "  ";
        }
    }
    JOptionPane.showMessageDialog(null, "myArray contains:" + row);

Jagged array's contents

In .NET, which loop runs faster, 'for' or 'foreach'?

I ran into a case where foreach way WAY faster than For

why foreach is faster than for loop while reading richtextbox lines

I had a case similar to the OP in that question.

A textbox reading about 72K lines, and I was accessling the Lines property(which is actually a getter method). (And apparently often in winforms there are getter methods that aren't O(1). I suppose it's O(n), so the larger the textbox the longer it takes to get a value from that 'property'. And in the for loop I had as the OP there had for(int i=0;i<textBox1.lines.length;i++) str=textBox1.Lines[i] , and it was really quite slow as it was reading the entire textbox each time it read a line plus it was reading the entire textbox each time it checked the condition.

Jon Skeet shows that you can do it accessing the Lines property just one single time(not even once per iteration, just once). Rather than twice on each iteration (which is a ton of times). Do string[] strarrlines = textBox1.Lines; and loop through the strarrlines.

But certainly a for loop in a fairly intuitive form and accessing the Lines property, is very inefficient

for (int i = 0; i < richTextBox.Lines.Length; i++)
{
    s = richTextBox.Lines[i];
}

for a textbox, or a rich textbox, it's super slow.

The OP, testing that loop on a rich textbox, found that " with 15000 lines.for loop took 8 minutes to just loop down to 15000 lines.while foreach took fraction of a second to enumerate it."

The OP at that link found this foreach to be far more efficient than his(The same OP's) for loop mentioned above. As I did.

   String s=String.Empty;
   foreach(string str in txtText.Lines)
    {
       s=str;
    }

how to get the value of css style using jquery

You code is correct. replace items with .items as below

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

How do I remove an array item in TypeScript?

Here's a simple one liner for removing an object by property from an array of objects.

delete this.items[this.items.findIndex(item => item.item_id == item_id)];

or

this.items = this.items.filter(item => item.item_id !== item.item_id);

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.

In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.

See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.

Date format in dd/MM/yyyy hh:mm:ss

SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)

Git Pull is Not Possible, Unmerged Files

I got solved with git remove the unmerged file locally.

$ git rm <the unmerged file name>
$ git reset --hard
$ git pull --rebase
$ git rebase --skip
$ git pull
Already up-to-date.

When I send git commit afterward:

$ git commit . -m "my send commit"
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

You can use the following

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result : 1539594988651

Hope this will help. Just my suggestion and not for reward points.

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Default FirebaseApp is not initialized

As mentioned by @PSIXO in a comment, this might be the problem with the dependency version of google-services. For me changing,

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

to

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

worked.There might be some problem with 4.1.0 version. Because I wasted many hours on this, I thought to write this as an answer.

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

In Typescript with relative path to the icon:

import path from 'path';

route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

jQuery "blinking highlight" effect on div?

You may want to look into jQuery UI. Specifically, the highlight effect:

http://jqueryui.com/demos/effect/

Is there a RegExp.escape function in JavaScript?

Rather than only escaping characters which will cause issues in your regular expression (e.g.: a blacklist), consider using a whitelist instead. This way each character is considered tainted unless it matches.

For this example, assume the following expression:

RegExp.escape('be || ! be');

This whitelists letters, number and spaces:

RegExp.escape = function (string) {
    return string.replace(/([^\w\d\s])/gi, '\\$1');
}

Returns:

"be \|\| \! be"

This may escape characters which do not need to be escaped, but this doesn't hinder your expression (maybe some minor time penalties - but it's worth it for safety).

How to set full calendar to a specific start date when it's initialized for the 1st time?

This can be used in v5.3.2 to goto a date after initialization

calendar.gotoDate( '2020-09-12' );

eg on datepicker change

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
     ...
     initialDate: '2020-09-02',
     ...
});    

$(".date-picker").change(function(){
     var date = $(this).val();
     calendar.gotoDate( date );
});

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

An error occurred while collecting items to be installed (Access is denied)

None of the above worked for me.

Instead, I tried installing the plugins I needed via the Eclipse Market Place, and that worked without issue.

  1. Click "Help" Menu.
  2. Click "Eclipse Marketplace..." menu item.
  3. Enter the name of the plugin you want.
  4. Click "Install" when the plugin appears in the Marketplace List.
  5. Restart Eclipse.

Which is a better way to check if an array has more than one element?

I prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages. Many programmers expect sizeof() to return the amount of memory allocated.

GIT vs. Perforce- Two VCS will enter... one will leave

The command that sold me on git personally was bisect. I don't think that this feature is available in any other version control system as of now.

That being said, if people are used to a GUI client for source control they are not going to be impressed with git. Right now the only full-featured client is command-line.

Read a text file line by line in Qt

Since Qt 5.5 you can use QTextStream::readLineInto. It behaves similar to std::getline and is maybe faster as QTextStream::readLine, because it reuses the string:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

Rename specific column(s) in pandas

How do I rename a specific column in pandas?

From v0.24+, to rename one (or more) columns at a time,

If you need to rename ALL columns at once,

  • DataFrame.set_axis() method with axis=1. Pass a list-like sequence. Options are available for in-place modification as well.

rename with axis=1

df = pd.DataFrame('x', columns=['y', 'gdp', 'cap'], index=range(5))
df

   y gdp cap
0  x   x   x
1  x   x   x
2  x   x   x
3  x   x   x
4  x   x   x

With 0.21+, you can now specify an axis parameter with rename:

df.rename({'gdp':'log(gdp)'}, axis=1)
# df.rename({'gdp':'log(gdp)'}, axis='columns')
    
   y log(gdp) cap
0  x        x   x
1  x        x   x
2  x        x   x
3  x        x   x
4  x        x   x

(Note that rename is not in-place by default, so you will need to assign the result back.)

This addition has been made to improve consistency with the rest of the API. The new axis argument is analogous to the columns parameter—they do the same thing.

df.rename(columns={'gdp': 'log(gdp)'})

   y log(gdp) cap
0  x        x   x
1  x        x   x
2  x        x   x
3  x        x   x
4  x        x   x

rename also accepts a callback that is called once for each column.

df.rename(lambda x: x[0], axis=1)
# df.rename(lambda x: x[0], axis='columns')

   y  g  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For this specific scenario, you would want to use

df.rename(lambda x: 'log(gdp)' if x == 'gdp' else x, axis=1)

Index.str.replace

Similar to replace method of strings in python, pandas Index and Series (object dtype only) define a ("vectorized") str.replace method for string and regex-based replacement.

df.columns = df.columns.str.replace('gdp', 'log(gdp)')
df
 
   y log(gdp) cap
0  x        x   x
1  x        x   x
2  x        x   x
3  x        x   x
4  x        x   x

The advantage of this over the other methods is that str.replace supports regex (enabled by default). See the docs for more information.


Passing a list to set_axis with axis=1

Call set_axis with a list of header(s). The list must be equal in length to the columns/index size. set_axis mutates the original DataFrame by default, but you can specify inplace=False to return a modified copy.

df.set_axis(['cap', 'log(gdp)', 'y'], axis=1, inplace=False)
# df.set_axis(['cap', 'log(gdp)', 'y'], axis='columns', inplace=False)

  cap log(gdp)  y
0   x        x  x
1   x        x  x
2   x        x  x
3   x        x  x
4   x        x  x

Note: In future releases, inplace will default to True.

Method Chaining
Why choose set_axis when we already have an efficient way of assigning columns with df.columns = ...? As shown by Ted Petrou in this answer set_axis is useful when trying to chain methods.

Compare

# new for pandas 0.21+
df.some_method1()
  .some_method2()
  .set_axis()
  .some_method3()

Versus

# old way
df1 = df.some_method1()
        .some_method2()
df1.columns = columns
df1.some_method3()

The former is more natural and free flowing syntax.

[ :Unexpected operator in shell programming

you can use case/esac instead of if/else

case "$choose" in
  [yY]) echo "Yes" && exit;;
  [nN]) echo "No" && exit;;
  * ) echo "wrong input" && exit;;
esac

Passing an array/list into a Python function

Python lists (which are not just arrays because their size can be changed on the fly) are normal Python objects and can be passed in to functions as any variable. The * syntax is used for unpacking lists, which is probably not something you want to do now.

What causes: "Notice: Uninitialized string offset" to appear?

Check out the contents of your array with

echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Sometimes dict() is a good choice:

a=dict(zip(['Mon','Tue','Wed','Thu','Fri'], [x for x in range(1, 6)]))

mydict=dict(zip(['mon','tue','wed','thu','fri','sat','sun'],

[random.randint(0,100) for x in range(0,7)]))

Convert char * to LPWSTR

This version, using the Windows API function MultiByteToWideChar(), handles the memory allocation for arbitrarily long input strings.

int lenA = lstrlenA(input);
int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
if (lenW>0)
{
    output = new wchar_t[lenW];
    ::MultiByteToWideChar(CP_ACP, 0, input, lenA, output, lenW);
} 

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

sudo apt-get -y install python-software-properties && \
sudo apt-get -y install software-properties-common && \
sudo apt-get -y install gcc make build-essential libssl-dev libffi-dev python-dev

You need the libssl-dev and libffi-dev if especially you are trying to install python's cryptography libraries or python libs that depend on it(eg ansible)

Find Nth occurrence of a character in a string

Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):

public static int NthIndexOf(this string input, char value, int n)
{
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

    int i = -1;
    do
    {
        i = input.IndexOf(value, i + 1);
        n--;
    }
    while (i != -1 && n > 0);

    return i;
}

Or to search from the end of the string using LastIndexOf:

public static int NthLastIndexOf(this string input, char value, int n)
{
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

    int i = input.Length;
    do
    {
        i = input.LastIndexOf(value, i - 1);
        n--;
    }
    while (i != -1 && n > 0);

    return i;
}

Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.

C++ Structure Initialization

It is possible, but only if the struct you're initializing is a POD (plain old data) struct. It cannot contain any methods, constructors, or even default values.

Swift: declare an empty dictionary

If you want to create a generic dictionary with any type

var dictionaryData = [AnyHashable:Any]()

'pip' is not recognized as an internal or external command

When installing SQL 2019 Python, there are known issues for PIP which require a fix (step 7) https://docs.microsoft.com/en-us/sql/advanced-analytics/known-issues-for-sql-server-machine-learning-services?view=sql-server-ver15

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

Workaround
Copy the following files:

libssl-1_1-x64.dll
libcrypto-1_1-x64.dll

from the folder 
C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\Library\bin
to the folder 
C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\DLLs

Then open a new DOS command shell prompt.

Auto start print html page using javascript

The following code must be put at the end of your HTML file so that once the content has loaded, the script will be executed and the window will print.

<script type="text/javascript">
<!--
window.print();
//-->
</script>

How do you get a query string on Flask?

Every form of the query string retrievable from flask request object as described in O'Reilly Flask Web Devleopment:

From O'Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:

from flask import request

request is an object exposed by Flask as a context variable named (you guessed it) request. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.

You have quite a few request attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O'Reilly book of that attribute.

First there is args which is "a dictionary with all the arguments passed in the query string of the URL." So if you want the query string parsed into a dictionary, you'd do something like this:

from flask import request

@app.route('/'):
    queryStringDict = request.args

(As others have pointed out, you can also use .get('<arg_name>') to get a specific value from the dictionary)

Then, there is the form attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form is "A dictionary with all the form fields submitted with the request." I say that to say this: there is another dictionary attribute available in the flask request object called values. values is "A dictionary that combines the values in form and args." Retrieving that would look something like this:

from flask import request

@app.route('/'):
    formFieldsAndQueryStringDict = request.values

(Again, use .get('<arg_name>') to get a specific item out of the dictionary)

Another option is query_string which is "The query string portion of the URL, as a raw binary value." Example of that:

from flask import request

@app.route('/'):
    queryStringRaw = request.query_string

Then as an added bonus there is full_path which is "The path and query string portions of the URL." Por ejemplo:

from flask import request

@app.route('/'):
    pathWithQueryString = request.full_path

And finally, url, "The complete URL requested by the client" (which includes the query string):

from flask import request

@app.route('/'):
    pathWithQueryString = request.url

Happy hacking :)

Android open pdf file

The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}   

Change/Get check state of CheckBox

<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />

C# switch on type

I did it one time with a workaround, hope it helps.

string fullName = typeof(MyObj).FullName;

switch (fullName)
{
    case "fullName1":
    case "fullName2":
    case "fullName3":
}

cannot import name patterns

Yes:

from django.conf.urls.defaults import ... # is for django 1.3
from django.conf.urls  import ...         # is for django 1.4

I met this problem too.

PDF Blob - Pop up window not showing content

I have been struggling for days finally the solution which worked for me is given below. I had to make the window.print() for PDF in new window needs to work.

 var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function(e) {
        if (this['status'] == 200) {          
          var blob = new Blob([this['response']], {type: 'application/pdf'});
          var url = URL.createObjectURL(blob);
          var printWindow = window.open(url, '', 'width=800,height=500');
          printWindow.print()
        }
      };

      xhr.send();

Some notes on loading PDF & printing in a new window.

  • Loading pdf in a new window via an iframe will work, but the print will not work if url is an external url.
  • Browser pop ups must be allowed, then only it will work.
  • If you try to load iframe from external url and try window.print() you will get empty print or elements which excludes iframe. But you can trigger print manually, which will work.

Is there a way to run Python on Android?

Cross-Compilation & Ignifuga

My blog has instructions and a patch for cross compiling Python 2.7.2 for Android.

I've also open sourced Ignifuga, my 2D Game Engine. It's Python/SDL based, and it cross compiles for Android. Even if you don't use it for games, you might get useful ideas from the code or builder utility (named Schafer, after Tim... you know who).

Android intent for playing video?

from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException error from the uriString. I think some of that code from VideoActivity:

Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();

startVideo(b.getString(uri));

Cannot receive the uri from here:

public void playsquirrelmp4(View v) {
    Intent VideoIntent = (new Intent(this, VideoActivity.class));
    VideoIntent.putExtra("android.resource://" + getPackageName()
        + "/"+   R.raw.squirrel, uri);
    startActivity(VideoIntent);
}

Run an OLS regression with Pandas Data Frame

I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas' optional dependencies before pandas' version 0.20.0 (it was used for a few things in pandas.stats.)

>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept    14.952480
B             0.401182
C             0.000352
dtype: float64
>>> print(result.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.579
Model:                            OLS   Adj. R-squared:                  0.158
Method:                 Least Squares   F-statistic:                     1.375
Date:                Thu, 14 Nov 2013   Prob (F-statistic):              0.421
Time:                        20:04:30   Log-Likelihood:                -18.178
No. Observations:                   5   AIC:                             42.36
Df Residuals:                       2   BIC:                             41.19
Df Model:                           2                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept     14.9525     17.764      0.842      0.489       -61.481    91.386
B              0.4012      0.650      0.617      0.600        -2.394     3.197
C              0.0004      0.001      0.650      0.583        -0.002     0.003
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   1.061
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.498
Skew:                          -0.123   Prob(JB):                        0.780
Kurtosis:                       1.474   Cond. No.                     5.21e+04
==============================================================================

Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

How to split a single column values to multiple column values?

SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX(rent, ' ', 1), ' ', -1) AS currency,
   SUBSTRING_INDEX(SUBSTRING_INDEX(rent, ' ', 3), ' ', -1) AS rent
FROM tolets

Removing duplicate rows in Notepad++

Search for the regular expression: \b(\w+)\b([\w\W]*)\b\1\b

Replace it with: $1$2

Hit the Replace button until there are no more matches for the regular expression in your file.

Static variable inside of a function in C

The output will be 6 7. A static variable (whether inside a function or not) is initialized exactly once, before any function in that translation unit executes. After that, it retains its value until modified.

How to set initial value and auto increment in MySQL?

Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.

Now, Set your values and then press Go under the Table Options Box.

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

adding css file with jquery

Have you tried simply using the media attribute for you css reference?

<link rel="stylesheet" href="css/style2.css" media="print" type="text/css" />

Or set it to screen if you don't want the printed version to use the style:

<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />

This way you don't need to add it dynamically.

Replacing Numpy elements if condition is met

You can create your mask array in one step like this

mask_data = input_mask_data < 3

This creates a boolean array which can then be used as a pixel mask. Note that we haven't changed the input array (as in your code) but have created a new array to hold the mask data - I would recommend doing it this way.

>>> input_mask_data = np.random.randint(0, 5, (3, 4))
>>> input_mask_data
array([[1, 3, 4, 0],
       [4, 1, 2, 2],
       [1, 2, 3, 0]])
>>> mask_data = input_mask_data < 3
>>> mask_data
array([[ True, False, False,  True],
       [False,  True,  True,  True],
       [ True,  True, False,  True]], dtype=bool)
>>> 

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Loop timer in JavaScript

It should be:

function moveItem() {
  jQuery(".stripTransmitter ul li a").trigger('click');
}
setInterval(moveItem,2000);

setInterval(f, t) calls the the argument function, f, once every t milliseconds.

"Least Astonishment" and the Mutable Default Argument

A simple workaround using None

>>> def bar(b, data=None):
...     data = data or []
...     data.append(b)
...     return data
... 
>>> bar(3)
[3]
>>> bar(3)
[3]
>>> bar(3)
[3]
>>> bar(3, [34])
[34, 3]
>>> bar(3, [34])
[34, 3]

Execute the setInterval function without delay the first time

I'm not sure if I'm understanding you correctly, but you could easily do something like this:

setInterval(function hello() {
  console.log('world');
  return hello;
}(), 5000);

There's obviously any number of ways of doing this, but that's the most concise way I can think of.

MySQL: can't access root account

This worked for me:

https://blog.dotkam.com/2007/04/10/mysql-reset-lost-root-password/

Step 1: Stop MySQL daemon if it is currently running

  ps -ef | grep mysql      - checks if mysql/mysqld is one of the running processes.

  pkill mysqld             - kills the daemon, if it is running.

Step 2: Run MySQL safe daemon with skipping grant tables

  mysqld_safe --skip-grant-tables &

  mysql -u root mysql

Step 3: Login to MySQL as root with no password

  mysql -u root mysql

Step 4: Run UPDATE query to reset the root password

  UPDATE user SET password=PASSWORD("value=42") WHERE user="root";
  FLUSH PRIVILEGES;

In MySQL 5.7, the 'password' field was removed, now the field name is 'authentication_string':

  UPDATE user SET authentication_string=PASSWORD("42") WHERE 
  user="root";
  FLUSH PRIVILEGES;

Step 5: Stop MySQL safe daemon

Step 6: Start MySQL daemon

When a 'blur' event occurs, how can I find out which element focus went *to*?

2015 answer: according to UI Events, you can use the relatedTarget property of the event:

Used to identify a secondary EventTarget related to a Focus event, depending on the type of event.

For blur events,

relatedTarget: event target receiving focus.

Example:

_x000D_
_x000D_
function blurListener(event) {_x000D_
  event.target.className = 'blurred';_x000D_
  if(event.relatedTarget)_x000D_
    event.relatedTarget.className = 'focused';_x000D_
}_x000D_
[].forEach.call(document.querySelectorAll('input'), function(el) {_x000D_
  el.addEventListener('blur', blurListener, false);_x000D_
});
_x000D_
.blurred { background: orange }_x000D_
.focused { background: lime }
_x000D_
<p>Blurred elements will become orange.</p>_x000D_
<p>Focused elements should become lime.</p>_x000D_
<input /><input /><input />
_x000D_
_x000D_
_x000D_

Note Firefox won't support relatedTarget until version 48 (bug 962251, MDN).

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

When using a Settings.settings file in .NET, where is the config actually stored?

All your settings are stored in the respective .config file.

The .settings file simply provides a strongly typed class for a set of settings that belong together, but the actual settings are stored in app.config or a .config file in your application.

If you add a .settings file, an app.config will be automatically added to house the settings if you don't already have one.

Export a list into a CSV or TXT file in R

Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000

Exporting large lists in R as .txt or .csv

Getting attribute using XPath

How could I get the value of lang (where lang=eng in book title), for the first element?

Use:

/*/book[1]/title/@lang

This means:

Select the lang attribute of the title element that is a child of the first book child of the top element of the XML document.

To get just the string value of this attribute use the standard XPath function string():

string(/*/book[1]/title/@lang)

Python, how to check if a result set is empty?

For reference, cursor.rowcount will only return on CREATE, UPDATE and DELETE statements:

 |  rowcount
 |      This read-only attribute specifies the number of rows the last DML statement
 |      (INSERT, UPDATE, DELETE) affected.  This is set to -1 for SELECT statements.

What is a NoReverseMatch error, and how do I fix it?

And make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

https://github.com/django-extensions/django-extensions

How to resolve "must be an instance of string, string given" prior to PHP 7?

I got this error when invoking a function from a Laravel Controller to a PHP file.

After a couple of hours, I found the problem: I was using $this from within a static function.

Docker-compose: node_modules not present in a volume after npm install succeeds

You can also ditch your Dockerfile, because of its simplicity, just use a basic image and specify the command in your compose file:

version: '3.2'

services:
  frontend:
    image: node:12-alpine
    volumes:
      - ./frontend/:/app/
    command: sh -c "cd /app/ && yarn && yarn run start"
    expose: [8080]
    ports:
      - 8080:4200

This is particularly useful for me, because I just need the environment of the image, but operate on my files outside the container and I think this is what you want to do too.

How to convert a string to integer in C?

There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
     strtonum(const char *nptr, long long minval, long long maxval,
     const char **errstr);

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
    /* Could not convert. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

What is tempuri.org?

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

tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.

Add (insert) a column between two columns in a data.frame

I would suggest you to use the function add_column() from the tibble package.

library(tibble)
dataset <- data.frame(a = 1:5, b = 2:6, c=3:7)
add_column(dataset, d = 4:8, .after = 2)

Note that you can use column names instead of column index :

add_column(dataset, d = 4:8, .after = "b")

Or use argument .before instead of .after if more convenient.

add_column(dataset, d = 4:8, .before = "c")

Select element based on multiple classes

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB {
/*style here*/
}

Class & Id

.classA#idB {
/*style here*/
}

Id & Id

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector {
/*style here*/
}

or

.left.ui-class-selector {
/*style here*/
}

What is difference between monolithic and micro kernel?

In the spectrum of kernel designs the two extreme points are monolithic kernels and microkernels.

The (classical) Linux kernel for instance is a monolithic kernel (and so is every commercial OS to date as well - though they might claim otherwise);

In that its code is a single C file giving rise to a single process that implements all of the above services.
To exemplify the encapsulation of the Linux kernel we remark that the Linux kernel does not even have access to any of the standard C libraries. Indeed the Linux kernel cannot use rudimentary C library functions such as printf. Instead it implements its own printing function (called prints).

This seclusion of the Linux kernel and self-containment provide Linux kernel with its main advantage: the kernel resides in a single address space1 enabling all features to communicate in the fastest way possible without resorting to any type of message passing. In particular, a monolithic kernel implements all of the device drivers of the system.

This however is the main drawback of a monolithic kernel: introduction of any new unsupported hardware requires a rewrite of the kernel (in the relevant parts), recompilation of it, and re-installing the entire OS.
More importantly, if any device driver crashes the entire kernel suffers as a result. This un-modular approach to hardware additions and hardware crashes is the main argument for supporting the other extreme design approach for kernels. A microkernel is in a sense a minimalistic kernel that houses only the very basic of OS services (like process management and file system management). In a microkernel the device drivers lie outside of the kernel allowing for addition and removal of device drivers while the OS is running and require no alternations of the kernel.

Variables as commands in bash scripts

Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.

It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.

With perl, as my example, I'd be able to do something like:

@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );

The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)

Jenkins "Console Output" log location in filesystem

For very large output logs it could be difficult to open (network delay, scrolling). This is the solution I'm using to check big log files:

    https://${URL}/jenkins/job/${jobName}/${buildNumber}/

in the left column you see: View as plain text. Do a right mouse click on it and choose save links as. Now you can save your big log as .txt file. Open it with notepad++ and you can go through your logs easily without network delays during scrolling.

How to print all key and values from HashMap in Android?

for (Map.Entry<String,String> entry : map.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue();
  // do stuff
}

How can I break up this long line in Python?

For anyone who is also trying to call .format() on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format( call, you can do str.format("", 1, 2) instead of "".format(1, 2). This lets you break the string with whatever technique you like. For example:

logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))

can be

logger.info(str.format(("Skipping {0} because its thumbnail was already"
+ "in our system as {1}"), line[indexes['url']], video.title))

Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.

Regex to replace multiple spaces with a single space

This is one solution, though it will target all space characters:

"The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')

"The dog has a long tail, and it is RED!"

Edit: This is probably better since it targets a space followed by 1 or more spaces:

"The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')

"The dog has a long tail, and it is RED!"

Alternative method:

"The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"

I didn't use /\s+/ by itself since that replaces spaces that span 1 character multiple times and might be less efficient since it targets more than necessary.

I didn't deeply test any of these so lmk if there are bugs.

Also, if you're going to do string replacement remember to re-assign the variable/property to its own replacement, eg:

var string = 'foo'
string = string.replace('foo', '')

Using jQuery.prototype.text:

var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )

Redirect all output to file in Bash

Command:

foo >> output.txt 2>&1

appends to the output.txt file, without replacing the content.

How to disable "prevent this page from creating additional dialogs"?

I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.

So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:

var countdown = 99;
function annoy(){
    if(countdown>0){
        alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
        countdown--;

        // Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
        setTimeout(function(){
            annoy();
        }, 1000);
    }
}

// Don't alert right away or Chrome will catch you
setTimeout(function(){
    annoy();
}, 1000);

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

Alternative to deprecated getCellType

    FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));

    //create workbook instance
    XSSFWorkbook wb = new XSSFWorkbook(fis);

    //create a sheet object to retrieve the sheet
    XSSFSheet sheet = wb.getSheetAt(0);

    //to evaluate cell type
    FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();

    for(Row row : sheet)
    {
        for(Cell cell : row)
        {
            switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
            {
            case NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                break;
            case STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                break;
            default:
                break;

            }
        }
        System.out.println();
    }

This code will work fine. Use getCellTypeEnum() and to compare use just NUMERIC or STRING.

Python: TypeError: cannot concatenate 'str' and 'int' objects

I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:

_x000D_
_x000D_
def main():_x000D_
 rolling = True; import random_x000D_
 while rolling:_x000D_
  roll = input("ENTER = roll; Q = quit ")_x000D_
  if roll.lower() != 'q':_x000D_
   num = (random.randint(1,6))_x000D_
   print("----------------------"); print("you rolled " + str(num))_x000D_
  else:_x000D_
   rolling = False_x000D_
main()
_x000D_
_x000D_
_x000D_

I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.

phpmyadmin "Not Found" after install on Apache, Ubuntu

Run the following command in terminal:

sudo ln -s /usr/share/phpmyadmin /var/www/html/

JavaScript closures vs. anonymous functions

Consider the following. This creates and recreates a function f that closes on i, but different ones!:

_x000D_
_x000D_
i=100;_x000D_
_x000D_
f=function(i){return function(){return ++i}}(0);_x000D_
alert([f,f(),f(),f(),f(),f(),f(),f(),f(),f(),f()].join('\n\n'));_x000D_
_x000D_
f=function(i){return new Function('return ++i')}(0);        /*  function declarations ~= expressions! */_x000D_
alert([f,f(),f(),f(),f(),f(),f(),f(),f(),f(),f()].join('\n\n'));
_x000D_
_x000D_
_x000D_

while the following closes on "a" function "itself"
( themselves! the snippet after this uses a single referent f )

_x000D_
_x000D_
for(var i = 0; i < 10; i++) {_x000D_
    setTimeout( new Function('console.log('+i+')'),  1000 );_x000D_
}
_x000D_
_x000D_
_x000D_

or to be more explicit:

_x000D_
_x000D_
for(var i = 0; i < 10; i++) {_x000D_
    console.log(    f = new Function( 'console.log('+i+')' )    );_x000D_
    setTimeout( f,  1000 );_x000D_
}
_x000D_
_x000D_
_x000D_

NB. the last definition of f is function(){ console.log(9) } before 0 is printed.

Caveat! The closure concept can be a coercive distraction from the essence of elementary programming:

_x000D_
_x000D_
for(var i = 0; i < 10; i++) {     setTimeout( 'console.log('+i+')',  1000 );      }
_x000D_
_x000D_
_x000D_

x-refs.:
How do JavaScript closures work?
Javascript Closures Explanation
Does a (JS) Closure Require a Function Inside a Function
How to understand closures in Javascript?
Javascript local and global variable confusion

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

Solution 1

If you use a newer version of Visual Studio, you may not have this problem. I'm currently using Visual Studio 2015 and it works great.

Solution 2

You can solve this problem by changing the project's port number.
Because the reason is a port number conflict with some other application.

I had the same issue and fixed by doing that (by changing the port number).
I had solved this here : Changing project port number in Visual Studio 2013

If you use a different version of Visual Studio; you may also change the port number by project's Properties Window in Solution Explorer.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I have summarised what I did for my issue.

1) Delete .m2 folder. 2) Change the apache-maven-3.5.4\conf\settings.xml as follow

<proxies>
<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <host>proxyserver.company.com</host> --> Please change it according to your proxy
  <port>8080</port> -->Please change it accordingly
  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>

3) Try again in cmd. It will work.

4) For eclipse, delete the existing maven project and go to

window ->prefernces -> maven -> user settings -> browse -> configure this path apache-maven-3.5.4\conf\settings.xml

5) Delete .m2 folder.

6) Restart the eclipse and try creating new maven project.

These steps worked for me.

Loop in Jade (currently known as "Pug") template engine

Using node I have a collection of stuff @stuff and access it like this:

- each stuff in stuffs
  p
    = stuff.sentence

Android: ScrollView vs NestedScrollView

Other than the advantages listed in the answers given, one more advantage of NestedScrollView over ScrollView is its compatibility with CoordinatorLayout. The ScrollView does not cooperate with the CoordinatorLayout. You have to use NestedScrollView to get "scroll off-screen" behaviour for the toolbar.

Toolbar will not collapse with Scrollview as child of CoordinatorLayout

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

Textarea resize control is available via the CSS3 resize property:

textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }

Allowable values self-explanatory: none (disables textarea resizing), both, vertical and horizontal.

Notice that in Chrome, Firefox and Safari the default is both.

If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height, max-width, min-height, and min-width CSS properties to provide resizing within certain proportions.

Code example:

_x000D_
_x000D_
#textarea-wrapper {_x000D_
  padding: 10px;_x000D_
  background-color: #f4f4f4;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
  min-height:50px;_x000D_
  max-height:120px;_x000D_
  width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
  resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
  <label for="resize-default">Textarea (default):</label>_x000D_
  <textarea name="resize-default" id="resize-default"></textarea>_x000D_
  _x000D_
  <label for="resize-vertical">Textarea (vertical):</label>_x000D_
  <textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Writing new lines to a text file in PowerShell

Try this;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Prevent textbox autofill with previously entered values

Autocomplete need to set off from textbox

<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>

How can I make Flexbox children 100% height of their parent?

I found the solution by myself. Suppose you have the CSS below:

.parent {
  align-items: center;
  display: flex;
  justify-content: center;
}

.child {
  height: 100%; <- didn't work
}

In this case, setting the height 100% will not work, so I set the margin-bottom rule to auto, like:

.child {
  margin-bottom: auto;
}

And the child will be aligned to the topmost of the parent.

You can also use the align-self rule anyway if you prefer:

.child {
  align-self: flex-start;
}

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

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

Could be simplified to this:

SELECT article FROM table1 ORDER BY publish_date DESC FETCH FIRST 20 ROWS ONLY;

You could also add many argument in the ORDER BY that is just comma separated like: ORDER BY publish_date, tab2, tab3 DESC etc...

What's the difference between event.stopPropagation and event.preventDefault?

_x000D_
_x000D_
$("#but").click(function(event){_x000D_
console.log("hello");_x000D_
  event.preventDefault();_x000D_
 });_x000D_
_x000D_
_x000D_
$("#foo").click(function(){_x000D_
 alert("parent click event fired !");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo">_x000D_
  <button id="but">button</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP - count specific array values

You can do this with array_keys and count.

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));

Output:

3

Java reverse an int value without using array

Reversing integer

  int n, reverse = 0;
  Scanner in = new Scanner(System.in);
  n = in.nextInt();

  while(n != 0)
  {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
  }

  System.out.println("Reverse of the number is " + reverse);

How to display errors on laravel 4?

In the Laravel root folder chmod the storage directory to 777

Generating an array of letters in the alphabet

char[] alphabet = Enumerable.Range('A', 26).Select(x => (char)x).ToArray();

Eclipse - Failed to create the java virtual machine

Recently i encounter this issue and try all of the above method but none of them works for me.

Here is another Trick for to solve this error is

i just delete the eclipse configuration file and eclipse start working.. i don't know why but it works.

Maybe this helps someone else.

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

How to create composite primary key in SQL Server 2008

Via Enterprise Manager (SSMS)...

  • Right Click on the Table you wish to create the composite key on and select Design.
  • Highlight the columns you wish to form as a composite key
  • Right Click over those columns and Set Primary Key

To see the SQL you can then right click on the Table > Script Table As > Create To

Copy array by value

For ES6 array containing objects

cloneArray(arr) {
    return arr.map(x => ({ ...x }));
}

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Is there a way to reset IIS 7.5 to factory settings?

There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.

http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx

You will have to regularly back up manually using appcmd.

If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.

WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via http://support.microsoft.com and consult.

node.js string.replace doesn't work?

Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";

variableABC = variableABC.replace('B', 'D') //output: 'A D C'

Calling a function on bootstrap modal open

will not work.. use $(window) instead

For Showing

$(window).on('shown.bs.modal', function() { 
    $('#code').modal('show');
    alert('shown');
});

For Hiding

$(window).on('hidden.bs.modal', function() { 
    $('#code').modal('hide');
    alert('hidden');
});

Getting Spring Application Context

If you use a web-app there is also another way to access the application context without using singletons by using a servletfilter and a ThreadLocal. In the filter you can access the application context using WebApplicationContextUtils and store either the application context or the needed beans in the TheadLocal.

Caution: if you forget to unset the ThreadLocal you will get nasty problems when trying to undeploy the application! Thus, you should set it and immediately start a try that unsets the ThreadLocal in the finally-part.

Of course, this still uses a singleton: the ThreadLocal. But the actual beans do not need to be anymore. The can even be request-scoped, and this solution also works if you have multiple WARs in an Application with the libaries in the EAR. Still, you might consider this use of ThreadLocal as bad as the use of plain singletons. ;-)

Perhaps Spring already provides a similar solution? I did not find one, but I don't know for sure.

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

Index inside map() function

Array.prototype.map() index:

One can access the index Array.prototype.map() via the second argument of the callback function. Here is an example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
_x000D_
const map = array.map((x, index) => {_x000D_
  console.log(index);_x000D_
  return x + index;_x000D_
});_x000D_
_x000D_
console.log(map);
_x000D_
_x000D_
_x000D_

Other arguments of Array.prototype.map():

  • The third argument of the callback function exposes the array on which map was called upon
  • The second argument of Array.map() is a object which will be the this value for the callback function. Keep in mind that you have to use the regular function keyword in order to declare the callback since an arrow function doesn't have its own binding to the this keyword.

For example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
const thisObj = {prop1: 1}_x000D_
_x000D_
_x000D_
const map = array.map( function (x, index, array) {_x000D_
  console.log(array);_x000D_
  console.log(this)_x000D_
}, thisObj);
_x000D_
_x000D_
_x000D_

Strip Leading and Trailing Spaces From Java String

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs

SQL Server - copy stored procedures from one db to another

use

select * from sys.procedures

to show all your procedures;

sp_helptext @objname = 'Procedure_name'

to get the code

and your creativity to build something to loop through them all and generate the export code :)

How do I get the parent directory in Python?

Update from Python 3.4

Use the pathlib module.

from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)

Old answer

Try this:

import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))

where yourpath is the path you want the parent for.

How do I find the current machine's full hostname in C (hostname and domain information)?

To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.

The easiest way to do this is by first getting the local hostname using uname() or gethostname() and then performing a lookup with gethostbyname() and looking at the h_name member of the struct it returns. If you are using ANSI c, you must use uname() instead of gethostname().

Example:

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);

Unfortunately, gethostbyname() is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use getaddrinfo().

Example:

struct addrinfo hints, *info, *p;
int gai_result;

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;

if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
    exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
    printf("hostname: %s\n", p->ai_canonname);
}

freeaddrinfo(info);

Of course, this will only work if the machine has a FQDN to give - if not, the result of the getaddrinfo() ends up being the same as the unqualified hostname.

How to declare a variable in MySQL?

There are mainly three types of variables in MySQL:

  1. User-defined variables (prefixed with @):

    You can access any user-defined variable without declaring it or initializing it. If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.

    SELECT @var_any_var_name
    

    You can initialize a variable using SET or SELECT statement:

    SET @start = 1, @finish = 10;    
    

    or

    SELECT @start := 1, @finish := 10;
    
    SELECT * FROM places WHERE place BETWEEN @start AND @finish;
    

    User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.

    User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.

    They can be used in SELECT queries using Advanced MySQL user variable techniques.

  2. Local Variables (no prefix) :

    Local variables needs to be declared using DECLARE before accessing it.

    They can be used as local variables and the input parameters inside a stored procedure:

    DELIMITER //
    
    CREATE PROCEDURE sp_test(var1 INT) 
    BEGIN   
        DECLARE start  INT unsigned DEFAULT 1;  
        DECLARE finish INT unsigned DEFAULT 10;
    
        SELECT  var1, start, finish;
    
        SELECT * FROM places WHERE place BETWEEN start AND finish; 
    END; //
    
    DELIMITER ;
    
    CALL sp_test(5);
    

    If the DEFAULT clause is missing, the initial value is NULL.

    The scope of a local variable is the BEGIN ... END block within which it is declared.

  3. Server System Variables (prefixed with @@):

    The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSION or BOTH.

    Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.

    To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT @@var_name.

    SHOW VARIABLES LIKE '%wait_timeout%';
    
    SELECT @@sort_buffer_size;
    

    They can be set at server startup using options on the command line or in an option file. Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:

    -- Syntax to Set value to a Global variable:
    SET GLOBAL sort_buffer_size=1000000;
    SET @@global.sort_buffer_size=1000000;
    
    -- Syntax to Set value to a Session variable:
    SET sort_buffer_size=1000000;
    SET SESSION sort_buffer_size=1000000;
    SET @@sort_buffer_size=1000000;
    SET @@local.sort_buffer_size=10000;
    

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

In my case, this error was caused by renaming my client machine. I used a new name longer than 13 characters (despite the warning), which resulted in the NETBIOS name being truncated and being different from the full machine name. Once I re-renamed the client to a shorter name, the error went away.

Declaring a variable and setting its value from a SELECT query in Oracle

Not entirely sure what you are after but in PL/SQL you would simply

DECLARE
  v_variable INTEGER;
BEGIN
  SELECT mycolumn
    INTO v_variable
    FROM myTable;
END;

Ollie.

MySQL high CPU usage

First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.

Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.

Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.

Some other things you can check would be to run the following query while the CPU load is high:

SHOW PROCESSLIST;

This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).

You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.

You'll also probably want to give the following a read over as they contain some good information.

It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.

How to convert string to long

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");

Does Go have "if x in" construct similar to Python?

The above example using sort is close, but in the case of strings simply use SearchString:

files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.SearchStrings(files, target)
if i < len(files) && files[i] == target {
    fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}

https://golang.org/pkg/sort/#SearchStrings

Media query to detect if device is touchscreen

In 2017, CSS media query from second answer still doesn't work on Firefox. I found a soluton for that: -moz-touch-enabled


So, here is cross-browser media query:

@media (-moz-touch-enabled: 1), (pointer:coarse) {
    .something {
        its: working;
    }
}

How to use a servlet filter in Java to change an incoming servlet request url?

You could use the ready to use Url Rewrite Filter with a rule like this one:

<rule>
  <from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
  <to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>

Check the Examples for more... examples.

Validate select box

   <script type="text/JavaScript">  
function validate() 
{
if( document.form1.quali.value == "-1" )
   {
     alert( "Please select qualification!" );
     return false;
   }
}

</script>
<form name="form1" method="post" action="" onsubmit="return validate(this);">
<select name="quali" id="quali" ">
        <option value="-1" selected="selected">select</option>
        <option value="1">Graduate</option>
        <option value="2">Post Graduate</option>
      </select> 
</form>





// this code works 110% tested by me after many complex jquery method validation but it is simple javascript method plz try this if u fail in drop down required validation//

Give all permissions to a user on a PostgreSQL database

GRANT ALL PRIVILEGES ON DATABASE "my_db" to my_user;

Redirect on select option in select box

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value=""></option>
    <option value="http://google.com">Google</option>
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

How can I check for "undefined" in JavaScript?

    var x;
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("I am not even declared.")
    };

    /* One more thing to understand: typeof ==='undefined' also checks 
       for if a variable is declared, but no value is assigned. In other 
       words, the variable is declared, but not defined. */

    // Will repeat above logic of x for typeof === 'undefined'
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    /* So typeof === 'undefined' works for both, but x === undefined 
       only works for a variable which is at least declared. */

    /* Say if I try using typeof === undefined (not in quotes) for 
       a variable which is not even declared, we will get run a 
       time error. */

    if (z === undefined) {
        alert ("I am neither declared nor defined.")
    };
    // I got this error for z ReferenceError: z is not defined 

Detecting when user scrolls to bottom of div with jQuery

$(window).on("scroll", function() {
    //get height of the (browser) window aka viewport
    var scrollHeight = $(document).height();
    // get height of the document 
    var scrollPosition = $(window).height() + $(window).scrollTop();
    if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
        // code to run when scroll to bottom of the page
    }
});

This is the code on github.

How to extract Month from date in R

?month states:

Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.

Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE). You have to convert your vector to some datetime class, for instance to POSIXlt:

library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4

There's also a convenience function dmy, that can do the same (tip proposed by @Henrik):

month(dmy(some_date))
[1] 2 4

Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:

month(some_date)
[1] 2 4

For a list of formats, see ?strptime. You'll find that "standard unambiguous format" stands for

The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.

Removing "http://" from a string

preg_replace('/^[^:\/?]+:\/\//','',$url); 

some results:

input: http://php.net/preg_replace output: php.net/preg_replace  input: https://www.php.net/preg_replace output: www.php.net/preg_replace  input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace  input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com 

Regular expression to match balanced parentheses

[^\(]*(\(.*\))[^\)]*

[^\(]* matches everything that isn't an opening bracket at the beginning of the string, (\(.*\)) captures the required substring enclosed in brackets, and [^\)]* matches everything that isn't a closing bracket at the end of the string. Note that this expression does not attempt to match brackets; a simple parser (see dehmann's answer) would be more suitable for that.

What does java.lang.Thread.interrupt() do?

Thread.interrupt() sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted() can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

Where can I find "make" program for Mac OS X Lion?

Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

How to make bootstrap 3 fluid layout without horizontal scrollbar

You can add a 10px padding on the sides to your body element if all it's children are rows

body {
  padding: 0 10px;
}

if your HTML markup looks something like this:

<body>
    <div class="row"></div>
    <div class="row"></div>
    <div class="row"></div>
</body>

The rows have a 10 px negative margin. That's what's causing the overflow. If you add 10px padding to the body, they will cancel each other out.

Is there any difference between GROUP BY and DISTINCT

Please don't use GROUP BY when you mean DISTINCT, even if they happen to work the same. I'm assuming you're trying to shave off milliseconds from queries, and I have to point out that developer time is orders of magnitude more expensive than computer time.

How to convert a currency string to a double with jQuery or Javascript?

var parseCurrency = function (e) {
    if (typeof (e) === 'number') return e;
    if (typeof (e) === 'string') {
        var str = e.trim();
        var value = Number(e.replace(/[^0-9.-]+/g, ""));
        return str.startsWith('(') && str.endsWith(')') ? -value: value;
    }

    return e;
} 

Facebook Graph API : get larger pictures in one request

You can use full_picture instead of picture key to get full size image.

Beautiful way to remove GET-variables with PHP?

How about a function to rewrite the query string by looping through the $_GET array

! Rough outline of a suitable function

function query_string_exclude($exclude, $subject = $_GET, $array_prefix=''){
   $query_params = array;
   foreach($subject as $key=>$var){
      if(!in_array($key,$exclude)){
         if(is_array($var)){ //recursive call into sub array
            $query_params[]  = query_string_exclude($exclude, $var, $array_prefix.'['.$key.']');
         }else{
            $query_params[] = (!empty($array_prefix)?$array_prefix.'['.$key.']':$key).'='.$var;
         }
      }
   }

   return implode('&',$query_params);
}

Something like this would be good to keep handy for pagination links etc.

<a href="?p=3&<?= query_string_exclude(array('p')) ?>" title="Click for page 3">Page 3</a>

Escaping double quotes in JavaScript onClick event handler

You may also want to try two backslashes (\\") to escape the escape character.

Change bullets color of an HTML list without using span

I really liked Marc's answer too - I needed a set of different colored ULs and obviously it would be easier just to use a class. Here is what I used for orange, for example:

ul.orange {
    list-style: none;
    padding: 0px;
}
ul.orange > li:before {
    content: '\25CF ';
    font-size: 15px;
    color: #F00;
    margin-right: 10px;
    padding: 0px;
    line-height: 15px;
}

Plus, I found that the hex code I used for "content:" was different than Marc's (that hex circle seemed to sit a bit too high). The one I used seems to sit perfectly in the middle. I also found several other shapes (squares, triangles, circles, etc.) right here

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

The problem might probably be due to the mismatch of the extension types given by the programmer and the actual extensions of the images present in the drawable folder of your app. or fixing this follow the steps given below:-

Step 1- Double click on each of the image resources and and check the extension i.e whether the image is png or jpeg or any other format.

Step 2- Now check if the same extension is given by you in the drawable folder dropdown in package explorer(a.k.a Android in Android Studio).

Step 3 - If the extensions are not matching then delete that image and paste another image of the same name in its place making sure the extension is matching with the actual extension of the image (for example, if the image is "a.png" then make sure the extension of the image given by you is also of .png type) .

Step 4 - Sync your gradle file and run the project. This time there should be no errors.

How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Remote Connections Mysql Ubuntu

Add few points on top of apesa's excellent post:

1) You can use command below to check the ip address mysql server is listening

netstat -nlt | grep 3306

sample result:

tcp 0  0  xxx.xxx.xxx.xxx:3306  0.0.0.0:*   LISTEN

2) Use FLUSH PRIVILEGES to force grant tables to be loaded if for some reason the changes not take effective immediately

GRANT ALL ON *.* TO 'user'@'localhost' IDENTIFIED BY 'passwd' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'user'@'%' IDENTIFIED BY 'passwd' WITH GRANT OPTION;
FLUSH PRIVILEGES; 
EXIT;

user == the user u use to connect to mysql ex.root
passwd == the password u use to connect to mysql with

3) If netfilter firewall is enabled (sudo ufw enable) on mysql server machine, do the following to open port 3306 for remote access:

sudo ufw allow 3306

check status using

sudo ufw status

4) Once a remote connection is established, it can be verified in either client or server machine using commands

netstat -an | grep 3306
netstat -an | grep -i established

How to replace url parameter with javascript/jquery?

The following solution combines other answers and handles some special cases:

  • The parameter does not exist in the original url
  • The parameter is the only parameter
  • The parameter is first or last
  • The new parameter value is the same as the old
  • The url ends with a ? character
  • \b ensures another parameter ending with paramName won't be matched

Solution:

function replaceUrlParam(url, paramName, paramValue)
{
    if (paramValue == null) {
        paramValue = '';
    }
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

Meaning of @classmethod and @staticmethod for beginner?

One would use @classmethod when he/she would want to change the behaviour of the method based on which subclass is calling the method. remember we have a reference to the calling class in a class method.

While using static you would want the behaviour to remain unchanged across subclasses

Example:

class Hero:

  @staticmethod
  def say_hello():
     print("Helllo...")

  @classmethod
  def say_class_hello(cls):
     if(cls.__name__=="HeroSon"):
        print("Hi Kido")
     elif(cls.__name__=="HeroDaughter"):
        print("Hi Princess")

class HeroSon(Hero):
  def say_son_hello(self):
     print("test  hello")



class HeroDaughter(Hero):
  def say_daughter_hello(self):
     print("test  hello daughter")


testson = HeroSon()

testson.say_class_hello() #Output: "Hi Kido"

testson.say_hello() #Outputs: "Helllo..."

testdaughter = HeroDaughter()

testdaughter.say_class_hello() #Outputs: "Hi Princess"

testdaughter.say_hello() #Outputs: "Helllo..."

How to upgrade Git on Windows to the latest version?

Git Bash

Note, if you are instead looking to find out what version of Git Bash you are running, or want to see if you need to update Git Bash, it is part of Git for Windows.

So your Git Bash version is:

git --version

git version 2.23.0.windows.1

Note that it is technically different from Bash. On my same machine when I run:

echo $BASH_VERSION

4.4.23(1)-release

Git for Windows installer

To update to the latest version of Git and Git Bash, you can download and install the latest version of git for Windows. As per FAQ, settings/customizations should be preserved if they were installed in the appropriate configuration folders.

Note: Their installer is actually intelligently designed to do the right thing (except for telling you that it's doing the right thing automatically). If you are doing an update, then every screen on the installer is pre-marked with the settings from your current (soon to be previous) install.

It is not showing you generic default settings. You do not need to look any of them up, or fear for breaking your carefully honed setup. Just leave everything as is, to retain your previous choices.

In fact, they made it even easier (if only it was clear that they did so).
There is a checkbox at the bottom [] Show only new settings (I don't remember the exact wording). Since nothing on the first screen changes when you mark the box, it is not exactly obvious what it is for. If you mark the box, then all of your current settings will be retained, and it will skip showing those subsequent settings screens to you. Only screens with newly introduced settings will be shown.

git update-git-for-windows

Alternatively, as others have noted, you can also update Git Bash and Git (by definition, both are always updated at the same time) from the Git Bash command line, via:

git update-git-for-windows  

If you type git update, git kindly reminds you that the command has been updated to git update-git-for-windows:

Warning! git update has been deprecated;
Please use git update-git-for-windows instead.
Git for Windows 2.26.0.windows.1 (64bit)
Up to date

How to remove margin space around body or clear default css styles

I found this problem continued even when setting the BODY MARGIN to zero.

However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.

body { margin:0px; }

header { border:1px black solid; }

If you have any H1, H2, tags within your HEADER you will also need to set the MARGIN for these tags to zero, this will get rid of any extra space which may show up.

Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)

How to split page into 4 equal parts?

try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.

 <html>
   <head>
   <title>CSS devide window by 25% horizontally</title>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
   <style type="text/css" media="screen"> 
     body {
     margin:0;
     padding:0;
     height:100%;
     }
     #top_div
     {
       height:25%;
       width:100%;
       background-color:#009900;
       margin:auto;
       text-align:center;
     }
     #mid1_div
     {
       height:25%;
       width:100%;
       background-color:#990000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
     #mid2_div
     {
       height:25%;
       width:100%;
       background-color:#000000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
     #bottom_div
     {
       height:25%;
       width:100%;
       background-color:#990000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
   </style>
   </head>
   <body>
     <div id="top_div">Top- height is 25% of window height</div>
     <div id="mid1_div">Middle 1 - height is 25% of window height</div>
     <div id="mid2_div">Middle 2 - height is 25% of window height</div>
     <div id="bottom_div">Bottom - height is 25% of window height</div>
   </body>
 </html>

Tested and works fine, copy the code above into a HTML file, and open with your browser.

check if file exists in php

You can also use PHP get_headers() function.

Example:

function check_file_exists_here($url){
   $result=get_headers($url);
   return stripos($result[0],"200 OK")?true:false; //check if $result[0] has 200 OK
}

if(check_file_exists_here("http://www.mywebsite.com/file.pdf"))
   echo "This file exists";
else
   echo "This file does not exist";

Launch Pycharm from command line (terminal)

Easy solution without need for pathes:

open -b com.jetbrains.pycharm



You can set it as alias for every-day easier usage (put to your .bash_rc etc.):

alias pycharm='open -b com.jetbrains.pycharm'

Usage:

pycharm .
pycharm file.py

How to get the real and total length of char * (char array)?

You could try this:

int lengthChar(const char* chararray) {
   int n = 0;
   while(chararray[n] != '\0')
     n ++;
   return n;  
}

Check if a JavaScript string is a URL

This seems to be one of the hardest problems in CS ;)

Here's another incomplete solution that works well enough for me and better than the others I've seen here. I'm using a input[type=url] for this in order to support IE11, otherwise it would be much simpler using window.URL to perform the validation instead:

_x000D_
_x000D_
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;_x000D_
function isValidIpv4(ip) {_x000D_
  if (!ipv4Regex.test(ip)) return false;_x000D_
  return !ip.split('.').find(n => n > 255);_x000D_
}_x000D_
_x000D_
const domainRegex = /(?:[a-z0-9-]{1,63}\.){1,125}[a-z]{2,63}$/i;_x000D_
function isValidDomain(domain) {_x000D_
  return isValidIpv4(domain) || domainRegex.test(domain);_x000D_
}_x000D_
_x000D_
let input;_x000D_
function validateUrl(url) {_x000D_
  if (! /^https?:\/\//.test(url)) url = `http://${url}`; // assuming Babel is used_x000D_
  // to support IE11 we'll resort to input[type=url] instead of window.URL:_x000D_
  // try { return isValidDomain(new URL(url).host) && url; } catch(e) { return false; }_x000D_
  if (!input) { input = document.createElement('input'); input.type = 'url'; }_x000D_
  input.value = url;_x000D_
  if (! input.validity.valid) return false;_x000D_
  const domain = url.split(/^https?:\/\//)[1].split('/')[0].split('@').pop();_x000D_
  return isValidDomain(domain) && url;_x000D_
}_x000D_
_x000D_
console.log(validateUrl('google'), // false_x000D_
  validateUrl('user:[email protected]'),_x000D_
  validateUrl('https://google.com'),_x000D_
  validateUrl('100.100.100.100/abc'),_x000D_
  validateUrl('100.100.100.256/abc')); // false
_x000D_
_x000D_
_x000D_

In order to accept incomplete inputs such as "www.mydomain.com" it will also make it valid assuming the protocol is "http" in those cases and returning the valid URL if the address is valid. It returns false when invalid.

It also supports IPv4 domains, but not IPv6.

Refresh Part of Page (div)

$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request. among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .

Map enum in JPA with fixed values?

This is now possible with JPA 2.1:

@Column(name = "RIGHT")
@Enumerated(EnumType.STRING)
private Right right;

Further details:

How do I remove lines between ListViews on Android?

You can try the following. It worked for me...

android:divider="@android:color/transparent"
android:dividerHeight="0dp" 

Amazon AWS Filezilla transfer permission denied

If you're using Ubuntu then use the following:

sudo chown -R ubuntu /var/www/html

sudo chmod -R 755 /var/www/html

Best way to convert IList or IEnumerable to Array

Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray() and be done with it.

If you only have a non-generic IEnumerable, do something like this:

IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();

If you don't know the type within that method but the method's callers do know it, make the method generic and try this:

public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}

executing shell command in background from script

This works because the it's a static variable. You could do something much cooler like this:

filename="filename"
extension="txt"
for i in {1..20}; do
    eval "filename${i}=${filename}${i}.${extension}"
    touch filename${i}
    echo "this rox" > filename${i}
done

This code will create 20 files and dynamically set 20 variables. Of course you could use an array, but I'm just showing you the feature :). Note that you can use the variables $filename1, $filename2, $filename3... because they were created with evaluate command. In this case I'm just creating files, but you could use to create dynamically arguments to the commands, and then execute in background.

GET and POST methods with the same Action name in the same Controller

I like to accept a form post for my POST actions, even if I don't need it. For me it just feels like the right thing to do as you're supposedly posting something.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //Code...
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }
}

BeautifulSoup: extract text from anchor tag

>>> txt = '<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a> '
>>> fragment = bs4.BeautifulSoup(txt)
>>> fragment
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a> 
>>> fragment.find('a', {'class': 'title'})
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a>
>>> fragment.find('a', {'class': 'title'}).string
u'Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)'

How can I query a value in SQL Server XML column

I used the below statement to retrieve the values in the XML in the Sql table

with xmlnamespaces(default 'http://test.com/2008/06/23/HL.OnlineContract.ValueObjects')
select * from (
select
            OnlineContractID,
            DistributorID,
            SponsorID,
    [RequestXML].value(N'/OnlineContractDS[1]/Properties[1]/Name[1]', 'nvarchar(30)') as [Name]
   ,[RequestXML].value(N'/OnlineContractDS[1]/Properties[1]/Value[1]', 'nvarchar(30)') as [Value]
     ,[RequestXML].value(N'/OnlineContractDS[1]/Locale[1]', 'nvarchar(30)') as [Locale]
from [OnlineContract]) as olc
where olc.Name like '%EMAIL%' and olc.Value like '%EMAIL%' and olc.Locale='UK EN'

How to get line count of a large file cheaply in Python?

Why wouldn't the following work?

import sys

# input comes from STDIN
file = sys.stdin
data = file.readlines()

# get total number of lines in file
lines = len(data)

print lines

In this case, the len function uses the input lines as a means of determining the length.

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views