Programs & Examples On #Tree structure

Error: stray '\240' in program

SOLUTION: DELETE THAT LINE OF CODE [*IF YOU COPIED IT FROM ANOTHER SOURCE DOCUMENT] AND TYPE IT YOURSELF.

Error: stray '\240' in program is simply a character encoding error message.

From my experience, it is just a matter of character encoding. For example, if you copy a piece of code from a web page or you first write it in a text editor before copying and pasting in an IDE, it can come with the character encoding of the source document or editor.

browser.msie error after update to jQuery 1.9.1

Update! Complete answer overhaul for new plugin!

The following plugin has been tested in all major browsers. It makes traditional use of userAgent string to re-equip jQuery.browser only if you're using jQuery version 1.9 or Greater!

It has the traditional jQuery.browser.msie type properties as well as a few new ones, including a .mobile property to help decide if user is on a mobile device.

Note: This is not a suitable replacement for feature testing. If you expect to support a specific feature on a specific device, it's still best to use traditional feature testing

_x000D_
_x000D_
/** jQuery.browser_x000D_
 * @author J.D. McKinstry (2014)_x000D_
 * @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
 * @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
 *_x000D_
 * @extends jQuery_x000D_
 * @namespace jQuery.browser_x000D_
 * @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
 * @example jQuery.browser.version_x000D_
 * @example jQuery.browser.mobile @returns BOOLEAN_x000D_
 * @example jQuery.browser['browserNameInLowerCase']_x000D_
 * @example jQuery.browser.chrome @returns BOOLEAN_x000D_
 * @example jQuery.browser.safari @returns BOOLEAN_x000D_
 * @example jQuery.browser.opera @returns BOOLEAN_x000D_
 * @example jQuery.browser.msie @returns BOOLEAN_x000D_
 * @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
 * @example jQuery.browser.webkit @returns BOOLEAN_x000D_
 * @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
 */_x000D_
;;(function($){var a=$.fn.jquery.split("."),b;for(b in a)a[b]=parseInt(a[b]);if(!$.browser&&(1<a[0]||9<=a[1])){a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?_x000D_
a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].match(/[0-9\.]{1,}/)[0])?parseFloat(a.ua.split("MSIE")[1].match(/[0-9\.]{1,}/)[0]):_x000D_
"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].match(/[0-9\.]{1,}/)[0]))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].match(/[0-9\.]{1,}/)[0])):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",_x000D_
/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0]))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].match(/[0-9\.]{1,}/)[0])):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):_x000D_
/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].match(/[0-9\.]{1,}/)[0])):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].match(/[0-9\.]{1,}/)[0])):_x000D_
/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].match(/[0-9\.]{1,}/)[0])));if(a.browser)for(var c in a.browserArray)a[a.browserArray[c].toLowerCase()]=a.browser==a.browserArray[c];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser);    //    see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
    if (x != 'init')_x000D_
        $('<tr />').append(_x000D_
            $('<th />', { text: x }),_x000D_
            $('<td />', { text: b[x] })_x000D_
        ).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
_x000D_
_x000D_

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

Try using a callback like this with the catch block.

document.getElementById("audio").play().catch(function() {
    // do something
});

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

If you have recently installed or updated the Microsoft.CodeDom.Providers.DotNetCompilerPlatform package, double-check that the versions of that package referenced in your project point to the correct, and same, version of that package:

  • In ProjectName.csproj, ensure that an <Import> tag for Microsoft.CodeDom.Providers.DotNetCompilerPlatform is present and points to the correct version.

  • In ProjectName.csproj, ensure that a <Reference> tag for Microsoft.CodeDom.Providers.DotNetCompilerPlatform is present, and points to the correct version, both in the Include attribute and the child <HintPath>.

  • In that project's web.config, ensure that the <system.codedom> tag is present, and that its child <compiler> tags have the same version in their type attribute.

For some reason, in my case an upgrade of this package from 1.0.5 to 1.0.8 caused the <Reference> tag in the.csproj to have its Include pointing to the old version 1.0.5.0 (which I had deleted after upgrading the package), but everything else was pointing to the new and correct version 1.0.8.0.

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

How do I create a crontab through a script

Well /etc/crontab just an ascii file so the simplest is to just

 echo "*/15 * * * *   root     date" >> /etc/crontab

which will add a job which will email you every 15 mins. Adjust to taste, and test via grep or other means whether the line was already added to make your script idempotent.

On Ubuntu et al, you can also drop files in /etc/cron.* which is easier to do and test for---plus you don't mess with (system) config files such as /etc/crontab.

Sending emails with Javascript

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

How to _really_ programmatically change primary and accent color in Android Lollipop?

I used the Dahnark's code but I also need to change the ToolBar background:

if (dark_ui) {
    this.setTheme(R.style.Theme_Dark);

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_primary));
        getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_primary_dark));
    }
} else {
    this.setTheme(R.style.Theme_Light);
}

setContentView(R.layout.activity_main);

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

if(dark_ui) {
    toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
}

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

How to Load an Assembly to AppDomain with all references recursively?

You need to invoke CreateInstanceAndUnwrap before your proxy object will execute in the foreign application domain.

 class Program
{
    static void Main(string[] args)
    {
        AppDomainSetup domaininfo = new AppDomainSetup();
        domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);

        Type type = typeof(Proxy);
        var value = (Proxy)domain.CreateInstanceAndUnwrap(
            type.Assembly.FullName,
            type.FullName);

        var assembly = value.GetAssembly(args[0]);
        // AppDomain.Unload(domain);
    }
}

public class Proxy : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            return Assembly.LoadFile(assemblyPath);
        }
        catch (Exception)
        {
            return null;
            // throw new InvalidOperationException(ex);
        }
    }
}

Also, note that if you use LoadFrom you'll likely get a FileNotFound exception because the Assembly resolver will attempt to find the assembly you're loading in the GAC or the current application's bin folder. Use LoadFile to load an arbitrary assembly file instead--but note that if you do this you'll need to load any dependencies yourself.

INNER JOIN in UPDATE sql for DB2

The reference documentation for the UPDATE statement on DB2 LUW 9.7 gives the following example:

   UPDATE (SELECT EMPNO, SALARY, COMM,
     AVG(SALARY) OVER (PARTITION BY WORKDEPT),
     AVG(COMM) OVER (PARTITION BY WORKDEPT)
     FROM EMPLOYEE E) AS E(EMPNO, SALARY, COMM, AVGSAL, AVGCOMM)
   SET (SALARY, COMM) = (AVGSAL, AVGCOMM)
   WHERE EMPNO = '000120'

The parentheses after UPDATE can contain a full-select, meaning any valid SELECT statement can go there.

Based on that, I would suggest the following:

UPDATE (
  SELECT
    f1.firstfield,
    f2.anotherfield,
    f2.something
  FROM file1 f1
  WHERE f1.firstfield like 'BLAH%' 
  INNER JOIN file2 f2
  ON substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
AS my_files(firstfield, anotherfield, something)
SET
  firstfield = ( 'BIT OF TEXT' || something )

Edit: Ian is right. My first instinct was to try subselects instead:

UPDATE file1 f1
SET f1.firstfield = ( 'BIT OF TEXT' || (
  SELECT f2.something
  FROM file2 f2
  WHERE substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
))
WHERE f1.firstfield LIKE 'BLAH%' 
AND substr(f1.firstfield,10,20) IN (
  SELECT substr(f2.anotherfield,1,10)
  FROM file2 f2
)

But I'm not sure if the concatenation would work. It also assumes that there's a 1:1 mapping between the substrings. If there are multiple rows that match, it wouldn't work.

How do I get the HTTP status code with jQuery?

this is possible with jQuery $.ajax() method

$.ajax(serverUrl, {
   type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
   data: dataToSave,
   statusCode: {
      200: function (response) {
         alert('1');
         AfterSavedAll();
      },
      201: function (response) {
         alert('1');
         AfterSavedAll();
      },
      400: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      },
      404: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      }
   }, success: function () {
      alert('1');
   },
});

Why doesn't Java offer operator overloading?

Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.

However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.

// a = b + c
Complex a, b, c; a = b.add(c);

Does MS SQL Server's "between" include the range boundaries?

The BETWEEN operator is inclusive.

From Books Online:

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

DateTime Caveat

NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.

e.g. to get all values within June 2016 you'd need to run:

where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')

i.e.

where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'

datetime2 and datetimeoffset

Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:

where myDateTime >= '20160601' AND myDateTime < '20160701'

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced the same issue but, in my case, I had only to point my project to a JDK instead of the JRE in the build path then it solved the issue and I was able to import all maven dependencies with no problem!

center a row using Bootstrap 3

Simply use text-center class

 <div class="row">
     <div class="col-md-12">
          <h3 class="text-center">Here Comes your Text</h3>
     </div>
 </div>

How to "pretty" format JSON output in Ruby on Rails

I use the following as I find the headers, status and JSON output useful as a set. The call routine is broken out on recommendation from a railscasts presentation at: http://railscasts.com/episodes/151-rack-middleware?autoplay=true

  class LogJson

  def initialize(app)
    @app = app
  end

  def call(env)
    dup._call(env)
  end

  def _call(env)
    @status, @headers, @response = @app.call(env)
    [@status, @headers, self]
  end

  def each(&block)
    if @headers["Content-Type"] =~ /^application\/json/
      obj = JSON.parse(@response.body)
      pretty_str = JSON.pretty_unparse(obj)
      @headers["Content-Length"] = Rack::Utils.bytesize(pretty_str).to_s
      Rails.logger.info ("HTTP Headers:  #{ @headers } ")
      Rails.logger.info ("HTTP Status:  #{ @status } ")
      Rails.logger.info ("JSON Response:  #{ pretty_str} ")
    end

    @response.each(&block)
  end
  end

Map with Key as String and Value as List in Groovy

One additional small piece that is helpful when dealing with maps/list as the value in a map is the withDefault(Closure) method on maps in groovy. Instead of doing the following code:

Map m = [:]
for(object in listOfObjects)
{
  if(m.containsKey(object.myKey))
  {
    m.get(object.myKey).add(object.myValue)
  }
  else
  {
    m.put(object.myKey, [object.myValue]
  }
}

You can do the following:

Map m = [:].withDefault{key -> return []}
for(object in listOfObjects)
{
  List valueList = m.get(object.myKey)
  m.put(object.myKey, valueList)
}

With default can be used for other things as well, but I find this the most common use case for me.

API: http://www.groovy-lang.org/gdk.html

Map -> withDefault(Closure)

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

I keep coming back to this post, I've encountered this error several times. It might have to do with importing all my databases after doing a fresh install.

I'm using homebrew. The only thing that used to fix it for me:

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

This morning, the issue returned after my machine decided to shut down overnight. The only thing that fixed it now was to upgrade mysql.

brew upgrade mysql

How can I get this ASP.NET MVC SelectList to work?

This is an option:

myViewData.PageOptionsDropDown = new[] 
{
 new SelectListItem { Text = "10", Value = "10" },
 new SelectListItem { Text = "15", Value = "15", Selected = true }
 new SelectListItem { Text = "25", Value = "25" },
 new SelectListItem { Text = "50", Value = "50" },
 new SelectListItem { Text = "100", Value = "100" },
 new SelectListItem { Text = "1000", Value = "1000" },
}

insert echo into the specific html element like div which has an id or class

There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:

document.getElementById('//ID//').innerHTML="HTML CODE";

If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:

var url = document.URL;
// to get url and then use split() to check the parameter

How to get form values in Symfony2 controller

I think that in order to get the request data, bound and validated by the form object, you must use this command :

$form->getViewData();
$form->getClientData(); // Deprecated since version 2.1, to be removed in 2.3.

How can I check if some text exist or not in the page using Selenium?

  boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
    if (Error == true)
    {
     System.out.print("Login unsuccessful");
    }
    else
    {
     System.out.print("Login successful");
    }

How to get the number of threads in a Java process

There is a static method on the Thread Class that will return the number of active threads controlled by the JVM:

Thread.activeCount()

Returns the number of active threads in the current thread's thread group.

Additionally, external debuggers should list all active threads (and allow you to suspend any number of them) if you wish to monitor them in real-time.

c++ custom compare function for std::sort()

Your comparison function is not even wrong.

Its arguments should be the type stored in the range, i.e. std::pair<K,V>, not const void*.

It should return bool not a positive or negative value. Both (bool)1 and (bool)-1 are true so your function says every object is ordered before every other object, which is clearly impossible.

You need to model the less-than operator, not strcmp or memcmp style comparisons.

See StrictWeakOrdering which describes the properties the function must meet.

What is the difference between Select and Project Operations

Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice.

Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation.

See more : Relational Algebra and its operations

How can I parse a JSON file with PHP?

To iterate over a multidimensional array, you can use RecursiveArrayIterator

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}

Output:

John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0

run on codepad

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me it was a missing static keyword in one of the JUnit annotated methods, e.g.:

@AfterClass
public static void cleanUp() {
    // ...
}

How to prevent Right Click option using jquery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script>
 $(document).ready(function(){
  $(document).bind("contextmenu",function(e){
  return false;
  });
});
</script>
</head>
<body>

<p>Right click is disabled on this page.</p>

</body>
</html>

Oracle Insert via Select from multiple tables where one table may not have a row

It was not clear to me in the question if ts.tax_status_code is a primary or alternate key or not. Same thing with recipient_code. This would be useful to know.

You can deal with the possibility of your bind variable being null using an OR as follows. You would bind the same thing to the first two bind variables.

If you are concerned about performance, you would be better to check if the values you intend to bind are null or not and then issue different SQL statement to avoid the OR.

insert into account_type_standard 
(account_type_Standard_id, tax_status_id, recipient_id)
(
select 
   account_type_standard_seq.nextval,
   ts.tax_status_id, 
   r.recipient_id
from tax_status ts, recipient r
where (ts.tax_status_code = ? OR (ts.tax_status_code IS NULL and ? IS NULL))
and (r.recipient_code = ? OR (r.recipient_code IS NULL and ? IS NULL))

How to call a JavaScript function within an HTML body

First include the file in head tag of html , then call the function in script tags under body tags e.g.

Js file function to be called

function tryMe(arg) {
    document.write(arg);
}

HTML FILE

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src='object.js'> </script>
    <title>abc</title><meta charset="utf-8"/>
</head>
<body>
    <script>
    tryMe('This is me vishal bhasin signing in');
    </script>
</body>
</html>

finish

What is the instanceof operator in JavaScript?

instanceof

The Left Hand Side (LHS) operand is the actual object being tested to the Right Hand Side (RHS) operand which is the actual constructor of a class. The basic definition is:

Checks the current object and returns true if the object
is of the specified object type.

Here are some good examples and here is an example taken directly from Mozilla's developer site:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)

One thing worth mentioning is instanceof evaluates to true if the object inherits from the classe's prototype:

var p = new Person("Jon");
p instanceof Person

That is p instanceof Person is true since p inherits from Person.prototype.

Per the OP's request

I've added a small example with some sample code and an explanation.

When you declare a variable you give it a specific type.

For instance:

int i;
float f;
Customer c;

The above show you some variables, namely i, f, and c. The types are integer, float and a user defined Customer data type. Types such as the above could be for any language, not just JavaScript. However, with JavaScript when you declare a variable you don't explicitly define a type, var x, x could be a number / string / a user defined data type. So what instanceof does is it checks the object to see if it is of the type specified so from above taking the Customer object we could do:

var c = new Customer();
c instanceof Customer; //Returns true as c is just a customer
c instanceof String; //Returns false as c is not a string, it's a customer silly!

Above we've seen that c was declared with the type Customer. We've new'd it and checked whether it is of type Customer or not. Sure is, it returns true. Then still using the Customer object we check if it is a String. Nope, definitely not a String we newed a Customer object not a String object. In this case, it returns false.

It really is that simple!

How do you specify a different port number in SQL Management Studio?

Using the client manager affects all connections or sets a client machine specific alias.

Use the comma as above: this can be used in an app.config too

It's probably needed if you have firewalls between you and the server too...

Android camera android.hardware.Camera deprecated

 if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {

          CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);


           try {
               String cameraId = cameraManager.getCameraIdList()[0];
               cameraManager.setTorchMode(cameraId,true);
           } catch (CameraAccessException e) {
               e.printStackTrace();
           }


 }

Visual Studio Code cannot detect installed git

i have recently start visual studio code and have this issue and just write the exact path of executable git solve the issue .... here is the code ...

"git.path": "C:\Program Files\Git\bin\git.exe",

Git pull a certain branch from GitHub

Simply put, If you want to pull from GitHub the branch the_branch_I_want:

git fetch origin
git branch -f the_branch_I_want origin/the_branch_I_want
git checkout the_branch_I_want

Saving numpy array to txt file row wise

The numpy.savetxt() method has several parameters which are worth noting:

fmt : str or sequence of strs, optional
    it is used to format the numbers in the array, see the doc for details on formating

delimiter : str, optional
    String or character separating columns

newline : str, optional
    String or character separating lines.

Let's take an example. I have an array of size (M, N), which consists of integer numbers in the range (0, 255). To save the array row-wise and show it nicely, we can use the following code:

import numpy as np

np.savetxt("my_array.txt", my_array, fmt="%4d", delimiter=",", newline="\n")

HTML tag inside JavaScript

<html>
 <body>
  <input type="checkbox" id="number1" onclick="number1();">Number 1</br>
  <p id="h1"></p>
   <script type="text/javascript">
    function number1() {
    if(document.getElementById('number1').checked) {

      document.getElementById("h1").innerHTML = "<h1>Hello member</h1>";
         }
    }
   </script>
 </body>
</html>

How to find all the tables in MySQL with specific column names in them?

To get all tables with columns columnA or ColumnB in the database YourDatabase:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('columnA','ColumnB')
        AND TABLE_SCHEMA='YourDatabase';

Angular 2: How to call a function after get a response from subscribe http.post

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

How to run SUDO command in WinSCP to transfer files from Windows to linux

AFAIK you can't do that.
What I did at my place of work, is transfer the files to your home (~) folder (or really any folder that you have full permissions in, i.e chmod 777 or variants) via WinSCP, and then SSH to to your linux machine and sudo from there to your destination folder.

Another solution would be to change permissions of the directories you are planning on uploading the files to, so your user (which is without sudo privileges) could write to those dirs.

I would also read about WinSCP Remote Commands for further detail.

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

Error handling in C code

If you want your program to crash and not know the reason, then go ahead and trust the programmers and c basic error handling.

I think it's best to build in some kind of error reporting, call it debug mode, turn it off when your want best performance and turn it on when you want to debug a issue. Hopefully you can hit it again.

There will be bugs, the question is how do you want to spend your days and nights looking for them.

DLL and LIB files - what and why?

There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).

Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.

Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.

As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.

angularjs getting previous route path

Just to document:

The callback argument previousRoute is having a property called $route which is much similar to the $route service. Unfortunately currentRoute argument, is not having much information about the current route.

To overcome this i have tried some thing like this.

$routeProvider.
   when('/', {
    controller:...,
    templateUrl:'...',
    routeName:"Home"
  }).
  when('/menu', {
    controller:...,
    templateUrl:'...',
    routeName:"Site Menu"
  })

Please note that in the above routes config a custom property called routeName is added.

app.run(function($rootScope, $route){
    //Bind the `$routeChangeSuccess` event on the rootScope, so that we dont need to 
    //bind in induvidual controllers.
    $rootScope.$on('$routeChangeSuccess', function(currentRoute, previousRoute) {
        //This will give the custom property that we have defined while configuring the routes.
        console.log($route.current.routeName)
    })
})

How to compute the sum and average of elements in an array?

Calculating average (mean) using reduce and ES6:

const average = list => list.reduce((prev, curr) => prev + curr) / list.length;

const list = [0, 10, 20, 30]
average(list) // 15

Find size of object instance in bytes in c#

For unmanaged types aka value types, structs:

        Marshal.SizeOf(object);

For managed objects the closer i got is an approximation.

        long start_mem = GC.GetTotalMemory(true);

        aclass[] array = new aclass[1000000];
        for (int n = 0; n < 1000000; n++)
            array[n] = new aclass();

        double used_mem_median = (GC.GetTotalMemory(false) - start_mem)/1000000D;

Do not use serialization.A binary formatter adds headers, so you can change your class and load an old serialized file into the modified class.

Also it won't tell you the real size in memory nor will take into account memory alignment.

[Edit] By using BiteConverter.GetBytes(prop-value) recursivelly on every property of your class you would get the contents in bytes, that doesn't count the weight of the class or references but is much closer to reality. I would recommend to use a byte array for data and an unmanaged proxy class to access values using pointer casting if size matters, note that would be non-aligned memory so on old computers is gonna be slow but HUGE datasets on MODERN RAM is gonna be considerably faster, as minimizing the size to read from RAM is gonna be a bigger impact than unaligned.

Convert string to date in bash

We can use date -d option

1) Change format to "%Y-%m-%d" format i.e 20121212 to 2012-12-12

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

2)Get next or last day from a given date=20121212. Like get a date 7 days in past with specific format

date -d '20121212 -7 days' +'%Y-%m-%d'

3) If we are getting date in some variable say dat

dat2=$(date -d "$dat -1 days" +'%Y%m%d')

How to make fixed header table inside scrollable div?

I think you need something like this ?

Like this

.....
<style>
.table{width: 500px;height: 200px;border-collapse:collapse;}
.table-wrap{max-height: 200px;width:100%;overflow-y:auto;overflow-x:hidden;}
.table-dalam{height:300px;width:500px;border-collapse:collapse;}
.td-nya{border-left:1px solid white;border-right:1px solid grey;border-bottom:1px solid    grey;}

</style>

<table class="table">
<thead>
    <tr>
    <th>Judul1</th>
    <th>Judul2</th>
    <th>Judul3</th>
    <th>Judul4</th>
   </tr>
 </thead>
 <tbody>
   <tr>
      <td colspan="4">
      <div class="table-wrap" >
      <table class="table-dalam">
         <tbody>
             <?php foreach(range(1,10) as $i): ?>
                 <tr >
                     <td class="td-nya">td1 </td>
                     <td class="td-nya">td2</td>
                     <td class="td-nya">td2</td>
                     <td class="td-nya">td2</td>
                 </tr> 
            <?php endforeach;?>
        </tbody>
       </table>
     </div>
   </td>
 </tr>
  </tbody>
 </table>

Source

When should I create a destructor?

It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.

It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.

In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.

A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.

c# regex matches example

This pattern should work:

#\d

foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
    Console.WriteLine(match.Value);
}

(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).

How to read a CSV file from a URL with Python?

This question is tagged python-2.x so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.

It's now necessary to decode urlopen's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:

import csv, urllib.request

url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)

for row in cr:
    print(row)

Note the extra line beginning with lines =, the fact that urlopen is now in the urllib.request module, and print of course requires parentheses.

It's hardly advertised, but yes, csv.reader can read from a list of strings.

And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:

python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'

(Yes, it's three lines, but you can copy-paste it as one command. ;)

What is bootstrapping?

As a humble beginner in the world of programming, and flicking through all the answers here after seeing this word used a lot in apparently slightly different ways in different places, I found reading the Wikipedia page on Bootstrapping (duh! I didn't think of it either at first) is very informative to understand differences in use of this word. Could it be......on extremely rare occasions......Wikipedia might even have better explanations of certain terms than....(redacted)? Will they bring in rep points on Wikipedia though?

To me, it seems all the meanings something to do with: start with something as simple as possible Thing1, make something slightly more complex with that Thing2, and now you can use Thing2 to do some kind of tasks more efficiently and quickly than you could originally with Thing1. Then repeat from Thing2 to Thing 3 ad infinitum...

I see it as closely connected to both biological evolution and 'Layers of Abstraction' (newbies like me see, ahem, Wikipedia, cough) - the evolution from 1940's computers with switches, machine code, Assembly, C, Python, AIs you can give all kinds of complex instructions to like "make the %4^% dinner to my default &^$% requirements and clean the floor you %$£"@:~" in drunken slang English or Amazon tribal dialect without them 'raising an exception' (for newbies again...you guessed it) - missed out lot of links there due to simple ignorance.

Then in certain specific software meanings: Meaning1: Thing1 is used to load latest version of Thing2 (because of course Thing2 will be bigger than Thing1, just as Thing3 will be be bigger than Thing2).

Meaning2: Thing1 is a lower level language (closer to 1001011100....011001 than print("Hello, ", user.name)) used to write a little bit of the higher language of Thing2, then this little bit of Thing2 is used to expand Thing2 itself from baby vocabulary level towards adult vocabulary level (Thing2 starts to be processed, or to use correct technical term 'compiled', by the baby version of itself (it's a clever baby!), whereas the baby version of Thing2 itself could of course only be compiled by Thing1, cause it can't exist before it exists, right duh!), then child version of Thing2 compiles Surly Teenager version of Thing2, at which point programming community decides whether Surly Teenager's 'issues' (software term and metaphor term!) are worth spending enough time resolving to be accepted long term, or to abandon them to (not sure where to take the analogy here).

If yes, then Thing2 has 'Bootstrapped' itself (possibly a few times) from babyhood to adulthood: "the child is the father of the man" (Wordsworth, suggest don't try looking up the quote or the author on Stack Overflow).

HTML5 <video> element on Android

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

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

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

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

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

Getting Index of an item in an arraylist;

To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?

Yes to the loop (either using indexes or an Iterator). On the return value, either return its index, or the item iteself, depending on your needs. ArrayList doesn't have an indexOf(Object target, Comparator compare)` or similar. Now that Java is getting lambda expressions (in Java 8, ~March 2014), I expect we'll see APIs get methods that accept lambdas for things like this.

Best way to find os name and version in Unix/Linux platform

I prepared following commands to find concise information about a Linux system:

clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"

Copy and paste in an sh file like info.sh and then run it using command sh info.sh

How to determine whether a given Linux is 32 bit or 64 bit?

If you were running a 64 bit platform you would see x86_64 or something very similar in the output from uname -a

To get your specific machine hardware name run

uname -m

You can also call

getconf LONG_BIT

which returns either 32 or 64

JAVA_HOME does not point to the JDK

I had a similar problem and it turned out the issue was having both versions 6 & 7 of OpenJDK. The answer comes from r-senior on ubuntu forums (http://ubuntuforums.org/showthread.php?t=1977619) --- just uninstall version 6:

sudo apt-get remove openjdk-6-*

make sure that JAVA_HOME and CLASSPATH aren't set to anything since that isn't actually the problem.

How to run console application from Windows Service?

Services are required to connect to the Service Control Manager and provide feedback at start up (ie. tell SCM 'I'm alive!'). That's why C# application have a different project template for services. You have two alternatives:

  • wrapp your exe on srvany.exe, as described in KB How To Create a User-Defined Service
  • have your C# app detect when is launched as a service (eg. command line param) and switch control to a class that inherits from ServiceBase and properly implements a service.

How to concatenate strings in django templates?

Use with:

{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}

Writing MemoryStream to Response Object

First We Need To Write into our Memory Stream and then with the help of Memory Stream method "WriteTo" we can write to the Response of the Page as shown in the below code.

   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);

   filecontent.WriteTo(Response.OutputStream);

   Response.End();

FormName is the fileName given,This code will make the generated PDF file downloadable by invoking a PopUp.

Read .mat files in Python

from os.path import dirname, join as pjoin
import scipy.io as sio
data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')
mat_contents = sio.loadmat(mat_fname)

You can use above code to read the default saved .mat file in Python.

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

Materialize CSS - Select Doesn't Seem to Render

Call the materialize css jquery code only after the html has rendered. So you can have a controller and then fire a service which calls the jquery code in the controller. This will render the select button alright. How ever if you try to use ngChange or ngSubmit it may not work due to the dynamic styling of the select tag.

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Internet Explorer cache location

The location of the Temporary Internet Files folder depends on your version of Windows and whether or not you are using user profiles.

  • If you have Windows Vista, then temporary Internet files are in these locations (note that on your PC they can be on some drive other than C):

    C:\Users[username]\AppData\Local\Microsoft\Windows\Temporary Internet Files\ C:\Users[username]\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\

    Note that you will have to change the settings of Windows Explorer to show all kinds of files (including the protected system files) in order to access these folders.

  • If you have Windows XP or Windows 2000, then temporary Internet files are in this location (note that on your PC they can be on some drive other than C):

    C:\Documents and Settings[username]\Local Settings\Temporary Internet Files\

    If you have only one user account, then replace [username] with Administrator to get the path of the Temporary Internet Files folder.

  • If you have Windows Me, Windows 98, Windows NT or Windows 95, then index.dat files are in these locations:

    C:\Windows\Temporary Internet Files\
    C:\Windows\Profiles[username]\Temporary Internet Files\

    Note that on your computer, the Windows directory may not be C:\Windows but some other directory. If you don't have a Profiles directory in your Windows directory, don't worry — this just means that you are not using user profiles.

Should I call Close() or Dispose() for stream objects?

The documentation says that these two methods are equivalent:

StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.

StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.

Stream.Close: This method calls Dispose, specifying true to release all resources.

So, both of these are equally valid:

/* Option 1, implicitly calling Dispose */
using (StreamWriter writer = new StreamWriter(filename)) { 
   // do something
} 

/* Option 2, explicitly calling Close */
StreamWriter writer = new StreamWriter(filename)
try {
    // do something
}
finally {
    writer.Close();
}

Personally, I would stick with the first option, since it contains less "noise".

Facebook API: Get fans of / people who like a page

Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552 and replace the page_id number with your page's id number and it will return the page name and the fan count.

How do you convert a byte array to a hexadecimal string in C?

For simple usage I made a function that encodes the input string (binary data):

/* Encodes string to hexadecimal string reprsentation
    Allocates a new memory for supplied lpszOut that needs to be deleted after use
    Fills the supplied lpszOut with hexadecimal representation of the input
    */
void StringToHex(unsigned char *szInput, size_t size_szInput, char **lpszOut)
{
    unsigned char *pin = szInput;
    const char *hex = "0123456789ABCDEF";
    size_t outSize = size_szInput * 2 + 2;
    *lpszOut = new char[outSize];
    char *pout = *lpszOut;
    for (; pin < szInput + size_szInput; pout += 2, pin++)
    {
        pout[0] = hex[(*pin >> 4) & 0xF];
        pout[1] = hex[*pin & 0xF];
    }
    pout[0] = 0;
}

Usage:

unsigned char input[] = "This is a very long string that I want to encode";
char *szHexEncoded = NULL;
StringToHex(input, strlen((const char *)input), &szHexEncoded);

printf(szHexEncoded);

// The allocated memory needs to be deleted after usage
delete[] szHexEncoded;

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

If you're importing a third-party module 'foo' that doesn't provide any typings, either in the library itself, or in the @types/foo package (generated from the DefinitelyTyped repository), then you can make this error go away by declaring the module in a file with a .d.ts extension. TypeScript looks for .d.ts files in the same places that it will look for normal .ts files: as specified under "files", "include", and "exclude" in the tsconfig.json.

// foo.d.ts
declare module 'foo';

Then when you import foo it'll just be typed as any.


Alternatively, if you want to roll your own typings you can do that too:

// foo.d.ts
declare module 'foo' {
    export function getRandomNumber(): number
} 

Then this will compile correctly:

import { getRandomNumber } from 'foo';
const x = getRandomNumber(); // x is inferred as number

You don't have to provide full typings for the module, just enough for the bits that you're actually using (and want proper typings for), so it's particularly easy to do if you're using a fairly small amount of API.


On the other hand, if you don't care about the typings of external libraries and want all libraries without typings to be imported as any, you can add this to a file with a .d.ts extension:

declare module '*';

The benefit (and downside) of this is that you can import absolutely anything and TS will compile.

How to fix/convert space indentation in Sublime Text?

I also followed Josh Frankel's advice and created a Sublime Macro + added key binding. The difference is that this script ensures that spacing is first set to tabs and set to a tab size of 2. The macro won't work if that's not the starting point.

Here's a gist of the macro: https://gist.github.com/drivelous/aa8dc907de34efa3e462c65a96e05f09

In Mac, to use the macro + key binding:

  1. Create a file called spaces2to4.sublime-macro and copy/paste the code from the gist. For me this is located at:

/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/spaces2to4.sublime-macro

  1. Select Sublime Text > Preferences > Key Bindings
  2. Add this command to the User specified sublime-keymap (it's in an array -- it may be empty):
{
    "keys": ["super+shift+o"],
    "command": "run_macro_file",
    "args": {
        "file":"Packages/User/spaces2to4.sublime-macro"
    }
}

Now ? + shift + o now automatically converts each file from 2 space indentation to 4 (but will keep indenting if you run it further)

Bootstrap 3 navbar active li not changing background-color

In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:

<body data-spy="scroll" data-target="Id or class of the element you want to track">

In most cases I usually track active elements on my navbar, so I do the following:

<body data-spy="scroll" data-target=".navbar-fixed-top" >

Now in your CSS you can target .navbar-fixed-top .active a:

.navbar-fixed-top .active a { 
    // Put in some styling 
}

This should work if you are tracking active li elements in your top fixed navigation bar.

Convert Unix timestamp to a date string

Other examples here are difficult to remember. At its simplest:

date -r 1305712800

How do I test if a variable is a number in Bash?

This is a little rough around the edges but a little more novice friendly.

if [ $number -ge 0 ]
then
echo "Continue with code block"
else
echo "We matched 0 or $number is not a number"
fi

This will cause an error and print "Illegal number:" if $number is not a number but it will not break out of the script. Oddly there is not a test option I could find to just test for an integer. The logic here will match any number that is greater than or equal to 0.

Twitter Bootstrap vs jQuery UI?

I have on several projects.

The biggest difference in my opinion

  • jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old

  • Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding

  • jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)

So what to choose?

That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?

I always end up using both, so I can use the best of both worlds.

Here are the links to both frameworks, if you decide to use them.

  1. jQuery UI
  2. Bootstrap

What is the difference between vmalloc and kmalloc?

Linux Kernel Development by Robert Love (Chapter 12, page 244 in 3rd edition) answers this very clearly.

Yes, physically contiguous memory is not required in many of the cases. Main reason for kmalloc being used more than vmalloc in kernel is performance. The book explains, when big memory chunks are allocated using vmalloc, kernel has to map the physically non-contiguous chunks (pages) into a single contiguous virtual memory region. Since the memory is virtually contiguous and physically non-contiguous, several virtual-to-physical address mappings will have to be added to the page table. And in the worst case, there will be (size of buffer/page size) number of mappings added to the page table.

This also adds pressure on TLB (the cache entries storing recent virtual to physical address mappings) when accessing this buffer. This can lead to thrashing.

How do you create a Spring MVC project in Eclipse?

You want to create a "Dynamic Web Project". Follow the steps here: Spring MVC Tutorial with Eclipse and Tomcat.

Also, here is the Eclipse documentation for Dynamic Web Projects: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.webtools.doc.user/topics/ccwebprj.html

Easier way to create circle div than using an image?

Give width and height depending on the size but,keep both equal

_x000D_
_x000D_
.circle {_x000D_
  background-color: gray;_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  border-radius: 100%;_x000D_
}
_x000D_
<div class="circle">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link vs compile vs controller

I wanted to add also what the O'Reily AngularJS book by the Google Team has to say:

Controller - Create a controller which publishes an API for communicating across directives. A good example is Directive to Directive Communication

Link - Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile - Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

ggplot with 2 y axes on each side and different scales

The following article helped me to combine two plots generated by ggplot2 on a single row:

Multiple graphs on one page (ggplot2) by Cookbook for R

And here is what the code may look like in this case:

p1 <- 
  ggplot() + aes(mns)+ geom_histogram(aes(y=..density..), binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1) +  geom_density(alpha=.2)

p2 <- 
  ggplot() + aes(mns)+ geom_histogram( binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1)  

multiplot(p1,p2,cols=2)

How to get JSON object from Razor Model object in javascript

Pass the object from controller to view, convert it to markup without encoding, and parse it to json.

@model IEnumerable<CollegeInformationDTO>

@section Scripts{
    <script>
          var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
    </script>
}

Adding a dictionary to another

foreach(var newAnimal in NewAnimals)
    Animals.Add(newAnimal.Key,newAnimal.Value)

Note: this throws an exception on a duplicate key.


Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange extension method that works on any ICollection<T>, and not just on Dictionary<TKey,TValue>.

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException(nameof(target));
    if(source==null)
      throw new ArgumentNullException(nameof(source));
    foreach(var element in source)
        target.Add(element);
}

(throws on duplicate keys for dictionaries)

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

Explanation of the UML arrows

Aggregations and compositions are a little bit confusing. However, think like compositions are a stronger version of aggregation. What does that mean? Let's take an example: (Aggregation) 1. Take a classroom and students: In this case, we try to analyze the relationship between them. A classroom has a relationship with students. That means classroom comprises of one or many students. Even if we remove the Classroom class, the Students class does not need to destroy, which means we can use Student class independently.

(Composition) 2. Take a look at pages and Book Class. In this case, pages is a book, which means collections of pages makes the book. If we remove the book class, the whole Page class will be destroyed. That means we cannot use the class of the page independently.

If you are still unclear about this topic, watch out this short wonderful video, which has explained the aggregation more clearly.

https://www.youtube.com/watch?v=d5ecYmyFZW0

Using os.walk() to recursively traverse directories in Python

Would be the best way

def traverse_dir_recur(dir):
    import os
    l = os.listdir(dir)
    for d in l:
        if os.path.isdir(dir + d):
            traverse_dir_recur(dir+  d +"/")
        else:
            print(dir + d)

How to render a DateTime in a specific format in ASP.NET MVC 3?

Only View File Adjust like this. You may try this.

@Html.FormatValue( (object)Convert.ChangeType(item.transdate, typeof(object)), 
                            "{0: yyyy-MM-dd}")

item.transdate it is your DateTime type data.

What exactly is std::atomic?

I understand that std::atomic<> makes an object atomic.

That's a matter of perspective... you can't apply it to arbitrary objects and have their operations become atomic, but the provided specialisations for (most) integral types and pointers can be used.

a = a + 12;

std::atomic<> does not (use template expressions to) simplify this to a single atomic operation, instead the operator T() const volatile noexcept member does an atomic load() of a, then twelve is added, and operator=(T t) noexcept does a store(t).

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Because linux is a built-in macro defined when the compiler is running on, or compiling for (if it is a cross-compiler), Linux.

There are a lot of such predefined macros. With GCC, you can use:

cp /dev/null emptyfile.c
gcc -E -dM emptyfile.c

to get a list of macros. (I've not managed to persuade GCC to accept /dev/null directly, but the empty file seems to work OK.) With GCC 4.8.1 running on Mac OS X 10.8.5, I got the output:

#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __UINT_LEAST8_TYPE__ unsigned char
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __WINT_MAX__ 2147483647
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 18446744073709551615UL
#define __WCHAR_MAX__ 2147483647
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __FLT_EVAL_METHOD__ 0
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __x86_64 1
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 1
#define __UINT_FAST8_MAX__ 255
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __APPLE_CC__ 1
#define __UINTMAX_TYPE__ long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __UINT32_MAX__ 4294967295U
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ (-__WINT_MAX__ - 1)
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 8
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __strong 
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 8
#define __APPLE__ 1
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __LDBL_HAS_QUIET_NAN__ 1
#define __DYNAMIC__ 1
#define __GNUC__ 4
#define __MMX__ 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 16
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __INT_FAST32_MAX__ 2147483647
#define __DBL_HAS_INFINITY__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define __LDBL_HAS_DENORM__ 1
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __weak 
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __SSE2_MATH__ 1
#define __ATOMIC_HLE_RELEASE 131072
#define __PTRDIFF_MAX__ 9223372036854775807L
#define __amd64 1
#define __tune_core2__ 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WINT_T__ 4
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __LP64__ 1
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__ 
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __UINT8_TYPE__ unsigned char
#define __NO_INLINE__ 1
#define __FLT_MANT_DIG__ 24
#define __VERSION__ "4.8.1"
#define __UINT64_C(c) c ## ULL
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 1080
#define __SIZE_TYPE__ long unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## UL
#define __SSE_MATH__ 1
#define __k8 1
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 8
#define __x86_64__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 9223372036854775807L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __INT64_MAX__ 9223372036854775807LL
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 9223372036854775807L
#define __LITTLE_ENDIAN__ 1
#define __SSE2__ 1
#define __LDBL_MANT_DIG__ 64
#define __CONSTANT_CFSTRINGS__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __code_model_small__ 1
#define __k8__ 1
#define __INTPTR_TYPE__ long int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ int
#define __SIZEOF_FLOAT__ 4
#define __pic__ 2
#define __UINTPTR_MAX__ 18446744073709551615UL
#define __DEC64_MIN_EXP__ (-382)
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define __MACH__ 1
#define __amd64__ 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __ORDER_BIG_ENDIAN__ 4321
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __SSE__ 1
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __SIZEOF_INT128__ 16
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define _LP64 1
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 4
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __DBL_DECIMAL_DIG__ 17
#define __FXSR__ 1
#define __DEC_EVAL_METHOD__ 2
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807L
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __PIC__ 2
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __FLT_MIN_10_EXP__ (-37)
#define __INTMAX_TYPE__ long int
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 8
#define __UINTMAX_MAX__ 18446744073709551615UL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ long int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ long unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GNUC_GNU_INLINE__ 1
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __SSE3__ 1
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3

That's 236 macros from an empty file. When I added #include <stdio.h> to the file, the number of macros defined went up to 505. These includes all sorts of platform-identifying macros.

Get Bitmap attached to ImageView

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

Git: add vs push vs commit

  • git add adds files to the Git index, which is a staging area for objects prepared to be commited.
  • git commit commits the files in the index to the repository, git commit -a is a shortcut to add all the modified tracked files to the index first.
  • git push sends all the pending changes to the remote repository to which your branch is mapped (eg. on GitHub).

In order to understand Git you would need to invest more effort than just glancing over the documentation, but it's definitely worth it. Just don't try to map Git commands directly to Subversion, as most of them don't have a direct counterpart.

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

Using Keras & Tensorflow with AMD GPU

Tensorflow 1.3 has been supported on AMD ROCm stack:

A pre-built docker image has also been posted publicly:

Get the last insert id with doctrine 2?

More simple: SELECT max(id) FROM client

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

Why is my CSS style not being applied?

Posting, since it might be useful for someone in the future:

For me, when I got here, the solution was browser cache. Had to hard refresh Chrome (cmd/ctrl+shift+R) to get the new styles applied, it seems the old ones got cached really "deep".

This question/answer might come in handy for someone. And hard refresh tips for different browsers for those who don't use Chrome.

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Location of the android sdk has not been setup in the preferences in mac os?

I had the same problem when I was trying to upgrade from ADT 20.0.x to ADT 23.0.x on Eclipse Indigo.

To fix the issue, I had to uninstall the ADT plugin (remove feature) from Eclipse, then reinstall the newer versions.

This maybe done by going to Help->Install New Software. Then at the bottom of the page, click What is already installed?

All what is left now is to install the newer versions as usual from help->Install New Software.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: Each "child" Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: A Skill has a Set of Person(s) which relate to it.

In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).

Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.

What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!

All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.

parsing JSONP $http.jsonp() response in angular.js

This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:

var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
    $http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
        $scope.data = data;
    });
});

Then display or manipulate {{ data }} in your Angular template.

Laravel Soft Delete posts

Updated Version (Version 5.0 & Later):

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {

    use SoftDeletes;

    protected $table = 'posts';

    // ...
}

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model (Documentation).

For (Version 4.2):

use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required

class Post extends Eloquent {

    use SoftDeletingTrait;

    protected $table = 'posts';

    // ...
}

Prior to Version 4.2 (But not 4.2 & Later)

For example (Using a posts table and Post model):

class Post extends Eloquent {

    protected $table = 'posts';
    protected $softDelete = true;
    
    // ...
}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

For example (Migration class' up method for posts table) :

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function(Blueprint $table)
    {
        $table->increments('id');
        // more fields
        $table->softDeletes(); // <-- This will add a deleted_at field
        $table->timeStamps();
    });
}

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete a model you may use:

$model = Contents::find( $id );
$model->delete();

Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL. To permanently delete a model you may use forceDelete method.

Regex date format validation on Java

Putting it all together:

  • REGEX doesn't validate values (like "2010-19-19")
  • SimpleDateFormat does not check format ("2010-1-2", "1-0002-003" are accepted)

it's necessary to use both to validate format and value:

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setLenient(false);
    try {
        df.parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}



A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call.
It is needed in a multithread context since the SimpleDateFormat is not thread safe:

private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        System.out.println("created");
        return df;
    }
};

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    try {
        format.get().parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

(same can be done for a Matcher, that also is not thread safe)

Github: Can I see the number of downloads for a repo?

I ended up writing a scraper script to find my clone count:

#!/bin/sh
#
# This script requires:
#   apt-get install html-xml-utils
#   apt-get install jq
#
USERNAME=dougluce
PASSWORD="PASSWORD GOES HERE, BE CAREFUL!"
REPO="dougluce/node-autovivify"

TOKEN=`curl https://github.com/login -s -c /tmp/cookies.txt | \
     hxnormalize | \
     hxselect 'input[name=authenticity_token]' 2>/dev/null | \
     perl -lne 'print $1 if /value=\"(\S+)\"/'`

curl -X POST https://github.com/session \
     -s -b /tmp/cookies.txt -c /tmp/cookies2.txt \
     --data-urlencode commit="Sign in" \
     --data-urlencode authenticity_token="$TOKEN" \
     --data-urlencode login="$USERNAME" \
     --data-urlencode password="$PASSWORD" > /dev/null

curl "https://github.com/$REPO/graphs/clone-activity-data" \
     -s -b /tmp/cookies2.txt \
     -H "x-requested-with: XMLHttpRequest" | jq '.summary'

This'll grab the data from the same endpoint that Github's clone graph uses and spit out the totals from it. The data also includes per-day counts, replace .summary with just . to see those pretty-printed.

How to get the focused element with jQuery?

Try this:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});

Need a good hex editor for Linux

wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install

Defining a HTML template to append using JQuery

Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.

While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for), conditionals (<% if) and transforms (<%= myString | uppercase %>) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).

Templates Inside HTML

One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script> type, e.g. <script type="text/template">. For your case:

<script type="text/template" data-template="listitem">
    <a href="${url}" class="list-group-item">
        <table>
            <tr>
                <td><img src="${img}"></td>
                <td><p class="list-group-item-text">${title}</p></td>
            </tr>
        </table>
    </a>
</script>

On document load, read your template and tokenize it using a simple String#split

var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);

Notice that with our token, you get it in the alternating [text, property, text, property] format. This lets us nicely map it using an Array#map, with a mapping function:

function render(props) {
  return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}

Where props could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }.

Putting it all together assuming you've parsed and loaded your itemTpl as above, and you have an items array in-scope:

$('.search').keyup(function () {
  $('.list-items').append(items.map(function (item) {
    return itemTpl.map(render(item)).join('');
  }));
});

This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector and .innerHTML.

jsfiddle

Templates inside JS

A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.

In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html method above.

const Item = ({ url, img, title }) => `
  <a href="${url}" class="list-group-item">
    <div class="image">
      <img src="${img}" />
    </div>
    <p class="list-group-item-text">${title}</p>
  </a>
`;

Then you could easily render it, even mapped from an array, like so:

$('.list-items').html([
  { url: '/foo', img: 'foo.png', title: 'Foo item' },
  { url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));

Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.

private constructor

One common use is in the singleton pattern where you want only one instance of the class to exist. In that case, you can provide a static method which does the instantiation of the object. This way the number of objects instantiated of a particular class can be controlled.

Create a folder inside documents folder in iOS apps

Swift 1.2 and iOS 8

Create custom directory (name = "MyCustomData") inside the documents directory but only if the directory does not exist.

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}

MySQL, Check if a column exists in a table with SQL

DO NOT put ALTER TABLE/MODIFY COLS or any other such table mod operations inside a TRANSACTION. Transactions are for being able to roll back a QUERY failure not for ALTERations...it will error out every time in a transaction.

Just run a SELECT * query on the table and check if the column is there...

Datatype for storing ip address in SQL Server

The following answer is based on answers by M. Turnhout and Jerry Birchler to this question but with the following improvements:

  • Replaced the use of undocumented functions (sys.fn_varbintohexsubstring, fn_varbintohexstr) with CONVERT() for binary styles
  • Replaced XML "hacks" ( CAST('' as xml).value('xs:hexBinary()) ) with CONVERT() for binary styles
  • Fixed bug in Jerry Birchler's implementation of fn_ConvertIpAddressToBinary (as pointed out by C.Plock)
  • Add minor syntax sugar

The code has been tested in SQL Server 2014 and SQL Server 2016 (see test cases at the end)

IPAddressVarbinaryToString

Converts 4 bytes values to IPV4 and 16 byte values to IPV6 string representations. Note that this function does not shorten addresses.

ALTER FUNCTION dbo.IPAddressVarbinaryToString
(
    @varbinaryValue VARBINARY( 16 )
)
RETURNS VARCHAR(39)
AS
BEGIN
    IF @varbinaryValue IS NULL
        RETURN NULL;
    ELSE IF DATALENGTH( @varbinaryValue ) = 4
        RETURN 
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 1, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 2, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 3, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 4, 1 )));
    ELSE IF DATALENGTH( @varbinaryValue ) = 16
        RETURN 
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  1, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  3, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  5, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  7, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  9, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 11, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 13, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 15, 2 ), 2 );

    RETURN 'Invalid';
END

Test Cases:

SELECT dbo.IPAddressVarbinaryToString(0x00000000000000000000000000000000) -- 0000:0000:0000:0000:0000:0000:0000:0000 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(0x00010002000300400500060070000089) -- 0001:0002:0003:0040:0500:0600:7000:0089
SELECT dbo.IPAddressVarbinaryToString(0xC0A80148) -- 255.168.1.72
SELECT dbo.IPAddressVarbinaryToString(0x7F000001) -- 127.0.0.1 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(NULL) -- NULL

IPAddressStringToVarbinary

Converts IPV4 and IPV6 string representations to 4 byte and 16 bytes binary values respectively. Note that this function is able to parse most (all of the commonly used) of shorthand address representations (e.g. 127...1 and 2001:db8::1319:370:7348). To force this function to always return 16 byte binary values uncomment leading 0s concatenation at the end of the function.

ALTER FUNCTION [dbo].[IPAddressStringToVarbinary]
(
    @IPAddress VARCHAR( 39 )
)
RETURNS VARBINARY(16) AS
BEGIN

IF @ipAddress IS NULL
    RETURN NULL;

DECLARE @bytes VARBINARY(16), @token VARCHAR(4),
    @vbytes VARBINARY(16) = 0x, @vbzone VARBINARY(2),
    @tIPAddress VARCHAR( 40 ),
    @colIndex TINYINT,
    @delim CHAR(1) = '.',
    @prevColIndex TINYINT = 0,
    @parts TINYINT = 0, @limit TINYINT = 4;

-- Get position if IPV4 delimiter
SET @colIndex = CHARINDEX( @delim, @ipAddress );

-- If not IPV4, then assume IPV6
IF @colIndex = 0
BEGIN
    SELECT @delim = ':', @limit = 8, @colIndex = CHARINDEX( @delim, @ipAddress );

    -- Get number of parts (delimiters)
    WHILE @colIndex > 0
        SELECT @parts += 1, @colIndex = CHARINDEX( @delim, @ipAddress, @colIndex + 1 );

    SET @colIndex = CHARINDEX( @delim, @ipAddress );

    IF @colIndex = 0
        RETURN NULL;
END

-- Add trailing delimiter (need new variable of larger size)
SET @tIPAddress = @IPAddress + @delim;

WHILE @colIndex > 0
BEGIN
    SET @token = SUBSTRING( @tIPAddress, @prevColIndex + 1, @Colindex - @prevColIndex - 1 );

    IF @delim = ':'
    BEGIN
        SELECT @vbzone = CONVERT( VARBINARY(2), RIGHT( '0000' + @token, 4 ), 2 ), @vbytes += @vbzone;

        -- Handles consecutive sections of zeros representation rule (i.e. ::)(https://en.wikipedia.org/wiki/IPv6#Address_representation)
        IF @token = ''
            WHILE @parts + 1 < @limit
                SELECT @vbytes += @vbzone, @parts += 1;
    END
    ELSE
    BEGIN
        SELECT @vbzone = CONVERT( VARBINARY(1), CONVERT( TINYINT, @token )), @vbytes += @vbzone
    END

    SELECT @prevColIndex = @colIndex, @colIndex = CHARINDEX( @delim, @tIPAddress, @colIndex + 1 ) 
END

SET @bytes =
    CASE @delim
        WHEN ':' THEN @vbytes
        ELSE /*0x000000000000000000000000 +*/ @vbytes -- Return IPV4 addresses as 4 byte binary (uncomment leading 0s section to force 16 byte binary)
    END 

RETURN @bytes

END

Test Cases

Valid cases

SELECT dbo.IPAddressStringToVarbinary( '0000:0000:0000:0000:0000:0000:0000:0001' ) -- 0x0000000000000000000000000001 (check bug fix)
SELECT dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' ) -- 0x00010002000300400500060070000089
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' )     -- 0x20010DB885A308D31319000003707348 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319:0000:370:7348' ) -- 0x20010DB885A308D31319000003707348
SELECT dbo.IPAddressStringToVarbinary( '192.168.1.72' ) -- 0xC0A80148
SELECT dbo.IPAddressStringToVarbinary( '127...1' ) -- 0x7F000001 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( NULL ) -- NULL
SELECT dbo.IPAddressStringToVarbinary( '' ) -- NULL
-- Check that conversions return original address
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' )) -- '0001:0002:0003:0040:0500:0600:7000:0089' 
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127...1' )) -- 127.0.0.1
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '192.168.1.72' )) -- 192.168.1.72
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' ))     -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1314:0000:370:7348' )) -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3::370:7348' )) -- 2001:0DB8:85A3:08D3:0000:0000:0370:7348
-- This is technically an invalid IPV6 (according to Wikipedia) but it parses correctly
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::370:7348' )) -- 2001:0DB8:0000:0000:1319:0000:0370:7348

Invalid cases

SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::7348' )) -- 2001:0DB8:0000:0000:0000:1319:0000:7348 (ambiguous address)
SELECT dbo.IPAddressStringToVarbinary( '127.1' ) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127.1' )) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressStringToVarbinary( '0300.0000.0002.0353' ) -- octal byte values
SELECT dbo.IPAddressStringToVarbinary( '0xC0.0x00.0x02.0xEB' ) -- hex values
SELECT dbo.IPAddressStringToVarbinary( 'C0.00.02.EB' ) -- hex values

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

htaccess redirect to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Notes: Make sure you have done the following steps

  1. sudo a2enmod rewrite
  2. sudo service apache2 restart
  3. Add Following in your vhost file, located at /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  allow from all
  Require all granted
</Directory>

Now your .htaccess will work and your site will redirect to http:// to https://www

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

If anyone got an error while signing in to Google and this message appear:

Couldn't Sign In
can't establish a reliable connection to the server...

then try to sign in from the browser - in YouTube, Gmail, Google sites, etc.

This helped me. After signing in in the browser I was able to sign in the Google Play app...

Linq : select value in a datatable column

Use linq and set the data table as Enumerable and select the fields from the data table field that matches what you are looking for.

Example

I want to get the currency Id and currency Name from the currency table where currency is local currency, and assign the currency id and name to a text boxes on the form:

DataTable dt = curData.loadCurrency();
            var curId = from c in dt.AsEnumerable()
                        where c.Field<bool>("LocalCurrency") == true
                        select c.Field<int>("CURID");

            foreach (int cid in curId)
            {
                txtCURID.Text = cid.ToString();
            }
            var curName = from c in dt.AsEnumerable()
                          where c.Field<bool>("LocalCurrency") == true
                          select c.Field<string>("CurName");
            foreach (string cName in curName)
            {
                txtCurrency.Text = cName.ToString();
            }

The FastCGI process exited unexpectedly

For user using PHP 5.6.x follow this link and install the x86 version.

How to calculate the running time of my program?

Use System.nanoTime to get the current time.

long startTime = System.nanoTime();
.....your program....
long endTime   = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);

The above code prints the running time of the program in nanoseconds.

How to use localization in C#

ResourceManager and .resx are bit messy.

You could use Lexical.Localization¹ which allows embedding default value and culture specific values into the code, and be expanded in external localization files for futher cultures (like .json or .resx).

public class MyClass
{
    /// <summary>
    /// Localization root for this class.
    /// </summary>
    static ILine localization = LineRoot.Global.Type<MyClass>();

    /// <summary>
    /// Localization key "Ok" with a default string, and couple of inlined strings for two cultures.
    /// </summary>
    static ILine ok = localization.Key("Success")
            .Text("Success")
            .fi("Onnistui")
            .sv("Det funkar");

    /// <summary>
    /// Localization key "Error" with a default string, and couple of inlined ones for two cultures.
    /// </summary>
    static ILine error = localization.Key("Error")
            .Format("Error (Code=0x{0:X8})")
            .fi("Virhe (Koodi=0x{0:X8})")
            .sv("Sönder (Kod=0x{0:X8})");

    public void DoOk()
    {
        Console.WriteLine( ok );
    }

    public void DoError()
    {
        Console.WriteLine( error.Value(0x100) );
    }
}

¹ (I'm maintainer of that library)

docker build with --build-arg with multiple arguments

Use --build-arg with each argument.

If you are passing two argument then add --build-arg with each argument like:

docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .

Can someone post a well formed crossdomain.xml sample?

In production site this seems suitable:

<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="www.mysite.com" />
<allow-access-from domain="mysite.com" />
</cross-domain-policy>

Is a URL allowed to contain a space?

URL can have an Space Character in them and they will be displayed as %20 in most of the browsers, but browser encoding rules change quite often and we cannot depend on how a browser will display the URL.

So Instead you can replace the Space Character in the URL with any character that you think shall make the URL More readable and ' Pretty ' ;) ..... O so general characters that are preferred are "-","_","+" .... but these aren't the compulsions so u can use any of the character that is not supposed to be in the URL Already.

Please avoid the %,&,},{,],[,/,>,< as the URL Space Character Replacement as they can pull up an error on certain browsers and Platforms.

As you can see the Stak overflow itself uses the '-' character as Space(%20) replacement.

Have an Happy questioning.

Convert Month Number to Month Name Function in SQL

Use the Best way

Select DateName( month , DateAdd( month , @MonthNumber , -1 ))

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

How to execute a program or call a system command from Python

It can be this simple:

import os
cmd = "your command"
os.system(cmd)

How to use Google fonts in React.js?

In some sort of main or first loading CSS file, just do:

@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:regular,bold,italic&subset=latin,latin-ext');

You don't need to wrap in any sort of @font-face, etc. the response you get back from Google's API is ready to go and lets you use font families like normal.

Then in your main React app JavaScript, at the top put something like:

import './assets/css/fonts.css';

What I did actually was made an app.css that imported a fonts.css with a few font imports. Simply for organization (now I know where all my fonts are). The important thing to remember is that you import the fonts first.

Keep in mind that any component you import to your React app should be imported after the style import. Especially if those components also import their own styles. This way you can be sure of the ordering of styles. This is why it's best to import fonts at the top of your main file (don't forget to check your final bundled CSS file to double check if you're having trouble).

There's a few options you can pass the Google Font API to be more efficient when loading fonts, etc. See official documentation: Get Started with the Google Fonts API

Edit, note: If you are dealing with an "offline" application, then you may indeed need to download the fonts and load through Webpack.

How to stop a function

def player(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over: 
        computer(game_over)  #We are only going to do this if check_winner comes back as False

def check_winner(): 
    check something
    #here needs to be an if / then statement deciding if the game is over, return True if over, false if not
    if score == 100:
        return True
    else:
        return False

def computer(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over:
        player(game_over) #We are only going to do this if check_winner comes back as False

game_over = False   #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over)   #Start your loops, sending in the status of game_over

Above is a pretty simple example... I made up a statement for check_winner using score = 100 to denote the game being over.

You will want to use similar method of passing score into check_winner, using game_over = check_winner(score). Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.

How to get the sizes of the tables of a MySQL database?

Calculate the total size of the database at the end:

(SELECT 
  table_name AS `Table`, 
  round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
  FROM information_schema.TABLES 
  WHERE table_schema = "$DB_NAME"
)
UNION ALL
(SELECT 
  'TOTAL:',
  SUM(round(((data_length + index_length) / 1024 / 1024), 2) )
  FROM information_schema.TABLES 
  WHERE table_schema = "$DB_NAME"
)

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

SSH library for Java

Take a look at the very recently released SSHD, which is based on the Apache MINA project.

How do I read and parse an XML file in C#?

You can either:

Examples are on the msdn pages provided

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

It is very clear from your exception that it is trying to connect to localhost and not to 10.101.3.229

exception snippet : Could not connect to SMTP host: localhost, port: 25;

1.) Please check if there are any null check which is setting localhost as default value

2.) After restarting, if it is working fine, then it means that only at first-run, the proper value is been taken from Properties and from next run the value is set to default. So keep the property-object as a singleton one and use it all-over your project

Spring @Autowired and @Qualifier

@Autowired to autowire(or search) by-type
@Qualifier to autowire(or search) by-name
Other alternate option for @Qualifier is @Primary

@Component
@Qualifier("beanname")
public class A{}

public class B{

//Constructor
@Autowired  
public B(@Qualifier("beanname")A a){...} //  you need to add @autowire also 

//property
@Autowired
@Qualifier("beanname")
private A a;

}

//If you don't want to add the two annotations, we can use @Resource
public class B{

//property
@Resource(name="beanname")
private A a;

//Importing properties is very similar
@Value("${property.name}")  //@Value know how to interpret ${}
private String name;
}

more about @value

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Couldn't connect to server 127.0.0.1:27017

In the terminal run these commands

1)

$ sudo service mongod start

2)

 $ mongo

Material effect on button with background color

I used the backgroundTint and foreground:

<Button
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:backgroundTint="@color/colorAccent"
    android:foreground="?android:attr/selectableItemBackground"
    android:textColor="@android:color/white"
    android:textSize="10sp"/>

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

Git commit with no commit message

--allow-empty-message -m '' (and -m "") fail in Git 2.29.2 on PowerShell:

error: switch `m' requires a value

(oddly enough, with a backtick on one side and a single quote on the other)


The following works consistently in Linux, PowerShell, and Command Prompt:

git commit --allow-empty-message --no-edit

The --no-edit bit does the trick, as it prevents the editor from launching.

I find this form more explicit and a bit less hacky than forcing an empty message with -m ''.

What is the difference between utf8mb4 and utf8 charsets in MySQL?

MySQL added this utf8mb4 code after 5.5.3, Mb4 is the most bytes 4 meaning, specifically designed to be compatible with four-byte Unicode. Fortunately, UTF8MB4 is a superset of UTF8, except that there is no need to convert the encoding to UTF8MB4. Of course, in order to save space, the general use of UTF8 is enough.

The original UTF-8 format uses one to six bytes and can encode 31 characters maximum. The latest UTF-8 specification uses only one to four bytes and can encode up to 21 bits, just to represent all 17 Unicode planes. UTF8 is a character set in Mysql that supports only a maximum of three bytes of UTF-8 characters, which is the basic multi-text plane in Unicode.

To save 4-byte-long UTF-8 characters in Mysql, you need to use the UTF8MB4 character set, but only 5.5. After 3 versions are supported (View version: Select version ();). I think that in order to get better compatibility, you should always use UTF8MB4 instead of UTF8. For char type data, UTF8MB4 consumes more space and, according to Mysql's official recommendation, uses VARCHAR instead of char.

In MariaDB utf8mb4 as the default CHARSET when it not set explicitly in the server config, hence COLLATE utf8mb4_unicode_ci is used.

Refer MariaDB CHARSET & COLLATE Click

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Return an empty Observable

Or you can try ignoreElements() as well

How to detect DataGridView CheckBox event change?

I use DataGridView with VirtualMode=true and only this option worked for me (when both the mouse and the space bar are working, including repeated space clicks):

private void doublesGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
   var data_grid = (DataGridView)sender;
      
   if (data_grid.CurrentCell.IsInEditMode && data_grid.IsCurrentCellDirty) {
      data_grid.EndEdit();            
   }
}

private void doublesGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
   if (e.ColumnIndex == CHECKED_COLUMN_NUM && e.RowIndex >= 0 && e.RowIndex < view_objects.Count) { // view_objects - pseudocode   
     view_objects[e.RowIndex].marked = !view_objects[e.RowIndex].marked;        // Invert the state of the displayed object
   }
}  

How to extract the n-th elements from a list of tuples?

n = 1 # N. . .
[x[n] for x in elements]

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

How do I get the size of a java.sql.ResultSet?

Easiest approach, Run Count(*) query, do resultSet.next() to point to the first row and then just do resultSet.getString(1) to get the count. Code :

ResultSet rs = statement.executeQuery("Select Count(*) from your_db");
if(rs.next()) {
   int count = rs.getString(1).toInt()
}

Copy all values from fields in one class to another through reflection

  1. Without using BeanUtils or Apache Commons

  2. public static <T1 extends Object, T2 extends Object>  void copy(T1     
    origEntity, T2 destEntity) throws IllegalAccessException, NoSuchFieldException {
        Field[] fields = origEntity.getClass().getDeclaredFields();
        for (Field field : fields){
            origFields.set(destEntity, field.get(origEntity));
         }
    }
    

Calling multiple JavaScript functions on a button click

At times it gives syntax error that "return is not a function" so in that case just remove return and it will work fine :) as shown below

OnClientClick="var b = validateView(); if(b) var b = ShowDiv1(); b;"

Increasing the Command Timeout for SQL command

it takes this command about 2 mins to return the data as there is a lot of data

Probably, Bad Design. Consider using paging here.

default connection time is 30 secs, how do I increase this

As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this

// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;

Sending email with PHP from an SMTP server

When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).

For example, I usually use PHPMailer with similar settings to this ones:

$mail = new PHPMailer();

// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';

$mail->Host       = "mail.example.com"; // SMTP server example
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
$mail->Username   = "username"; // SMTP account username example
$mail->Password   = "password";        // SMTP account password example

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();

You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer

Draw path between two points using Google Maps Android API v2

Dont know whether I should put this as answer or not...

I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..

going through some other question over SO, I had the following solution

I add the following function in Zeeshan's class

 public void clearRoute(){

         for(Polyline line1 : polylines)
         {
             line1.remove();
         }

         polylines.clear();

     }

in my map activity, before drawing the path, I called this function.. example usage as per my app is

private Route rt;

rt.clearRoute();

            if (src == null) {
                Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
            }else if (Destination == null) {
                Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
            }else if (src.equals(Destination)) {
                Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
            }else{

                rt.drawRoute(mMap, MapsMainActivity.this, src,
                        Destination, false, "en");
            }

you can use rt.clearRoute(); as per your requirements.. Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..

Complete Class Code

see on github

Edit: here is part of code from mainactivity..

case R.id.mkrbtn_set_dest:
                    Destination = selmarker.getPosition();
                    destmarker = selmarker;
                    desShape = createRouteCircle(Destination, false);

                    if (src == null) {
                        Toast.makeText(getApplicationContext(),
                                "Please select your Source first...",
                                Toast.LENGTH_LONG).show();
                    } else if (src.equals(Destination)) {
                        Toast.makeText(getApplicationContext(),
                                "Source and Destinatin can not be the same..",
                                Toast.LENGTH_LONG).show();
                    } else {

                        if (isNetworkAvailable()) {
                            rt.drawRoute(mMap, MapsMainActivity.this, src,
                                    Destination, false, "en");
                            src = null;
                            Destination = null;

                        } else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Internet Connection seems to be OFFLINE...!",
                                    Toast.LENGTH_LONG).show();

                        }

                    }

                    break;

Edit 2 as per comments

usage :

//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned

rt.drawRoute(mMap, MapsMainActivity.this, src,
                            Destination, false, "en");

Blocking device rotation on mobile web pages

In JavaScript-enabled browsers it should be easy to determine if the screen is in landscape or portrait mode and compensate using CSS. It may be helpful to give users the option to disable this or at least warn them that device rotation will not work properly.

Edit

The easiest way to detect the orientation of the browser is to check the width of the browser versus the height of the browser. This also has the advantage that you'll know if the game is being played on a device that is naturally oriented in landscape mode (as some mobile devices like the PSP are). This makes more sense than trying to disable device rotation.

Edit 2

Daz has shown how you can detect device orientation, but detecting orientation is only half of the solution. If want to reverse the automatic orientation change, you'll need to rotate everything either 90° or 270°/-90°, e.g.

$(window).bind('orientationchange resize', function(event){
  if (event.orientation) {
    if (event.orientation == 'landscape') {
      if (window.rotation == 90) {
        rotate(this, -90);
      } else {
        rotate(this, 90);
      }
    }
  }
});

function rotate(el, degs) {
  iedegs = degs/90;
  if (iedegs < 0) iedegs += 4;
  transform = 'rotate('+degs+'deg)';
  iefilter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+iedegs+')';
  styles = {
    transform: transform,
    '-webkit-transform': transform,
    '-moz-transform': transform,
    '-o-transform': transform,
    filter: iefilter,
    '-ms-filter': iefilter
  };
  $(el).css(styles);
}

Note: if you want to rotate in IE by an arbitrary angle (for other purposes), you'll need to use matrix transform, e.g.

rads = degs * Math.PI / 180;
m11 = m22 = Math.cos(rads);
m21 = Math.sin(rads);
m12 = -m21;
iefilter = "progid:DXImageTransform.Microsoft.Matrix("
  + "M11 = " + m11 + ", "
  + "M12 = " + m12 + ", "
  + "M21 = " + m21 + ", "
  + "M22 = " + m22 + ", sizingMethod = 'auto expand')";
styles['filter'] = styles['-ms-filter'] = iefilter;

—or use CSS Sandpaper. Also, this applies the rotation style to the window object, which I've never actually tested and don't know if works or not. You may need to apply the style to a document element instead.

Anyway, I would still recommend simply displaying a message that asks the user to play the game in portrait mode.

What __init__ and self do in Python?

Had trouble undestanding this myself. Even after reading the answers here.

To properly understand the __init__ method you need to understand self.

The self Parameter

The arguments accepted by the __init__ method are :

def __init__(self, arg1, arg2):

But we only actually pass it two arguments :

instance = OurClass('arg1', 'arg2')

Where has the extra argument come from ?

When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs.

In order to access object attributes from within the __init__ method we need a reference to the object.

Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self.

This means in the __init__ method we can do :

self.arg1 = arg1
self.arg2 = arg2

Here we are setting attributes on the object. You can verify this by doing the following :

instance = OurClass('arg1', 'arg2')
print instance.arg1
arg1

values like this are known as object attributes. Here the __init__ method sets the arg1 and arg2 attributes of the instance.

source: http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method

VB.NET Connection string (Web.Config, App.Config)

I don't know if this still is an issue, but i prefere just to use the My.Settings in my code.

Visual Studio generates a simple class with functions for reading settings from the app.config file.

You can simply access it using My.Settings.ConnectionString.

    Using Context As New Data.Context.DataClasses()
        Context.Connection.ConnectionString = My.Settings.ConnectionString
    End Using

How can I pretty-print JSON using node.js?

what about this?

console.table(object)

sample

Difference between partition key, composite key and clustering key in Cassandra?

Primary Key: Is composed of partition key(s) [and optional clustering keys(or columns)]
Partition Key: The hash value of Partition key is used to determine the specific node in a cluster to store the data
Clustering Key: Is used to sort the data in each of the partitions(or responsible node and it's replicas)

Compound Primary Key: As said above, the clustering keys are optional in a Primary Key. If they aren't mentioned, it's a simple primary key. If clustering keys are mentioned, it's a Compound primary key.

Composite Partition Key: Using just one column as a partition key, might result in wide row issues (depends on use case/data modeling). Hence the partition key is sometimes specified as a combination of more than one column.

Regarding confusion of which one is mandatory, which one can be skipped etc. in a query, trying to imagine Cassandra as a giant HashMap helps. So in a HashMap, you can't retrieve the values without the Key.
Here, the Partition keys play the role of that key. So each query needs to have them specified. Without which Cassandra won't know which node to search for.
The clustering keys (columns, which are optional) help in further narrowing your query search after Cassandra finds out the specific node(and it's replicas) responsible for that specific Partition key.

RuntimeError on windows trying python multiprocessing

As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':

So, in my case, ended like this:

if __name__ == '__main__':       
    import librosa
    import os
    import pandas as pd
    run_my_program()

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality


The addwithvalue method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add method requires that you specify the Database type first. This helps to reduce such errors.

For more detail Please click here

How to get the response of XMLHttpRequest?

I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

_x000D_
_x000D_
const url = "https://stackoverflow.com";
fetch(url)
    .then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );
_x000D_
_x000D_
_x000D_

In Node.js, you'll need to import fetch using:

const fetch = require("node-fetch");

If you want to use it synchronously (doesn't work in top scope):

const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});

More Info:

Mozilla Documentation

Can I Use (95% Feb 2020)

Matt Walsh Tutorial

Convert pandas dataframe to NumPy array

A Simpler Way for Example DataFrame:

df

         gbm       nnet        reg
0  12.097439  12.047437  12.100953
1  12.109811  12.070209  12.095288
2  11.720734  11.622139  11.740523
3  11.824557  11.926414  11.926527
4  11.800868  11.727730  11.729737
5  12.490984  12.502440  12.530894

USE:

np.array(df.to_records().view(type=np.matrix))

GET:

array([[(0, 12.097439  , 12.047437, 12.10095324),
        (1, 12.10981081, 12.070209, 12.09528824),
        (2, 11.72073428, 11.622139, 11.74052253),
        (3, 11.82455653, 11.926414, 11.92652727),
        (4, 11.80086775, 11.72773 , 11.72973699),
        (5, 12.49098389, 12.50244 , 12.53089367)]],
dtype=(numpy.record, [('index', '<i8'), ('gbm', '<f8'), ('nnet', '<f4'),
       ('reg', '<f8')]))

Finding the number of non-blank columns in an Excel sheet using VBA

Result is shown in the following code as column number (8,9 etc.):

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

Result is shown in the following code as letter (H,I etc.):

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox Split(Sheet1.Cells(1, lastColumn).Address, "$")(1)

Propagation Delay vs Transmission delay

Because they're measuring different things.

Propagation delay is how long it takes one bit to travel from one end of the "wire" to the other (it's proportional to the length of the wire, crudely).

Transmission delay is how long it takes to get all the bits into the wire in the first place (it's packet_length/data_rate).

How do I ignore a directory with SVN?

Important to mention:

On the commandline you can't use

svn add *

This will also add the ignored files, because the command line expands * and therefore svn add believes that you want all files to be added. Therefore use this instead:

svn add --force .

MIT vs GPL license

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.

The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.

is the GPL is more restrictive than the MIT license?

Yes, very much so.

Clone Object without reference javascript

If you use an = statement to assign a value to a var with an object on the right side, javascript will not copy but reference the object.

You can use lodash's clone method

var obj = {a: 25, b: 50, c: 75};
var A = _.clone(obj);

Or lodash's cloneDeep method if your object has multiple object levels

var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.cloneDeep(obj);

Or lodash's merge method if you mean to extend the source object

var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.merge({}, obj, {newkey: "newvalue"});

Or you can use jQuerys extend method:

var obj = {a: 25, b: 50, c: 75};
var A = $.extend(true,{},obj);

Here is jQuery 1.11 extend method's source code :

jQuery.extend = jQuery.fn.extend = function() {
    var src, copyIsArray, copy, name, options, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;

        // skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }

    for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};

AttributeError: 'str' object has no attribute 'append'

myList[1] is an element of myList and it's type is string.

myList[1] is str, you can not append to it. myList is a list, you should have been appending to it.

>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> 

Importing Excel files into R, xlsx or xls

For me the openxlx package worked in the easiest way.

install.packages("openxlsx")
library(openxlsx)
rawData<-read.xlsx("your.xlsx");

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

I use ? and ?, but they might not work for you. I use alt 11551 for the first one and 11550 for the second one. You can always copy paste them if the ascii isnt the same for your system.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

This is new way to do this using https://github.com/k06a/ABStaticTableViewController

NSIndexPath *ip = [NSIndexPath indexPathForRow:1 section:1];
[self deleteRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationFade]

Bootstrap 3 hidden-xs makes row narrower

How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.

<div class="container">
    <div class="row">
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col1
        </div>
        <div class="col-xs-4 col-sm-2" align="center">
            Col2
        </div>
        <div class="hidden-xs col-sm-6 col-md-5" align="center">
            Col3
        </div>
        <div class="visible-md col-md-3 " align="center">
            Col4
        </div>
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col5
        </div>
    </div>
</div>

System.MissingMethodException: Method not found?

I solved this problem by making a shelveset with my changes and running TFS Power Tools 'scorch' in my workspace (https://visualstudiogallery.msdn.microsoft.com/f017b10c-02b4-4d6d-9845-58a06545627f). Then I unshelved the changes and recompiled the project. This way you will cleanup any 'hanging-parties' that may be around in your workspace and will startup with a fresh one. This requires, of course, that you are using TFS.

IIS7 Permissions Overview - ApplicationPoolIdentity

On Windows Server 2008(r2) you can't assign an application pool identity to a folder through Properties->Security. You can do it through an admin command prompt using the following though:

icacls "c:\yourdirectory" /t /grant "IIS AppPool\DefaultAppPool":(R)

Caesar Cipher Function in Python

As @I82much said, you need to take cipherText = "" outside of your for loop. Place it at the beginning of the function. Also, your program has a bug which will cause it to generate encryption errors when you get capital letters as input. Try:

    if ch.isalpha(): 
        finalLetter = chr((ord(ch.lower()) - 97 + shift) % 26 + 97)

Update a column value, replacing part of a string

UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')

Which tool to build a simple web front-end to my database

For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.

For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.

Best way to generate xml?

I've tried a some of the solutions in this thread, and unfortunately, I found some of them to be cumbersome (i.e. requiring excessive effort when doing something non-trivial) and inelegant. Consequently, I thought I'd throw my preferred solution, web2py HTML helper objects, into the mix.

First, install the the standalone web2py module:

pip install web2py

Unfortunately, the above installs an extremely antiquated version of web2py, but it'll be good enough for this example. The updated source is here.

Import web2py HTML helper objects documented here.

from gluon.html import *

Now, you can use web2py helpers to generate XML/HTML.

words = ['this', 'is', 'my', 'item', 'list']
# helper function
create_item = lambda idx, word: LI(word, _id = 'item_%s' % idx, _class = 'item')
# create the HTML
items = [create_item(idx, word) for idx,word in enumerate(words)]
ul = UL(items, _id = 'my_item_list', _class = 'item_list')
my_div = DIV(ul, _class = 'container')

>>> my_div

<gluon.html.DIV object at 0x00000000039DEAC8>

>>> my_div.xml()
# I added the line breaks for clarity
<div class="container">
   <ul class="item_list" id="my_item_list">
      <li class="item" id="item_0">this</li>
      <li class="item" id="item_1">is</li>
      <li class="item" id="item_2">my</li>
      <li class="item" id="item_3">item</li>
      <li class="item" id="item_4">list</li>
   </ul>
</div>

Create a tag in a GitHub repository

You can create tags for GitHub by either using:

  • the Git command line, or
  • GitHub's web interface.

Creating tags from the command line

To create a tag on your current branch, run this:

git tag <tagname>

If you want to include a description with your tag, add -a to create an annotated tag:

git tag <tagname> -a

This will create a local tag with the current state of the branch you are on. When pushing to your remote repo, tags are NOT included by default. You will need to explicitly say that you want to push your tags to your remote repo:

git push origin --tags

From the official Linux Kernel Git documentation for git push:

--tags

All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

Or if you just want to push a single tag:

git push origin <tag>

See also my answer to How do you push a tag to a remote repository using Git? for more details about that syntax above.

Creating tags through GitHub's web interface

You can find GitHub's instructions for this at their Creating Releases help page. Here is a summary:

  1. Click the releases link on our repository page,

    Screenshot 1

  2. Click on Create a new release or Draft a new release,

    Screenshot 2

  3. Fill out the form fields, then click Publish release at the bottom,

    Screenshot 3 Screenshot 4

  4. After you create your tag on GitHub, you might want to fetch it into your local repository too:

    git fetch
    

Now next time, you may want to create one more tag within the same release from website. For that follow these steps:

Go to release tab

  1. Click on edit button for the release

  2. Provide name of the new tag ABC_DEF_V_5_3_T_2 and hit tab

  3. After hitting tab, UI will show this message: Excellent! This tag will be created from the target when you publish this release. Also UI will provide an option to select the branch/commit

  4. Select branch or commit

  5. Check "This is a pre-release" checkbox for qa tag and uncheck it if the tag is created for Prod tag.

  6. After that click on "Update Release"

  7. This will create a new Tag within the existing Release.

Turning a Comma Separated string into individual rows

;WITH tmp(SomeID, OtherID, DataItem, Data) as (
    SELECT SomeID, OtherID, LEFT(Data, CHARINDEX(',',Data+',')-1),
        STUFF(Data, 1, CHARINDEX(',',Data+','), '')
FROM Testdata
WHERE Data > ''
)
SELECT SomeID, OtherID, Data
FROM tmp
ORDER BY SomeID

with only tiny little modification to above query...

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to check if a character in a string is a digit or letter

I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.

public class test {
    public static void main(String[] args) {
        String c;
        boolean b;

        System.out.println("Enter the value");
        Scanner s = new Scanner(System.in);
        c = s.next();
        b = containsNumber(c);
        try {
            if (b == true) {
                throw new CharacterFormatException();
            } else {
                System.out.println("Valid String \t" + c);
            }
        } catch (CharacterFormatException ex) {
            System.out.println("Exception Raised-Contains Number");

        }
    }

    static boolean containsNumber(String c) {
        char[] ch = new char[10];
        ch = c.toCharArray();

        for (int i = 0; i < ch.length; i++) {
            if ((ch[i] >= 48) && (ch[i] <= 57)) {
                return true;
            }
        }
        return false;
    }
}

CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

Editor does not contain a main type

Make sure that your .java file is present either in the str package, or in some other package. If the java file with the main function is outside all packages, this error is thrown.

Echo newline in Bash prints literal \n

You can also do:

echo "hello
world"

This works both inside a script and from the command line.
In the command line, press Shift+Enter to do the line breaks inside the string.

This works for me on my macOS and my Ubuntu 18.04

printf a variable in C

Your printf needs a format string:

printf("%d\n", x);

This reference page gives details on how to use printf and related functions.

DataGridView.Clear()

I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!

foreach (DataGridViewRow row in dataGridView1.Rows) 
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        cell.Value = "";
    }
}

Safe Area of Xcode 9

I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreaLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).

From the property's documentation:

The layout guide representing the portion of your view that is unobscured by bars and other content. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

(emphasis mine)

If you read it as early as -viewDidLoad:, the layoutFrame of the guide will be {{0, 0}, {375, 812}} instead of the expected {{0, 44}, {375, 734}}

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

If you're using JNA, you can do thisPlatform.is64Bit().

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I have this issue, and all I did was make sure that I was referencing the right .Net framework in all the projects then just change the web.config from

From

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

To

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework" requirePermission="false"/>

All works..

How abstraction and encapsulation differ?

I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.

Abstraction is related to "why" I am encapsulating it the first place.

I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."

This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.

I really think that abstracting and encapsulation go together.

Add JavaScript object to JavaScript object

var jsonIssues = []; // new Array
jsonIssues.push( { ID:1, "Name":"whatever" } );
// "push" some more here

Razor MVC Populating Javascript array with Model Array

This would be better approach as I have implemented :)

@model ObjectUser
@using System.Web.Script.Serialization
@{ 
    var javaScriptSearilizer = new JavaScriptSerializer();
    var searializedObject = javaScriptSearilizer.Serialize(Model);
 }

<script>
    var searializedObject = @Html.Raw(searializedObject )
    console.log(searializedObject);
    alert(searializedObject);
</script>

Hope this will help you to prevent you from iterating model ( happy coding )

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]

Android: How to Programmatically set the size of a Layout

You can get the actual height of called layout with this code:

public int getLayoutSize() {
// Get the layout id
    final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
    final AtomicInteger layoutHeight = new AtomicInteger();

    root.post(new Runnable() { 
    public void run() { 
        Rect rect = new Rect(); 
        Window win = getWindow();  // Get the Window
                win.getDecorView().getWindowVisibleDisplayFrame(rect);

                // Get the height of Status Bar
                int statusBarHeight = rect.top;

                // Get the height occupied by the decoration contents 
                int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();

                // Calculate titleBarHeight by deducting statusBarHeight from contentViewTop  
                int titleBarHeight = contentViewTop - statusBarHeight; 
                Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop); 

                // By now we got the height of titleBar & statusBar
                // Now lets get the screen size
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);   
                int screenHeight = metrics.heightPixels;
                int screenWidth = metrics.widthPixels;
                Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);   

                // Now calculate the height that our layout can be set
                // If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also 
                layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
                Log.i("MY", "Layout Height = " + layoutHeight);   

            // Lastly, set the height of the layout       
            FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
            rootParams.height = layoutHeight.get();
            root.setLayoutParams(rootParams);
        }
    });

return layoutHeight.get();
}

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

How to encode the filename parameter of Content-Disposition header in HTTP?

There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."

RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.

How to parse a CSV in a Bash script?

See this youtube video: BASH scripting lesson 10 working with CSV files

CSV file:

Bob Brown;Manager;16581;Main
Sally Seaforth;Director;4678;HOME

Bash script:

#!/bin/bash
OLDIFS=$IFS
IFS=";"
while read user job uid location
 do

    echo -e "$user \
    ======================\n\
    Role :\t $job\n\
    ID :\t $uid\n\
    SITE :\t $location\n"
 done < $1
 IFS=$OLDIFS

Output:

Bob Brown     ======================
    Role :   Manager
    ID :     16581
    SITE :   Main

Sally Seaforth     ======================
    Role :   Director
    ID :     4678
    SITE :   HOME

Create a <ul> and fill it based on a passed array

First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ];

function makeUL(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for (var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));

Here's a demo. You might also want to note that set0 and set1 are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};

And access them like so:

makeUL(options.set0);

Vim clear last search highlighting

Janus for VIM and GVIM has a number of baked-in things for newbs like me, including

<leader>hs - toggles highlight search

which is exactly what you need. Just type \hs in normal mode. (The leader key is mapped to \ by default.)

HTH.

Writing files in Node.js

You can write in a file by the following code example:

var data = [{ 'test': '123', 'test2': 'Lorem Ipsem ' }];
fs.open(datapath + '/data/topplayers.json', 'wx', function (error, fileDescriptor) {
  if (!error && fileDescriptor) {
    var stringData = JSON.stringify(data);
    fs.writeFile(fileDescriptor, stringData, function (error) {
      if (!error) {
        fs.close(fileDescriptor, function (error) {
          if (!error) {
            callback(false);
          } else {
            callback('Error in close file');
          }
        });
      } else {
        callback('Error in writing file.');
      }
    });
  }
});