Programs & Examples On #Templatebinding

WPF TemplateBinding vs RelativeSource TemplatedParent

They are used in a similar way but they have a few differences. Here is a link to the TemplateBinding documentation: http://msdn.microsoft.com/en-us/library/ms742882.aspx

How do I login and authenticate to Postgresql after a fresh install?

If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".

Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

The server will automatically abort connections over which no message has been received for the duration equal to the receive timeout (default is 10 mins). This is a DoS mitigation to prevent clients from forcing the server to have connections open for an indefinite amount of time.

Since the server aborts the connection because it has gone idle, the client gets this exception.

You can control how long the server allows a connection to go idle before aborting it by configuring the receive timeout on the server's binding. Credit: T.R.Vishwanath - MSFT

How do I print part of a rendered HTML page in JavaScript?

I would go about it somewhat like this:

<html>
    <head>
        <title>Print Test Page</title>
        <script>
            printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
            function printDiv(divId) {
                window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
                window.frames["print_frame"].window.focus();
                window.frames["print_frame"].window.print();
            }
        </script>
    </head>

    <body>
        <h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
        <b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
        <div id="div1">This is the div1's print output</div>
        <br><br>
        <b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
        <div id="div2">This is the div2's print output</div>
        <br><br>
        <b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
        <div id="div3">This is the div3's print output</div>
        <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
    </body>
</html>

How do I display a decimal value to 2 decimal places?

You can use system.globalization to format a number in any required format.

For example:

system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");

If you have a decimal d = 1.2300000 and you need to trim it to 2 decimal places then it can be printed like this d.Tostring("F2",ci); where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo.

for more info check this link
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

How to delete last character in a string in C#?

Add a StringBuilder extension method.

public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
    if(sb.Length < 1) return sb;
    sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
    return sb;
}

then use:

yourStringBuilder.RemoveLast(",");

How to remove folders with a certain name

find ./ -name "FOLDERNAME" | xargs rm -Rf

Should do the trick. WARNING, if you accidentally pump a . or / into xargs rm -Rf your entire computer will be deleted without an option to get it back, requiring an OS reinstall.

Instance member cannot be used on type

Just in case someone really needs a closure like that, it can be done in the following way:

var categoriesPerPage = [[Int]]()
var numPagesClosure: ()->Int {
    return {
        return self.categoriesPerPage.count
    }
}

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

How to create a GUID / UUID

This creates a version 4 UUID (created from pseudo random numbers):

function uuid()
{
   var chars = '0123456789abcdef'.split('');

   var uuid = [], rnd = Math.random, r;
   uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
   uuid[14] = '4'; // version 4

   for (var i = 0; i < 36; i++)
   {
      if (!uuid[i])
      {
         r = 0 | rnd()*16;

         uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
      }
   }

   return uuid.join('');
}

Here is a sample of the UUIDs generated:

682db637-0f31-4847-9cdf-25ba9613a75c
97d19478-3ab2-4aa1-b8cc-a1c3540f54aa
2eed04c9-2692-456d-a0fd-51012f947136

Where do I find some good examples for DDD?

ddd-cqrs-sample is also a good resource. Written with Java, Spring and JPA.

Updated link: https://github.com/BottegaIT/ddd-leaven-v2

copying all contents of folder to another folder using batch file?

@echo off
xcopy /s C:\yourfile C:\anotherfile\

This is how it is done! Simple, right?

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

Ok First of all this is a very clear error message. Just look at this many devs miss this including my self. Have a look at the screen shot here please.

enter image description here

Under Products > Facebook Login > Settings

or just go to this url here (Replace YOUR_APP_ID with your app id lol):

https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/settings/

If you are working on localhost:3000 Make sure you have https://localhost:3000/auth/facebook/callback

Ofcourse you don't have to have the status live (Green Switch on top right corner) but in my case, I am deploying to heroku now and will soon replace localhost:3000 with https://myapp.herokuapp.com/auth/facebook/callback

Of course I will update the urls in Settings/Basic & Settings/Advanced and also add a privacy policy url in the basic section.

I am assuming that you have properly configured initializers/devise.rb if you are using devise and you have the proper facebook gem 'omniauth-facebook', '~> 4.0' gem installed and gem 'omniauth', '~> 1.6', and you have the necessary columns in your users table such as uid, image, and provider. That's it.

Java split string to array

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

execute function after complete page load

Try this jQuery:

$(function() {
 // Handler for .ready() called.
});

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

How to make IPython notebook matplotlib plot inline

To make matplotlib inline by default in Jupyter (IPython 3):

  1. Edit file ~/.ipython/profile_default/ipython_config.py

  2. Add line c.InteractiveShellApp.matplotlib = 'inline'

Please note that adding this line to ipython_notebook_config.py would not work. Otherwise it works well with Jupyter and IPython 3.1.0

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

BEGIN and END have been well answered by others.

As Gary points out, GO is a batch separator, used by most of the Microsoft supplied client tools, such as isql, sqlcmd, query analyzer and SQL Server Management studio. (At least some of the tools allow the batch separator to be changed. I have never seen a use for changing the batch separator.)

To answer the question of when to use GO, one needs to know when the SQL must be separated into batches.

Some statements must be the first statement of a batch.

select 1
create procedure #Zero as
    return 0

On SQL Server 2000 the error is:

Msg 111, Level 15, State 1, Line 3
'CREATE PROCEDURE' must be the first statement in a query batch.
Msg 178, Level 15, State 1, Line 4
A RETURN statement with a return value cannot be used in this context.

On SQL Server 2005 the error is less helpful:

Msg 178, Level 15, State 1, Procedure #Zero, Line 5
A RETURN statement with a return value cannot be used in this context.

So, use GO to separate statements that have to be the start of a batch from the statements that precede it in a script.

When running a script, many errors will cause execution of the batch to stop, but then the client will simply send the next batch, execution of the script will not stop. I often use this in testing. I will start the script with begin transaction and end with rollback, doing all the testing in the middle:

begin transaction
go
... test code here ...
go
rollback transaction

That way I always return to the starting state, even if an error happened in the test code, the begin and rollback transaction statements being part of a separate batches still happens. If they weren't in separate batches, then a syntax error would keep begin transaction from happening, since a batch is parsed as a unit. And a runtime error would keep the rollback from happening.

Also, if you are doing an install script, and have several batches in one file, an error in one batch will not keep the script from continuing to run, which may leave a mess. (Always backup before installing.)

Related to what Dave Markel pointed out, there are cases when parsing will fail because SQL Server is looking in the data dictionary for objects that are created earlier in the batch, but parsing can happen before any statements are run. Sometimes this is an issue, sometimes not. I can't come up with a good example. But if you ever get an 'X does not exist' error, when it plainly will exist by that statement break into batches.

And a final note. Transaction can span batches. (See above.) Variables do not span batches.

declare @i int
set @i = 0
go
print @i

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@i".

Create a simple 10 second countdown

A solution using Promises, includes both progress bar & text countdown.

_x000D_
_x000D_
ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));_x000D_
_x000D_
function ProgressCountdown(timeleft, bar, text) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    var countdownTimer = setInterval(() => {_x000D_
      timeleft--;_x000D_
_x000D_
      document.getElementById(bar).value = timeleft;_x000D_
      document.getElementById(text).textContent = timeleft;_x000D_
_x000D_
      if (timeleft <= 0) {_x000D_
        clearInterval(countdownTimer);_x000D_
        resolve(true);_x000D_
      }_x000D_
    }, 1000);_x000D_
  });_x000D_
}
_x000D_
<div class="row begin-countdown">_x000D_
  <div class="col-md-12 text-center">_x000D_
    <progress value="10" max="10" id="pageBeginCountdown"></progress>_x000D_
    <p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

I was having this same issue and I resolved it in the following way...

I have the NVIDIA "Tegra Android Development Pack" installed and it seems to also have a version of mysysgit.exe with it. TortoiseGit automatically found that installation location (instead of the standard git installation) and auto-populated it in the settings menu.

To correct this, go to: "Settings -> General" and there is a field for the path to mysysgit.exe. Make sure this is pointing to the correct installation.

sql query to get earliest date

If you just want the date:

SELECT MIN(date) as EarliestDate
FROM YourTable
WHERE id = 2

If you want all of the information:

SELECT TOP 1 id, name, score, date
FROM YourTable
WHERE id = 2
ORDER BY Date

Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.

How do I unlock a SQLite database?

This error can be thrown if the file is in a remote folder, like a shared folder. I changed the database to a local directory and it worked perfectly.

How to implement a SQL like 'LIKE' operator in java?

The Comparator and Comparable interfaces are likely inapplicable here. They deal with sorting, and return integers of either sign, or 0. Your operation is about finding matches, and returning true/false. That's different.

Git Bash doesn't see my PATH

In case your git-bash's PATH presents but not latest and you don't want a reboot but regenerate your PATHs, you can try the following:

  • Close all cmd.exe, powershell.exe, and git-bash.exe and reopen one cmd.exe window from the Start Menu or Desktop context.
  • If you changed system-wide PATH, you may also need to open one privileged cmd window.
  • Open Git bash from Windows Explorer context menu and see if the PATH env is updated. Please note that the terminal in IntelliJ IDEA is probably a login shell or some other kind of magic, so PATH in it may won't change until you restart IDEA.
  • If that does not work, you may need to close all Windows Explorer process as well and retry the steps above.

Note: This doesn't work with all Windows versions, and open cmd.exe anywhere other than the Start Menu or Desktop context menu may not work, tested with my 4 computers and 3 of them works. I didn't figure out why this works, but since the PATH environment variable is generated automatically when I login and logout, I'd not to mess up that variable with variable concatenation.

How can I delete all of my Git stashes at once?

I wanted to keep a few recent stashes, but delete everything else.

Because all stashes get renumbered when you drop one, this is actually easy to do with while. To delete all stashes older than stash@{19}:

while git stash drop 'stash@{20}'; do true; done

What is the maximum recursion depth in Python, and how to increase it?

import sys
sys.setrecursionlimit(1500)

def fib(n, sum):
    if n < 1:
        return sum
    else:
        return fib(n-1, sum+n)

c = 998
print(fib(c, 0))

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

C++ Returning reference to local variable

A good thing to remember are these simple rules, and they apply to both parameters and return types...

  • Value - makes a copy of the item in question.
  • Pointer - refers to the address of the item in question.
  • Reference - is literally the item in question.

There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

void func1(int& oValue)
{
    oValue = 1;
}

Doing so would directly change the value of your passed in parameter. Whereas this code...

void func1(int oValue)
{
    oValue = 1;
}

would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

How to secure the ASP.NET_SessionId cookie?

Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.

    protected void Session_Start(Object sender, EventArgs e)
    {
        SessionStateSection sessionState = 
 (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
        string sidCookieName = sessionState.CookieName;

        if (Request.Cookies[sidCookieName] != null)
        {
            HttpCookie sidCookie = Response.Cookies[sidCookieName];
            sidCookie.Value = Session.SessionID;
            sidCookie.HttpOnly = true;
            sidCookie.Secure = true;
            sidCookie.Path = "/";
        }
    }

Android add placeholder text to EditText

In your Activity

<EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@null"
                android:hint="Text Example"
                android:padding="5dp"
                android:singleLine="true"
                android:id="@+id/name"
                android:textColor="@color/magenta"/>

enter image description here

How to read a line from the console in C?

If you are using the GNU C library or another POSIX-compliant library, you can use getline() and pass stdin to it for the file stream.

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

Xcode "Build and Archive" from command line

Updating my answer with Xcode 9 and Swift

Archive

xcodebuild -workspace <ProjectName>/<ProjectName>.xcworkspace \
  -scheme <schemeName> clean archive -configuration release \
  -sdk iphoneos -archivePath <ProjectName>.xcarchive

IPA Export (please note the export option plist)

xcodebuild -exportArchive -archivePath  <ProjectName>.xcarchive \
  -exportOptionsPlist  <ProjectName>/exportOptions.plist \
  -exportPath  <ProjectName>.ipa

For those who don't know about exportOptions.plist, https://blog.bitrise.io/new-export-options-plist-in-xcode-9


Those who were using this for building project in CI/CD tools like teamcity/jenkins, please make sure you are using the right xcode installed in the build agent for for both archive and export.

You can use either of below 2 options for this.

  1. Use the full path to xcodebuild,
/Applications/Xcode 9.3.1.app/Contents/Developer/usr/bin/xcodebuild
  1. Use xcode-select,
xcode-select -switch /Applications/Xcode 9.3.1.app

Below is my old answer

Here is command line script for creating archive and IPA example. I have an iPhone xcode project , which is located in Desktop/MyiOSApp folder.

Execute following commands one by one:

cd /Users/username/Desktop/MyiOSApp/

xcodebuild -scheme MyiOSApp archive \
  -archivePath /Users/username/Desktop/MyiOSApp.xcarchive

xcodebuild -exportArchive -exportFormat ipa \
  -archivePath "/Users/username/Desktop/MyiOSApp.xcarchive" \
  -exportPath "/Users/username/Desktop/MyiOSApp.ipa" \
  -exportProvisioningProfile "MyCompany Distribution Profile"

This is tested with Xcode 5 and working fine for me.

Click event on select option element in chrome

Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use

$('#yourSelect option:selected').html();

You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.

 $ ('#yourSelect' ).change(() => {
    process($('#yourSelect option:selected').html());
  });

If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()

Convert String to Double - VB

Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If

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

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

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

whereas, with replace: false you get this:

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

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

OR

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

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

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

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

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

See this to read more about translusion.

Vue.js getting an element within a component

Vue 2.x

For Official information:

https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

A simple Example:

On any Element you have to add an attribute ref with a unique value

<input ref="foo" type="text" >

To target that elemet use this.$refs.foo

this.$refs.foo.focus(); // it will focus the input having ref="foo"

How to change color in markdown cells ipython/jupyter notebook?

<p style="font-family: Arial; font-size:1.4em;color:gold;"> Golden </p>

or

Text <span style="font-family: Arial; font-size:1.4em;color:gold;"> Golden </p> Text

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

Removing numbers from string

Say st is your unformatted string, then run

st_nodigits=''.join(i for i in st if i.isalpha())

as mentioned above. But my guess that you need something very simple so say s is your string and st_res is a string without digits, then here is your code

l = ['0','1','2','3','4','5','6','7','8','9']
st_res=""
for ch in s:
 if ch not in l:
  st_res+=ch

Is there a way to get the XPath in Google Chrome?

First open your Google Chrome

and open any website

and inspect that

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

  1. in eclipse, go to Project > Clean...
  2. select your project, then press OK
  3. relaunch the app

if it happens again delete the r.java file. it will generate automatically.

Getting mouse position in c#

System.Windows.Forms.Control.MousePosition

Gets the position of the mouse cursor in screen coordinates. "The Position property is identical to the Control.MousePosition property."

val() vs. text() for textarea

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Measuring the distance between two coordinates in PHP

The multiplier is changed at every coordinate because of the great circle distance theory as written here :

http://en.wikipedia.org/wiki/Great-circle_distance

and you can calculate the nearest value using this formula described here:

http://en.wikipedia.org/wiki/Great-circle_distance#Worked_example

the key is converting each degree - minute - second value to all degree value:

N 36°7.2', W 86°40.2'  N = (+) , W = (-), S = (-), E = (+) 
referencing the Greenwich meridian and Equator parallel

(phi)     36.12° = 36° + 7.2'/60' 

(lambda)  -86.67° = 86° + 40.2'/60'

How to show Snackbar when Activity starts?

Simple way to show some text:

Snackbar.make(view, "Sample Text", Snackbar.LENGTH_SHORT).show();

and to show text with button:

Snackbar.make(view, "Sample Text", Snackbar.LENGTH_SHORT).setAction("Ok", new View.OnClickListener() {
            @Override 
            public void onClick(View view) {

            } 
        }).show();

PHP - Redirect and send data via POST

A workaround wich works perfectly :

In the source page,, start opening a session and assign as many values as you might want. Then do the relocation with "header" :

<!DOCTYPE html>
<html>
   <head>
       <?php
           session_start();
           $_SESSION['val1'] = val1;
           ...
           $_SESSION['valn'] = valn;
           header('Location: http//Page-to-redirect-to');
       ?>
   </head>
</html>

And then, in the targe page :

<!DOCTYPE html>
<?php
    session_start();
?>
<html>
    ...
    <body>
        <?php
            if (isset($_SESSION['val1']) && ... && isset($_SESSION['valn'])) {
                YOUR CODE HERE based on $_SESSION['val1']...$_SESSION['valn'] values
            }
        ?>
    </body>
</html>

No need of Javascript nor JQuery.. Good luck !

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

Google Maps how to Show city or an Area outline

use this code:

<iframe width="600" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=place_id:ChIJ5Rw5v9dCXz4R3SUtcL5ZLMk&key=..." allowfullscreen></iframe>

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

jQuery to loop through elements with the same class

You could use the jQuery $each method to loop through all the elements with class testimonial. i => is the index of the element in collection and val gives you the object of that particular element and you can use "val" to further access the properties of your element and check your condition.

$.each($('.testimonal'), function(i, val) { 
    if(your condition){
       //your action
    }
});

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

Difference between HashMap, LinkedHashMap and TreeMap

All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes are the time guarantees and the ordering of the keys.

  1. HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists.
  2. TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means that keys must implement the Comparable interface.TreeMap is implemented by a Red-Black Tree.
  3. LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets.

Imagine you passed an empty TreeMap, HashMap, and LinkedHashMap into the following function:

void insertAndPrint(AbstractMap<Integer, String> map) {
  int[] array= {1, -1, 0};
  for (int x : array) {
    map.put(x, Integer.toString(x));
  }
  for (int k: map.keySet()) {
   System.out.print(k + ", ");
  }
}

The output for each will look like the results below.

For HashMap, the output was, in my own tests, { 0, 1, -1}, but it could be any ordering. There is no guarantee on the ordering.
Treemap,the output was,{ -1, 0, 1}
LinkedList,the output was,{ 1, -1, 0}

What is the difference between "px", "dip", "dp" and "sp"?

dpi -

  • Dots per inches
  • Measuring the pixel density of the screen.

px - pixel

  • For mapping screen pixels

pt - points

  • About 1/72 of an inch, with respect to physical screen size.

in - inch - with respect to physical screen size(1 inch = 2.54 cm).

mm- milimeter - with respect to physical screen size.

sp - scale-independent pixel.

  • Based on user`s font size preference.
  • Font should be in 'sp'.

dip -

  • dip == dp
  • Density independent pixel.
  • It varies based on Screen Density.
  • In 160 dpi screen, 1 dp = 1 pixel.
  • Use dp except the text font size.

In standard, dp and sp are used. sp for font size and dp for everything else.

Formula for conversion of units:

px = dp * ( dpi / 160 );

Density Bucket -> Screen Display => Physical Size        => Pixel Size                   

ldpi         -> 120 dpi          => 0.5 x 0.5 in         => 0.5 in * 120 dpi = 60x60 px   

mdpi         -> 160 dpi          => 0.5 x 0.5 in         => 0.5 in * 160 dpi = 80x80 px   

hdpi         -> 240 dpi          => 0.5 x 0.5 in         => 0.5 in * 240 dpi = 120x120 px  

xhdpi        -> 320 dpi          => 0.5 x 0.5 in         => 0.5 in * 320 dpi = 160x160 px  

xxhdpi       -> 480 dpi          => 0.5 x 0.5 in         => 0.5 in * 480 dpi = 240x240 px 

xxxhdpi      -> 640 dpi          => 0.5 x 0.5 in         => 0.5 in * 640 dpi = 320x320 px  

Return string without trailing slash

Here a small url example.

var currentUrl = location.href;

if(currentUrl.substr(-1) == '/') {
    currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}

log the new url

console.log(currentUrl);

How to completely uninstall kubernetes

kubeadm reset 
/*On Debian base Operating systems you can use the following command.*/
# on debian base 
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube* 


/*On CentOs distribution systems you can use the following command.*/
#on centos base
sudo yum remove kubeadm kubectl kubelet kubernetes-cni kube*


# on debian base
sudo apt-get autoremove

#on centos base
sudo yum autoremove

/For all/
sudo rm -rf ~/.kube

GoogleTest: How to skip a test?

I prefer to do it in code:

// Run a specific test only
//testing::GTEST_FLAG(filter) = "MyLibrary.TestReading"; // I'm testing a new feature, run something quickly

// Exclude a specific test
testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting"; // The writing test is broken, so skip it

I can either comment out both lines to run all tests, uncomment out the first line to test a single feature that I'm investigating/working on, or uncomment the second line if a test is broken but I want to test everything else.
You can also test/exclude a suite of features by using wildcards and writing a list, "MyLibrary.TestNetwork*" or "-MyLibrary.TestFileSystem*".

How do I show the number keyboard on an EditText in android?

To do it in a Java file:

EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);

How do I find the width & height of a terminal window?

There are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.

Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.

function term_size
{
    local i=0 digits='' tens_fmt='' tens_args=()
    for i in {80..8}
    do
        echo $i $(( i - 2 ))
    done
    echo "If columns below wrap, LINES is first number in highest line above,"
    echo "If truncated, LINES is second number."
    for i in {1..14}
    do
        digits="${digits}1234567890"
        tens_fmt="${tens_fmt}%10d"
        tens_args=("${tens_args[@]}" $i)
    done
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"
}

ORA-06508: PL/SQL: could not find program unit being called

seems like opening a new session is the key.

see this answer.

and here is an awesome explanation about this error

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

How can I hash a password in Java?

Fully agree with Erickson that PBKDF2 is the answer.

If you don't have that option, or only need to use a hash, Apache Commons DigestUtils is much easier than getting JCE code right: https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html

If you use a hash, go with sha256 or sha512. This page has good recommendations on password handling and hashing (note it doesn't recommend hashing for password handling): http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html

Scroll to the top of the page after render in react.js

This could, and probably should, be handled using refs:

"... you can use ReactDOM.findDOMNode as an "escape hatch" but we don't recommend it since it breaks encapsulation and in almost every case there's a clearer way to structure your code within the React model."

Example code:

class MyComponent extends React.Component {
    componentDidMount() {
        this._div.scrollTop = 0
    }

    render() {
        return <div ref={(ref) => this._div = ref} />
    }
}

Redirect on select option in select box

Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.

Here's an example:

https://jsfiddle.net/bL5sq/

_x000D_
_x000D_
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">_x000D_
  <option value="">Select...</option>_x000D_
  <option value="https://google.com">Google</option>_x000D_
  <option value="https://yahoo.com">Yahoo</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I list loaded plugins in Vim?

If you use vim-plug (Plug), " A minimalist Vim plugin manager.":

:PlugStatus

That will not only list your plugins but check their status.

Android - SMS Broadcast receiver

intent.getAction().equals(SMS_RECEIVED)

I have tried it out successfully.

How to display a readable array - Laravel

You can use this code on view.blade. {{var_dump($animales)}}

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Android Fragment onClick button Method

For Kotlin users:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?, 
    savedInstanceState: Bundle?) : View?
{
    // Inflate the layout for this fragment
    var myView = inflater.inflate(R.layout.fragment_home, container, false)
    var btn_test = myView.btn_test as Button
    btn_test.setOnClickListener {
        textView.text = "hunny home fragment"
    }

    return myView
}

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

How to get date in BAT file

This will give you DD MM YYYY YY HH Min Sec variables and works on any Windows machine from XP Pro and later.

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

Get List of connected USB Devices

  lstResult.Clear();
  foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
  {
       foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
       {
            foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
            {
                  foreach (var item in disk.Properties)
                  {
                       object value = disk.GetPropertyValue(item.Name);
                  }
                  string valor = disk["Name"].ToString();
                  lstResult.Add(valor);
                  }
             }
        }
   }

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.

Save text file UTF-8 encoded with VBA

Here is another way to do this - using the API function WideCharToMultiByte:

Option Explicit

Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
  ByVal CodePage As Long, _
  ByVal dwFlags As Long, _
  ByVal lpWideCharStr As Long, _
  ByVal cchWideChar As Long, _
  ByVal lpMultiByteStr As Long, _
  ByVal cbMultiByte As Long, _
  ByVal lpDefaultChar As Long, _
  ByVal lpUsedDefaultChar As Long) As Long

Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
  Erase b
  len_s = Len(s)
  If len_s = 0 Then _
    Err.Raise 30030, , "Len(WideChars) = 0"
  ptr_s = StrPtr(s)
  size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
  If size = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte() = 0"
  ReDim b(0 To size - 1)
  If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub

Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
  s = "äöüßµ@€|~{}[]²³\ .." & _
    " OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
    ", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
  file = FreeFile
  Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
  getUtf8 s, b
  Put #file, , b
  Close #file
End Sub

How can I take an UIImage and give it a black border?

all these answers work fine BUT add a rect to an image. Suppose You have a shape (in my case a butterfly) and You want to add a border (a red border):

we need two steps: 1) take the image, convert to CGImage, pass to a function to draw offscreen in a context using CoreGraphics, and give back a new CGImage

2) convert to uiimage back and draw:

// remember to release object!
+ (CGImageRef)createResizedCGImage:(CGImageRef)image toWidth:(int)width
andHeight:(int)height
{
// create context, keeping original image properties
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width,
                                             height,
                                             8
                                             4 * width,
                                             colorspace,
                                             kCGImageAlphaPremultipliedFirst
                                             );

 CGColorSpaceRelease(colorspace);

if(context == NULL)
    return nil;

// draw image to context (resizing it)
CGContextSetInterpolationQuality(context, kCGInterpolationDefault);

CGSize offset = CGSizeMake(2,2);
CGFloat blur = 4;   
CGColorRef color = [UIColor redColor].CGColor;
CGContextSetShadowWithColor ( context, offset, blur, color);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return imgRef;

}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

CGRect frame = CGRectMake(0,0,160, 122);
UIImage * img = [UIImage imageNamed:@"butterfly"]; // take low res OR high res, but frame should be the low-res one.
imgV = [[UIImageView alloc]initWithFrame:frame];
[imgV setImage: img];
imgV.center = self.view.center;
[self.view addSubview: imgV];

frame.size.width = frame.size.width * 1.3;
frame.size.height = frame.size.height* 1.3;
CGImageRef cgImage =[ViewController createResizedCGImage:[img CGImage] toWidth:frame.size.width andHeight: frame.size.height ];

imgV2 = [[UIImageView alloc]initWithFrame:frame];
[imgV2 setImage: [UIImage imageWithCGImage:cgImage] ];

// release:
if (cgImage) CGImageRelease(cgImage);

[self.view addSubview: imgV2];

}

I added a normal butterfly and a red-bordered bigger butterfly.

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

Is Google Play Store supported in avd emulators?

Starting from Android Studio 2.3.2 now you can create an AVD that has Play Store pre-installed on it. Currently, it is supported on the AVD's running

  • A device definition of Nexus 5 or 5X phone, or any Android Wear
  • A system image since Android 7.0 (API 24)

Official Source

For other emulators, you can try the solution mentioned in this answer.

How can I trim beginning and ending double quotes from a string?

To remove the first character and last character from the string, use:

myString = myString.substring(1, myString.length()-1);

Angular @ViewChild() error: Expected 2 arguments, but got 1

Use this

@ViewChild(ChildDirective, {static: false}) Component

Do I need to explicitly call the base virtual destructor?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

Remove HTML tags from string including &nbsp in C#

I've been using this function for a while. Removes pretty much any messy html you can throw at it and leaves the text intact.

        private static readonly Regex _tags_ = new Regex(@"<[^>]+?>", RegexOptions.Multiline | RegexOptions.Compiled);

        //add characters that are should not be removed to this regex
        private static readonly Regex _notOkCharacter_ = new Regex(@"[^\w;&#@.:/\\?=|%!() -]", RegexOptions.Compiled);

        public static String UnHtml(String html)
        {
            html = HttpUtility.UrlDecode(html);
            html = HttpUtility.HtmlDecode(html);

            html = RemoveTag(html, "<!--", "-->");
            html = RemoveTag(html, "<script", "</script>");
            html = RemoveTag(html, "<style", "</style>");

            //replace matches of these regexes with space
            html = _tags_.Replace(html, " ");
            html = _notOkCharacter_.Replace(html, " ");
            html = SingleSpacedTrim(html);

            return html;
        }

        private static String RemoveTag(String html, String startTag, String endTag)
        {
            Boolean bAgain;
            do
            {
                bAgain = false;
                Int32 startTagPos = html.IndexOf(startTag, 0, StringComparison.CurrentCultureIgnoreCase);
                if (startTagPos < 0)
                    continue;
                Int32 endTagPos = html.IndexOf(endTag, startTagPos + 1, StringComparison.CurrentCultureIgnoreCase);
                if (endTagPos <= startTagPos)
                    continue;
                html = html.Remove(startTagPos, endTagPos - startTagPos + endTag.Length);
                bAgain = true;
            } while (bAgain);
            return html;
        }

        private static String SingleSpacedTrim(String inString)
        {
            StringBuilder sb = new StringBuilder();
            Boolean inBlanks = false;
            foreach (Char c in inString)
            {
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case '\t':
                    case ' ':
                        if (!inBlanks)
                        {
                            inBlanks = true;
                            sb.Append(' ');
                        }   
                        continue;
                    default:
                        inBlanks = false;
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString().Trim();
        }

Android Studio is slow (how to speed up)?

to sum it up

1) in AndroidStudio's settings > compile enable checkbox named Compile independent modules in parallel.

2) Under Help> Edit Custom VM Options I have:

-Xms1024m 
-Xmx4096m # <------ increase this to most of your RAM 
-XX:MaxPermSize=1024m 
-XX:ReservedCodeCacheSize=440m 
-XX:+UseCompressedOops 
-XX:-HeapDumpOnOutOfMemoryError 
-Dfile.encoding=UTF-8

P.S. - Some people say Note, instead of VM options, it's better to combine can be overriden by combining those lines into one line single command in gradle.properties, like this :

org.gradle.jvmargs=-Xms1024m -Xmx4096m ......

3) I have an old dual core with 4GB ram, running ubuntu. Qs command line option I have only --offline (which specifies that the build should operate without accessing network resources). I also enabled the remaining checkboxes and now it's running ok:

  • Make project automatically

  • Use in-process building Configure on demand

  • Check the AndroidStudio's settings, under compile that the checkbox Compile independent modules in parallel is enabled.

Under Vmoptions I have

-Xmx2048m -XX:MaxPermSize=1024

I have an old dual core with 4GB ram, running ubuntu. Qs commandline option I have only --offline , which specifies that the build should operate without accessing network resources. I enabled also the remaining checkboxes:

  1. Make project automatically
  2. Use in-process building
  3. Configure on demand

    and it is running ok

Edit

It is possible to provide additional options through studio.vmoptions located at (just replace X.X with version):

  • Windows: go to %USERPROFILE%\.AndroidStudioX.X\studio.exe.vmoptions (or studio64.exe.vmoptions)

  • Mac: ~/Library/Preferences/.AndroidStudioX.X/studio.vmoptions

  • Linux: ~/.AndroidStudioX.X/studio.vmoptions (and/or studio64.vmoptions)

Increasing the value of -Xmx should help a lot. E.g

-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=256m
-XX:+UseCompressedOops

will assign 4G as max heap, with initial value of 1G

Edit:

On windows the defaults are stored into C:\Program Files\Android\Android Studio\bin\*.vmoptions. The IDE allows you to tweak those values through Help->Edit Custom VM options (thanks to @Code-Read for pointing it out).

EDIT 2:

Android studio 3.5 makes easier to change same of those values. Just go to:

Preferences > Appearance & Behavior > System Settings > Memory Settings

Make outer div be automatically the same height as its floating content

First of all you don't use width=300px that's an attribute setting for the tag not CSS, use width: 300px; instead.

I would suggest applying the clearfix technique on the #outerdiv. Clearfix is a general solution to clear 2 floating divs so the parent div will expand to accommodate the 2 floating divs.

<div id='outerdiv' class='clearfix' style='width:600px; background-color: black;'>
    <div style='width:300px; float: left;'>
        <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
    </div>

    <div style='width:300px; float: left;'>
        <p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
    </div>
</div>

Here is an example of your situation and what Clearfix does to resolve it.

Is there a naming convention for git repositories?

lowercase-with-hyphens is the style I most often see on GitHub.*

lowercase_with_underscores is probably the second most popular style I see.

The former is my preference because it saves keystrokes.

* Anecdotal; I haven't collected any data.

How to cast or convert an unsigned int to int in C?

IMHO this question is an evergreen. As stated in various answers, the assignment of an unsigned value that is not in the range [0,INT_MAX] is implementation defined and might even raise a signal. If the unsigned value is considered to be a two's complement representation of a signed number, the probably most portable way is IMHO the way shown in the following code snippet:

#include <limits.h>
unsigned int u;
int i;

if (u <= (unsigned int)INT_MAX)
  i = (int)u; /*(1)*/
else if (u >= (unsigned int)INT_MIN)
  i = -(int)~u - 1; /*(2)*/
else
  i = INT_MIN; /*(3)*/
  • Branch (1) is obvious and cannot invoke overflow or traps, since it is value-preserving.

  • Branch (2) goes through some pains to avoid signed integer overflow by taking the one's complement of the value by bit-wise NOT, casts it to 'int' (which cannot overflow now), negates the value and subtracts one, which can also not overflow here.

  • Branch (3) provides the poison we have to take on one's complement or sign/magnitude targets, because the signed integer representation range is smaller than the two's complement representation range.

This is likely to boil down to a simple move on a two's complement target; at least I've observed such with GCC and CLANG. Also branch (3) is unreachable on such a target -- if one wants to limit the execution to two's complement targets, the code could be condensed to

#include <limits.h>
unsigned int u;
int i;

if (u <= (unsigned int)INT_MAX)
  i = (int)u; /*(1)*/
else
  i = -(int)~u - 1; /*(2)*/

The recipe works with any signed/unsigned type pair, and the code is best put into a macro or inline function so the compiler/optimizer can sort it out. (In which case rewriting the recipe with a ternary operator is helpful. But it's less readable and therefore not a good way to explain the strategy.)

And yes, some of the casts to 'unsigned int' are redundant, but

  • they might help the casual reader

  • some compilers issue warnings on signed/unsigned compares, because the implicit cast causes some non-intuitive behavior by language design

Set JavaScript variable = null, or leave undefined?

Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:

_x000D_
_x000D_
var a, b = null;_x000D_
_x000D_
c = {a, b};_x000D_
_x000D_
console.log(c);_x000D_
console.log(JSON.stringify(c)) // a omited
_x000D_
_x000D_
_x000D_

*or some utility function/library that works in similar way or uses JSON.stringify underneath

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

If WorkSheet("wsName") Exists

Another version of the function without error handling. This time it is not case sensitive and a little bit more efficient.

Function WorksheetExists(wsName As String) As Boolean
    Dim ws As Worksheet
    Dim ret As Boolean        
    wsName = UCase(wsName)
    For Each ws In ThisWorkbook.Sheets
        If UCase(ws.Name) = wsName Then
            ret = True
            Exit For
        End If
    Next
    WorksheetExists = ret
End Function

C# Enum - How to Compare Value

You should convert the string to an enumeration value before comparing.

Enum.TryParse("Retailer", out AccountType accountType);

Then

if (userProfile?.AccountType == accountType)
{
    //your code
}

Difference between long and int data types

From this reference:

An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease.

Also, this bit:

On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platforms, such as Windows and Linux, run primarily on 32 bit processors and most compilers for these platforms use a 32 bit int which has the same size and representation as a long.

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

To the power of in C?

just use pow(a,b),which is exactly 3**4 in python

How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

NGINX to reverse proxy websockets AND enable SSL (wss://)?

for .net core 2.0 Nginx with SSL

location / {
    # redirect all HTTP traffic to localhost:8080
    proxy_pass http://localhost:8080;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # WebSocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
}

This worked for me

How to display count of notifications in app launcher icon

I have figured out how this is done for Sony devices.

I've blogged about it here. I've also posted a seperate SO question about this here.


Sony devices use a class named BadgeReciever.

  1. Declare the com.sonyericsson.home.permission.BROADCAST_BADGE permission in your manifest file:

  2. Broadcast an Intent to the BadgeReceiver:

    Intent intent = new Intent();
    
    intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
    
    sendBroadcast(intent);
    
  3. Done. Once this Intent is broadcast the launcher should show a badge on your application icon.

  4. To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE set to false:

    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
    

I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.

How can I generate a tsconfig.json file?

i am using this,

yarn tsc --init

this fixed it for me

Remove rows with all or some NAs (missing values) in data.frame

Assuming dat as your dataframe, the expected output can be achieved using

1.rowSums

> dat[!rowSums((is.na(dat))),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

2.lapply

> dat[!Reduce('|',lapply(dat,is.na)),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

Is there any "font smoothing" in Google Chrome?

Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing property on yer h4 tags like this.

h4 {
    -webkit-font-smoothing: antialiased;
}

You can also use subpixel-antialiased, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.

Variables as commands in bash scripts

eval is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:

If you need to build up your commands over time, use arrays:

tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"

Alternately, if this is just about defining your commands in one central place, use functions:

tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd

How to write a:hover in inline CSS?

While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.

Approach CSS only

CSS


/* Set your parent color for the inherit property */
.sidebar {
  color: green;
}

/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
  color: inherit
}

.list-item a:hover {
  color: inherit
}

/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
  color: inherit !important;
}

Then your markup will be somewhat like:

Markup

<nav class="sidebar">
  <ul>
    <li class="list-item">
      <a
        href="/foo"
        class="dynamic-hover-color"
        style="color: #{{category.color}};"
      >
        Category
      </a>
    </li>
  </ul>
</nav>

I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)

Determine installed PowerShell version

The below cmdlet will return the PowerShell version.

$PSVersionTable.PSVersion.Major

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

How can I multiply all items in a list together with Python?

I would use the numpy.prod to perform the task. See below.

import numpy as np
mylist = [1, 2, 3, 4, 5, 6] 
result = np.prod(np.array(mylist))  

How to parse float with two decimal places in javascript?

If you need performance (like in games):

Math.round(number * 100) / 100

It's about 100 times as fast as parseFloat(number.toFixed(2))

http://jsperf.com/parsefloat-tofixed-vs-math-round

What svn command would list all the files modified on a branch?

svn log -q -v shows paths and hides comments. All the paths are indented so you can search for lines starting with whitespace. Then pipe to cut and sort to tidy up:

svn log --stop-on-copy -q -v | grep '^[[:space:]]'| cut -c6- | sort -u

This gets all the paths mentioned on the branch since its branch point. Note it will list deleted and added, as well as modified files. I just used this to get the stuff I should worry about reviewing on a slightly messy branch from a new dev.

Transparent scrollbar with css

if you don't have any content with 100% width, you can set the background color of the track to the same color of the body's background

How can I get screen resolution in java?

Here is a snippet of code I often use. It returns the full available screen area (even on multi-monitor setups) while retaining the native monitor positions.

public static Rectangle getMaximumScreenBounds() {
    int minx=0, miny=0, maxx=0, maxy=0;
    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    for(GraphicsDevice device : environment.getScreenDevices()){
        Rectangle bounds = device.getDefaultConfiguration().getBounds();
        minx = Math.min(minx, bounds.x);
        miny = Math.min(miny, bounds.y);
        maxx = Math.max(maxx,  bounds.x+bounds.width);
        maxy = Math.max(maxy, bounds.y+bounds.height);
    }
    return new Rectangle(minx, miny, maxx-minx, maxy-miny);
}

On a computer with two full-HD monitors, where the left one is set as the main monitor (in Windows settings), the function returns

java.awt.Rectangle[x=0,y=0,width=3840,height=1080]

On the same setup, but with the right monitor set as the main monitor, the function returns

java.awt.Rectangle[x=-1920,y=0,width=3840,height=1080]

XAMPP - MySQL shutdown unexpectedly

In my case in which I synced my mysql data and htdocs to dropbox, I just needed to delete the conflicted files in mysql/data folder and subfolders. The conflicted files can be identified by its names, dropbox will tell you that. It has solved the problem for me.

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

string minusvalue = TextBox1.Text.ToString();

if (Convert.ToDouble(minusvalue) < 0)
{ 
    // set color of text in TextBox1 to red color and bold.
    TextBox1.ForeColor = Color.Red;
}

sql select with column name like

Thank you @Blorgbeard for the genious idea.

By the way Blorgbeard's query was not working for me so I edited it:

DECLARE @Table_Name as VARCHAR(50) SET @Table_Name = 'MyTable'          -- put here you table name
DECLARE @Column_Like as VARCHAR(20) SET @Column_Like = '%something%'    -- put here you element
DECLARE @sql NVARCHAR(MAX) SET @sql = 'select '

SELECT @sql = @sql + '[' + sys.columns.name + '],'
FROM sys.columns 
JOIN sys.tables ON sys.columns.object_id = tables.object_id
WHERE sys.columns.name like @Column_Like
and sys.tables.name = @Table_Name

SET @sql = left(@sql,len(@sql)-1) -- remove trailing comma
SET @sql = @sql + ' from ' + @Table_Name

EXEC sp_executesql @sql

Delete file from internal storage

You can also use: file.getCanonicalFile().delete();

Bootstrap 3 .col-xs-offset-* doesn't work?

You could get the offset set only for xs devises by negating the higher pixels with 0 offset. Like so,

class="col-xs-offset-1 col-md-offset-0"

Remove property for all objects in array

To remove some key value pair form object array uses Postgres SQL as database like this example:

This is user function return user details object, we have to remove "api_secret" key from rows :

    function getCurrentUser(req, res, next) { // user function
    var userId = res.locals.userId;
    console.log(userId)
    db.runSQLWithParams("select * from users where id = $1", [userId], function(err, rows) {
      if(err){
        console.log(err)
      }
      var responseObject = {
        _embedded: rows,
      }
      responseObject._embedded[0].api_secret = undefined
      // console.log(api);
      // console.log(responseObject);
      res.json(responseObject);
    }); 
}

The above function return below object as JSON response before

 {
    "_embedded": [
        {
            "id": "0123abd-345gfhgjf-dajd4456kkdj",
            "secret_key: "secret",
            "email": "[email protected]",
            "created": "2020-08-18T00:13:16.077Z"
        }
    ]
}

After adding this line responseObject._embedded[0].api_secret = undefined It gives below result as JSON response:

{
        "_embedded": [
            {
                "id": "0123abd-345gfhgjf-dajd4456kkdj",
                "email": "[email protected]",
                "created": "2020-08-18T00:13:16.077Z"
            }
        ]
    }

R plot: size and resolution

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

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

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

"getaddrinfo failed", what does that mean?

The problem in my case was that I needed to add environment variables for http_proxy and https_proxy.

E.g.,

http_proxy=http://your_proxy:your_port
https_proxy=https://your_proxy:your_port

To set these environment variables in Windows, see the answers to this question.

no match for ‘operator<<’ in ‘std::operator

You need to overload operator << for mystruct class

Something like :-

friend ostream& operator << (ostream& os, const mystruct& m)
{
    os << m.m_a <<" " << m.m_b << endl;
    return os ;
}

See here

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

How about using a simple loop to count the occurrences of number of spaces!?

_x000D_
_x000D_
txt = "Just an example here move along" _x000D_
count = 1_x000D_
for i in txt:_x000D_
if i == " ":_x000D_
   count += 1_x000D_
print(count)
_x000D_
_x000D_
_x000D_

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

I struggled with this problem many times.

The solution I am currently using is weather the webapp(or the folder where you kept the views like jsp) is under deployment assembly.

To do so Right click on the project > Build Path > Configure Build path > Deployment Assembly > Add(right hand side) > Folder > (add your jsp folder. In default case it is src/main/webapp)

You could also get this error after you did everything correct but on the JSP you put the anchor tag the old fashion(I am adding this incase if it help anybody else with the same issue).

I had the following syntax on the jsp. <a href="/mappedpath">TakeMeToTheController</a> and I kept seeing the error mentioned in the question. However changing the tag into the one shown below solved the issue.

<a href=" <spring:url value="/mappedpath" /> ">TakeMeToTheController</a>

No value accessor for form control

If you get this issue, then either

  • the formControlName is not located on the value accessor element.
  • or you're not importing the module for that element.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

Here's my take on the problem. I create AbsoluteLayout overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.

Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).

Code of the demo: https://github.com/deville/info-window-demo

An article providing details (in Russian): http://habrahabr.ru/post/213415/

iptables block access to port 8000 except from IP address

This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:

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

After installing with pip, "jupyter: command not found"

The only thing that worked me is to export to PATH the Python version that is related to the pip3 of course :) (after a lot of struggling) just run:

which pip3

you should get something like (in Mac):

/Library/Frameworks/Python.framework/Versions/3.6/bin/pip3

Now run:

export PATH=/Library/Python/3.6/bin:$PATH

If it works for you :) just add it to your bashrc or zshrc

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

Segmentation fault on large array sizes

You array is being allocated on the stack in this case attempt to allocate an array of the same size using alloc.

Where does Anaconda Python install on Windows?

where conda

F:\Users\christos\Anaconda3\Library\bin\conda.bat

F:\Users\christos\Anaconda3\Scripts\conda.exe

F:\Users\christos\Anaconda3\condabin\conda.bat

F:\Users\christos\Anaconda3\Scripts\conda.exe --version

conda 4.6.11

this worked for me

How to install PHP intl extension in Ubuntu 14.04

For php 5.6 on ubuntu 16.04

sudo apt-get install php5.6-intl

General guidelines to avoid memory leaks in C++

You can intercept the memory allocation functions and see if there are some memory zones not freed upon program exit (though it is not suitable for all the applications).

It can also be done at compile time by replacing operators new and delete and other memory allocation functions.

For example check in this site [Debugging memory allocation in C++] Note: There is a trick for delete operator also something like this:

#define DEBUG_DELETE PrepareDelete(__LINE__,__FILE__); delete
#define delete DEBUG_DELETE

You can store in some variables the name of the file and when the overloaded delete operator will know which was the place it was called from. This way you can have the trace of every delete and malloc from your program. At the end of the memory checking sequence you should be able to report what allocated block of memory was not 'deleted' identifying it by filename and line number which is I guess what you want.

You could also try something like BoundsChecker under Visual Studio which is pretty interesting and easy to use.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How to run multiple sites on one apache instance

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

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

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

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

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

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

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

NameVirtualHost *:80

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

Now your vhost definitions:

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

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

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

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

Linux Command History with date and time

Try this:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

You can adjust the format to your liking, of course.

How to find out what character key is pressed?

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

node.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
});

If you want to make sure only single characters are entered, check key.length === 1, or that it is one of the characters you expect.

Mozilla Docs

Supported Browsers

What exactly do "u" and "r" string flags do, and what are raw string literals?

There are two types of string in python: the traditional str type and the newer unicode type. If you type a string literal without the u in front you get the old str type which stores 8-bit characters, and with the u in front you get the newer unicode type that can store any Unicode character.

The r doesn't change the type at all, it just changes how the string literal is interpreted. Without the r, backslashes are treated as escape characters. With the r, backslashes are treated as literal. Either way, the type is the same.

ur is of course a Unicode string where backslashes are literal backslashes, not part of escape codes.

You can try to convert a Unicode string to an old string using the str() function, but if there are any unicode characters that cannot be represented in the old string, you will get an exception. You could replace them with question marks first if you wish, but of course this would cause those characters to be unreadable. It is not recommended to use the str type if you want to correctly handle unicode characters.

OpenSSL Command to check if a server is presenting a certificate

I was debugging an SSL issue today which resulted in the same write:errno=104 error. Eventually I found out that the reason for this behaviour was that the server required SNI (servername TLS extensions) to work correctly. Supplying the -servername option to openssl made it connect successfully:

openssl s_client -connect domain.tld:443 -servername domain.tld

Hope this helps.

How to select data of a table from another database in SQL Server?

Using Microsoft SQL Server Management Studio you can create Linked Server. First make connection to current (local) server, then go to Server Objects > Linked Servers > context menu > New Linked Server. In window New Linked Server you have to specify desired server name for remote server, real server name or IP address (Data Source) and credentials (Security page).

And further you can select data from linked server:

select * from [linked_server_name].[database].[schema].[table]

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Looking over these solutions, the one provided by Al Johri above is the closest to my needs, but his directive was a little less programmable then I wanted. Here is my version of his solutions:

angular.module("app", [])
    .directive("dynamicFormName", function() {
        return {
            restrict: "A",
            priority: 0,
            require: ["form"],
            compile: function() {
                return {
                    pre: function preLink(scope, iElement, iAttrs, ctrls) {
                        var name = "field" + scope.$index;

                        if (iAttrs.dnfnNameExpression) {
                            name = scope.$eval(iAttrs.dnfnNameExpression);
                        }

                        var parentForm = iElement.parent().controller("form");
                        if (parentForm) {
                            var formCtrl = ctrls[0];
                            delete parentForm[formCtrl.$name];
                            formCtrl.$name = name;
                            parentForm[formCtrl.$name] = formCtrl;
                        }
                    }
                 }
            }
        };
   });

This solution lets you just pass a name generator expression to the directive and avoids the lock down to pattern substitution he was using.

I also had trouble initially with this solution since it didn't show an example of using it in markup, so here is how I used it.

<form name="theForm">
    <div ng-repeat="field in fields">
        <input type="number" ng-form name="theInput{{field.id}}" ng-model="field.value" dynamic-form-name dnfn-name-expression="'theInput' + field.id">        
    </div>
</form>

I have a more complete working example on github.

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

How to create a floating action button (FAB) in android, using AppCompat v21?

Add padding and elevation:

 android:elevation="10dp"
 android:padding="10dp"

Passing ArrayList from servlet to JSP

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");

        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        /////////////////////////
        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

        //////////////////////////////////////////////////////////
        out.println(
                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while (rs.next()) {
                Actor actor = new Actor();
                actor.setId(rs.getInt("id"));
                actor.setLastname(rs.getString("lastname"));
                actor.setFirstname(rs.getString("firstname"));
                list.add(actor);
            }
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {
            }
        }
        out.println("</body></html>");

        out.close();
    }

}

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

Working with varchars is fundamentally slow and inefficient compared to working with numerics, for obvious reasons. The functions you link to in the original post will indeed be quite slow, as they loop through each character in the string to determine whether or not it's a number. Do that for thousands of records and the process is bound to be slow. This is the perfect job for Regular Expressions, but they're not natively supported in SQL Server. You can add support using a CLR function, but it's hard to say how slow this will be without trying it I would definitely expect it to be significantly faster than looping through each character of each phone number, however!

Once you get the phone numbers formatted in your database so that they're only numbers, you could switch to a numeric type in SQL which would yield lightning-fast comparisons against other numeric types. You might find that, depending on how fast your new data is coming in, doing the trimming and conversion to numeric on the database side is plenty fast enough once what you're comparing to is properly formatted, but if possible, you would be better off writing an import utility in a .NET language that would take care of these formatting issues before hitting the database.

Either way though, you're going to have a big problem regarding optional formatting. Even if your numbers are guaranteed to be only North American in origin, some people will put the 1 in front of a fully area-code qualified phone number and others will not, which will cause the potential for multiple entries of the same phone number. Furthermore, depending on what your data represents, some people will be using their home phone number which might have several people living there, so a unique constraint on it would only allow one database member per household. Some would use their work number and have the same problem, and some would or wouldn't include the extension which would cause artificial uniqueness potential again.

All of that may or may not impact you, depending on your particular data and usages, but it's important to keep in mind!

href="javascript:" vs. href="javascript:void(0)"

Why have all the click events as a href links?

If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

Android ViewPager with bottom dots

Here is how I did this, somewhat similar to the solutions above. Just make sure you call the loadDots() method after all images are downloaded.

    private int dotsCount;
    private TextView dotsTextView[];

    private void setupAdapter() {
        adapter = new SomeAdapter(getContext(), images);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
    }

    private final ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < dotsCount; i++)
                dotsTextView[i].setTextColor(Color.GRAY);

            dotsTextView[position].setTextColor(Color.WHITE);
        }

        @Override
        public void onPageScrollStateChanged(int state) {}
    };

    protected void loadDots() {
        dotsCount = adapter.getCount();
        dotsTextView = new TextView[dotsCount];
        for (int i = 0; i < dotsCount; i++) {
            dotsTextView[i] = new TextView(getContext());
            dotsTextView[i].setText(R.string.dot);
            dotsTextView[i].setTextSize(45);
            dotsTextView[i].setTypeface(null, Typeface.BOLD);
            dotsTextView[i].setTextColor(android.graphics.Color.GRAY);
            mDotsLayout.addView(dotsTextView[i]);
        }
        dotsTextView[0].setTextColor(Color.WHITE);
    }

XML

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:background="#00000000"/>


    <ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/introImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:id="@+id/image_count"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00000000"
        android:gravity="center|bottom"
        android:orientation="horizontal"/>
</FrameLayout>

There is no tracking information for the current branch

git branch --set-upstream-to=origin/main

Java: how to initialize String[]?

String[] errorSoon = { "foo", "bar" };

-- or --

String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Count distinct value pairs in multiple columns in SQL

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

github changes not staged for commit

Is week1 a submodule?

Note the relevant part from the output of the git status command:

(commit or discard the untracked or modified content in submodules)

Try cd week1 and issuing another git status to see what changes you have made to the week1 submodule.

See http://git-scm.com/book/en/Git-Tools-Submodules for more information about how submodules work in Git.

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

Tesseract running error

I'm using windows OS, I tried all solutions above and none of them work.

Finally, I install Tesseract-OCR on D drive(Where I run my python script from) instead of C drive and it works.

So, if you are using windows, run your python script in the same drive as your Tesseract-OCR.

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

Using Exit button to close a winform program

Remove the method, I suspect you might also need to remove it from your Form.Designer.

Otherwise: Application.Exit();

Should work.

That's why the designer is bad for you. :)

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Visual Studio, when starting up, will (for some reason) attempt to access the URL:

/debugattach.aspx

If you have a rewrite rule that redirects (or otherwise catches), say, .aspx files, somewhere else then you will get this error. The solution is to add this section to the beginning of your web.config's <system.webServer>/<rewrite>/<rules> section:

<rule name="Ignore Default.aspx" enabled="true" stopProcessing="true">
    <match url="^debugattach\.aspx" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
    <action type="None" />
</rule>

This will make sure to catch this one particular request, do nothing, and, most importantly, stop execution so none of your other rules will get run. This is a robust solution, so feel free to keep this in your config file for production.

no default constructor exists for class

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.

C++ Array of pointers: delete or delete []?

It would make sens if your code was like this:

#include <iostream>

using namespace std;

class Monster
{
public:
        Monster() { cout << "Monster!" << endl; }
        virtual ~Monster() { cout << "Monster Died" << endl; }
};

int main(int argc, const char* argv[])
{
        Monster *mon = new Monster[6];

        delete [] mon;

        return 0;
}

Use dynamic variable names in JavaScript

In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.

Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.

var id = "abc";
var mine = {};
mine[id] = 123;
console.log(mine.abc);

gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.

var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);

How to auto import the necessary classes in Android Studio with shortcut?

On my Mac Auto import option was not showing it was initially hidden

Android studio ->Preferences->editor->General->Auto Import

and then typed in searched field auto then auto import option appeared. And now auto import option is now always shown as default in Editor->General. hopefully this option will also help others. See attached screenshot screenshot

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I had similar issue and just wanted to post an answer for others in my situation.

I have a solution running a ASP.NET Web Application with multiple other C# class lib projects.

My ASP.NET Web Application wasn't using json, but other projects where.

This is how I fixed it:

  1. I made sure all projects where using latest version (6) using NuGet Update on all projects currently using any version of json - this didn't fix the issue
  2. I added json to the web application using NuGet - this fixed the issue (let me dive into why):

Step 2 was first of all adding a configuration information for json, that suggest that all projects, use the latest version (6) no matter what version they have. Adding the assembly binding to Web.Config is most likely the fix.

However, step 2 also cleaned up som legacy code. It turned out we have previously used an old version (5) of json in our Web Application and the NuGet folders wasn't deleted when the reference was (I suspect: manually) removed. Adding the latest json (6), removed the old folders (json v5). This might be part of the fix as well.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

How does `scp` differ from `rsync`?

scp is best for one file.
OR a combination of tar & compression for smaller data sets like source code trees with small resources (ie: images, sqlite etc).


Yet, when you begin dealing with larger volumes say:

  • media folders (40 GB)
  • database backups (28 GB)
  • mp3 libraries (100 GB)

It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.

As an exercise, you can do some gymnastics like piping tar into ssh and redirecting the results into a remote file. (saving the need to build a swap or temporary clone aka zip or tar.gz)

However,

rsync simplify's this process and allows you to transfer data without consuming any additional disc space.

Also,

Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.

tl;dr
scp == small scale (with room to build compressed files on the same drive)
rsync == large scale (with the necessity to backup large data and no room left)

What are the alternatives now that the Google web search API has been deprecated?

You could just send them through like a browser does, and then parse the html, that is what I have always done, even for things like Youtube.

How to install an apk on the emulator in Android Studio?

In Android Studio: View - Tool Windows - Gradle

In the Gradle tool window navigate to your :app - Tasks - install and then execute (by double-clicking): any of your install*tasks: e.g. installDebug, installRelease

Note: the apk will also automatically installed when you Run your application

How to find my php-fpm.sock?

When you look up your php-fpm.conf

example location:
cat /usr/src/php/sapi/fpm/php-fpm.conf

you will see, that you need to configure the PHP FastCGI Process Manager to actually use Unix sockets. Per default, the listen directive` is set up to listen on a TCP socket on one port. If there's no Unix socket defined, you won't find a Unix socket file.

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all IPv4 addresses on a
;                            specific port;
;   '[::]:port'            - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

Real escape string and PDO

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

Deck of cards JAVA

I think the solution is just as simple as this:

Card temp = deck[cardAindex];
deck[cardAIndex]=deck[cardBIndex]; 
deck[cardBIndex]=temp;

Is there a Social Security Number reserved for testing/examples?

all zeros would probably be the most obvious that it wasn't a real SSN.

Pretty-Print JSON Data to a File using Python

You could redirect a file to python and open using the tool and to read it use more.

The sample code will be,

cat filename.json | python -m json.tool | more

Closing Applications

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread(). This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run().

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

I hope it is best to use Application.Exit

See also these links:

Get bottom and right position of an element

Vanilla Javascript Answer

var c = document.getElementById("myElement").getBoundingClientRect();
var bot = c.bottom;
var rgt = c.right;

To be clear the element can be anything so long as you have allocated an id to it <img> <div> <p> etc.

for example

<img
    id='myElement'
    src='/img/logout.png'
    className='logoutImg img-button'
    alt='Logout'
/>

ComboBox- SelectionChanged event has old value, not new value

This worked for me:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    var text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;            
}

Socket.IO - how do I get a list of connected sockets/clients?

I believe you can access this from the socket's manager property?

var handshaken = io.manager.handshaken;
var connected = io.manager.connected;
var open = io.manager.open;
var closed = io.manager.closed;

python variable NameError

I would approach it like this:

sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s)                 for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1):     size = sizes[choice - 1] # note index offset from choice print "You  want to create a random song list that is {0}Mb.".format(size) 

You could also loop until you get an acceptable answer and cover yourself in case of error:

choice = 0 while choice not in range(1, len(sizes) + 1): # loop     try: # guard against error         choice = int(raw_input(...))     except ValueError: # couldn't make an int         print "Please enter a number"         choice = 0 size = sizes[choice - 1] # now definitely valid 

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):

>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0    False
1     True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  res_values = method(rvalues)
0    False
1    False

I think with pandas 1.0 they really want you to use the new 'string' datatype which allows for pd.NA values:

>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0    False
1    False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0    <NA>
1    <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0    False
1    False

Don't love at which point they tinkered with every-day functionality such as boolean indexing.

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

What's "tools:context" in Android layout files?

tools:context=".MainActivity" thisline is used in xml file which indicate that which java source file is used to access this xml file. it means show this xml preview for perticular java files.

Why shouldn't I use mysql_* functions in PHP?

Speaking of technical reasons, there are only a few, extremely specific and rarely used. Most likely you will never ever use them in your life.
Maybe I am too ignorant, but I never had an opportunity to use them things like

  • non-blocking, asynchronous queries
  • stored procedures returning multiple resultsets
  • Encryption (SSL)
  • Compression

If you need them - these are no doubt technical reasons to move away from mysql extension toward something more stylish and modern-looking.

Nevertheless, there are also some non-technical issues, which can make your experience a bit harder

  • further use of these functions with modern PHP versions will raise deprecated-level notices. They simply can be turned off.
  • in a distant future, they can be possibly removed from the default PHP build. Not a big deal too, as mydsql ext will be moved into PECL and every hoster will be happy to compile PHP with it, as they don't want to lose clients whose sites were working for decades.
  • strong resistance from Stackoverflow community. ?verytime you mention these honest functions, you being told that they are under strict taboo.
  • being an average PHP user, most likely your idea of using these functions is error-prone and wrong. Just because of all these numerous tutorials and manuals which teach you the wrong way. Not the functions themselves - I have to emphasize it - but the way they are used.

This latter issue is a problem.
But, in my opinion, the proposed solution is no better either.
It seems to me too idealistic a dream that all those PHP users will learn how to handle SQL queries properly at once. Most likely they would just change mysql_* to mysqli_* mechanically, leaving the approach the same. Especially because mysqli makes prepared statements usage incredible painful and troublesome.
Not to mention that native prepared statements aren't enough to protect from SQL injections, and neither mysqli nor PDO offers a solution.

So, instead of fighting this honest extension, I'd prefer to fight wrong practices and educate people in the right ways.

Also, there are some false or non-significant reasons, like

  • Doesn't support Stored Procedures (we were using mysql_query("CALL my_proc"); for ages)
  • Doesn't support Transactions (same as above)
  • Doesn't support Multiple Statements (who need them?)
  • Not under active development (so what? does it affect you in any practical way?)
  • Lacks an OO interface (to create one is a matter of several hours)
  • Doesn't support Prepared Statements or Parametrized Queries

The last one is an interesting point. Although mysql ext do not support native prepared statements, they aren't required for the safety. We can easily fake prepared statements using manually handled placeholders (just like PDO does):

function paraQuery()
{
    $args  = func_get_args();
    $query = array_shift($args);
    $query = str_replace("%s","'%s'",$query); 

    foreach ($args as $key => $val)
    {
        $args[$key] = mysql_real_escape_string($val);
    }

    $query  = vsprintf($query, $args);
    $result = mysql_query($query);
    if (!$result)
    {
        throw new Exception(mysql_error()." [$query]");
    }
    return $result;
}

$query  = "SELECT * FROM table where a=%s AND b LIKE %s LIMIT %d";
$result = paraQuery($query, $a, "%$b%", $limit);

voila, everything is parameterized and safe.

But okay, if you don't like the red box in the manual, a problem of choice arises: mysqli or PDO?

Well, the answer would be as follows:

  • If you understand the necessity of using a database abstraction layer and looking for an API to create one, mysqli is a very good choice, as it indeed supports many mysql-specific features.
  • If, like vast majority of PHP folks, you are using raw API calls right in the application code (which is essentially wrong practice) - PDO is the only choice, as this extension pretends to be not just API but rather a semi-DAL, still incomplete but offers many important features, with two of them makes PDO critically distinguished from mysqli:

    • unlike mysqli, PDO can bind placeholders by value, which makes dynamically built queries feasible without several screens of quite messy code.
    • unlike mysqli, PDO can always return query result in a simple usual array, while mysqli can do it only on mysqlnd installations.

So, if you are an average PHP user and want to save yourself a ton of headaches when using native prepared statements, PDO - again - is the only choice.
However, PDO is not a silver bullet too and has its hardships.
So, I wrote solutions for all the common pitfalls and complex cases in the PDO tag wiki

Nevertheless, everyone talking about extensions always missing the 2 important facts about Mysqli and PDO:

  1. Prepared statement isn't a silver bullet. There are dynamical identifiers which cannot be bound using prepared statements. There are dynamical queries with an unknown number of parameters which makes query building a difficult task.

  2. Neither mysqli_* nor PDO functions should have appeared in the application code.
    There ought to be an abstraction layer between them and application code, which will do all the dirty job of binding, looping, error handling, etc. inside, making application code DRY and clean. Especially for the complex cases like dynamical query building.

So, just switching to PDO or mysqli is not enough. One has to use an ORM, or a query builder, or whatever database abstraction class instead of calling raw API functions in their code.
And contrary - if you have an abstraction layer between your application code and mysql API - it doesn't actually matter which engine is used. You can use mysql ext until it goes deprecated and then easily rewrite your abstraction class to another engine, having all the application code intact.

Here are some examples based on my safemysql class to show how such an abstraction class ought to be:

$city_ids = array(1,2,3);
$cities   = $db->getCol("SELECT name FROM cities WHERE is IN(?a)", $city_ids);

Compare this one single line with amount of code you will need with PDO.
Then compare with crazy amount of code you will need with raw Mysqli prepared statements. Note that error handling, profiling, query logging already built in and running.

$insert = array('name' => 'John', 'surname' => "O'Hara");
$db->query("INSERT INTO users SET ?u", $insert);

Compare it with usual PDO inserts, when every single field name being repeated six to ten times - in all these numerous named placeholders, bindings, and query definitions.

Another example:

$data = $db->getAll("SELECT * FROM goods ORDER BY ?n", $_GET['order']);

You can hardly find an example for PDO to handle such practical case.
And it will be too wordy and most likely unsafe.

So, once more - it is not just raw driver should be your concern but abstraction class, useful not only for silly examples from beginner's manual but to solve whatever real-life problems.

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

How to copy Docker images from one host to another without using a repository

You will need to save the Docker image as a tar file:

docker save -o <path for generated tar file> <image name>

Then copy your image to a new system with regular file transfer tools such as cp, scp or rsync(preferred for big files). After that you will have to load the image into Docker:

docker load -i <path to image tar file>

PS: You may need to sudo all commands.

EDIT: You should add filename (not just directory) with -o, for example:

docker save -o c:/myfile.tar centos:16

How to show a GUI message box from a bash script in linux?

Example bash script for using Gambas GTK/QT Controls(GUI Objects): The Gambas IDE can be used to design even large GUIs and act as a GUI server. Example expplications can be downloaded from the Gambas App store.
https://gambas.one/gambasfarm/?id=823&action=search

enter image description here

Flutter position stack widget in center

Remove everything, but this:

Align(
  alignment: Alignment.bottomCenter,
  child: new ButtonBar(
    alignment: MainAxisAlignment.center,
    children: <Widget>[
      new OutlineButton(
        onPressed: () {
          Navigator.push(
            context,
            new MaterialPageRoute(
              builder: (context) => new LoginPage()));
        },
        child: new Text(
          "Login",
          style: new TextStyle(color: Colors.white),
        ),
      ),
      new RaisedButton(
        color: Colors.white,
        onPressed: () {
          Navigator.push(
            context,
            new MaterialPageRoute(
              builder: (context) =>
                new RegistrationPage()));
        },
        child: new Text(
          "Register",
          style: new TextStyle(color: Colors.black),
        ),
      )
    ],
  ),
)

In my theory, the additional Container is destroying it. I would advise you to just surround this by adding Padding:

Padding(
  padding: EdgeInsets.only(bottom: 20.0),
  child: Align...
),

This seems a lot more reasonable to me than the Positioned and also I do not quite understand your Column with a single child only.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

The exception can also occur because of the class path not being defined.

After hours of research and literally going through hundreds of pages, the problem was that the class path of the library was not defined.

Set the class path as follows in your windows machine

set classpath=path\to\your\jdbc\jar\file;.

TypeError: 'undefined' is not a function (evaluating '$(document)')

wrap all the script between this...

<script>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
      // Code that uses jQuery's $ can follow here.
    });
</script>

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

SQL Developer is returning only the date, not the time. How do I fix this?

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

Unable to show a Git tree in terminal

How can you get the tree-like view of commits in terminal?

git log --graph --oneline --all

is a good start.

You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your .bashrc:

export LESS="-R"

such that you do not need use Tig's ASCII filter by

git log --graph --pretty=oneline --abbrev-commit | tig   // Masi needed this 

The article text-based graph from Git-ready contains other options:

git log --graph --pretty=oneline --abbrev-commit

git log graph

Regarding the article you mention, I would go with Pod's answer: ad-hoc hand-made output.


Jakub Narebski mentions in the comments tig, a ncurses-based text-mode interface for git. See their releases.
It added a --graph option back in 2007.

Moment.js - two dates difference in number of days

const FindDate = (date, allDate) => {
        
    // moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
    let nearestDate = -1; 
    
    allDate.some(d => {
        const currentDate = moment(d)
        const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
        if(difference >= 0){
            nearestDate = d
        }
    });
    
    console.log(nearestDate)
}

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I had this problem and I realized I had not bound my component to a variable.

Changed

<input #myComponent="ngModel" />

to

<input #myComponent="ngModel" [(ngModel)]="myvar" />

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

ICollection<T> is used because the IEnumerable<T> interface provides no way of adding items, removing items, or otherwise modifying the collection.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Find out whether radio button is checked with JQuery?

dynamic generated Radio Button Check radio get value

$("input:radio[name=radiobuttonname:checked").val();

On change dynamic Radio button

$('input[name^="radioname"]').change(function () {if (this.value == 2) { }else{}});