Programs & Examples On #Imacros

iMacros is an extension for the Mozilla Firefox, Google Chrome and Internet Explorer web browsers which adds record and replay functionality similar to that found in web testing and form filler software.

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

MVVM: Tutorial from start to finish?

I was in exactly the same situation recently, mate, and I can tell you what I did.

Josh Smith "WPF Apps With The Model-View-ViewModel Design Pattern" read again, again and again :-) download the code, examine, compile and keep it around

MVVM foundation

  1. Examine the framework, use it in your app.
  2. Look at the Demo application in that framework.

No real start-to-finish tutorials, sorry...

Negative regex for Perl string pattern match

Your regex does not work because [] defines a character class, but what you want is a lookahead:

(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)

So try: (?!bush)

Are (non-void) self-closing tags valid in HTML5?

As Nikita Skvortsov pointed out, a self-closing div will not validate. This is because a div is a normal element, not a void element.

According to the HTML5 spec, tags that cannot have any contents (known as void elements) can be self-closing*. This includes the following tags:

area, base, br, col, embed, hr, img, input, 
keygen, link, meta, param, source, track, wbr

The "/" is completely optional on the above tags, however, so <img/> is not different from <img>, but <img></img> is invalid.

*Note: foreign elements can also be self-closing, but I don't think that's in scope for this answer.

C++ catching all exceptions

Let me just mention this here: the Java

try 
{
...
}
catch (Exception e)
{
...
}

may NOT catch all exceptions! I've actually had this sort of thing happen before, and it's insantiy-provoking; Exception derives from Throwable. So literally, to catch everything, you DON'T want to catch Exceptions; you want to catch Throwable.

I know it sounds nitpicky, but when you've spent several days trying to figure out where the "uncaught exception" came from in code that was surrounded by a try ... catch (Exception e)" block comes from, it sticks with you.

Difference between F5, Ctrl + F5 and click on refresh button?

I did small research regarding this topic and found different behavior for the browsers:

enter image description here

See my blog post "Behind refresh button" for more details.

How to remove the border highlight on an input text element

You can remove the orange or blue border (outline) around text/input boxes by using: outline:none

input {
    background-color: transparent;
    border: 0px solid;
    height: 20px;
    width: 160px;
    color: #CCC;
    outline:none !important;
}

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

how to break the _.each function in underscore.js

worked in my case

var arr2 = _.filter(arr, function(item){
    if ( item == 3 ) return item;
});

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Permissions

You need the s3:GetObject permission for this operation. For more information, see Specifying Permissions in a Policy. If the object you request does not exist, the error Amazon S3 returns depends on whether you also have the s3:ListBucket permission.

If you have the s3:ListBucket permission on the bucket, Amazon S3 returns an HTTP status code 404 ("no such key") error.

If you don’t have the s3:ListBucket permission, Amazon S3 returns an HTTP status code 403 ("access denied") error.

The following operation is related to HeadObject:

GetObject

Source: https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

Just remove Trusted_Connection=True property from the connection string.

What is the difference between partitioning and bucketing a table in Hive ?

There are great responses here. I would like to keep it short to memorize the difference between partition & buckets.

You generally partition on a less unique column. And bucketing on most unique column.

Example if you consider World population with country, person name and their bio-metric id as an example. As you can guess, country field would be the less unique column and bio-metric id would be the most unique column. So ideally you would need to partition the table by country and bucket it by bio-metric id.

how to append a css class to an element by javascript?

addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));

This will add ONE class or MULTIPLE classes :

addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"

What does "export default" do in JSX?

In simple word export means letting the script we wrote to be used by another script. If we say export, we mean any module can use this script by importing it.

How do I find out if the GPS of an Android device is enabled

In android, we can easily check whether GPS is enabled in device or not using LocationManager.

Here is a simple program to Check.

GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Your java class file should be

public class ExampleApp extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

    private void showGPSDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}

The output will looks like

enter image description here

enter image description here

Is there a function to make a copy of a PHP array to another?

Safest and cheapest way I found is:

<?php 
$b = array_values($a);

This has also the benefit to reindex the array.

This will not work as expected on associative array (hash), but neither most of previous answer.

How to build splash screen in windows forms application?

Here is the easiest way of creating a splash screen:

First of all, add the following line of code before the namespace in Form1.cs code:

using System.Threading;

Now, follow the following steps:

  1. Add a new form in you application

  2. Name this new form as FormSplashScreen

  3. In the BackgroundImage property, choose an image from one of your folders

  4. Add a progressBar

  5. In the Dock property, set it as Bottom

  6. In MarksAnimationSpeed property, set as 50

  7. In your main form, named as Form1.cs by default, create the following method:

     private void StartSplashScreen()
     {
         Application.Run(new Forms.FormSplashScreen());
     }
    
  8. In the constructor method of Form1.cs, add the following code:

     public Form1()
     {
         Thread t = new Thread(new ThreadStart(StartSplashScreen));
         t.Start();
         Thread.Sleep(5000);
    
         InitializeComponent();//This code is automatically generated by Visual Studio
    
         t.Abort();
     }
    
  9. Now, just run the application, it is going to work perfectly.

Check if string is in a pandas dataframe

If there is any chance that you will need to search for empty strings,

    a['Names'].str.contains('') 

will NOT work, as it will always return True.

Instead, use

    if '' in a["Names"].values

to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.

Why doesn't Java allow overriding of static methods?

What good will it do to override static methods. You cannot call static methods through an instance.

MyClass.static1()
MySubClass.static1()   // If you overrode, you have to call it through MySubClass anyway.

EDIT : It appears that through an unfortunate oversight in language design, you can call static methods through an instance. Generally nobody does that. My bad.

The module ".dll" was loaded but the entry-point was not found

I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

Thanks! If anyone has the same problem, I'll be happy to help.

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

Finding elements not in a list

Your code is not doing what I think you think it is doing. The line for item in z: will iterate through z, each time making item equal to one single element of z. The original item list is therefore overwritten before you've done anything with it.

I think you want something like this:

item = [0,1,2,3,4,5,6,7,8,9]

for element in item:
    if element not in z:
        print element

But you could easily do this like:

[x for x in item if x not in z]

or (if you don't mind losing duplicates of non-unique elements):

set(item) - set(z)

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

Turn a number into star rating display using jQuery and CSS

I ended up going totally JS-free to avoid client-side render lag. To accomplish that, I generate HTML like this:

<span class="stars" title="{value as decimal}">
    <span style="width={value/5*100}%;"/>
</span>

To help with accessibility, I even add the raw rating value in the title attribute.

Eclipse count lines of code

One possible way to count lines of code in Eclipse:

using the Search / File... menu, select File Search tab, specify \n[\s]* for Containing text (this will not count empty lines), and tick Regular expression.

Hat tip: www.monblocnotes.com/node/2030

Adding header to all request with Retrofit 2

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request().newBuilder().addHeader("parameter", "value").build();
        return chain.proceed(request);
    }
});
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build();

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

Can't find AVD or SDK manager in Eclipse

Unfortunately I ended up having to re-install eclipse. but first (In Linux)(not sure of folder in Windows) do:

sudo rm -R /usr/share/eclipse/

How to remove numbers from a string?

A secondary option would be to match and return non-digits with some expression similar to,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

Demo

Test

_x000D_
_x000D_
function non_digit_string(str) {_x000D_
 const regex = /\D+/g;_x000D_
 let m;_x000D_
_x000D_
 non_digit_arr = [];_x000D_
 while ((m = regex.exec(str)) !== null) {_x000D_
  // This is necessary to avoid infinite loops with zero-width matches_x000D_
  if (m.index === regex.lastIndex) {_x000D_
   regex.lastIndex++;_x000D_
  }_x000D_
_x000D_
_x000D_
  m.forEach((match, groupIndex) => {_x000D_
   if (match.trim() != '') {_x000D_
    non_digit_arr.push(match.trim());_x000D_
   }_x000D_
  });_x000D_
 }_x000D_
 return non_digit_arr;_x000D_
}_x000D_
_x000D_
const str = `1 ding ? 124_x000D_
12 ding ?_x000D_
123 ding ? 123`;_x000D_
console.log(non_digit_string(str));
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Add multiple items to a list

Thanks to AddRange:

Example:

public class Person
{ 
    private string Name;
    private string FirstName;

    public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}

To add multiple Person to a List<>:

List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
    new Person("John1", "Doe" ),
    new Person("John2", "Doe" ),
    new Person("John3", "Doe" ),
 });

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

How do I make a checkbox required on an ASP.NET form?

C# version of andrew's answer:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
        ErrorMessage="Please accept the terms..." 
        onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    <asp:CheckBox ID="CheckBox1" runat="server" />

Code-behind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = CheckBox1.Checked;
}

ASP.NET set hiddenfield a value in Javascript

document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value

The id you set in server is the server id which is different from client id.

Multiple modals overlay

I created a Bootstrap plugin that incorporates a lot of the ideas posted here.

Demo on Bootply: http://www.bootply.com/cObcYInvpq

Github: https://github.com/jhaygt/bootstrap-multimodal

It also addresses the issue with successive modals causing the backdrop to become darker and darker. This ensures that only one backdrop is visible at any given time:

if(modalIndex > 0)
    $('.modal-backdrop').not(':first').addClass('hidden');

The z-index of the visible backdrop is updated on both the show.bs.modal and hidden.bs.modal events:

$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (modalIndex * 20));

Sort a Custom Class List<T>

You are right - you need to implement IComparable. To do this, simply declare your class:

public MyClass : IComparable
{
  int IComparable.CompareTo(object obj)
  {
  }
}

In CompareTo, you just implement your custom comparison algorithm (you can use DateTime objects to do this, but just be certain to check the type of "obj" first). For further information, see here and here.

Are list-comprehensions and functional functions faster than "for loops"?

If you check the info on python.org, you can see this summary:

Version Time (seconds)
Basic loop 3.47
Eliminate dots 2.45
Local variable & no dots 1.79
Using map function 0.54

But you really should read the above article in details to understand the cause of the performance difference.

I also strongly suggest you should time your code by using timeit. At the end of the day, there can be a situation where, for example, you may need to break out of for loop when a condition is met. It could potentially be faster than finding out the result by calling map.

How can I kill all sessions connecting to my oracle database?

Additional info

Important Oracle 11g changes to alter session kill session

Oracle author Mladen Gogala notes that an @ sign is now required to kill a session when using the inst_id column:

alter system kill session '130,620,@1';

http://www.dba-oracle.com/tips_killing_oracle_sessions.htm

What is key=lambda

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

ISO C90 forbids mixed declarations and code in C

Up until the C99 standard, all declarations had to come before any statements in a block:

void foo()
{
  int i, j;
  double k;
  char *c;

  // code

  if (c)
  {
    int m, n;

    // more code
  }
  // etc.
}

C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft's) don't support C99 at all.

So, you will need to do the following:

  1. Determine if your compiler supports C99 or later; if it does, configure it so that it's compiling C99 instead of C89;

  2. If your compiler doesn't support C99 or later, you will either need to find a different compiler that does support it, or rewrite your code so that all declarations come before any statements within the block.

Application Crashes With "Internal Error In The .NET Runtime"

In my case the issue was due to duplicate binding redirects in my web.config. More info here.

I assume it was because of NuGet modifying the binding redirects, but for example it was looking like this:

  <dependentAssembly>
    <assemblyIdentity name="Lucene.Net" publicKeyToken="85089178b9ac3181"/>
    <bindingRedirect oldVersion="0.0.0.0-2.9.4.0" newVersion="3.0.3.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"/>
    <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Lucene.Net" publicKeyToken="85089178b9ac3181"/>
    <bindingRedirect oldVersion="0.0.0.0-2.9.4.0" newVersion="3.0.3.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"/>
    <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0"/>
  </dependentAssembly>

Removing all the duplicates solved the problem.

Is there a command line command for verifying what version of .NET is installed

If you're going to run a little console app, you may as well install clrver.exe from the .NET SDK. I don't think you can get cleaner than that. This isn't my answer (but I happen to agree), I found it here.

ASP.NET Core 1.0 on IIS error 502.5

I had the same problem, in my case it was insufficient permission of the user identity of my Application Pool, on Publishing to IIS page of asp.net doc, there is a couple of reason listed for this error:

  • If you published a self-contained application, confirm that you didn’t set a platform in buildOptions of project.json that conflicts with the publishing RID. For example, do not specify a platform of x86 and publish with an RID of win81-x64 (dotnet publish -c Release -r win81-x64). The project will publish without warning or error but fail with the above logged exceptions on the server.
  • Check the processPath attribute on the <aspNetCore> element in web.config to confirm that it is dotnet for a portable application or .\my_application.exe for a self-contained application.
  • For a portable application, dotnet.exe might not be accessible via the PATH settings. Confirm that C:\Program Files\dotnet\ exists in the System PATH settings.
  • For a portable application, dotnet.exe might not be accessible for the user identity of the Application Pool. Confirm that the AppPool user identity has access to the C:\Program Files\dotnet directory.
  • Confirm that you have correctly referenced the IIS Integration middleware by calling the .UseIISIntegration() method of the application’s WebHostBuilder().
  • If you are using the .UseUrls() extension method when self-hosting with Kestrel, confirm that it is positioned before the .UseIISIntegration() extension method on WebHostBuilder(). .UseIISIntegration() must set the Url for the reverse-proxy when running Kestrel behind IIS and not have its value overridden by .UseUrls().

In my case it was the fourth reason, I changed it by right clicking my app pool, and in advanced setting under Process Model, I set the Identity to a user with enough permission: user identity of my Application Pool

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

If your databaseName value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")

Accessing JSON elements

Just for more one option...You can do it this way too:

MYJSON = {
    'username': 'gula_gut',
    'pics': '/0/myfavourite.jpeg',
    'id': '1'
}

#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])

I hope this can help.

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Excel - Shading entire row based on change of value

you could use this formular to do the job -> get the CellValue for the specific row by typing: = indirect("$A&Cell()) depending on which column you have to check, you have to change the $A

For Example -> You could use a customized VBA Function in the Background:

Public Function IstDatum(Zelle) As Boolean IstDatum = False If IsDate(Zelle) Then IstDatum = True End Function

I need it to check for a date-entry in column A:

=IstDatum(INDIREKT("$A"&ZEILE()))

have a look at the picture:

Delete rows with blank values in one particular column

An easy approach would be making all the blank cells NA and only keeping complete cases. You might also look for na.omit examples. It is a widely discussed topic.

df[df==""]<-NA
df<-df[complete.cases(df),]

Add Marker function with Google Maps API

You have added the add marker method call outside the function and that causes it to execute before the initialize method which will be called when google maps script loads and thus the marker is not added because map is not initialized Do as below.... Create separate method TestMarker and call it from initialize.

<script type="text/javascript">

    // Standard google maps function
    function initialize() {
        var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
        var myOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        TestMarker();
    }

    // Function for adding a marker to the page.
    function addMarker(location) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
    }

    // Testing the addMarker function
    function TestMarker() {
           CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
           addMarker(CentralPark);
    }
</script>

How to find if directory exists in Python

Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir() and exists() methods of a Path object can be used to answer the question:

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.exists()
Out[3]: True

In [4]: p.is_dir()
Out[4]: True

Paths (and strings) can be joined together with the / operator:

In [5]: q = p / 'bin' / 'vim'

In [6]: q
Out[6]: PosixPath('/usr/bin/vim') 

In [7]: q.exists()
Out[7]: True

In [8]: q.is_dir()
Out[8]: False

Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.

Compile a DLL in C/C++, then call it from another program

There is but one difference. You have to take care or name mangling win C++. But on windows you have to take care about 1) decrating the functions to be exported from the DLL 2) write a so called .def file which lists all the exported symbols.

In Windows while compiling a DLL have have to use

__declspec(dllexport)

but while using it you have to write __declspec(dllimport)

So the usual way of doing that is something like

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

The naming is a bit confusing, because it is often named EXPORT.. But that's what you'll find in most of the headers somwhere. So in your case you'd write (with the above #define)

int DLL_EXPORT add.... int DLL_EXPORT mult...

Remember that you have to add the Preprocessor directive BUILD_DLL during building the shared library.

Regards Friedrich

How can I run Tensorboard on a remote server?

Another option if you can't get it working for some reason is to simply mount a logdir directory on your filesystem with sshfs:

sshfs user@host:/home/user/project/summary_logs ~/summary_logs

and then run Tensorboard locally.

What is the purpose of using -pedantic in GCC/G++ compiler?

<-ansi is an obsolete switch that requests the compiler to compile according to the 30-year-old obsolete revision of C standard, ISO/IEC 9899:1990, which is essentially a rebranding of the ANSI standard X3.159-1989 "Programming Language C. Why obsolete? Because after C90 was published by ISO, ISO has been in charge of the C standardization, and any technical corrigenda to C90 have been standardized by ISO. Thus it is more apt to use the -std=c90.

Without this switch, the recent GCC C compilers will conform to the C language standardized in ISO/IEC 9899:2011, or the newest 2018 revision.

Unfortunately there are some lazy compiler vendors that believe it is acceptable to stick to an older obsolete standard revision, for which the standardization document is not even available from standard bodies.

Using the switch helps ensuring that the code should compile in these obsolete compilers.


The -pedantic is an interesting one. In absence of -pedantic, even when a specific standard is requested, GCC will still allow some extensions that are not acceptable in the C standard. Consider for example the program

struct test {
    int zero_size_array[0];
};

The C11 draft n1570 paragraph 6.7.6.2p1 says:

In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero.[...]

The C standard requires that the array length be greater than zero; and this paragraph is in the constraints; the standard says the following 5.1.1.3p1:

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined. Diagnostic messages need not be produced in other circumstances.9)

However, if you compile the program with gcc -c -std=c90 pedantic_test.c, no warning is produced.

-pedantic causes the compiler to actually comply to the C standard; so now it will produce a diagnostic message, as is required by the standard:

gcc -c -pedantic -std=c90 pedantic_test.c
pedantic_test.c:2:9: warning: ISO C forbids zero-size array ‘zero_size_array’ [-Wpedantic]
     int zero_size_array[0];
         ^~~~~~~~~~~~~~~

Thus for maximal portability, specifying the standard revision is not enough, you must also use -pedantic (or -pedantic-errors) to ensure that GCC actually does comply to the letter of the standard.


The last part of the question was about using -ansi with C++. ANSI never standardized the C++ language - only adopting it from ISO, so this makes about as much sense as saying "English as standardized by France". However GCC still seems to accept it for C++, as stupid as it sounds.

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

laravel throwing MethodNotAllowedHttpException

That is because you are posting data through a get method.

Instead of

Route::get('/validate', 'MemberController@validateCredentials');

Try this

Route::post('/validate', 'MemberController@validateCredentials');

Looping over elements in jQuery

This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.

EDIT JSFIDDLE

The below will work

$('form[name=formName]').find('input, textarea, select').each(function() {
    alert($(this).attr('name'));
});

Regarding Java switch statements - using return and omitting breaks in each case

Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.

That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.

While we are on the topic you must check this out. Its an interesting read.

Default instance name of SQL Server Express

in my case the right server name was the name of my computer. for example John-PC, or somth

Active Menu Highlight CSS

Let's say we have a menu like this:

<div class="menu">
  <a href="link1.html">Link 1</a>
  <a href="link2.html">Link 2</a>
  <a href="link3.html">Link 3</a>
  <a href="link4.html">Link 4</a>
</div>

Let our current url be https://demosite.com/link1.html

With the following function we can add the active class to which menu's href is in our url.

let currentURL = window.location.href;

document.querySelectorAll(".menu a").forEach(p => {
  if(currentURL.indexOf(p.getAttribute("href")) !== -1){
    p.classList.add("active");
  }
})

How to pause javascript code execution for 2 seconds

Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

Note: The above code is NOT recommended.

Command to get nth line of STDOUT

ls -l | head -2 | tail -1

C++ program converts fahrenheit to celsius

Best way would be

#include <iostream>                        
using namespace std;                       

int main() {                               
    float celsius;                         
    float fahrenheit;

    cout << "Enter Celsius temperature: "; 
    cin >> celsius;
    fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
    cout << "Fahrenheit = " << fahrenheit << endl;

    return 0;                             
}

:)

Installing lxml module in python

You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev:

apt-get install python-dev libxml2 libxml2-dev libxslt-dev

How to view unallocated free space on a hard disk through terminal

Just follow below.

  • find out the dev type, whether it is /dev/sda /dev/hda /dev/vda etc.

  • look for vi /etc/fstab and find out the mounted partisions and there UUIDs etc

  • say, your harddisk is labeled as /dev/sda and you know number of /dev/sda under df -hT

then you need to find out remaining /dev/sda* right.

so,

fdisk -l /dev/sda* will give the ALL /dev/sda* and you will find for example, /dev/sda4 or /dev/sda5

then find out UUIDs of mounted partisions and those are not listed in /etc/fstab are the ones you can format and mount.

just follow this up. a world to wise is sufficient.

PHP header redirect 301 - what are the implications?

Just a tip: using http_response_code is much easier to remember than writing the full header:

http_response_code(301);
header('Location: /option-a'); 
exit;

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Android Studio - No JVM Installation found

Just make sure that the installed version of both, Android Studio and JDK, are of either 32-bit or 64-bit. If JDK is of 32-bit and Android Studio of 64-bit or vice-verse, then it won't work though you set up JAVA_HOME.

Self-references in object literals / initializers

Throwing in an option since I didn't see this exact scenario covered. If you don't want c updated when a or b update, then an ES6 IIFE works well.

var foo = ((a,b) => ({
    a,
    b,
    c: a + b
}))(a,b);

For my needs, I have an object that relates to an array which will end up being used in a loop, so I only want to calculate some common setup once, so this is what I have:

let processingState = ((indexOfSelectedTier) => ({
    selectedTier,
    indexOfSelectedTier,
    hasUpperTierSelection: tiers.slice(0,indexOfSelectedTier)
                         .some(t => pendingSelectedFiltersState[t.name]),
}))(tiers.indexOf(selectedTier));

Since I need to set a property for indexOfSelectedTier and I need to use that value when setting the hasUpperTierSelection property, I calculate that value first and pass it in as a param to the IIFE

What is the way of declaring an array in JavaScript?

To declare it:

var myArr = ["apples", "oranges", "bananas"];

To use it:

document.write("In my shopping basket I have " + myArr[0] + ", " + myArr[1] + ", and " + myArr[2]);

How to tell if tensorflow is using gpu acceleration from inside python shell?

This is the line I am using to list devices available to tf.session directly from bash:

python -c "import os; os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'; import tensorflow as tf; sess = tf.Session(); [print(x) for x in sess.list_devices()]; print(tf.__version__);"

It will print available devices and tensorflow version, for example:

_DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 10588614393916958794)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 12320120782636586575)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 13378821206986992411)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:GPU:0, GPU, 32039954023, 12481654498215526877)
1.14.0

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:

<?php

$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

C++ unordered_map using a custom class type as the key

For enum type, I think this is a suitable way, and the difference between class is how to calculate hash value.

template <typename T>
struct EnumTypeHash {
  std::size_t operator()(const T& type) const {
    return static_cast<std::size_t>(type);
  }
};

enum MyEnum {};
class MyValue {};

std::unordered_map<MyEnum, MyValue, EnumTypeHash<MyEnum>> map_;

how to kill the tty in unix

You can run:

ps -ft pts/6 -t pts/9 -t pts/10

This would produce an output similar to:

UID        PID  PPID  C STIME TTY          TIME CMD
Vidya      772  2701  0 15:26 pts/6    00:00:00 bash
Vidya      773  2701  0 16:26 pts/9    00:00:00 bash
Vidya      774  2701  0 17:26 pts/10   00:00:00 bash

Grab the PID from the result.

Use the PIDs to kill the processes:

kill <PID1> <PID2> <PID3> ...

For the above example:

kill 772 773 774

If the process doesn't gracefully terminate, just as a last option you can forcefully kill by sending a SIGKILL

kill -9 <PID>

How to stop mysqld

for Binary installer use this:

to stop:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop

to start:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM start

to restart:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart

The maximum value for an int type in Go

https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1

The germane part:

Since integer types use two's complement arithmetic, you can infer the min/max constant values for int and uint. For example,

const MaxUint = ^uint(0) 
const MinUint = 0 
const MaxInt = int(MaxUint >> 1) 
const MinInt = -MaxInt - 1

As per @CarelZA's comment:

uint8  : 0 to 255 
uint16 : 0 to 65535 
uint32 : 0 to 4294967295 
uint64 : 0 to 18446744073709551615 
int8   : -128 to 127 
int16  : -32768 to 32767 
int32  : -2147483648 to 2147483647 
int64  : -9223372036854775808 to 9223372036854775807

Big-O summary for Java Collections Framework implementations?

The guy above gave comparison for HashMap / HashSet vs. TreeMap / TreeSet.

I will talk about ArrayList vs. LinkedList:

ArrayList:

  • O(1) get()
  • amortized O(1) add()
  • if you insert or delete an element in the middle using ListIterator.add() or Iterator.remove(), it will be O(n) to shift all the following elements

LinkedList:

  • O(n) get()
  • O(1) add()
  • if you insert or delete an element in the middle using ListIterator.add() or Iterator.remove(), it will be O(1)

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

How can I use a C++ library from node.js?

There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.

I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.

As a small example, say you have a library with the header myclass.h:

#include<iostream>

class MyClass {
        int myNumber;
public:
        MyClass(int number): myNumber(number){}
        void sayHello() {
                std::cout << "Hello, my number is:" 
                << myNumber <<std::endl;
        }
};

In order to use this class in node, you simply write the following SWIG interface file (mylib.i):

%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"

Create the binding file binding.gyp:

{
  "targets": [
    {
      "target_name": "mylib",
      "sources": [ "mylib_wrap.cxx" ]
    }
  ]
}

Run the following commands:

swig -c++ -javascript -node mylib.i
node-gyp build

Now, running node from the same folder, you can do:

> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5

Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass constructor nor the sayHello method anywhere, SWIG discovers these things, and automatically generates natural interfaces.

How can I format decimal property to currency?

Properties can return anything they want to, but it's going to need to return the correct type.

private decimal _amount;

public string FormattedAmount
{
    get { return string.Format("{0:C}", _amount); }
}

Question was asked... what if it was a nullable decimal.

private decimal? _amount;

public string FormattedAmount
{
    get
    {
         return _amount == null ? "null" : string.Format("{0:C}", _amount.Value);
    }
}  

Return a value of '1' a referenced cell is empty

Since required quite often it might as well be brief:

=1*(A1="")

This will not return 1 if the cell appears empty but contains say a space or a formula of the kind =IF(B1=3,"Yes","") where B1 does not contain 3.

=A1="" will return either TRUE or FALSE but those in an equation are treated as 1 and 0 respectively so multiplying TRUE by 1 returns 1.

Much the same can be achieved with the double unary --:

=--(A1="")  

where when A1 is empty one minus negates TRUE into -1 and the other negates that to 1 (just + in place of -- however does not change TRUE to 1).

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

I'm sure -webkit-appearance:none does the trick for Chrome and Safari.

EDIT : -moz-appearance: none should now work as well on Firefox.

How to install maven on redhat linux

Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.

This exception is because your JDK/Java version need to be updated/installed.

How to fix: Error device not found with ADB.exe

I solved:

Just turn off USB debugging and re-enable debugging it immediately

How can I properly handle 404 in ASP.NET MVC?

Requirements for 404

The following are my requirements for a 404 solution and below i show how i implement it:

  • I want to handle matched routes with bad actions
  • I want to handle matched routes with bad controllers
  • I want to handle un-matched routes (arbitrary urls that my app can't understand) - i don't want these bubbling up to the Global.asax or IIS because then i can't redirect back into my MVC app properly
  • I want a way to handle in the same manner as above, custom 404s - like when an ID is submitted for an object that does not exist (maybe deleted)
  • I want all my 404s to return an MVC view (not a static page) to which i can pump more data later if necessary (good 404 designs) and they must return the HTTP 404 status code

Solution

I think you should save Application_Error in the Global.asax for higher things, like unhandled exceptions and logging (like Shay Jacoby's answer shows) but not 404 handling. This is why my suggestion keeps the 404 stuff out of the Global.asax file.

Step 1: Have a common place for 404-error logic

This is a good idea for maintainability. Use an ErrorController so that future improvements to your well designed 404 page can adapt easily. Also, make sure your response has the 404 code!

public class ErrorController : MyController
{
    #region Http404

    public ActionResult Http404(string url)
    {
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        var model = new NotFoundViewModel();
        // If the url is relative ('NotFound' route) then replace with Requested path
        model.RequestedUrl = Request.Url.OriginalString.Contains(url) & Request.Url.OriginalString != url ?
            Request.Url.OriginalString : url;
        // Dont get the user stuck in a 'retry loop' by
        // allowing the Referrer to be the same as the Request
        model.ReferrerUrl = Request.UrlReferrer != null &&
            Request.UrlReferrer.OriginalString != model.RequestedUrl ?
            Request.UrlReferrer.OriginalString : null;

        // TODO: insert ILogger here

        return View("NotFound", model);
    }
    public class NotFoundViewModel
    {
        public string RequestedUrl { get; set; }
        public string ReferrerUrl { get; set; }
    }

    #endregion
}

Step 2: Use a base Controller class so you can easily invoke your custom 404 action and wire up HandleUnknownAction

404s in ASP.NET MVC need to be caught at a number of places. The first is HandleUnknownAction.

The InvokeHttp404 method creates a common place for re-routing to the ErrorController and our new Http404 action. Think DRY!

public abstract class MyController : Controller
{
    #region Http404 handling

    protected override void HandleUnknownAction(string actionName)
    {
        // If controller is ErrorController dont 'nest' exceptions
        if (this.GetType() != typeof(ErrorController))
            this.InvokeHttp404(HttpContext);
    }

    public ActionResult InvokeHttp404(HttpContextBase httpContext)
    {
        IController errorController = ObjectFactory.GetInstance<ErrorController>();
        var errorRoute = new RouteData();
        errorRoute.Values.Add("controller", "Error");
        errorRoute.Values.Add("action", "Http404");
        errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
        errorController.Execute(new RequestContext(
             httpContext, errorRoute));

        return new EmptyResult();
    }

    #endregion
}

Step 3: Use Dependency Injection in your Controller Factory and wire up 404 HttpExceptions

Like so (it doesn't have to be StructureMap):

MVC1.0 example:

public class StructureMapControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(Type controllerType)
    {
        try
        {
            if (controllerType == null)
                return base.GetControllerInstance(controllerType);
        }
        catch (HttpException ex)
        {
            if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                IController errorController = ObjectFactory.GetInstance<ErrorController>();
                ((ErrorController)errorController).InvokeHttp404(RequestContext.HttpContext);

                return errorController;
            }
            else
                throw ex;
        }

        return ObjectFactory.GetInstance(controllerType) as Controller;
    }
}

MVC2.0 example:

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        try
        {
            if (controllerType == null)
                return base.GetControllerInstance(requestContext, controllerType);
        }
        catch (HttpException ex)
        {
            if (ex.GetHttpCode() == 404)
            {
                IController errorController = ObjectFactory.GetInstance<ErrorController>();
                ((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);

                return errorController;
            }
            else
                throw ex;
        }

        return ObjectFactory.GetInstance(controllerType) as Controller;
    }

I think its better to catch errors closer to where they originate. This is why i prefer the above to the Application_Error handler.

This is the second place to catch 404s.

Step 4: Add a NotFound route to Global.asax for urls that fail to be parsed into your app

This route should point to our Http404 action. Notice the url param will be a relative url because the routing engine is stripping the domain part here? That is why we have all that conditional url logic in Step 1.

        routes.MapRoute("NotFound", "{*url}", 
            new { controller = "Error", action = "Http404" });

This is the third and final place to catch 404s in an MVC app that you don't invoke yourself. If you don't catch unmatched routes here then MVC will pass the problem up to ASP.NET (Global.asax) and you don't really want that in this situation.

Step 5: Finally, invoke 404s when your app can't find something

Like when a bad ID is submitted to my Loans controller (derives from MyController):

    //
    // GET: /Detail/ID

    public ActionResult Detail(int ID)
    {
        Loan loan = this._svc.GetLoans().WithID(ID);
        if (loan == null)
            return this.InvokeHttp404(HttpContext);
        else
            return View(loan);
    }

It would be nice if all this could be hooked up in fewer places with less code but i think this solution is more maintainable, more testable and fairly pragmatic.

Thanks for the feedback so far. I'd love to get more.

NOTE: This has been edited significantly from my original answer but the purpose/requirements are the same - this is why i have not added a new answer

Create a BufferedImage from file and make it TYPE_INT_ARGB

try {
    File img = new File("somefile.png");
    BufferedImage image = ImageIO.read(img ); 
    System.out.println(image);
} catch (IOException e) { 
    e.printStackTrace(); 
}

Example output for my image file:

BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = java.awt.color.ICC_ColorSpace@50a649 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2

You can run System.out.println(object); on just about any object and get some information about it.

Difference between "@id/" and "@+id/" in Android

In Short

android:id="@+id/my_button"

+id Plus sign tells android to add or create a new id in Resources.

while

android:layout_below="@id/my_button"

it just help to refer the already generated id..

How to implement "confirmation" dialog in Jquery UI dialog?

(As of 03/22/2016, the download on the page linked to doesn't work. I'm leaving the link here in case the developer fixes it at some point because it's a great little plugin. The original post follows. An alternative, and a link that actually works: jquery.confirm.)

It may be too simple for your needs, but you could try this jQuery confirm plugin. It's really simple to use and does the job in many cases.

What is the proper way to test if a parameter is empty in a batch file?

Script 1:

Input ("Remove Quotes.cmd" "This is a Test")

@ECHO OFF

REM Set "string" variable to "first" command line parameter
SET STRING=%1

REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%

REM IF %1 [or String] is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel


REM   OR   IF "." equals "." GOTO MyLabel
IF "%STRING%." == "." GOTO MyLabel

REM GOTO End of File
GOTO :EOF

:MyLabel
ECHO Welcome!

PAUSE

Output (There is none, %1 was NOT blank, empty, or NULL):


Run ("Remove Quotes.cmd") without any parameters with the above script 1

Output (%1 is blank, empty, or NULL):

Welcome!

Press any key to continue . . .

Note: If you set a variable inside an IF ( ) ELSE ( ) statement, it will not be available to DEFINED until after it exits the "IF" statement (unless "Delayed Variable Expansion" is enabled; once enabled use an exclamation mark "!" in place of the percent "%" symbol}.

For example:

Script 2:

Input ("Remove Quotes.cmd" "This is a Test")

@ECHO OFF

SETLOCAL EnableDelayedExpansion

SET STRING=%0
IF 1==1 (
  SET STRING=%1
  ECHO String in IF Statement='%STRING%'
  ECHO String in IF Statement [delayed expansion]='!STRING!'
) 

ECHO String out of IF Statement='%STRING%'

REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%

ECHO String without Quotes=%STRING% 

REM IF %1 is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel

REM GOTO End of File
GOTO :EOF

:MyLabel
ECHO Welcome!

ENDLOCAL
PAUSE

Output:

C:\Users\Test>"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd" "This is a Test"  
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'  
String in IF Statement [delayed expansion]='"This is a Test"'  
String out of IF Statement='"This is a Test"'  
String without Quotes=This is a Test  

C:\Users\Test>  

Note: It will also remove quotes from inside the string.

For Example (using script 1 or 2): C:\Users\Test\Documents\Batch Files>"Remove Quotes.cmd" "This is "a" Test"

Output (Script 2):

String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'  
String in IF Statement [delayed expansion]='"This is "a" Test"'  
String out of IF Statement='"This is "a" Test"'  
String without Quotes=This is a Test  

Execute ("Remove Quotes.cmd") without any parameters in Script 2:

Output:

Welcome!

Press any key to continue . . .

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

On a fresh Debian image, cloning https://github.com/python/cpython and running:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev

Now execute the configure file cloned above:

./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall

Got 3.7 installed and working for me.

SLIGHT UPDATE

Looks like I said I would update this answer with some more explanation and two years later I don't have much to add.

  • this SO post explains why certain libraries like python-dev might be necessary.
  • this SO post explains why one might use the altinstall as opposed to install argument in the make command.

Aside from that I guess the choice would be to either read through the cpython codebase looking for #include directives that need to be met, but what I usually do is keep trying to install the package and just keep reading through the output installing the required packages until it succeeds.

Reminds me of the story of the Engineer, the Manager and the Programmer whose car rolls down a hill.

Maven Modules + Building a Single Specific Module

If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.

You can define a multi-module project with an aggregator pom to build a set of projects.

It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.

Traverse a list in reverse order in Python

How about without recreating a new list, you can do by indexing:

>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
...     print foo[-(i+1)]
...
4d
3c
2b
1a
>>>

OR

>>> length = len(foo)
>>> for i in range(length):
...     print foo[length-i-1]
...
4d
3c
2b
1a
>>>

Populate dropdown select with array using jQuery

Try for loops:

var numbers = [1, 2, 3, 4, 5];

for (var i=0;i<numbers.length;i++){
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}

Much better approach:

var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
   option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);

Check if list contains element that contains a string and get that element

You could use Linq's FirstOrDefault extension method:

string element = myList.FirstOrDefault(s => s.Contains(myString));

This will return the fist element that contains the substring myString, or null if no such element is found.

If all you need is the index, use the List<T> class's FindIndex method:

int index = myList.FindIndex(s => s.Contains(myString));

This will return the the index of fist element that contains the substring myString, or -1 if no such element is found.

Double array initialization in Java

This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:

int[] x = {1,2,3,4};
String y = {"a","b","c"};

If you're not on the RHS of a variable declaration, use an array constructor instead:

int[] x;
x = new int[]{1,2,3,4};
String y;
y = new String[]{"a","b","c"};

These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.

In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:

double[][] m = new double[4][4];

for(int i=0; i<4; i++) {
    for(int j=0; j<4; j++) {
        m[i][j] = i*j;
    }
}

make html text input field grow as I type?

For those strictly looking for a solution that works for input or textarea, this is the simplest solution I've came across. Only a few lines of CSS and one line of JS.

The JavaScript sets a data-* attribute on the element equal to the value of the input. The input is set within a CSS grid, where that grid is a pseudo-element that uses that data-* attribute as its content. That content is what stretches the grid to the appropriate size based on the input value.

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I created a script to ignore differences in line endings:

It will display the files which are not added to the commit list and were modified (after ignoring differences in line endings). You can add the argument "add" to add those files to your commit.

#!/usr/bin/perl

# Usage: ./gitdiff.pl [add]
#    add : add modified files to git

use warnings;
use strict;

my ($auto_add) = @ARGV;
if(!defined $auto_add) {
    $auto_add = "";
}

my @mods = `git status --porcelain 2>/dev/null | grep '^ M ' | cut -c4-`;
chomp(@mods);
for my $mod (@mods) {
    my $diff = `git diff -b $mod 2>/dev/null`;
    if($diff) {
        print $mod."\n";
        if($auto_add eq "add") {
            `git add $mod 2>/dev/null`;
        }
    }
}

Source code: https://github.com/lepe/scripts/blob/master/gitdiff.pl

Updates:

  • fix by evandro777 : When the file has space in filename or directory

jQuery detect if textarea is empty

if (!$("#myTextArea").val()) {
    // textarea is empty
}

You can also use $.trim to make sure the element doesn't contain only white-space:

if (!$.trim($("#myTextArea").val())) {
    // textarea is empty or contains only white-space
}

How to sort multidimensional array by column?

Yes. The sorted built-in accepts a key argument:

sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]

note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

or alternatively,

from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]

Read more on the python wiki.

How to insert new cell into UITableView in Swift

Swift 5.0, 4.0, 3.0 Updated Solution

Insert at Bottom

self.yourArray.append(msg)

self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

Listen to changes within a DIV and act accordingly

You can opt to create your own custom events so you'll still have a clear separation of logic.

Bind to a custom event:

$('#laneconfigdisplay').bind('contentchanged', function() {
  // do something after the div content has changed
  alert('woo');
});

In your function that updates the div:

// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above

Detecting which UIButton was pressed in a UITableView

In Apple's Accessory sample the following method is used:

[button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

Then in touch handler touch coordinate retrieved and index path is calculated from that coordinate:

- (void)checkButtonTapped:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     ...
    }
}

Add a list item through javascript

If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

Give the list the ID:

<ol id="demo"></ol>

and get a reference to it:

var list = document.getElementById('demo');

In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);

DEMO

Check if a PHP cookie exists and if not set its value

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

How to attach a file using mail command on Linux?

I use mailutils and the confusing part is that in order to attach a file you need to use the capital A parameter. below is an example.

echo 'here you put the message body' | mail -A syslogs.tar.gz [email protected]

If you want to know if your mail command is from mailutils just run "mail -V".

root@your-server:~$ mail -V
mail (GNU Mailutils) 2.99.98
Copyright (C) 2010 Free Software Foundation, inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Factorial in numpy and scipy

You can save some homemade factorial functions on a separate module, utils.py, and then import them and compare the performance with the predefinite one, in scipy, numpy and math using timeit. In this case I used as external method the last proposed by Stefan Gruenwald:

import numpy as np


def factorial(n):
    return reduce((lambda x,y: x*y),range(1,n+1))

Main code (I used a framework proposed by JoshAdel in another post, look for how-can-i-get-an-array-of-alternating-values-in-python):

from timeit import Timer
from utils import factorial
import scipy

    n = 100

    # test the time for the factorial function obtained in different ways:

    if __name__ == '__main__':

        setupstr="""
    import scipy, numpy, math
    from utils import factorial
    n = 100
    """

        method1="""
    factorial(n)
    """

        method2="""
    scipy.math.factorial(n)  # same algo as numpy.math.factorial, math.factorial
    """

        nl = 1000
        t1 = Timer(method1, setupstr).timeit(nl)
        t2 = Timer(method2, setupstr).timeit(nl)

        print 'method1', t1
        print 'method2', t2

        print factorial(n)
        print scipy.math.factorial(n)

Which provides:

method1 0.0195569992065
method2 0.00638914108276

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000


Process finished with exit code 0

Cannot install signed apk to device manually, got error "App not installed"

Android Studio 4.1.1 If you want to create the debug apk, and just before creating the apk you tried running on your phone/simulator (doing create signed apk right away will cause the APP NOT INSTALLED),YOU SHOULD CLEAN THE PROJECT before creating signed bundle/apk

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.

On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.

I did not want to enable db ownership when for their reports since they only needed to have select permissions.

How to implement a Keyword Search in MySQL?

You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches

This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.

Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching

In the FULLTEXT Index you can have more than one column listed, the result would be an SQL Statement with an index named search:

SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance  FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;

I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.

Depending in your criterias you can use either options.

Get the selected option id with jQuery

$('#my_select option:selected').attr('id');

launch sms application with an intent

If you want to launch SMS Composing activity from some of your other activity and you also have to pass a phone number and SMS text, then use this code:

Uri sms_uri = Uri.parse("smsto:+92xxxxxxxx"); 
Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri); 
sms_intent.putExtra("sms_body", "Good Morning ! how r U ?"); 
startActivity(sms_intent); 

Note: here the sms_body and smsto: is keys for recognizing the text and phone no at SMS compose activity, so be careful here.

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

Prepend text to beginning of string

EcmaScript 2017 added special functions to string prototype for that. padStart and padEnd are two new methods available in JavaScript string prototype object. As their name implies, they allow for formatting a string by adding padding characters at the start or the end. (Not supported by IE11 and lower)

var mystr = "Doe";
mystr = mystr.padStart('John ');

How to scale a UIImageView proportionally?

Fixed easily, once I found the documentation!

 imageView.contentMode = .scaleAspectFit

Must issue a STARTTLS command first

    String username = "[email protected]";
    String password = "some-password";
    String recipient = "[email protected]");

    Properties props = new Properties();

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.from", "[email protected]");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.port", "587");
    props.setProperty("mail.debug", "true");

    Session session = Session.getInstance(props, null);
    MimeMessage msg = new MimeMessage(session);

    msg.setRecipients(Message.RecipientType.TO, recipient);
    msg.setSubject("JavaMail hello world example");
    msg.setSentDate(new Date());
    msg.setText("Hello, world!\n");

    Transport transport = session.getTransport("smtp");

    transport.connect(username, password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();

Should I write script in the body or the head of the html?

I always put my scripts in the header. My reasons:

  1. I like to separate code and (static) text
  2. I usually load my script from external sources
  3. The same script is used from several pages, so it feels like an include file (which also goes in the header)

Remove the last character in a string in T-SQL?

Try this

DECLARE @String VARCHAR(100)
SET @String = 'TEST STRING'
SELECT LEFT(@String, LEN(@String) - 1) AS MyTrimmedColumn

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

What is the most useful script you've written for everyday life?

I suppose I should include my own answer to this, for completion's sake.

I wrote a simple script that takes in the expenses of two people living together, and calculates which person owes the other money at the end of the month so that each person spent equally. I plan to extend it to store the categories of each expense and store them in a database. Sure, I could just use existing software...but where's the fun in that?

Not very complex, sure, but as far as non-work related scripts that I use a lot at home, this one is the current leader.

Delete all objects in a list

tl;dr;

mylist.clear()  # Added in Python 3.3
del mylist[:]

are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn't work.


cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. a refers to the same object that c[0] references. When you loop over c (for i in c:), at some point i also refers to that same object. the del keyword removes a single reference, so:

for i in c:
   del i

creates a reference to an object in c and then deletes that reference -- but the object still has other references (one stored in c for example) so it will persist.

In the same way:

def kill(self):
    del self

only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:

mylist = list(range(10000))
mylist[:] = []
print(mylist)

Apparently you can also delete the slice to remove objects in place:

del mylist[:]  #This will implicitly call the `__delslice__` or `__delitem__` method.

This will remove all the references from mylist and also remove the references from anything that refers to mylist. Compared that to simply deleting the list -- e.g.

mylist = list(range(10000))
b = mylist
del mylist
#here we didn't get all the references to the objects we created ...
print(b) #[0, 1, 2, 3, 4, ...]

Finally, more recent python revisions have added a clear method which does the same thing that del mylist[:] does.

mylist = [1, 2, 3]
mylist.clear()
print(mylist)

How to store(bitmap image) and retrieve image from sqlite database in android?

Setting Up the database

public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database_name";

    // Table Names
    private static final String DB_TABLE = "table_image";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }
}

Insert in the Database:

public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieving data:

 byte[] image = cursor.getBlob(1);

Note:

  1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
  2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

Below is an Utility class which I hope could help you:

public class DbBitmapUtility {

    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}


Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I had the same issue using an older version of Fancybox. Upgrading to v3 will solve your problem OR you can just add:

html, body {
    -webkit-overflow-scrolling : touch !important;
    overflow: auto !important;
    height: 100% !important;
}

How to print the number of characters in each line of a text file

I've tried the other answers listed above, but they are very far from decent solutions when dealing with large files -- especially once a single line's size occupies more than ~1/4 of available RAM.

Both bash and awk slurp the entire line, even though for this problem it's not needed. Bash will error out once a line is too long, even if you have enough memory.

I've implemented an extremely simple, fairly unoptimized python script that when tested with large files (~4 GB per line) doesn't slurp, and is by far a better solution than those given.

If this is time critical code for production, you can rewrite the ideas in C or perform better optimizations on the read call (instead of only reading a single byte at a time), after testing that this is indeed a bottleneck.

Code assumes newline is a linefeed character, which is a good assumption for Unix, but YMMV on Mac OS/Windows. Be sure the file ends with a linefeed to ensure the last line character count isn't overlooked.

from sys import stdin, exit

counter = 0
while True:
    byte = stdin.buffer.read(1)
    counter += 1
    if not byte:
        exit()
    if byte == b'\x0a':
        print(counter-1)
        counter = 0

node.js http 'get' request with query string parameters

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network.

Delete duplicate records from a SQL table without a primary key

there are two columns in the a table ID and name where names are repeating with different IDs so for that you may use this query: . .

DELETE FROM dbo.tbl1
WHERE id NOT IN (
     Select MIN(Id) AS namecount FROM tbl1
     GROUP BY Name
)

What is the difference between call and apply?

Even though call and apply achive the same thing, I think there is atleast one place where you cannot use call but can only use apply. That is when you want to support inheritance and want to call the constructor.

Here is a function allows you to create classes which also supports creating classes by extending other classes.

function makeClass( properties ) {
    var ctor = properties['constructor'] || function(){}
    var Super = properties['extends'];
    var Class = function () {
                 // Here 'call' cannot work, only 'apply' can!!!
                 if(Super)
                    Super.apply(this,arguments);  
                 ctor.apply(this,arguments);
                }
     if(Super){
        Class.prototype = Object.create( Super.prototype );
        Class.prototype.constructor = Class;
     }
     Object.keys(properties).forEach( function(prop) {
           if(prop!=='constructor' && prop!=='extends')
            Class.prototype[prop] = properties[prop];
     });
   return Class; 
}

//Usage
var Car = makeClass({
             constructor: function(name){
                         this.name=name;
                        },
             yourName: function() {
                     return this.name;
                   }
          });
//We have a Car class now
 var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat

var SuperCar = makeClass({
               constructor: function(ignore,power){
                     this.power=power;
                  },
               extends:Car,
               yourPower: function() {
                    return this.power;
                  }
              });
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6

Changing git commit message after push (given that no one pulled from remote)

If you want to modify an older commit, not the last one, you will need to use rebase command as explained in here,Github help page , on the Amending the message of older or multiple commit messages section

Stretch background image css?

This works flawlessly @ 2019

.marketing-panel  {
    background-image: url("../images/background.jpg");
    background-repeat: no-repeat;
    background-size: auto;
    background-position: center;
}

Linux: command to open URL in default browser

on ubuntu you can try gnome-open.

$ gnome-open http://www.google.com

How to check if running in Cygwin, Mac or Linux?

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

All the info you'll ever need. Google is your friend.

Use uname -s to query the system name.

  • Mac: Darwin
  • Cygwin: CYGWIN_...
  • Linux: various, LINUX for most

Display a loading bar before the entire page is loaded

HTML

<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>

<div class="content">
I would like to display a loading bar before the entire page is loaded. 
</div>

JAVASCRIPT

$(function() {
    $(".preload").fadeOut(2000, function() {
        $(".content").fadeIn(1000);        
    });
});?

CSS

.content {display:none;}
.preload { 
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
}
?

DEMO

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

How to get jQuery to wait until an effect is finished?

With jQuery 1.6 version you can use the .promise() method.

$(selector).fadeOut('slow');
$(selector).promise().done(function(){
    // will be called when all the animations on the queue finish
});

Java/ JUnit - AssertTrue vs AssertFalse

assertTrue will fail if the checked value is false, and assertFalse will do the opposite: fail if the checked value is true.

Another thing, your last assertEquals will very likely fail, as it will compare the "Book was already checked out" string with the output of m1.checkOut(b1,p2). It needs a third parameter (the second value to check for equality).

How to compare two lists in python?

a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']

# if you care about order
a == b # True
a == c # False

# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True

By casting a, b and c as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.

BEGIN - END block atomic transactions in PL/SQL

BEGIN-END blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN-END blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.

If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.

However, you cannot declare this pragma for nested blocks. You can only declare this for:

  • Top-level (not nested) anonymous PL/SQL blocks
  • List item
  • Local, standalone, and packaged functions and procedures
  • Methods of a SQL object type
  • Database triggers

Reference: Oracle

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

How to configure Eclipse build path to use Maven dependencies?

Make sure your POM follows the naming convention, and is named in lowercase lettering as pom.xml and NOT POM.xml.

In my case all was right, but Eclipse still complained when trying to Right-click and Update project configuration - told me that the POM could not be read. Changed the name to lowercase - pom.xml from POM.xml - and it worked.

Remove the newline character in a list read from a file

You can use the strip() function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:

for i in range(len(lists)):
    grades.append(lists[i].strip('\n'))

It looks like you can just simplify the whole block though, since if your file stores one ID per line grades is just lists with newlines stripped:

Before

lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

After

grades = [x.strip() for x in files.readlines()]

(the above is a list comprehension)


Finally, you can loop over a list directly, instead of using an index:

Before

for i in range(len(grades)):
    # do something with grades[i]

After

for thisGrade in grades:
    # do something with thisGrade

how to create Socket connection in Android?

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

C library function to perform sort

Use qsort() in <stdlib.h>.

@paxdiablo The qsort() function conforms to ISO/IEC 9899:1990 (``ISO C90'').

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml, I just faced the same problem and resolved it by adding this one here:

<dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.9</version>
</dependency>

Animate element transform rotate

As far as I know, basic animates can't animate non-numeric CSS properties.

I believe you could get this done using a step function and the appropriate css3 transform for the users browser. CSS3 transform is a bit tricky to cover all your browsers in (IE6 you need to use the Matrix filter, for instance).

EDIT: here's an example that works in webkit browsers (Chrome, Safari): http://jsfiddle.net/ryleyb/ERRmd/

If you wanted to support IE9 only, you could use transform instead of -webkit-transform, or -moz-transform would support FireFox.

The trick used is to animate a CSS property we don't care about (text-indent) and then use its value in a step function to do the rotation:

$('#foo').animate(
..
step: function(now,fx) {
  $(this).css('-webkit-transform','rotate('+now+'deg)'); 
}
...

How is Docker different from a virtual machine?

I have used Docker in production environments and staging very much. When you get used to it you will find it very powerful for building a multi container and isolated environments.

Docker has been developed based on LXC (Linux Container) and works perfectly in many Linux distributions, especially Ubuntu.

Docker containers are isolated environments. You can see it when you issue the top command in a Docker container that has been created from a Docker image.

Besides that, they are very light-weight and flexible thanks to the dockerFile configuration.

For example, you can create a Docker image and configure a DockerFile and tell that for example when it is running then wget 'this', apt-get 'that', run 'some shell script', setting environment variables and so on.

In micro-services projects and architecture Docker is a very viable asset. You can achieve scalability, resiliency and elasticity with Docker, Docker swarm, Kubernetes and Docker Compose.

Another important issue regarding Docker is Docker Hub and its community. For example, I implemented an ecosystem for monitoring kafka using Prometheus, Grafana, Prometheus-JMX-Exporter, and Docker.

For doing that, I downloaded configured Docker containers for zookeeper, kafka, Prometheus, Grafana and jmx-collector then mounted my own configuration for some of them using YAML files, or for others, I changed some files and configuration in the Docker container and I build a whole system for monitoring kafka using multi-container Dockers on a single machine with isolation and scalability and resiliency that this architecture can be easily moved into multiple servers.

Besides the Docker Hub site there is another site called quay.io that you can use to have your own Docker images dashboard there and pull/push to/from it. You can even import Docker images from Docker Hub to quay then running them from quay on your own machine.

Note: Learning Docker in the first place seems complex and hard, but when you get used to it then you can not work without it.

I remember the first days of working with Docker when I issued the wrong commands or removing my containers and all of data and configurations mistakenly.

How to map an array of objects in React

@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this

[{
    name: 'Sam',
    email: '[email protected]'
 },
 {
    name: 'Ash',
    email: '[email protected]'
 }
].map( ( {name, email} ) => {
    return <p key={email}>{name} - {email}</p>
})

Cheers!

Renaming a branch in GitHub

Another way is to rename the following files:

  1. Navigate your project directory.
  2. Rename .git/refs/head/[branch-name] to .git/refs/head/new-branch-name.
  3. Rename .git/refs/remotes/[all-remote-names]/[branch-name] to .git/refs/remotes/[all-remote-names]/new-branch-name.

Rename head and remotes both on your local PC and on origins(s)/remote server(s).

Branch is now renamed (local and remote!)


Attention

If your current branch-name contains slashes (/) Git will create the directories like so:

current branch-name: "awe/some/branch"

  • .git/refs/head/awe/some/branch
  • .git/refs/remotes/[all-remote-names]/awe/some/branch

wish branch-name: "new-branch-name"

  1. Navigate your project directory.
  2. Copy the branch file from .git/refs/*/awe/some/.
  3. Put it in .git/refs/head/.
  4. Copy the branch file from all of .git/refs/remotes/*/awe/some/.
  5. Put them in .git/refs/remotes/*/.
  6. Rename all copied branch files to new-branch-name.
  7. Check if the directory and file structure now looks like this:
  • .git/refs/head/new-branch-name
  • .git/refs/remotes/[all-remote-names]/new-branch-name
  1. Do the same on all your remote origins/servers (if they exist)
  • Info: on remote-servers there are usually no refs/remotes/* directories because you're already on remote-server ;) (Well, maybe in advanced Git configurations it might be possible, but I have never seen that)

Branch is now renamed from awe/some/branch to new-branch-name (local and remote!)

Directories in branch-name got removed.


Information: This way might not be the best, but it still works for people who might have problems with the other ways

What is the best way to compare floats for almost-equality in Python?

In terms of absolute error, you can just check

if abs(a - b) <= error:
    print("Almost equal")

Some information of why float act weird in Python https://youtu.be/v4HhvoNLILk?t=1129

You can also use math.isclose for relative errors

Difference between float and decimal data type

A "float" in most environments is a binary floating-point type. It can accurately store base-2 values (to a certain point), but cannot accurately store many base-10 (decimal) values. Floats are most appropriate for scientific calculations. They're not appropriate for most business-oriented math, and inappropriate use of floats will bite you. Many decimal values can't be exactly represented in base-2. 0.1 can't, for instance, and so you see strange results like 1.0 - 0.1 = 0.8999999.

Decimals store base-10 numbers. Decimal is an good type for most business math (but any built-in "money" type is more appropriate for financial calculations), where the range of values exceeds that provided by integer types, and fractional values are needed. Decimals, as the name implies, are designed for base-10 numbers - they can accurately store decimal values (again, to a certain point).

MySQL error - #1062 - Duplicate entry ' ' for key 2

Check out your table index. If that field got index (e.g. B+ tree index.) At that time update or insert query throws these kinds of error.

Remove indexing and then try to fire same query.

There can be only one auto column

The full error message sounds:

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

So add primary key to the auto_increment field:

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

How to Merge Two Eloquent Collections?

Creating a new base collection for each eloquent collection the merge works for me.

$foo = collect(Foo::all());
$bar = collect(Bar::all());
$merged = $foo->merge($bar);

In this case don't have conflits by its primary keys.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

If you are getting errors even after downloading the newest SDK and Android Studio, here is what I did:

  1. Download the most recent SDK
  2. Open file-Project structure (Ctrl + Alt + Shift + S)
  3. In modules, select app
  4. In the properties tab: Change compile SDK version to API 23 Android 6.0 marshmallow (latest)

I hope it helps someone so that he won't suffer like I did for these couple of days.

Converting PKCS#12 certificate into PEM using OpenSSL

I had a PFX file and needed to create KEY file for NGINX, so I did this:

openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes

Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----. After that NGINX accepted the KEY file.

How to add a vertical Separator?

In the past I've used the style found here

<Style x:Key="VerticalSeparatorStyle" 
       TargetType="{x:Type Separator}"
       BasedOn="{StaticResource {x:Type Separator}}">
    <Setter Property="Margin" Value="6,0,6,0"/>
    <Setter Property="LayoutTransform">
        <Setter.Value>
            <TransformGroup>
                <TransformGroup.Children>
                    <TransformCollection>
                        <RotateTransform Angle="90"/>
                    </TransformCollection>
                </TransformGroup.Children>
            </TransformGroup>
        </Setter.Value>
    </Setter>
</Style>

<Separator Style="{DynamicResource VerticalSeparatorStyle}" />

You need to set the transformation in LayoutTransform instead of RenderTransform so the transformation occurs during the Layout pass, not during the Render pass. The Layout pass occurs when WPF is trying to layout controls and figure out how much space each control takes up, while the Render pass occurs after the layout pass when WPF is trying to render controls.

You can read more about the difference between LayoutTransform and RenderTransform here or here

Run as java application option disabled in eclipse

I had this same problem. For me, the reason turned out to be that I had a mismatch in the name of the class and the name of the file. I declared class "GenSig" in a file called "SignatureTester.java".

I changed the name of the class to "SignatureTester", and the "Run as Java Application" option showed up immediately.

MySQl Error #1064

Sometimes when your table has a similar name to the database name you should use back tick. so instead of:

INSERT INTO books.book(field1, field2) VALUES ('value1', 'value2');

You should have this:

INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');

how to setup ssh keys for jenkins to publish via ssh

You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.

Generating the SSH Key Pair

On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:

On the Target Server

On the target server, you will need to place the content of the public key (id_rsa.pub per the above article) into the .ssh/authorized_keys file under the home directory of the user which Jenkins will be using for deployment.

In Jenkins

Using "Publish over SSH" Plugin

Ref: https://plugins.jenkins.io/publish-over-ssh/

Visit: Jenkins > Manage Jenkins > Configure System > Publish over SSH

  • If the private key is encrypted, then you will need to enter the passphrase for the key into the "Passphrase" field, otherwise leave it alone.
  • Leave the "Path to key" field empty as this will be ignored anyway when you use a pasted key (next step)
  • Copy and paste the contents of the private key (id_rsa per the above article) into the "Key" field
  • Under "SSH Servers", "Add" a new server configuration for your target server.

Using Stored Global Credentials

Visit: Jenkins > Credentials > System > Global credentials (unrestricted) > Add Credentials

  • Kind: "SSH Username with private key"
  • Scope: "Global"
  • ID: [CREAT A UNIQUE ID FOR THIS KEY]
  • Description: [optionally, enter a decription]
  • Username: [USERNAME JENKINS WILL USE TO CONNECT TO REMOTE SERVER]
  • Private Key: [select "Enter directly"]
  • Key: [paste the contents of the private key (id_rsa per the above article)]
  • Passphrase: [enter the passphrase for the key, or leave it blank if the key is not encrypted]

Why is JsonRequestBehavior needed?

Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):

using System.Web.Mvc;
public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        var jsonResult = context.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var jsonResult = filterContext.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        base.OnResultExecuting(filterContext);
    }
}

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

How to search a string in multiple files and return the names of files in Powershell?

I modified one of the answers above to give me a bit more information. This spared me a second query later on. It was something like this:

Get-ChildItem `
        -Path "C:\data\path" -Filter "Example*.dat" -recurse | `
    Select-String -pattern "dummy" | `
    Select-Object -Property Path,LineNumber,Line | `
    Export-CSV "C:\ResultFile.csv"

I can specify the path and file wildcards with this structures, and it saves the filename, line number and relevant line to an output file.

Pick any kind of file via an Intent in Android

If you want to know this, it exists an open source library called aFileDialog that it is an small and easy to use which provides a file picker.

The difference with another file chooser's libraries for Android is that aFileDialog gives you the option to open the file chooser as a Dialog and as an Activity.

It also lets you to select folders, create files, filter files using regular expressions and show confirmation dialogs.

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

How to get all privileges back to the root user in MySQL?

Log in as root, then run the following MySQL commands:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

ReactJS: Warning: setState(...): Cannot update during an existing state transition

That usually happens when you call

onClick={this.handleButton()} - notice the () instead of:

onClick={this.handleButton} - notice here we are not calling the function when we initialize it

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

How to link html pages in same or different folders?

Use

../

For example if your file, lets say image is in folder1 in folder2 you locate it this way

../folder1/folder2/image

How to select Python version in PyCharm?

Go to:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

There you can see which external libraries you have installed for python2 and which for python3.

Select the required python version according to your requirements.

Image

ASP.NET Core Web API exception handling

First, configure ASP.NET Core 2 Startup to re-execute to an error page for any errors from the web server and any unhandled exceptions.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment()) {
        // Debug config here...
    } else {
        app.UseStatusCodePagesWithReExecute("/Error");
        app.UseExceptionHandler("/Error");
    }
    // More config...
}

Next, define an exception type that will let you throw errors with HTTP status codes.

public class HttpException : Exception
{
    public HttpException(HttpStatusCode statusCode) { StatusCode = statusCode; }
    public HttpStatusCode StatusCode { get; private set; }
}

Finally, in your controller for the error page, customize the response based on the reason for the error and whether the response will be seen directly by an end user. This code assumes all API URLs start with /api/.

[AllowAnonymous]
public IActionResult Error()
{
    // Gets the status code from the exception or web server.
    var statusCode = HttpContext.Features.Get<IExceptionHandlerFeature>()?.Error is HttpException httpEx ?
        httpEx.StatusCode : (HttpStatusCode)Response.StatusCode;

    // For API errors, responds with just the status code (no page).
    if (HttpContext.Features.Get<IHttpRequestFeature>().RawTarget.StartsWith("/api/", StringComparison.Ordinal))
        return StatusCode((int)statusCode);

    // Creates a view model for a user-friendly error page.
    string text = null;
    switch (statusCode) {
        case HttpStatusCode.NotFound: text = "Page not found."; break;
        // Add more as desired.
    }
    return View("Error", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorText = text });
}

ASP.NET Core will log the error detail for you to debug with, so a status code may be all you want to provide to a (potentially untrusted) requester. If you want to show more info, you can enhance HttpException to provide it. For API errors, you can put JSON-encoded error info in the message body by replacing return StatusCode... with return Json....

db.collection is not a function when using MongoClient v3.0

For people on version 3.0 of the MongoDB native NodeJS driver:

(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)

In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:

MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
  // Database returned
});

According to the changelog for 3.0 you now get a client object containing the database object instead:

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});

The close() method has also been moved to the client. The code in the question can therefore be translated to:

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
}); 

Getting the last argument passed to a shell script

There is a much more concise way to do this. Arguments to a bash script can be brought into an array, which makes dealing with the elements much simpler. The script below will always print the last argument passed to a script.

  argArray=( "$@" )                        # Add all script arguments to argArray
  arrayLength=${#argArray[@]}              # Get the length of the array
  lastArg=$((arrayLength - 1))             # Arrays are zero based, so last arg is -1
  echo ${argArray[$lastArg]}

Sample output

$ ./lastarg.sh 1 2 buckle my shoe
shoe

How to check whether an array is empty using PHP?

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.


Main Notes:

An array with a key (or keys) will be determined as NOT empty by PHP.

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

Take these arrays for example:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

And testing the above arrays with empty() returns the following results:

ARRAY ONE:
$ArrayOne is not empty

ARRAY TWO:
$ArrayTwo is not empty

ARRAY THREE:
$ArrayThree is not empty

An array will always be empty when you assign an array but don't use it thereafter, such as:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).


Here's an approach which uses very little code to check if an array has values:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

ARRAY ONE:
$arrayone is not empty

ARRAY TWO:
$arraytwo is not empty

ARRAY THREE:
$arraythree is empty

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Initializing a two dimensional std::vector

Suppose you want to initialize a two dimensional integer vector with n rows and m column each having value 'VAL'

Write it as

std::vector<vector<int>> arr(n, vector<int>(m,VAL));

This VAL can be a integer type variable or constant such as 100

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

Dynamically add event listener

Renderer has been deprecated in Angular 4.0.0-rc.1, read the update below

The angular2 way is to use listen or listenGlobal from Renderer

For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement)

constructor(elementRef: ElementRef, renderer: Renderer) {

    // Listen to click events in the component
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
      // Do something with 'event'
    })
);

You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

Note that since beta.2 both listen and listenGlobal return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).

So to remove the listener we added dynamically we must assign listen or listenGlobal to a variable that will hold the function returned, and then we execute it.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {
    
    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();
    
    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

Here's a plnkr with an example working. The example contains the usage of listen and listenGlobal.

Using RendererV2 with Angular 4.0.0-rc.1+ (Renderer2 since 4.0.0-rc.3)

  • 25/02/2017: Renderer has been deprecated, now we should use RendererV2 (see line below). See the commit.

  • 10/03/2017: RendererV2 was renamed to Renderer2. See the breaking changes.

RendererV2 has no more listenGlobal function for global events (document, body, window). It only has a listen function which achieves both functionalities.

For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).

listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
      () => void {
    if (typeof target === 'string') {
      return <() => void>this.eventManager.addGlobalEventListener(
          target, event, decoratePreventDefault(callback));
    }
    return <() => void>this.eventManager.addEventListener(
               target, event, decoratePreventDefault(callback)) as() => void;
  }

As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener

To remove the listener it's the same as it was with Renderer in angular 2.x. listen returns a function, then call that function.

Example

// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
  console.log('Clicking the document', evt);
})

let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
  console.log('Clicking the button', evt);
});

// Remove listeners
global();
simple();

plnkr with Angular 4.0.0-rc.1 using RendererV2

plnkr with Angular 4.0.0-rc.3 using Renderer2

Is it possible to format an HTML tooltip (title attribute)?

I know this is an old post but I would like to add my answer for future reference. I use jQuery and css to style my tooltips: easiest-tooltip-and-image-preview-using-jquery (for a demo: http://cssglobe.com/lab/tooltip/02/) On my static websites this just worked great. However, during migrating to Wordpress it stopped. My solution was to change tags like <br> and <span> into this: &lt;br&gt; and &lt;span&gt; This works for me.

Data binding to SelectedItem in a WPF Treeview

I bring you my solution which offers the following features:

  • Supports 2 ways binding

  • Auto updates the TreeViewItem.IsSelected properties (according to the SelectedItem)

  • No TreeView subclassing

  • Items bound to ViewModel can be of any type (even null)

1/ Paste the following code in your CS:

public class BindableSelectedItem
{
    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.RegisterAttached(
        "SelectedItem", typeof(object), typeof(BindableSelectedItem), new PropertyMetadata(default(object), OnSelectedItemPropertyChangedCallback));

    private static void OnSelectedItemPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var treeView = d as TreeView;
        if (treeView != null)
        {
            BrowseTreeViewItems(treeView, tvi =>
            {
                tvi.IsSelected = tvi.DataContext == e.NewValue;
            });
        }
        else
        {
            throw new Exception("Attached property supports only TreeView");
        }
    }

    public static void SetSelectedItem(DependencyObject element, object value)
    {
        element.SetValue(SelectedItemProperty, value);
    }

    public static object GetSelectedItem(DependencyObject element)
    {
        return element.GetValue(SelectedItemProperty);
    }

    public static void BrowseTreeViewItems(TreeView treeView, Action<TreeViewItem> onBrowsedTreeViewItem)
    {
        var collectionsToVisit = new System.Collections.Generic.List<Tuple<ItemContainerGenerator, ItemCollection>> { new Tuple<ItemContainerGenerator, ItemCollection>(treeView.ItemContainerGenerator, treeView.Items) };
        var collectionIndex = 0;
        while (collectionIndex < collectionsToVisit.Count)
        {
            var itemContainerGenerator = collectionsToVisit[collectionIndex].Item1;
            var itemCollection = collectionsToVisit[collectionIndex].Item2;
            for (var i = 0; i < itemCollection.Count; i++)
            {
                var tvi = itemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
                if (tvi == null)
                {
                    continue;
                }

                if (tvi.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                {
                    collectionsToVisit.Add(new Tuple<ItemContainerGenerator, ItemCollection>(tvi.ItemContainerGenerator, tvi.Items));
                }

                onBrowsedTreeViewItem(tvi);
            }

            collectionIndex++;
        }
    }

}

2/ Example of use in your XAML file

<TreeView myNS:BindableSelectedItem.SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" />  

How to merge a Series and DataFrame

Here's one way:

df.join(pd.DataFrame(s).T).fillna(method='ffill')

To break down what happens here...

pd.DataFrame(s).T creates a one-row DataFrame from s which looks like this:

   s1  s2
0   5   6

Next, join concatenates this new frame with df:

   a  b  s1  s2
0  1  3   5   6
1  2  4 NaN NaN

Lastly, the NaN values at index 1 are filled with the previous values in the column using fillna with the forward-fill (ffill) argument:

   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

To avoid using fillna, it's possible to use pd.concat to repeat the rows of the DataFrame constructed from s. In this case, the general solution is:

df.join(pd.concat([pd.DataFrame(s).T] * len(df), ignore_index=True))

Here's another solution to address the indexing challenge posed in the edited question:

df.join(pd.DataFrame(s.repeat(len(df)).values.reshape((len(df), -1), order='F'), 
        columns=s.index, 
        index=df.index))

s is transformed into a DataFrame by repeating the values and reshaping (specifying 'Fortran' order), and also passing in the appropriate column names and index. This new DataFrame is then joined to df.

Play/pause HTML 5 video using JQuery

By JQuery using selectors

$("video_selector").trigger('play');  
$("video_selector").trigger('pause');
$("div.video:first").trigger('play');$("div.video:first").trigger('pause');
$("#video_ID").trigger('play');$("#video_ID").trigger('pause');

By Javascript using ID

video_ID.play();  video_ID.pause();

OR

document.getElementById('video_ID').play();  document.getElementById('video_ID').pause();

Visual Studio loading symbols

Visual Studio 2017 Debug symbol "speed-up" options, assuming you haven't gone crazy on option-customization already:

  1. At Tools -> Options -> Debugging -> Symbols
    a. Enable the "Microsoft Symbol Server" option
    b. Click "Empty Symbol Cache"
    c. Set your symbol cache to an easy to find spot, like C:\dbg_symbols or %USERPROFILE%\dbg_symbols
  2. After re-running Debug, let it load all the symbols once, from start-to-end, or as much as reasonably possible.

1A and 2 are the most important steps. 1B and 1C are just helpful changes to help you keep track of your symbols.

After your app has loaded all the symbols at least once and debugging didn't prematurely terminate, those symbols should be quickly loaded the next time debug runs.

I've noticed that if I cancel a debug-run, I have to reload those symbols, as I'm guessing they're "cleaned" up if newly introduced and suddenly cancelled. I understand the core rationale for that kind of flow, but in this case it seems poorly thought out.

How to overcome "'aclocal-1.15' is missing on your system" warning?

2017 - High Sierra

It is really hard to get autoconf 1.15 working on Mac. We hired an expert to get it working. Everything worked beautifully.

Later I happened to upgrade a Mac to High Sierra.

The Docker pipeline stopped working!

Even though autoconf 1.15 is working fine on the Mac.

How to fix,

Short answer, I simply trashed the local repo, and checked out the repo again.

This suggestion is noted in the mix on this QA page and elsewhere.

It then worked fine!

It likely has something to do with the aclocal.m4 and similar files. (But who knows really). I endlessly massaged those files ... but nothing.

For some unknown reason if you just scratch your repo and get the repo again: everything works!

I tried for hours every combo of touching/deleting etc etc the files in question, but no. Just check out the repo from scratch!

How do I set <table> border width with CSS?

Like this:

border: 1px solid black;

Why it didn't work? because:

Always declare the border-style (solid in my example) property before the border-width property. An element must have borders before you can change the color.

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

Set style for TextView programmatically

We can use TextViewCompact.setTextAppearance(textView, R.style.xyz).

Android doc for reference.

SSRS Query execution failed for dataset

I enabled remote errors to pinpoint the problem.

I identified that a column in a particular dataset (one of my views) was throwing an error.

So using a tool "SQL Delta", I compared the development version of the database with the live version on the reporting server. I noticed that one of the views had an extra column on the development server, that was not on the live version of the db.

SQL Delta generated the script I needed to run to update the view on my live db.

I ran this script, re-ran the report, everything worked.

How can I list the contents of a directory in Python?

The os module handles all that stuff.

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Availability: Unix, Windows.

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In this case no conditionals are needed to set the variable.

This one-liner XPath expression:

boolean(joined-subclass)

is true() only when the child of the current node, named joined-subclass exists and it is false() otherwise.

The complete stylesheet is:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

 <xsl:template match="class">
   <xsl:variable name="subexists"
        select="boolean(joined-subclass)"
   />

   subexists:  <xsl:text/>
   <xsl:value-of select="$subexists" />
 </xsl:template>
</xsl:stylesheet>

Do note, that the use of the XPath function boolean() in this expression is to convert a node (or its absense) to one of the boolean values true() or false().

C++ JSON Serialization

For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.

I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :

Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.

For example you can serialize like that :

    // Random class initialization
    com::class1* aObject = new com::class1();

    for (int i=0; i<10; i++){
            aObject->setData(i,i);
    }      

    aObject->pdata = new char[7];
    for (int i=0; i<7; i++){
            aObject->pdata[i] = 7-i;
    }
    // dictionary initialization
    cjson::dictionary aDict("./data/dictionary.xml");

    // json transformation
    std::string aJson = aDict.toJson<com::class1>(aObject);

    // print encoded class
    cout << aJson << std::endl ;

To deserialize data it works like that:

    // decode the object
    com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);

    // modify data
    aDecodedObject->setData(4,22);

    // json transformation
    aJson = aDict.toJson<com::class1>(aDecodedObject);

    // print encoded class
    cout << aJson << std::endl ;

Ouptuts:

>:~/cjson$ ./main
{"_index":54,"_inner":  {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$ 

Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.