Programs & Examples On #Array algorithms

Array Algorithms are defined as functional algorithms where each step of the algorithm results in a function being applied to an array, producing an array result

Default Activity not found in Android Studio

In Android Studio, right click on the project and choose Open Module Settings. Then go to the Sources tab in your module, find the src folder, right click on it and mark it as Sources (blue color).

EDIT: There is no sources tab in later versions of Android Studio, but you can edit the build.gradle file instead: https://stackoverflow.com/a/22028681/1101730 (thanks for comment Josh)

Easy way to test an LDAP User's Credentials

You should check out Softerra's LDAP Browser (the free version of LDAP Administrator), which can be downloaded here :

http://www.ldapbrowser.com/download.htm

I've used this application extensively for all my Active Directory, OpenLDAP, and Novell eDirectory development, and it has been absolutely invaluable.

If you just want to check and see if a username\password combination works, all you need to do is create a "Profile" for the LDAP server, and then enter the credentials during Step 3 of the creation process :

enter image description here

By clicking "Finish", you'll effectively issue a bind to the server using the credentials, auth mechanism, and password you've specified. You'll be prompted if the bind does not work.

SQL Developer with JDK (64 bit) cannot find JVM

Today I try to use oracle client 64 and failed connect Connection Identifier which is defined at tnsnames.ora file. I assume that try to connect Oracle 32 Bit Server using SQL Developer 64 bit. That is why I install new jdk x86 and trying to change jdk path but this error happened:

msvcr100.dll error

Trying to download SQL Developer 32 Bit, but at the site said that the bundle support both 32 bit and 64 bit depend on java installed.

Windows 32-bit/64-bit: This archive. will work on a 32 or 64 bit Windows OS. The bit level of the JDK you install will determine if it runs as a 32 or 64 bit application. This download does not include the required Oracle Java JDK. You will need to install it if it's not already on your machine.

My java home is 64 bit. New installed 32 bit jdk is not set at java home.

I need to open $User_dir\AppData\Roaming\sqldeveloper\version\product.conf

Remove line SetJavaHome C:\Program Files\Java\jdk1.8.0_201

Start sqldeveloper.exe instead of sqldeveloper64W.exe

New popup will shown and choose java home to new jdk version (32 bit mine) :

C:\Program Files (x86)\Java\jdk1.8.0_201

My fault, I pin sqldeveloper64W.exe to taskbar, why that error occured then after I move cursor and it was sqldeveloper64W.exe, I try to click sqldeveloper.exe, then I found that my setting is goes well.

So check it maybe it was happened on your system too. If sqldeveloper.exe does not working, try to choose sqldeveloper64W.exe.

Now I can call my Connection Identifier which is defined at tnsnames.ora using new setting SQL developer 32 bit mode.

Cross-Origin Read Blocking (CORB)

Try to install "Moesif CORS" extension if you are facing issue in google chrome. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Eclipse not recognizing JVM 1.8

OK, so I don't really know what the problem was, but I simply fixed it by navigating to here http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html and installing 8u74 instead of 8u73 which is what I was prompted to do when I would go to "download latest version" in Java. So changing the versions is what did it in the end. Eclipse launched fine, now. Thanks for everyone's help!

edit: Apr 2018- Now is 8u161 and 8u162 (Just need one, I used 8u162 and it worked.)

mongodb: insert if not exists

As of MongoDB 2.4, you can use $setOnInsert (http://docs.mongodb.org/manual/reference/operator/setOnInsert/)

Set 'insertion_date' using $setOnInsert and 'last_update_date' using $set in your upsert command.

To turn your pseudocode into a working example:

now = datetime.utcnow()
for document in update:
    collection.update_one(
        {"_id": document["_id"]},
        {
            "$setOnInsert": {"insertion_date": now},
            "$set": {"last_update_date": now},
        },
        upsert=True,
    )

"Thinking in AngularJS" if I have a jQuery background?

To describe the "paradigm shift", I think a short answer can suffice.

AngularJS changes the way you find elements

In jQuery, you typically use selectors to find elements, and then wire them up:
$('#id .class').click(doStuff);

In AngularJS, you use directives to mark the elements directly, to wire them up:
<a ng-click="doStuff()">

AngularJS doesn't need (or want) you to find elements using selectors - the primary difference between AngularJS's jqLite versus full-blown jQuery is that jqLite does not support selectors.

So when people say "don't include jQuery at all", it's mainly because they don't want you to use selectors; they want you to learn to use directives instead. Direct, not select!

Webpack.config how to just copy the index.html to the dist folder

You can add the index directly to your entry config and using a file-loader to load it

module.exports = {

  entry: [
    __dirname + "/index.html",
    .. other js files here
  ],

  module: {
    rules: [
      {
        test: /\.html/, 
        loader: 'file-loader?name=[name].[ext]', 
      },
      .. other loaders
    ]
  }

}

Credentials for the SQL Server Agent service are invalid

the button 'Use same account' below thee main window will fill in all the textboxes automatically. this worked fpr me.

Print time in a batch file (milliseconds)

You have to be careful with what you want to do, because it is not just about to get the time.

The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.

%Date%:

  • dd.MM.yyyy
  • dd.MM.yy
  • d.M.yy
  • dd/MM/yy
  • yyyy-MM-dd

%TIME%:

  • H:mm:ss,msec
  • HH:mm:ss,msec

Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.

The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.

I am using the wmic windows builtin utility to request such things (put it in a script file):

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE`) do if "%%i" == "LocalDateTime" echo.%%j

or type it in the cmd.exe console:

for /F "usebackq tokens=1,2 delims==" %i in (`wmic os get LocalDateTime /VALUE`) do @if "%i" == "LocalDateTime" echo.%j

The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.

If you want to continue use this then you can write something like this (get_datetime.bat):

@echo off

rem Description:
rem   Independent to Windows locale date/time request.

rem Drop last error level
cd .

rem drop return value
set "RETURN_VALUE="

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if "%%i" == "LocalDateTime" set "RETURN_VALUE=%%j"

if not "%RETURN_VALUE%" == "" (
  set "RETURN_VALUE=%RETURN_VALUE:~0,18%"
  exit /b 0
)

exit /b 1

Now, you can parse %RETURN_VALUE% somethere in your script:

call get_datetime.bat
set "FILE_SUFFIX=%RETURN_VALUE:.=_%"
set "FILE_SUFFIX=%FILE_SUFFIX:~8,2%_%FILE_SUFFIX:~10,2%_%FILE_SUFFIX:~12,6%"
echo.%FILE_SUFFIX%

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

If you're open to use third party libraries,'Angular Filters' with a nice collection of filters may be useful:

https://github.com/a8m/angular-filter#filterby

collection | filterBy: [prop, nested.prop, etc..]: search

How to check if a registry value exists using C#?

For Registry Key you can check if it is null after getting it. It will be, if it doesn't exist.

For Registry Value you can get names of Values for the current key and check if this array contains the needed Value name.

Example:

public static bool checkMachineType()
{    
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    return (winLogonKey.GetValueNames().Contains("Start"));
}

Upgrading PHP on CentOS 6.5 (Final)

I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:

sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php

It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Insert all data of a datagridview to database at once

You have a syntax error Please try the following syntax as given below:

string StrQuery="INSERT INTO tableName VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "',' " + dataGridView1.Rows[i].Cells[1].Value + "', '" + dataGridView1.Rows[i].Cells[2].Value + "', '" + dataGridView1.Rows[i].Cells[3].Value + "',' " + dataGridView1.Rows[i].Cells[4].Value + "')";

How to send emails from my Android application?

This function first direct intent gmail for sending email, if gmail is not found then promote intent chooser. I used this function in many commercial app and it's working fine. Hope it will help you:

public static void sentEmail(Context mContext, String[] addresses, String subject, String body) {

    try {
        Intent sendIntentGmail = new Intent(Intent.ACTION_VIEW);
        sendIntentGmail.setType("plain/text");
        sendIntentGmail.setData(Uri.parse(TextUtils.join(",", addresses)));
        sendIntentGmail.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
        sendIntentGmail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentGmail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentGmail.putExtra(Intent.EXTRA_TEXT, body);
        mContext.startActivity(sendIntentGmail);
    } catch (Exception e) {
        //When Gmail App is not installed or disable
        Intent sendIntentIfGmailFail = new Intent(Intent.ACTION_SEND);
        sendIntentIfGmailFail.setType("*/*");
        sendIntentIfGmailFail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_TEXT, body);
        if (sendIntentIfGmailFail.resolveActivity(mContext.getPackageManager()) != null) {
            mContext.startActivity(sendIntentIfGmailFail);
        }
    }
}

Convert DateTime to long and also the other way around

Since you're using ToFileTime, you'll want to use FromFileTime to go the other way. But note:

Ordinarily, the FromFileTime method restores a DateTime value that was saved by the ToFileTime method. However, the two values may differ under the following conditions:

If the serialization and deserialization of the DateTime value occur in different time zones. For example, if a DateTime value with a time of 12:30 P.M. in the U.S. Eastern Time zone is serialized, and then deserialized in the U.S. Pacific Time zone, the original value of 12:30 P.M. is adjusted to 9:30 A.M. to reflect the difference between the two time zones.

If the DateTime value that is serialized represents an invalid time in the local time zone. In this case, the ToFileTime method adjusts the restored DateTime value so that it represents a valid time in the local time zone.

If you don't care which long representation of a DateTime is stored, you can use Ticks as others have suggested (Ticks is probably preferable, depending on your requirements, since the value returned by ToFileTime seems to be in the context of the Windows filesystem API).

(SC) DeleteService FAILED 1072

make sure the service is stopped, the services control panel is closed, and no open file handles are open by the service.

Also make sure ProcessExplorer is not running.

how to change class name of an element by jquery

$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

How to set root password to null

This is from MySQL 8.0.13:

use mysql;

update user set authentication_string=null  where user='root';

quit;

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

Calculate percentage Javascript

_x000D_
_x000D_
function calculate() {_x000D_
    // amount_x000D_
        var salary = parseInt($('#salary').val());_x000D_
    // percent    _x000D_
        var incentive_rate = parseInt($('#incentive_rate').val());_x000D_
        var perc = "";_x000D_
        if (isNaN(salary) || isNaN(incentive_rate)) {_x000D_
            perc = " ";_x000D_
        } else {_x000D_
            perc =  (incentive_rate/100) * salary;_x000D_
          _x000D_
_x000D_
        } $('#total_income').val(perc);_x000D_
    }
_x000D_
_x000D_
_x000D_

Alter and Assign Object Without Side Effects

You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.

Evaluate expression given as a string

Nowadays you can also use lazy_eval function from lazyeval package.

> lazyeval::lazy_eval("5+5")
[1] 10

Media query to detect if device is touchscreen

adding a class touchscreen to the body using JS or jQuery

  //allowing mobile only css
    var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
    if(isMobile){
        jQuery("body").attr("class",'touchscreen');
    }

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

Replace a string in a file with nodejs

This may help someone:

This is a little different than just a global replace

from the terminal we run
node replace.js

replace.js:

function processFile(inputFile, repString = "../") {
var fs = require('fs'),
    readline = require('readline'),
    instream = fs.createReadStream(inputFile),
    outstream = new (require('stream'))(),
    rl = readline.createInterface(instream, outstream);
    formatted = '';   

const regex = /<xsl:include href="([^"]*)" \/>$/gm;

rl.on('line', function (line) {
    let url = '';
    let m;
    while ((m = regex.exec(line)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        url = m[1];
    }

    let re = new RegExp('^.* <xsl:include href="(.*?)" \/>.*$', 'gm');

    formatted += line.replace(re, `\t<xsl:include href="${repString}${url}" />`);
    formatted += "\n";
});

rl.on('close', function (line) {
    fs.writeFile(inputFile, formatted, 'utf8', function (err) {
        if (err) return console.log(err);
    });

});
}


// path is relative to where your running the command from
processFile('build/some.xslt');

This is what this does. We have several file that have xml:includes

However in development we need the path to move down a level.

From this

<xsl:include href="common/some.xslt" />

to this

<xsl:include href="../common/some.xslt" />

So we end up running two regx patterns one to get the href and the other to write there is probably a better way to do this but it work for now.

Thanks

Java collections convert a string to a list of characters

IntStream can be used to access each character and add them to the list.

String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));

How can I get a specific parameter from location.search?

The following uses regular expressions and searches only on the query string portion of the URL.

Most importantly, this method supports normal and array parameters as in http://localhost/?fiz=zip&foo[]=!!=&bar=7890#hashhashhash

function getQueryParam(param) {
    var result =  window.location.search.match(
        new RegExp("(\\?|&)" + param + "(\\[\\])?=([^&]*)")
    );

    return result ? result[3] : false;
}

console.log(getQueryParam("fiz"));
console.log(getQueryParam("foo"));
console.log(getQueryParam("bar"));
console.log(getQueryParam("zxcv"));

Output:

zip
!!=
7890
false

How to embed a PDF viewer in a page?

I would really opt for FlowPaper, especially their new Elements mode that can be found here : https://flowpaper.com/demo/

It flattens the PDFs significantly at the same time as keeping text sharp which means that it will load much faster on mobile devices

Best practices for catching and re-throwing .NET exceptions

FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:

    private void foo()
    {
        try
        {
            bar(3);
            bar(2);
            bar(1);
            bar(0);
        }
        catch(DivideByZeroException)
        {
            //log message and rethrow...
            throw;
        }
    }

    private void bar(int b)
    {
        int a = 1;
        int c = a/b;  // Generate divide by zero exception.
    }

The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.

How do I tell what type of value is in a Perl variable?

A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.

If you want to know if it is a reference, you can use ref. If you want to know the reference type, you can use the reftype routine from Scalar::Util.

If you want to know if it is an object, you can use the blessed routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL has some methods to tell you about an object: if you want to check that it has the method you want to call, use can; if you want to see that it inherits from something, use isa; and if you want to see it the object handles a role, use DOES.

If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied. If you get an object, continue your checks.

If you want to know if it looks like a number, you can use looks_like_number from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.

If you need to do something more fancy, you can use a module such as Params::Validate.

Having the output of a console application in Visual Studio instead of the console

Instead, you can collect the output in a test result.

You can't supply input, but you can easily provide several tests with different command line arguments, each test collecting the output.

If your goal is debugging, this is a low effort way of offering a repeatable debugging scenario.

namespace Commandline.Test
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class CommandlineTests
    {
        [TestMethod]
        public void RunNoArguments()
        {
            Commandline.Program.Main(new string[0]);
        }
    }
}

How to ALTER multiple columns at once in SQL Server

Put ALTER COLUMN statement inside a bracket, it should work.

ALTER TABLE tblcommodityOHLC alter ( column  
CC_CommodityContractID NUMERIC(18,0), 
CM_CommodityID NUMERIC(18,0) )

How to get html to print return value of javascript function?

if you really wanted to do that you could then do

<script type="text/javascript">
    document.write(produceMessage())
</script>

Wherever in the document you want the message.

sudo: npm: command not found

I resolved this problem by

apt-get install npm2deb

Printing result of mysql query from variable

$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);

you can change LIMIT 1 to LIMIT any number you want

This will show you the last INSERTED row first.

HTML5 Pre-resize images before uploading

Typescript

async resizeImg(file: Blob): Promise<Blob> {
    let img = document.createElement("img");
    img.src = await new Promise<any>(resolve => {
        let reader = new FileReader();
        reader.onload = (e: any) => resolve(e.target.result);
        reader.readAsDataURL(file);
    });
    await new Promise(resolve => img.onload = resolve)
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    let MAX_WIDTH = 1000;
    let MAX_HEIGHT = 1000;
    let width = img.naturalWidth;
    let height = img.naturalHeight;
    if (width > height) {
        if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
        }
    } else {
        if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }
    }
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
    return result;
}

Finding an elements XPath using IE Developer tool

Are you trying to find some work around getting xpath in IE?

There are many add-ons for other browsers like xpather for Chrome or xpather, xpath-checker and firebug for FireFox that will give you the xpath of an element in a second. But sadly there is no add-on or tool available that will do this for IE. For most cases you can get the xpath of the elements that fall in your script using the above tools in Firefox and tweak them a little (if required) to make them work in IE.

But if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH. Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other firefox addon.

STEPS TO INSTALL BOOKMARKLETS

1)Open IE

2)Type about:blank in the address bar and hit enter

3)From Favorites main menu select ---> Add favorites

4) In the Add a favorite popup window enter name GetXPATH1.

5)Click add button in the add a favorite popup window.

6)Open the Favorites menu and right click the newly added favorite and select properties option.

7)GetXPATH1 Properties will open up. Select the web Document Tab.

8)Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

12)Enter the following in the URL field for GetXPATH2

javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At this point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

Using custom fonts using CSS?

If you dont find any fonts that you like from Google.com/webfonts or fontsquirrel.com you can always make your own web font with a font you made.

here's a nice tutorial: Make your own font face web font kit

Although im not sure about preventing someone from downloading your font.

Hope this helps,

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

AWS EFS vs EBS vs S3 (differences & when to use?)

This question is very much answered by other people, I just want to make a point whenever deciding on any service to be in AWS is that understanding the use case for each and also see the solution that the service will provide in terms of the Well-Architected Framework, do you need High Availability, Fault Torelant, Cost optimization. This will help to decide on any kind of service to be used.

how to destroy bootstrap modal window completely?

For 3.x version

$( '.modal' ).modal( 'hide' ).data( 'bs.modal', null );

For 2.x version (risky; read comments below) When you create bootstrap modal three elements on your page being changed. So if you want to completely rollback all changes, you have to do it manually for each of it.

$( '.modal' ).remove();
$( '.modal-backdrop' ).remove();
$( 'body' ).removeClass( "modal-open" );

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Get the time difference between two datetimes

When you call diff, moment.js calculates the difference in milliseconds. If the milliseconds is passed to duration, it is used to calculate duration which is correct. However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT). That is why you get 1969 as the year together with wrong hour.

duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")

So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.

HTML select dropdown list

_x000D_
_x000D_
<select>_x000D_
    <option value="" style="display:none">Choose one provider</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This way the user cannot see this option, but it shows in the select box.

Storing and retrieving datatable from session

A simple solution for a very common problem

                 // DECLARATION
                HttpContext context = HttpContext.Current;
                DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;

                // TRY TO ADD rows with the info into the DataTable
                try
                {
                    // Add new Serial Code into DataTable dt_ShoppingBasket
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_ShoppingBasket;
                }
                catch (Exception)
                {
                    // IF FAIL (EMPTY OR DOESN'T EXIST) - 
                    // Create new Instance, 
                    DataTable dt_ShoppingBasket= new DataTable();

                    // Add column and Row with the info
                    dt_ShoppingBasket.Columns.Add("Serial");
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_PanierCommande;
                }



                // PRINT TESTS
                DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;

                foreach (DataRow row in dt_To_Print.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        Debug.WriteLine("DATATABLE IN SESSION: " + item);
                    }
                }

How can I add a username and password to Jenkins?

Assuming you have Manage Jenkins > Configure Global Security > Enable Security and Jenkins Own User Database checked you would go to:

  • Manage Jenkins > Manage Users > Create User

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

Return Index of an Element in an Array Excel VBA

'To return the position of an element within any-dimension array  
'Returns 0 if the element is not in the array, and -1 if there is an error  
Public Function posInArray(ByVal itemSearched As Variant, ByVal aArray As Variant) As Long  
Dim pos As Long, item As Variant  

posInArray = -1  
If IsArray(aArray) Then  
    If not IsEmpty(aArray) Then  
        pos = 1  
        For Each item In aArray  
            If itemSearched = item Then  
                posInArray = pos  
                Exit Function  
            End If  
            pos = pos + 1  
        Next item  
        posInArray = 0  
    End If  
End If

End Function

How to iterate over columns of pandas dataframe to run regression

A workaround is to transpose the DataFrame and iterate over the rows.

for column_name, column in df.transpose().iterrows():
    print column_name

How do I get the absolute directory of a file in bash?

Try our new Bash library product realpath-lib over at GitHub that we have given to the community for free and unencumbered use. It's clean, simple and well documented so it's great to learn from. You can do:

get_realpath <absolute|relative|symlink|local file path>

This function is the core of the library:

if [[ -f "$1" ]]
then
    # file *must* exist
    if cd "$(echo "${1%/*}")" &>/dev/null
    then
        # file *may* not be local
        # exception is ./file.ext
        # try 'cd .; cd -;' *works!*
        local tmppwd="$PWD"
        cd - &>/dev/null
    else
        # file *must* be local
        local tmppwd="$PWD"
    fi
else
    # file *cannot* exist
    return 1 # failure
fi

# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success

}

It's Bash 4+, does not require any dependencies and also provides get_dirname, get_filename, get_stemname and validate_path.

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

Eclipse CDT: no rule to make target all

Project -> Clean -> Clean all Projects and then Project -> Build Project worked for me (I did the un-checking generate make-file automatically and then rechecking it before doing this). This was for an AVR (micro-processor programming) project through the AVR CDT plugin in eclipse Juno though.

Entity framework code-first null foreign key

I prefer this (below):

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

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

What's the difference between lists and tuples?

Lists are mutable; tuples are not.

From docs.python.org/2/tutorial/datastructures.html

Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

how to show only even or odd rows in sql server 2008?

for SQL > odd:

select * from id in(select id from employee where id%2=1)

for SQL > Even:

select * from id in(select id from employee where id%2=0).....f5

How do I format a number with commas in T-SQL?

Another UDF which is hopefully generic enough and does not make assumptions about whether you want to round to a specific number of decimal places:

CREATE FUNCTION [dbo].[fn_FormatNumber] (@number decimal(38,18))

RETURNS varchar(50)

BEGIN
    -- remove minus sign before applying thousands seperator
    DECLARE @negative bit
    SET @negative = CASE WHEN @number < 0 THEN 1 ELSE 0 END
    SET @number = ABS(@number)

    -- add thousands seperator for every 3 digits to the left of the decimal place
    DECLARE @pos int, @result varchar(50) = CAST(@number AS varchar(50))
    SELECT @pos = CHARINDEX('.', @result)
    WHILE @pos > 4
    BEGIN
        SET @result = STUFF(@result, @pos-3, 0, ',')
        SELECT @pos = CHARINDEX(',', @result)
    END

    -- remove trailing zeros
    WHILE RIGHT(@result, 1) = '0'
        SET @result = LEFT(@result, LEN(@result)-1)
    -- remove decimal place if not required
    IF RIGHT(@result, 1) = '.'
        SET @result = LEFT(@result, LEN(@result)-1)

    IF @negative = 1
        SET @result = '-' + @result

    RETURN @result
END

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

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

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

I'm answering my own question because it provides a better overview of the cause and possible solutions. I've awarded the bonus to @Martin because he pin pointed the cause.

Cause

As suggested by @Martin the cause is the use of multiple threads. The request object is not available in these threads, as mentioned in the Spring Guide:

DispatcherServlet, RequestContextListener and RequestContextFilter all do exactly the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain.

Solution 1

It is possible to make the request object available to other threads, but it places a couple of limitations on the system, which may not be workable in all projects. I got this solution from Accessing request scoped beans in a multi-threaded web application:

I managed to get around this issue. I started using SimpleAsyncTaskExecutor instead of WorkManagerTaskExecutor / ThreadPoolExecutorFactoryBean. The benefit is that SimpleAsyncTaskExecutor will never re-use threads. That's only half the solution. The other half of the solution is to use a RequestContextFilter instead of RequestContextListener. RequestContextFilter (as well as DispatcherServlet) has a threadContextInheritable property which basically allows child threads to inherit the parent context.

Solution 2

The only other option is to use the session scoped bean inside the request thread. In my case this wasn't possible because:

  1. The controller method is annotated with @Async;
  2. The controller method starts a batch job which uses threads for parallel job steps.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

How to echo in PHP, HTML tags

This will also work fine with double quotes. To echo any html_tag with double quotes we just need to remember one thing, Do not use any other double quotes(") in the middle.

<?php
    echo "
    <div>
        <h3><a href='https://stackoverflow.com/questions/3931351/how-to-echo-in-php-html-tags'>First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
        </div>
    <div>";
?>

Notice here the link inside the PHP echo is enclosed within the single quotes. This is the precaution you should take while using the double quotes for this purpose.

How to printf long long

  • Your scanf() statement needs to use %lld too.
  • Your loop does not have a terminating condition.
  • There are far too many parentheses and far too few spaces in the expression

    pi += pow(-1.0, e) / (2.0*e + 1.0);
    
  • You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
  • You should use an explicit return type of int for main().
  • On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
  • I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.

I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.

Read a local text file using Javascript

Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true); 
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>

MassAssignmentException in Laravel

Read this section of Laravel doc : http://laravel.com/docs/eloquent#mass-assignment

Laravel provides by default a protection against mass assignment security issues. That's why you have to manually define which fields could be "mass assigned" :

class User extends Model
{
    protected $fillable = ['username', 'email', 'password'];
}

Warning : be careful when you allow the mass assignment of critical fields like password or role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Solution»

Pass a keyword argument name with value as your view name e.g home or home-view etc. to url() function.

Throws Error»

url(r'^home$', 'common.views.view1', 'home'),

Correct»

url(r'^home$', 'common.views.view1', name='home'),

nano error: Error opening terminal: xterm-256color

  1. edit your .bash_profile file

    vim .bash_profile

  2. commnet

    #export TERM=xterm-256color

  3. add this

    export TERMINFO=/usr/share/terminfo

    export TERM=xterm-basic

    to your .bash_profile

  4. finally

    run:

    source .bash_profile

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Something like this (sounds like you just need to change your SMTP server):

String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
    i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
    i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

File Upload ASP.NET MVC 3.0

I am giving you the simple and easy method to understand and learn.

First you have to write the following code in your .Cshtml file.

<input name="Image" type="file" class="form-control" id="resume" />

then in your controller put following code:

if (i > 0) {
    HttpPostedFileBase file = Request.Files["Image"];


    if (file != null && file.ContentLength > 0) {
        if (!string.IsNullOrEmpty(file.FileName)) {
            string extension = Path.GetExtension(file.FileName);

            switch ((extension.ToLower())) {
                case ".doc":
                    break;
                case ".docx":
                    break;
                case ".pdf":
                    break;
                default:
                    ViewBag.result = "Please attach file with extension .doc , .docx , .pdf";
                    return View();
            }

            if (!Directory.Exists(Server.MapPath("~") + "\\Resume\\")) {
                System.IO.Directory.CreateDirectory(Server.MapPath("~") + "\\Resume\\");
            }

            string documentpath = Server.MapPath("~") + "\\Resume\\" + i + "_" + file.FileName;
            file.SaveAs(documentpath);
            string filename = i + "_" + file.FileName;
            result = _objbalResume.UpdateResume(filename, i);
            Attachment at = new Attachment(documentpath);

            //ViewBag.result = (ans == true ? "Thanks for contacting us.We will reply as soon as possible" : "There is some problem. Please try again later.");
        }
    } else {
        ...
    }
}

For this you have to make BAL and DAL layer as per your Database.

how to check confirm password field in form without reloading page

HTML CODE

        <input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

        <input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

JS CODE

function checkPass(){
         var pass  = document.getElementById("password").value;
         var rpass  = document.getElementById("rpassword").value;
        if(pass != rpass){
            document.getElementById("submit").disabled = true;
            $('.missmatch').html("Entered Password is not matching!! Try Again");
        }else{
            $('.missmatch').html("");
            document.getElementById("submit").disabled = false;
        }
}

Remove directory from remote repository after adding them to .gitignore

If you're working from PowerShell, try the following as a single command.

PS MyRepo> git filter-branch --force --index-filter
>> "git rm --cached --ignore-unmatch -r .\\\path\\\to\\\directory"
>> --prune-empty --tag-name-filter cat -- --all

Then, git push --force --all.

Documentation: https://git-scm.com/docs/git-filter-branch

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

If you're having this problem with Spring Boot 1.4.x and up, you might be able to use @OverrideAutoConfiguration(enabled=true) to solve the problem.

Similar to what was asked/answered here https://stackoverflow.com/a/39253304/1410035

HashMap allows duplicates?

Hashmap type Overwrite that key if hashmap key is same key

map.put("1","1111");
map.put("1","2222");

output

key:value
1:2222

How to get an array of unique values from an array containing duplicates in JavaScript?

It's 2014 now guys, and time complexity still matters!

array.filter(function() {
  var seen = {};
  return function(element, index, array) {
    return !(element in seen) && (seen[element] = 1);
  };
}());

http://jsperf.com/array-filter-unique/13

In SQL how to compare date values?

Your problem may be that you are dealing with DATETIME data, not just dates. If a row has a mydate that is '2008-11-25 09:30 AM', then your WHERE mydate<='2008-11-25'; is not going to return that row. '2008-11-25' has an implied time of 00:00 (midnight), so even though the date part is the same, they are not equal, and mydate is larger.

If you use < '2008-11-26' instead of <= '2008-11-25', that would work. The Datediff method works because it compares just the date portion, and ignores the times.

Is it possible to remove inline styles with jQuery?

The easiest way to remove inline styles (generated by jQuery) would be:

$(this).attr("style", "");

The inline code should disappear and your object should adapt the style predefined in your CSS files.

Worked for me!

Owl Carousel, making custom navigation

my solution is

navigationText: ["", ""]

full code is below:

    var owl1 = $("#main-demo");
    owl1.owlCarousel({
        navigation: true, // Show next and prev buttons
        slideSpeed: 300,
        pagination:false,
        singleItem: true, transitionStyle: "fade",
        navigationText: ["", ""]
    });// Custom Navigation Events

    owl1.trigger('owl.play', 4500);

Display Back Arrow on Toolbar

There are many ways to achieve that, here is my favorite:

Layout:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:navigationIcon="?attr/homeAsUpIndicator" />

Activity:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // back button pressed
        }
    });

Big O, how do you calculate/approximate it?

Break down the algorithm into pieces you know the big O notation for, and combine through big O operators. That's the only way I know of.

For more information, check the Wikipedia page on the subject.

How to compare timestamp dates with date-only parameter in MySQL?

As suggested by some, by using DATE(timestamp) you are applying manipulation to the column and therefore you cannot rely on the index ordering.

However, using BETWEEN would only be reliable if you include the milliseconds. In the example timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59' you exclude records with a timestamp between 2012-05-05 23:59:59.001 and 2012-05-05 23:59:59.999. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.

The best thing to do is:

SELECT * FROM table
WHERE date>='2012-05-05' AND date<'2012-05-06'

What's the best UI for entering date of birth?

you can use plugin cxcalendar. It looks like other datepicker. but you can pick year and month in select after clicking year-month title.

enter image description here

Can you hide the controls of a YouTube embed without enabling autoplay?

Set autoplay=0

<iframe width="100%" height="100%" src="//www.youtube.com/embed/qUJYqhKZrwA?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen>

As seen here: Autoplay=0 Test

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

TypeError: $ is not a function WordPress

Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.

  1. Wrap your code using:

    <script> 
    jQuery(function($) {
    
    YOUR CODE GOES HERE
    
    });
    </script>
    
  2. You can also use jQuery's API using noConflict();

    <script>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
    // Code that uses jQuery's $ can follow here.
    });
    // Code that uses other library's $ can follow here.
    </script>
    
  3. Another example of using noConflict without using document ready:

    <script>
    jQuery.noConflict();
        (function( $ ) {
            $(function() { 
                // YOUR CODE HERE
            });
         });
    </script>
    
  4. You could even choose to create your very alias to avoid conflicts like so:

    var jExample = jQuery.noConflict();
    // Do something with jQuery
    jExample( "div p" ).hide();
    
  5. Yet another longer solution is to rename all referances of $ to jQuery:

    $( "div p" ).hide(); to jQuery( "div p" ).hide();

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Submitting a form on 'Enter' with jQuery?

I use now

$("form").submit(function(event){
...
}

At first I added an eventhandler to the submit button which produced an error for me.

Java: Static Class?

Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.

But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability

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

None of the solutions posted here worked for me. It was devenv.exe (Visual Studio) locking the file, but if I restarted it, it would re-lock it.

Bizarrely, Windows wouldn't let me Delete the files (to Recycle Bin), but Shift+Delete (permanent delete) worked.

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

Razor Views not seeing System.Web.Mvc.HtmlHelper

I used the following article on MSDN to solve this issue (in this case from MVC 4 to MVC 5)

https://docs.microsoft.com/en-us/aspnet/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

Main extracts from the article are:

Main Web.config (Not the one in the Views folder)

In the runtime block update System.Web.Mvc to 5.0.0.0 ,System.Web.Helpers to 3.0.0.0 and System.Web.WebPages to 3.0.0.0

<dependentAssembly>
  <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>

<dependentAssembly>
  <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

<dependentAssembly>
  <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>

Then look for the appsettings block and update the webpages:Version value to 3.0.0.0

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
</appSettings>

Views Web.config

Update the host factoryType block to System.Web.Mvc to 5.0.0.0

<system.web.webPages.razor>
   <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
   <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
         <add namespace="System.Web.Mvc" />
      </namespaces>
   </pages>
</system.web.webPages.razor>

Then under the pages block update any references to System.Web.Mvc to 5.0.0.0

    <pages
      validateRequest="false"
      pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <controls>
      <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
    </controls>
  </pages>

And finally under the configuration block update the System.Web references to 3.0.0.0

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

IllegalArgumentException or NullPointerException for a null parameter?

If you choose to throw a NPE and you are using the argument in your method, it might be redundant and expensive to explicitly check for a null. I think the VM already does that for you.

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with

for (const field of Object.keys(this.formErrors)) {

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

Calculate cosine similarity given 2 sentence strings

Well, if you are aware of word embeddings like Glove/Word2Vec/Numberbatch, your job is half done. If not let me explain how this can be tackled. Convert each sentence into word tokens, and represent each of these tokens as vectors of high dimension (using the pre-trained word embeddings, or you could train them yourself even!). So, now you just don't capture their surface similarity but rather extract the meaning of each word which comprise the sentence as a whole. After this calculate their cosine similarity and you are set.

Is it valid to replace http:// with // in a <script src="http://...">?

We are seeing 404 errors in our logs when using //somedomain.com as references to JS files.

The references that cause the 404s come out looking like this: ref:

<script src="//somedomain.com/somescript.js" />

404 request:

http://mydomain.com//somedomain.com/somescript.js

With these showing up regularly in our web server logs, it is safe to say that: All browsers and Bots DO NOT honor RFC 3986 section 4.2. The safest bet is to include the protocol whenever possible.

(Deep) copying an array using jQuery

If you want to use pure JavaScript then try this:

 var arr=["apple","ball","cat","dog"];
 var narr=[];

 for(var i=0;i<arr.length;i++){
     narr.push(arr[i]);
 }
 alert(narr); //output: apple,ball,vat,dog
 narr.push("elephant");
 alert(arr); // output: apple,ball,vat,dog
 alert(narr); // apple,ball,vat,dog,elephant

What does "dereferencing" a pointer mean?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

int a = 10;
int* ptr = &a;

printf("%d", *ptr); // With *ptr I'm dereferencing the pointer. 
                    // Which means, I am asking the value pointed at by the pointer.
                    // ptr is pointing to the location in memory of the variable a.
                    // In a's location, we have 10. So, dereferencing gives this value.

// Since we have indirect control over a's location, we can modify its content using the pointer. This is an indirect way to access a.

 *ptr = 20;         // Now a's content is no longer 10, and has been modified to 20.

Pass array to MySQL stored routine

I've come up with an awkward but functional solution for my problem. It works for a one-dimensional array (more dimensions would be tricky) and input that fits into a varchar:

  declare pos int;           -- Keeping track of the next item's position
  declare item varchar(100); -- A single item of the input
  declare breaker int;       -- Safeguard for while loop 

  -- The string must end with the delimiter
  if right(inputString, 1) <> '|' then
     set inputString = concat(inputString, '|');
  end if;

  DROP TABLE IF EXISTS MyTemporaryTable;
  CREATE TEMPORARY TABLE MyTemporaryTable ( columnName varchar(100) );
  set breaker = 0;

  while (breaker < 2000) && (length(inputString) > 1) do
     -- Iterate looking for the delimiter, add rows to temporary table.
     set breaker = breaker + 1;
     set pos = INSTR(inputString, '|');
     set item = LEFT(inputString, pos - 1);
     set inputString = substring(inputString, pos + 1);
     insert into MyTemporaryTable values(item);
  end while;

For example, input for this code could be the string Apple|Banana|Orange. MyTemporaryTable will be populated with three rows containing the strings Apple, Banana, and Orange respectively.

I thought the slow speed of string handling would render this approach useless, but it was quick enough (only a fraction of a second for a 1,000 entries array).

Hope this helps somebody.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I did this way:

Step 1: Go to this folder

On Mac: /Users/<username>/.android/

On Windows: C:\Documents and Settings\<username>\.android\

On Linux: ~/.android/

Step 2: Run this command line:

keytool -list -v -keystore debug.keystore -storepass android

You will see the SHA-1 key.

How can I insert new line/carriage returns into an element.textContent?

Change the h1.textContent to h1.innerHTML and use <br> to go to the new line.

How to use ADB to send touch events to device using sendevent command?

Building on top of Tomas's answer, this is the best approach of finding the location tap position as an integer I found:

adb shell getevent -l | grep ABS_MT_POSITION --line-buffered | awk '{a = substr($0,54,8); sub(/^0+/, "", a); b = sprintf("0x%s",a); printf("%d\n",strtonum(b))}'

Use adb shell getevent -l to get a list of events, the using grep for ABS_MT_POSITION (gets the line with touch events in hex) and finally use awk to get the relevant hex values, strip them of zeros and convert hex to integer. This continuously prints the x and y coordinates in the terminal only when you press on the device.

You can then use this adb shell command to send the command:

adb shell input tap x y

Discard all and get clean copy of latest revision?

Those steps should be able to be shortened down to:

hg pull
hg update -r MY_BRANCH -C

The -C flag tells the update command to discard all local changes before updating.

However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge extension for that:

hg pull
hg update -r MY_BRANCH -C
hg purge

In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.

How can I convert radians to degrees with Python?

Python convert radians to degrees or degrees to radians:

What are Radians and what problem does it solve?:

Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:

https://en.wikipedia.org/wiki/Radian

Conversion from radians to degrees

Python examples using libraries calculating degrees from radians:

>>> import math
>>> math.degrees(0)                       #0 radians == 0 degrees
0.0
>>> math.degrees(math.pi/2)               #pi/2 radians is 90 degrees
90.0
>>> math.degrees(math.pi)                 #pi radians is 180 degrees
180.0      
>>> math.degrees(math.pi+(math.pi/2))     #pi+pi/2 radians is 270 degrees
270.0 
>>> math.degrees(math.pi+math.pi)         #2*pi radians is 360 degrees
360.0      

Python examples using libraries calculating radians from degrees:

>>> import math
>>> math.radians(0)           #0 degrees == 0 radians
0.0
>>> math.radians(90)          #90 degrees is pi/2 radians
1.5707963267948966
>>> math.radians(180)         #180 degrees is pi radians
3.141592653589793
>>> math.radians(270)         #270 degrees is pi+(pi/2) radians
4.71238898038469
>>> math.radians(360)         #360 degrees is 2*pi radians
6.283185307179586

Source: https://docs.python.org/3/library/math.html#angular-conversion

The mathematical notation:

Mathematical notation of degrees and radians

You can do degree/radian conversion without libraries:

If you roll your own degree/radian converter, you have to write your own code to handle edge cases.

Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter who sunk $125m dollars crashing it into Mars because of non intuitive edge cases here.

Lets crash that orbiter and Roll our own Radians to Degrees:

Invalid radians as input return garbage output.

>>> 0 * 180.0 / math.pi                         #0 radians is 0 degrees
0.0
>>> (math.pi/2) * 180.0 / math.pi               #pi/2 radians is 90 degrees
90.0
>>> (math.pi) * 180.0 / math.pi                 #pi radians is 180 degrees
180.0
>>> (math.pi+(math.pi/2)) * 180.0 / math.pi     #pi+(pi/2) radians is 270 degrees
270.0
>>> (2 * math.pi) * 180.0 / math.pi             #2*pi radians is 360 degrees
360.0

Degrees to radians:

>>> 0 * math.pi / 180.0              #0 degrees in radians
0.0
>>> 90 * math.pi / 180.0             #90 degrees in radians
1.5707963267948966
>>> 180 * math.pi / 180.0            #180 degrees in radians
3.141592653589793
>>> 270 * math.pi / 180.0            #270 degrees in radians
4.71238898038469
>>> 360 * math.pi / 180.0            #360 degrees in radians
6.283185307179586

Expressing multiple rotations with degrees and radians

Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.

>>> import math
>>> math.radians(360)                 #one complete rotation
6.283185307179586
>>> math.radians(360+360)             #two rotations
12.566370614359172
>>> math.degrees(12.566370614359172)  #math.degrees and math.radians preserve the
720.0                                 #number of rotations

Collapsing multiple rotations:

You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.

>>> import math
>>> math.radians(720+90)        #2 whole rotations plus 90 is 14.14 radians
14.137166941154069
>>> math.radians((720+90)%360)  #14.1 radians brings you to 
1.5707963267948966              #the end point as 1.57 radians.

>>> math.degrees((2*math.pi)+(math.pi/2))            #one rotation plus a quarter 
450.0                                                #rotation is 450 degrees.
>>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter
90.0                                                    #rotation brings you to 90.

Protip

Khan academy has some excellent content to solidify intuition around trigonometry and angular mathematics: https://www.khanacademy.org/math/algebra2/trig-functions/intro-to-radians-alg2/v/introduction-to-radians

SQL Call Stored Procedure for each Row without using a cursor

I usually do it this way when it's a quite a few rows:

  1. Select all sproc parameters in a dataset with SQL Management Studio
  2. Right-click -> Copy
  3. Paste in to excel
  4. Create single-row sql statements with a formula like '="EXEC schema.mysproc @param=" & A2' in a new excel column. (Where A2 is your excel column containing the parameter)
  5. Copy the list of excel statements into a new query in SQL Management Studio and execute.
  6. Done.

(On larger datasets i'd use one of the solutions mentioned above though).

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

Best way to replace multiple characters in a string?

Simply chain the replace functions like this

strs = "abc&def#ghi"
print strs.replace('&', '\&').replace('#', '\#')
# abc\&def\#ghi

If the replacements are going to be more in number, you can do this in this generic way

strs, replacements = "abc&def#ghi", {"&": "\&", "#": "\#"}
print "".join([replacements.get(c, c) for c in strs])
# abc\&def\#ghi

Nested or Inner Class in PHP

Intro:

Nested classes relate to other classes a little differently than outer classes. Taking Java as an example:

Non-static nested classes have access to other members of the enclosing class, even if they are declared private. Also, non-static nested classes require an instance of the parent class to be instantiated.

OuterClass outerObj = new OuterClass(arguments);
outerObj.InnerClass innerObj = outerObj.new InnerClass(arguments);

There are several compelling reasons for using them:

  • It is a way of logically grouping classes that are only used in one place.

If a class is useful to only one other class, then it is logical to relate and embed it in that class and keep the two together.

  • It increases encapsulation.

Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

  • Nested classes can lead to more readable and maintainable code.

A nested class usually relates to it's parent class and together form a "package"

In PHP

You can have similar behavior in PHP without nested classes.

If all you want to achieve is structure/organization, as Package.OuterClass.InnerClass, PHP namespaces might sufice. You can even declare more than one namespace in the same file (although, due to standard autoloading features, that might not be advisable).

namespace;
class OuterClass {}

namespace OuterClass;
class InnerClass {}

If you desire to emulate other characteristics, such as member visibility, it takes a little more effort.

Defining the "package" class

namespace {

    class Package {

        /* protect constructor so that objects can't be instantiated from outside
         * Since all classes inherit from Package class, they can instantiate eachother
         * simulating protected InnerClasses
         */
        protected function __construct() {}

        /* This magic method is called everytime an inaccessible method is called 
         * (either by visibility contrains or it doesn't exist)
         * Here we are simulating shared protected methods across "package" classes
         * This method is inherited by all child classes of Package 
         */
        public function __call($method, $args) {

            //class name
            $class = get_class($this);

            /* we check if a method exists, if not we throw an exception 
             * similar to the default error
             */
            if (method_exists($this, $method)) {

                /* The method exists so now we want to know if the 
                 * caller is a child of our Package class. If not we throw an exception
                 * Note: This is a kind of a dirty way of finding out who's
                 * calling the method by using debug_backtrace and reflection 
                 */
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
                if (isset($trace[2])) {
                    $ref = new ReflectionClass($trace[2]['class']);
                    if ($ref->isSubclassOf(__CLASS__)) {
                        return $this->$method($args);
                    }
                }
                throw new \Exception("Call to private method $class::$method()");
            } else {
                throw new \Exception("Call to undefined method $class::$method()");
            }
        }
    }
}

Use case

namespace Package {
    class MyParent extends \Package {
        public $publicChild;
        protected $protectedChild;

        public function __construct() {
            //instantiate public child inside parent
            $this->publicChild = new \Package\MyParent\PublicChild();
            //instantiate protected child inside parent
            $this->protectedChild = new \Package\MyParent\ProtectedChild();
        }

        public function test() {
            echo "Call from parent -> ";
            $this->publicChild->protectedMethod();
            $this->protectedChild->protectedMethod();

            echo "<br>Siblings<br>";
            $this->publicChild->callSibling($this->protectedChild);
        }
    }
}

namespace Package\MyParent
{
    class PublicChild extends \Package {
        //Makes the constructor public, hence callable from outside 
        public function __construct() {}
        protected function protectedMethod() {
            echo "I'm ".get_class($this)." protected method<br>";
        }

        protected function callSibling($sibling) {
            echo "Call from " . get_class($this) . " -> ";
            $sibling->protectedMethod();
        }
    }
    class ProtectedChild extends \Package { 
        protected function protectedMethod() {
            echo "I'm ".get_class($this)." protected method<br>";
        }

        protected function callSibling($sibling) {
            echo "Call from " . get_class($this) . " -> ";
            $sibling->protectedMethod();
        }
    }
}

Testing

$parent = new Package\MyParent();
$parent->test();
$pubChild = new Package\MyParent\PublicChild();//create new public child (possible)
$protChild = new Package\MyParent\ProtectedChild(); //create new protected child (ERROR)

Output:

Call from parent -> I'm Package protected method
I'm Package protected method

Siblings
Call from Package -> I'm Package protected method
Fatal error: Call to protected Package::__construct() from invalid context

NOTE:

I really don't think trying to emulate innerClasses in PHP is such a good idea. I think the code is less clean and readable. Also, there are probably other ways to achieve similar results using a well established pattern such as the Observer, Decorator ou COmposition Pattern. Sometimes, even simple inheritance is sufficient.

sort files by date in PHP

$files = array_diff(scandir($dir,SCANDIR_SORT_DESCENDING), array('..', '.'));
print_r($files);

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

A corresponding cross for ✓ &#x2713; would be ✗ &#x2717; I think (Dingbats).

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

Getting the location from an IP address

The following is a modified version of a snippet I found that uses http://ipinfodb.com/ip_locator.php to get its information. Keep in mind, you can also apply for an API key with them and use the API directly to get the information supplied as you see fit.

Snippet

function detect_location($ip=NULL, $asArray=FALSE) {
    if (empty($ip)) {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
        else { $ip = $_SERVER['REMOTE_ADDR']; }
    }
    elseif (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') {
        $ip = '8.8.8.8';
    }

    $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
    $i = 0; $content; $curl_info;

    while (empty($content) && $i < 5) {
        $ch = curl_init();
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 1,
            CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
        );
        if (isset($_SERVER['HTTP_USER_AGENT'])) $curl_opt[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
        curl_setopt_array($ch, $curl_opt);
        $content = curl_exec($ch);
        if (!is_null($curl_info)) $curl_info = curl_getinfo($ch);
        curl_close($ch);
    }

    $araResp = array();
    if (preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs)) $araResp['city'] = trim($regs[1]);
    if (preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs)) $araResp['state'] = trim($regs[1]);
    if (preg_match('{<li>Country : ([^<]*)}i', $content, $regs)) $araResp['country'] = trim($regs[1]);
    if (preg_match('{<li>Zip or postal code : ([^<]*)</li>}i', $content, $regs)) $araResp['zip'] = trim($regs[1]);
    if (preg_match('{<li>Latitude : ([^<]*)</li>}i', $content, $regs)) $araResp['latitude'] = trim($regs[1]);
    if (preg_match('{<li>Longitude : ([^<]*)</li>}i', $content, $regs)) $araResp['longitude'] = trim($regs[1]);
    if (preg_match('{<li>Timezone : ([^<]*)</li>}i', $content, $regs)) $araResp['timezone'] = trim($regs[1]);
    if (preg_match('{<li>Hostname : ([^<]*)</li>}i', $content, $regs)) $araResp['hostname'] = trim($regs[1]);

    $strResp = ($araResp['city'] != '' && $araResp['state'] != '') ? ($araResp['city'] . ', ' . $araResp['state']) : 'UNKNOWN';

    return $asArray ? $araResp : $strResp;
}

To Use

detect_location();
//  returns "CITY, STATE" based on user IP

detect_location('xxx.xxx.xxx.xxx');
//  returns "CITY, STATE" based on IP you provide

detect_location(NULL, TRUE);    //   based on user IP
//  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }

detect_location('xxx.xxx.xxx.xxx', TRUE);   //   based on IP you provide
//  returns array(8) { ["city"] => "CITY", ["state"] => "STATE", ["country"] => "US", ["zip"] => "xxxxx", ["latitude"] => "xx.xxxxxx", ["longitude"] => "-xx.xxxxxx", ["timezone"] => "-07:00", ["hostname"] => "xx-xx-xx-xx.host.name.net" }

jQuery and AJAX response header

The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the target attribute set to the value of the name attribute of the iframe:

$('#myIframe').attr('name', 'myIframe');

var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
$('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);

form.appendTo(document.body);
form.submit();

The server's url.do page will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.

Exploitable PHP functions

Plattform-specific, but also theoretical exec vectors:

  • dotnet_load()
  • new COM("WScript.Shell")
  • new Java("java.lang.Runtime")
  • event_new() - very eventually

And there are many more disguising methods:

  • proc_open is an alias for popen
  • call_user_func_array("exE".chr(99), array("/usr/bin/damage", "--all"));
  • file_put_contents("/cgi-bin/nextinvocation.cgi") && chmod(...)
  • PharData::setDefaultStub - some more work to examine code in .phar files
  • runkit_function_rename("exec", "innocent_name") or APD rename_function

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

When you use Context.SECURITY_AUTHENTICATION as "simple", you need to supply the userPrincipalName attribute value (user@domain_base).

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

I think the point of those different types of logging is if you want your app to basically self filter its own logs. So Verbose could be to log absolutely everything of importance in your app, then the debug level would log a subset of the verbose logs, and then Info level will log a subset of the debug logs. When you get down to the Error logs, then you just want to log any sort of errors that may have occured. There is also a debug level called Fatal for when something really hits the fan in your app.

In general, you're right, it's basically arbitrary, and it's up to you to define what is considered a debug log versus informational, versus and error, etc. etc.

How do I call the base class constructor?

Regarding the alternative to super; you'd in most cases use use the base class either in the initialization list of the derived class, or using the Base::someData syntax when you are doing work elsewhere and the derived class redefines data members.

struct Base
{
    Base(char* name) { }
    virtual ~Base();
    int d;
};

struct Derived : Base
{
    Derived() : Base("someString") { }
    int d;
    void foo() { d = Base::d; }
};

Convert hex string to int

you can easily do it with parseInt with format parameter.

Integer.parseInt("-FF", 16) ; // returns -255

javadoc Integer

Using Switch Statement to Handle Button Clicks

I have found that the simplest way to do this is to set onClick for each button in the xml

<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />

and then you can do a switch case like this

  public void helpB(View v) {
    Button clickedButton = (Button) v;
    switch (clickedButton.getId()) {
      case R.id.vrHelp:
        dosomething...
        break;

      case R.id.coHelp:
        dosomething...
        break;

      case R.id.ksHelp:
        dosomething...
        break;

      case R.id.uHelp:
        dosomething...
        break;

      case R.id.pHelp:
        dosomething...
        break;
    }
  }

TypeError: 'dict_keys' object does not support indexing

Clearly you're passing in d.keys() to your shuffle function. Probably this was written with python2.x (when d.keys() returned a list). With python3.x, d.keys() returns a dict_keys object which behaves a lot more like a set than a list. As such, it can't be indexed.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

How to combine date from one field with time from another field - MS SQL Server

select s.SalesID from SalesTbl s 
        where cast(cast(s.SaleDate  as date) as datetime) + cast(cast(s.SaleCreatedDate as time) as datetime)  

between @FromDate and @ToDate

How do I add an image to a JButton

I did only one thing and it worked for me .. check your code is this method there ..

setResizable(false);

if it false make it true and it will work just fine .. I hope it helped ..

Horizontal ListView in Android?

well you can always create your textviews etc dynamically and set your onclicklisteners like you would do with an adapter

Python NoneType object is not callable (beginner)

I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it

example: 
Library           ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error  was resolved only after specifying the complete path, as it was not getting the callable function.

GROUP BY with MAX(DATE)

Another solution:

select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

All of the functionality of our lightweight IDEs can be found within IntelliJ IDEA (you need to install the corresponding plug-ins from the repository).

It includes support for all technologies developed for our more specific products such as Web/PhpStorm, RubyMine and PyCharm.

The specific feature missing from IntelliJ IDEA is simplified project creation ("Open Directory") used in lighter products as it is not applicable to the IDE that support such a wide range of languages and technologies. It also means that you can't create projects directly from the remote hosts in IDEA.

If you are missing any other feature that is available in lighter products, but is not available in IntelliJ IDEA Ultimate, you are welcome to report it and we'll consider adding it.

While PHP, Python and Ruby IDEA plug-ins are built from the same source code as used in PhpStorm, PyCharm and RubyMine, product release cycles are not synchronized. It means that some features may be already available in the lighter products, but not available in IDEA plug-ins at certain periods, they are added with the plug-in and IDEA updates later.

Error sending json in POST to web API service

  1. You have to must add header property Content-Type:application/json
  2. When you define any POST request method input parameter that should be annotated as [FromBody], e.g.:

    [HttpPost]
    public HttpResponseMessage Post([FromBody]ActivityResult ar)
    {
      return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  3. Any JSON input data must be raw data.

Select a date from date picker using Selenium webdriver

WebDriver driver;

public void launch(){

    driver = new FirefoxDriver();
    driver.get("http://www.cleartrip.com/");
    driver.manage().window().maximize();
    System.out.println("The browser launched successfully");
    }
public void clickdate(String inputDate){
    WebElement ele =driver.findElement(By.id("DepartDate"));
    ele.click();
    String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
    String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
    System.out.println("Application month : "+month + " Year :"+year);
    int monthNum = getMonthNum(month);
    System.out.println("Enum Num : "+monthNum);
    String[] parts = inputDate.split("/");
    int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
    System.out.println("No OF Hits "+noOfHits);
    for(int i=0; i< noOfHits;i++){
    driver.findElement(By.className("nextMonth ")).click();
    }
    List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
    System.out.println(cals.size());
    for( WebElement daterow : cals){
    List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
    /*iterating the "td" list*/
    for(WebElement date : datenums ){
    /* Checking The our input Date(if it match go inside and click*/
    if(date.getText().equalsIgnoreCase(parts[0])){
    date.click();
    break;
                          }
                     }
                 }
}

public  int getMonthNum(String month){
    for (Month mName : Month.values()) {
    if(mName.name().equalsIgnoreCase(month))
    return mName.value;
    }
    return -1;
    }

public enum Month{
    January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
    private int value;

    private Month(int value) {
    this.value = value;
    }

    }


public static void main(String[] args)  {
    // TODO Auto-generated method stub
    Cleartrip cl=new Cleartrip();
    cl.launch();
    cl.clickdate("24/11/2015");
    }
}

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

What are the sizes used for the iOS application splash screen?

Update 2020 - Xcode 11

In Xcode 11, you can provide only one image with 1x, 2x, and 3x scales then set it in LaunchScreen.storyboard to fill up the screen and everything goes well!

For Example: (1242pt x 2688pt @1x)

This is the portrait screen size of iPhone 11 Pro Max which is the large iPhone screen size yet so it will give you high-quality splash screen on all iOS devices.

Update 2019 - iOS 12

I have collected all sizes needed for the splash screen. All u need is to just drag images with these sizes and drop them, Xcode will place each size in the right place.

Good luck.

Sizes :

320×480

640×960

640×1136

750×1334

768×1004

768×1024

828×1792

1024×748

1024×768

1125×2436

1242×2208

1242×2688

1536×2008

1536×2048

1792×828

2048×1496

2048×1536

2208×1242

2436×1125

2688×1242

Note

Count of required images are 26 images but there are 6 duplicated sizes so u will find the above sizes are only 20.

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

Creating a recursive method for Palindrome

public static boolean isPalindrome(String str)
{
    int len = str.length();
    int i, j;
    j = len - 1;
    for (i = 0; i <= (len - 1)/2; i++)
    {
      if (str.charAt(i) != str.charAt(j))
      return false;
      j--;
    }
    return true;
} 

How can I customize the tab-to-space conversion factor?

I'm running version 1.21, but I think this may apply to earlier versions as well.

Take a look at the bottom right-hand side of the screen. You should see something that says Spaces or Tab-Size.

Mine shows spaces, →

Enter image description here

  1. Click on the Spaces (or Tab-Size)
  2. Choose Indent Using Spaces or Indent using Tabs
  3. Select the amount of spaces or tabs you like.

This only works per document, not project-wide. If you want to apply it project-wide, you need to also add "editor.detectIndentation": false to your user settings.

How to find files that match a wildcard string in Java?

Try FileUtils from Apache commons-io (listFiles and iterateFiles methods):

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
   System.out.println(files[i]);
}

To solve your issue with the TestX folders, I would first iterate through the list of folders:

File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
   File dir = dirs[i];
   if (dir.isDirectory()) {
       File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
   }
}

Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the RegexFileFilter.

Disable future dates after today in Jquery Ui Datepicker

//Disable future dates after current date

$("#datepicker").datepicker('setEndDate', new Date());

//Disable past dates after current date

$("#datepicker").datepicker('setEndDate', new Date());

How do I put double quotes in a string in vba?

I prefer the answer of tabSF . implementing the same to your answer. here below is my approach

Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How can I add private key to the distribution certificate?

since xcode5 organizer no longer team section exists. but the bold sentence was the answer for me. God thanks there is another mac to restore and import to problemmatic mac. now all is ok.

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

you can try this: adb install -r -d -f your_Apk_path

Android adding simple animations while setvisibility(view.Gone)

Please check this link. Which will allow animations like L2R, R2L, T2B, B2T animations.

This code shows animation from left to right

TranslateAnimation animate = new TranslateAnimation(0,view.getWidth(),0,0);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);

if you want to do it from R2L then use

TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);

for top to bottom as

TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());

and vice a versa..

How to remove item from a python list in a loop?

This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.

Workaround could be:

x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x[:]: # make a copy of x
    if len(item) != 2:
        print "length of %s is: %s" %(item, len(item))
        x.remove(item)

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:

#!/usr/bin/python2.7

Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.

#!/usr/bin/env python is generally the better approach, but this helps with special cases.

Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

You can alternatively download winutils.exe from GITHub:

https://github.com/steveloughran/winutils/tree/master/hadoop-2.7.1/bin

replace hadoop-2.7.1 with the version you want and place the file in D:\hadoop\bin

If you do not have access rights to the environment variable settings on your machine, simply add the below line to your code:

System.setProperty("hadoop.home.dir", "D:\\hadoop");

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

gradlew: Permission Denied

You could use "bash" before command:

bash ./gradlew compileDebug --stacktrace

Solr vs. ElasticSearch

I only use Elastic-search. Since I found solr is very hard to start. Elastic-search's features:

  1. Easy to start, very few setting. Even a newbie can setup a cluster step by step.
  2. Simple Restful API which using NoSQL query. And many language libraries for easy accessing.
  3. Good document, you can read the book: . There is a web version on official website.

Autoplay audio files on an iPad with HTML5

It seems to me that the answer to this question is (at least now) clearly documented on the Safari HTML5 docs:

User Control of Downloads Over Cellular Networks

In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad="play()" event does not.

This plays the movie: <input type="button" value="Play" onClick="document.myMovie.play()">

This does nothing on iOS: <body onLoad="document.myMovie.play()">

SELECTING with multiple WHERE conditions on same column

can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"

not really applicable seeing the formatted table.

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

Refresh Fragment at reload

This will refresh current fragment :

FragmentTransaction ft = getFragmentManager().beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
   ft.setReorderingAllowed(false);
}
ft.detach(this).attach(this).commit();

Adding 1 hour to time variable

2020 Update

It is weird that no one has suggested the OOP way:

$date = new \DateTime(); //now
$date->add(new \DateInterval('PT3600S'));//add 3600s / 1 hour

OR

$date = new \DateTime(); //now
$date->add(new \DateInterval('PT60M'));//add 60 min / 1 hour

OR

$date = new \DateTime(); //now
$date->add(new \DateInterval('PT1H'));//add 1 hour

Extract it in string with format:

var_dump($date->format('Y-m-d H:i:s'));

I hope it helps

Git stash pop- needs merge, unable to refresh index

Well, initially, we should know what caused the error to happen, then the solution will be easy. The reason have already been pointed out by the accepted answer, but it is somehow incomplete (also the solution).

The problem is, one or more files had conflict(s) previously, but Git sees them as unresolved. Yes, you might already edited those files and resolved the conflicts, but Git does not know about that. You should tell Git "Hey, there are no more conflicts from the previous merge!". Note that, the merge is not necessarily caused by a git merge, but also by a git stash pop, for example.

Remember, git status can tell you what Git knows now. If there are some unresolved merge conflicts to Git, then it is shown in a separated Unmerged paths section, with the files marked as both modified (always?). If you have noticed, this section is between two staged and unstaged sections. From this, I personally understand that, "Unmerged paths are those you should either move into staged or unstaged areas, as Git can work only with these two areas".

So, to tell Git the conflicts have been resolved, you should either move these changes to staged or unstaged areas. In recent versions of Git, when you do a git status, it tells you how (woah! You should ask yourself how you haven't seen this yet?):

$ git status
...
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
        both modified:   path/to/file.txt
...

So, to stage it (and maybe commit it):

$ git add path/to/file.txt

And to make it unstaged (e.g. you don't want to commit it now):

$ git restore --staged path/to/file.txt

Note: Forgetting to write --staged option possibly could spawn a super-hungry dragon to eat your past two days, in the case of not using a good text-editor or IDE.

Note: While git restore command is experimental yet, it should be stable enough to be used (thanks to a comment by @VonC, refer to it for more details on that).

how to import csv data into django models

You can use the django-csv-importer package. http://pypi.python.org/pypi/django-csv-importer/0.1.1

It works like a django model

MyCsvModel(CsvModel):
    field1 = IntegerField()
    field2 = CharField()
    etc

    class Meta:
        delimiter = ";"
        dbModel = Product

And you just have to: CsvModel.import_from_file("my file")

That will automatically create your products.

SVN: Is there a way to mark a file as "do not commit"?

You can configure the "ignore-on-commit" changelist directly with TortoiseSVN. No need to configure any other changelist including all the others files

1) Click "SVN Commit..." (we will not commit, just a way to find a graphical menu for the changelist) 2) On the list Right click on the file you want to exclude. 3) Menu: move to changelist > ignore-on-commit

The next time you do a SVN Commit... The files will appear unchecked at the end of the list, under the category ignore-on-commit.

Tested with : TortoiseSVN 1.8.7, Build 25475 - 64 Bit , 2014/05/05 20:52:12, Subversion 1.8.9, -release

select certain columns of a data table

Here's working example with anonymous output record, if you have any questions place a comment below:                    

public partial class Form1 : Form
{
    DataTable table;
    public Form1()
    {
        InitializeComponent();
        #region TestData
        table = new DataTable();
        table.Clear();
        for (int i = 1; i < 12; ++i)
            table.Columns.Add("Col" + i);
        for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
        {
            DataRow row = table.NewRow();
            for (int i = 0; i < table.Columns.Count; ++i)
                row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
            table.Rows.Add(row);
        }
        #endregion
        bind();
    }

    public void bind()
    {
        var filtered = from t in table.AsEnumerable()
                       select new
                       {
                           col1 = t.Field<string>(0),//column of index 0 = "Col1"
                           col2 = t.Field<string>(1),//column of index 1 = "Col2"
                           col3 = t.Field<string>(5),//column of index 5 = "Col6"
                           col4 = t.Field<string>(6),//column of index 6 = "Col7"
                           col5 = t.Field<string>(4),//column of index 4 = "Col3"
                       };
        filteredData.AutoGenerateColumns = true;
        filteredData.DataSource = filtered.ToList();
    }
}

How do I encode and decode a base64 string?

URL safe Base64 Encoding/Decoding

public static class Base64Url
{
    public static string Encode(string text)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
            .Replace('/', '_');
    }

    public static string Decode(string text)
    {
        text = text.Replace('_', '/').Replace('-', '+');
        switch (text.Length % 4)
        {
            case 2:
                text += "==";
                break;
            case 3:
                text += "=";
                break;
        }
        return Encoding.UTF8.GetString(Convert.FromBase64String(text));
    }
}

Best practice for storing and protecting private API keys in applications

The only true way to keep these private is to keep them on your server, and have the app send whatever it is to the server, and the server interacts with Dropbox. That way you NEVER distribute your private key in any format.

Word wrapping in phpstorm

In PhpStorm 2019.1.3, it is possible to enable soft wrap for some file types only.

enter image description here

Bash: Strip trailing linebreak from output

If you want to remove only the last newline, pipe through:

sed -z '$ s/\n$//'

sed won't add a \0 to then end of the stream if the delimiter is set to NUL via -z, whereas to create a POSIX text file (defined to end in a \n), it will always output a final \n without -z.

Eg:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender

And to prove no NUL added:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72                        foo.bar

To remove multiple trailing newlines, pipe through:

sed -Ez '$ s/\n+$//'

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

How to check if a variable is empty in python?

Just use not:

if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:

if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

Determine number of pages in a PDF file

I have used pdflib for this.

    p = new pdflib();

    /* Open the input PDF */
    indoc = p.open_pdi_document("myTestFile.pdf", "");
    pageCount = (int) p.pcos_get_number(indoc, "length:pages");

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How do I concatenate two text files in PowerShell?

To keep encoding and line endings:

Get-Content files.* -Raw | Set-Content newfile.file -NoNewline

Note: AFAIR, whose parameters aren't supported by old Powershells (<3? <4?)

How to hide scrollbar in Firefox?

In some particular cases (the element is on the very right of the screen, or its parent overflow is hidden) this can be a solution:

@-moz-document url-prefix() {
  .element {
    margin-right: -15px;
  }
}

What exactly is node.js used for?

From Node.js website

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Event-driven means that the server only reacts when an event occurs. This allow us to create high performance, highly scalable, “real-time” applications.

Finally, this is probably the best article that will get you excited about Node.js

How do I close an Android alertdialog

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
AlertDialog alert = builder.create(); 
alert.show();

The above code works but make sure you make alert a global variable so you can reach it from within the onClick method.

Microsoft Web API: How do you do a Server.MapPath?

Little bit late answering that but there we go.

I could solve this using Environment.CurrentDirectory

How to get all selected values from <select multiple=multiple>?

Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:

var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) { 
    return v.value; 
});

UPDATE (2017-02-14):

An even more succinct way using ES6/ES2015 (for the browsers that support it):

const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

How to declare an array of objects in C#

You are creating an array of null references. You should do something like:

for (int i = 0; i < houses.Count; i++)
{
    houses[i] = new GameObject();
}

Xcode 10 Error: Multiple commands produce

If the issue with your error is .app/ (and not .app/Info.plist) see this answer here: xcode 10 error: multiple commands produce - react native

Count number of rows per group and add result to original data frame

The base R function aggregate will obtain the counts with a one-liner, but adding those counts back to the original data.frame seems to take a bit of processing.

df <- data.frame(name=c('black','black','black','red','red'),
                 type=c('chair','chair','sofa','sofa','plate'),
                 num=c(4,5,12,4,3))
df
#    name  type num
# 1 black chair   4
# 2 black chair   5
# 3 black  sofa  12
# 4   red  sofa   4
# 5   red plate   3

rows.per.group  <- aggregate(rep(1, length(paste0(df$name, df$type))),
                             by=list(df$name, df$type), sum)
rows.per.group
#   Group.1 Group.2 x
# 1   black   chair 2
# 2     red   plate 1
# 3   black    sofa 1
# 4     red    sofa 1

my.summary <- do.call(data.frame, rows.per.group)
colnames(my.summary) <- c(colnames(df)[1:2], 'rows.per.group')
my.data <- merge(df, my.summary, by = c(colnames(df)[1:2]))
my.data
#    name  type num rows.per.group
# 1 black chair   4              2
# 2 black chair   5              2
# 3 black  sofa  12              1
# 4   red plate   3              1
# 5   red  sofa   4              1

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

Open a URL without using a browser from a batch file

Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:

powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"

Convert NVARCHAR to DATETIME in SQL Server 2008

alter table your_table
alter column LoginDate datetime;

SQLFiddle demo

Bootstrap footer at the bottom of the page

You can just add style="min-height:100vh" to your page content conteiner and place footer in another conteiner

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

I was facing the same issue.The dtypes of y_test and y_pred were different. Make sure that the dtypes are same for both. The dtypes of y_test and y_pred were different

Add quotation at the start and end of each line in Notepad++

You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:

  1. Find (in regular expression mode):

    (.+)
    

    Replace with:

    "\1"
    

    This adds the quotes:

    "AliceBlue"
    "AntiqueWhite"
    "Aqua"
    "Aquamarine"
    "Azure"
    "Beige"
    "Bisque"
    "Black"
    "BlanchedAlmond"
    
  2. Find (in extended mode):

    \r\n
    

    Replace with (with a space after the comma, not shown):

    , 
    

    This converts the lines into a comma-separated list:

    "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
    

  3. Add the var myArray = assignment and braces manually:

    var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
    

Adding Apostrophe in every field in particular column for excel

I'm going to suggest the non-obvious. There is a fantastic (and often under-used) tool called the Immediate Window in Visual Basic Editor. Basically, you can write out commands in VBA and execute them on the spot, sort of like command prompt. It's perfect for cases like this.

Press ALT+F11 to open VBE, then Control+G to open the Immediate Window. Type the following and hit enter:

for each v in range("K2:K5000") : v.value = "'" & v.value : next

And boom! You are all done. No need to create a macro, declare variables, no need to drag and copy, etc. Close the window and get back to work. The only downfall is to undo it, you need to do it via code since VBA will destroy your undo stack (but that's simple).

How to get Exception Error Code in C#

I suggest you to use Message Properte from The Exception Object Like below code

try
{
 object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{  
    //use Console.Write(e.Message); from Console Application 
    //and use MessageBox.Show(e.Message); from WindowsForm and WPF Application
}

Add content to a new open window

When you call document.write after a page has loaded it will eliminate all content and replace it with the parameter you provide. Instead use DOM methods to add content, for example:

var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
var text = document.createTextNode('hi');
OpenWindow.document.body.appendChild(text);

If you want to use jQuery you get some better APIs to deal with. For example:

var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).append('<p>hi</p>');

If you need the code to run after the new window's DOM is ready try:

var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).ready(function() {
    $(OpenWindow.document.body).append('<p>hi</p>');
});

How to copy only a single worksheet to another workbook using vba

I have 1 WorkBook("SOURCE") that contains around 20 Sheets. I want to copy only 1 particular sheet to another Workbook("TARGET") using Excel VBA. Please note that the "TARGET" Workbook doen't exist yet. It should be created at runtime.

Another Way

Sub Sample()
    '~~> Change Sheet1 to the relevant sheet
    '~~> This will create a new workbook with the relevant sheet
    ThisWorkbook.Sheets("Sheet1").Copy

    '~~> Save the new workbook
    ActiveWorkbook.SaveAs "C:\Target.xlsx", FileFormat:=51
End Sub

This will automatically create a new workbook called Target.xlsx with the relevant sheet

How to cut an entire line in vim and paste it?

  1. Go to the line, and first press esc, and then Shift + v.

(This would have highlighted the line)

  1. press d

(The line is now deleted)

  1. Go to the location, where you wanted to paste the line, and hit p.

In a nutshell,

Esc -> Shift + v -> d -> p

Identify if a string is a number

This is probably the best option in C#.

If you want to know if the string contains a whole number (integer):

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can't, it returns false.

Solutions using the int.Parse(someString) alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(...) was added to the C# language in version 2, and until then you didn't have a choice. Now you do: you should therefore avoid the Parse() alternative.

If you want to accept decimal numbers, the decimal class also has a .TryParse(...) method. Replace int with decimal in the above discussion, and the same principles apply.

Invoking Java main method with parameters from Eclipse

AFAIK there isn't a built-in mechanism in Eclipse for this.

The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.

How to calculate a mod b in Python?

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Android Camera Preview Stretched

F1Sher's solution is nice but sometimes doesn't work. Particularly, when your surfaceView doesn't cover whole screen. In this case you need to override onMeasure() method. I have copied my code here for your reference.

Since I measured surfaceView based on width then I have little bit white gap at the end of my screen that I filled it by design. You are able to fix this issue if you keep height and increase width by multiply it to ratio. However, it will squish surfaceView slightly.

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "CameraPreview";

    private Context mContext;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private List<Camera.Size> mSupportedPreviewSizes;
    private Camera.Size mPreviewSize;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mContext = context;
        mCamera = camera;

        // supported preview sizes
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        for(Camera.Size str: mSupportedPreviewSizes)
                Log.e(TAG, str.width + "/" + str.height);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // empty. surfaceChanged will take care of stuff
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        Log.e(TAG, "surfaceChanged => w=" + w + ", h=" + h);
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.
        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or reformatting changes here
        // start preview with new settings
        try {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            mCamera.setParameters(parameters);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }

        if (mPreviewSize!=null) {
            float ratio;
            if(mPreviewSize.height >= mPreviewSize.width)
                ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
            else
                ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;

            // One of these methods should be used, second method squishes preview slightly
            setMeasuredDimension(width, (int) (width * ratio));
  //        setMeasuredDimension((int) (width * ratio), height);
        }
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) h / w;

        if (sizes == null)
            return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        for (Camera.Size size : sizes) {
            double ratio = (double) size.height / size.width;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;

            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }

        return optimalSize;
    }
}

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Either switch your browser in VS2017. Or open up a command prompt as administrator and do a tskill chrome about 10 times to make sure the app fully dies. Then try again. Sometimes it gets stuck on another process and even it needs to be restarted.

How do I schedule a task to run at periodic intervals?

Use timer.scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:

  • task - task to be scheduled.
  • delay - delay in milliseconds before task is to be executed.
  • period - time in milliseconds between successive task executions.

Throws:

  • IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
  • IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.