Programs & Examples On #Multiple constructors

Best way to do multiple constructors in PHP

I know I'm super late to the party here, but I came up with a fairly flexible pattern that should allow some really interesting and versatile implementations.

Set up your class as you normally would, with whatever variables you like.

class MyClass{
    protected $myVar1;
    protected $myVar2;

    public function __construct($obj = null){
        if($obj){
            foreach (((object)$obj) as $key => $value) {
                if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
                    $this->$key = $value;
                }
            }
        }
    }
}

When you make your object just pass an associative array with the keys of the array the same as the names of your vars, like so...

$sample_variable = new MyClass([
    'myVar2'=>123, 
    'i_dont_want_this_one'=> 'This won\'t make it into the class'
    ]);

print_r($sample_variable);

The print_r($sample_variable); after this instantiation yields the following:

MyClass Object ( [myVar1:protected] => [myVar2:protected] => 123 )

Because we've initialize $group to null in our __construct(...), it is also valid to pass nothing whatsoever into the constructor as well, like so...

$sample_variable = new MyClass();

print_r($sample_variable);

Now the output is exactly as expected:

MyClass Object ( [myVar1:protected] => [myVar2:protected] => )

The reason I wrote this was so that I could directly pass the output of json_decode(...) to my constructor, and not worry about it too much.

This was executed in PHP 7.1. Enjoy!

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

load scripts asynchronously

HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.

async - The HTML

<script async src="siteScript.js" onload="myInit()"></script>

defer - The HTML

<script defer src="siteScript.js" onload="myInit()"></script>

While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

Angular 2 Scroll to bottom (Chat style)

this.contentList.nativeElement.scrollTo({left: 0 , top: this.contentList.nativeElement.scrollHeight, behavior: 'smooth'});

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

How to normalize a histogram in MATLAB?

hist can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar. Example:

Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)

or if you want a one-liner:

bar(hist(Y) ./ sum(hist(Y)))

Documentation:

Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz as proposed by R. M.

jQuery DIV click, with anchors

I know that if you were to change that to an href you'd do:

$("a#link1").click(function(event) {
  event.preventDefault();
  $('div.link1').show();
  //whatever else you want to do
});

so if you want to keep it with the div, I'd try

$("div.clickable").click(function(event) {
  event.preventDefault();
  window.location = $(this).attr("url");
});

How to edit default dark theme for Visual Studio Code?

You cannot "edit" a default theme, they are "locked in"

However, you can copy it into your own custom theme, with the exact modifications you'd like.

For more info, see these articles: https://code.visualstudio.com/Docs/customization/themes https://code.visualstudio.com/docs/extensions/install-extension#_your-extensions-folder

If all you want to change is the colors for C++ code, you should look at overwriting the c++ support colorizer. For info about that, go here: https://code.visualstudio.com/docs/customization/colorizer

EDIT: The dark theme is found here: https://github.com/Microsoft/vscode/tree/80f8000c10b4234c7b027dccfd627442623902d2/extensions/theme-colorful-defaults

EDIT2: To clarify:

Get host domain from URL?

The best way, and the right way to do it is using Uri.Authority field

Load and use Uri like so :

Uri NewUri;

if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
     Console.Writeline(NewUri.Authority);
}

Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com

Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com

Input : http://localhost/default.aspx?id=12345
Output : localhost

If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx

How to split a delimited string into an array in awk?

I know this is kind of old question, but I thought maybe someone like my trick. Especially since this solution not limited to a specific number of items.

# Convert to an array
_ITEMS=($(echo "12|23|11" | tr '|' '\n'))

# Output array items
for _ITEM in "${_ITEMS[@]}"; do
  echo "Item: ${_ITEM}"
done

The output will be:

Item: 12
Item: 23
Item: 11

Using $window or $location to Redirect in AngularJS

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

INNER JOIN vs INNER JOIN (SELECT . FROM)

You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.

My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries. Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID WHERE p.isactive = 1

The better version of this query is :

SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1

(Assuming isactive is a field in product table which represents the active/inactive products).

Objective-C - Remove last character from string

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

How to make sure that string is valid JSON using JSON.NET

Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:

public static bool IsValidJson<T>(this string strInput)
{
    if(string.IsNullOrWhiteSpace(strInput)) return false;

    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JsonConvert.DeserializeObject<T>(strInput);
            return true;
        }
        catch // not valid
        {             
            return false;
        }
    }
    else
    {
        return false;
    }
}

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

How to check a Long for null in java

Of course Primitive types cannot be null. But in Java 8 you can use Objects.isNull(longValue) to check. Ex. If(Objects.isNull(longValue))

Linq style "For Each"

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
{
    list.Add(x + 1);
}

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
   foreach (var x in @this)
      action(x);
}

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

Excellent answer already provide onsite here.

See the summary below:

  1. Go to the Build Path settings in the project properties.
  2. Remove the JRE System Library
  3. Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.

Create autoincrement key in Java DB using NetBeans IDE

If you want to use Netbeans to define tables read this https://codezone4.wordpress.com/2012/06/19/java-database-application-using-javadb-part-1/ Simply define column as integer and create database, then grab structure to a temporary file, then delete table. Right clik to tables folder and select recreate table, select saved file and edit script for auto increment.

Detect if a NumPy array contains at least one non-numeric value?

With numpy 1.3 or svn you can do this

In [1]: a = arange(10000.).reshape(100,100)

In [3]: isnan(a.max())
Out[3]: False

In [4]: a[50,50] = nan

In [5]: isnan(a.max())
Out[5]: True

In [6]: timeit isnan(a.max())
10000 loops, best of 3: 66.3 µs per loop

The treatment of nans in comparisons was not consistent in earlier versions.

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

How to pass parameters to maven build using pom.xml?

mvn install "-Dsomeproperty=propety value"

In pom.xml:

<properties>
    <someproperty> ${someproperty} </someproperty>
</properties>

Referred from this question

Set position / size of UI element as percentage of screen size

Take a look at this:

http://developer.android.com/reference/android/util/DisplayMetrics.html

You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.

Gantt chart for this ques will be:

| P3 | P2 | P4 | P5 | P1 |

1    4    5    7   11   14

Average waiting time=(0+2+2+3+3)/5=2

Average Turnaround time=(3+3+4+7+6)/5=4.6

SQL split values to multiple rows

Here is my attempt: The first select presents the csv field to the split. Using recursive CTE, we can create a list of numbers that are limited to the number of terms in the csv field. The number of terms is just the difference in the length of the csv field and itself with all the delimiters removed. Then joining with this numbers, substring_index extracts that term.

with recursive
    T as ( select 'a,b,c,d,e,f' as items),
    N as ( select 1 as n union select n + 1 from N, T
        where n <= length(items) - length(replace(items, ',', '')))
    select distinct substring_index(substring_index(items, ',', n), ',', -1)
group_name from N, T

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

JAVA_HOME is not the name of the java executable. But of the directory, java was installed in. The executable should be $JAVA_HOME/bin/java.

The which command is not helpful for you there. It will not give you the java home, but most likely this is just a wrapper or symlink to java installed in a very different directory.

Any reason to prefer getClass() over instanceof when generating .equals()?

It depends if you consider if a subclass of a given class is equals to its parent.

class LastName
{
(...)
}


class FamilyName
extends LastName
{
(..)
}

here I would use 'instanceof', because I want a LastName to be compared to FamilyName

class Organism
{
}

class Gorilla extends Organism
{
}

here I would use 'getClass', because the class already says that the two instances are not equivalent.

Material Design not styling alert dialogs

You can consider this project: https://github.com/fengdai/AlertDialogPro

It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.

VS 2012: Scroll Solution Explorer to current file

On Visual Studio 2017, the shortcut is: Ctrl+´,S.

enter image description here

Add image in pdf using jspdf

The above code not worked for me. I found new solution :

 var pdf = new jsPDF();
 var img = new Image;
 img.onload = function() {
     pdf.addImage(this, 10, 10);
     pdf.save("test.pdf");
 };
 img.crossOrigin = "";  
 img.src = "assets/images/logo.png";

PUT vs. POST in REST

Ruby on Rails 4.0 will use the 'PATCH' method instead of PUT to do partial updates.

RFC 5789 says about PATCH (since 1995):

A new method is necessary to improve interoperability and prevent errors. The PUT method is already defined to overwrite a resource with a complete new body, and cannot be reused to do partial changes. Otherwise, proxies and caches, and even clients and servers, may get confused as to the result of the operation. POST is already used but without broad interoperability (for one, there is no standard way to discover patch format support). PATCH was mentioned in earlier HTTP specifications, but not completely defined.

"Edge Rails: PATCH is the new primary HTTP method for updates" explains it.

What's the safest way to iterate through the keys of a Perl hash?

I usually use keys and I can't think of the last time I used or read a use of each.

Don't forget about map, depending on what you're doing in the loop!

map { print "$_ => $hash{$_}\n" } keys %hash;

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

Set width of dropdown element in HTML select dropdown options

Small And Better One

var i = 0;
$("#container > option").each(function(){ 
    if($(this).val().length > i) {
        i = $(this).val().length;

        console.log(i);
        console.log($(this).val());
    }
});

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

Here is some code I wrote to help us identify and correct untrusted CONSTRAINTs in a DATABASE. It generates the code to fix each issue.

    ;WITH Untrusted (ConstraintType, ConstraintName, ConstraintTable, ParentTable, IsDisabled, IsNotForReplication, IsNotTrusted, RowIndex) AS
(
    SELECT 
        'Untrusted FOREIGN KEY' AS FKType
        , fk.name AS FKName
        , OBJECT_NAME( fk.parent_object_id) AS FKTableName
        , OBJECT_NAME( fk.referenced_object_id) AS PKTableName 
        , fk.is_disabled
        , fk.is_not_for_replication
        , fk.is_not_trusted
        , ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( fk.parent_object_id), OBJECT_NAME( fk.referenced_object_id), fk.name) AS RowIndex
    FROM 
        sys.foreign_keys fk 
    WHERE 
        is_ms_shipped = 0 
        AND fk.is_not_trusted = 1       

    UNION ALL

    SELECT 
        'Untrusted CHECK' AS KType
        , cc.name AS CKName
        , OBJECT_NAME( cc.parent_object_id) AS CKTableName
        , NULL AS ParentTable
        , cc.is_disabled
        , cc.is_not_for_replication
        , cc.is_not_trusted
        , ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( cc.parent_object_id), cc.name) AS RowIndex
    FROM 
        sys.check_constraints cc 
    WHERE 
        cc.is_ms_shipped = 0
        AND cc.is_not_trusted = 1

)
SELECT 
    u.ConstraintType
    , u.ConstraintName
    , u.ConstraintTable
    , u.ParentTable
    , u.IsDisabled
    , u.IsNotForReplication
    , u.IsNotTrusted
    , u.RowIndex
    , 'RAISERROR( ''Now CHECKing {%i of %i)--> %s ON TABLE %s'', 0, 1' 
        + ', ' + CAST( u.RowIndex AS VARCHAR(64))
        + ', ' + CAST( x.CommandCount AS VARCHAR(64))
        + ', ' + '''' + QUOTENAME( u.ConstraintName) + '''' 
        + ', ' + '''' + QUOTENAME( u.ConstraintTable) + '''' 
        + ') WITH NOWAIT;'
    + 'ALTER TABLE ' + QUOTENAME( u.ConstraintTable) + ' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME( u.ConstraintName) + ';' AS FIX_SQL
FROM Untrusted u
CROSS APPLY (SELECT COUNT(*) AS CommandCount FROM Untrusted WHERE ConstraintType = u.ConstraintType) x
ORDER BY ConstraintType, ConstraintTable, ParentTable;

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

How to remove all callbacks from a Handler?

For any specific Runnable instance, call Handler.removeCallbacks(). Note that it uses the Runnable instance itself to determine which callbacks to unregister, so if you are creating a new instance each time a post is made, you need to make sure you have references to the exact Runnable to cancel. Example:

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
    public void run() {
        //Some interesting task
    }
};

You can call myHandler.postDelayed(myRunnable, x) to post another callback to the message queue at other places in your code, and remove all pending callbacks with myHandler.removeCallbacks(myRunnable)

Unfortunately, you cannot simply "clear" the entire MessageQueue for a Handler, even if you make a request for the MessageQueue object associated with it because the methods for adding and removing items are package protected (only classes within the android.os package can call them). You may have to create a thin Handler subclass to manage a list of Runnables as they are posted/executed...or look at another paradigm for passing your messages between each Activity

Hope that Helps!

Iterating Through a Dictionary in Swift

Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.

Read this article to know more about Collection Types: Swift Programming Language

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

From Django 2.0 on_delete is required:

user = models.OneToOneField(User, on_delete=models.CASCADE)

It will delete the child table data if the User is deleted. For more details check the Django documentation.

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

How to trim leading and trailing white spaces of a string?

For example,

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "\t Hello, World\n "
    fmt.Printf("%d %q\n", len(s), s)
    t := strings.TrimSpace(s)
    fmt.Printf("%d %q\n", len(t), t)
}

Output:

16 "\t Hello, World\n "
12 "Hello, World"

Convert regular Python string to raw string

As of Python 3.6, you can use the following (similar to @slashCoder):

def to_raw(string):
    return fr"{string}"

my_dir ="C:\data\projects"
to_raw(my_dir)

yields 'C:\\data\\projects'. I'm using it on a Windows 10 machine to pass directories to functions.

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

Activity transition in Android

Some versions of Android support custom Activity transitions and some don't (older devices). If you want to use custom transitions it's good practice to check whether the Activity has the overridePendingTransition() method, as on older versions it does not.

To know whether the method exists or not, reflection API can be used. Here is the simple code which will check and return the method if it exists:

Method mOverridePendingTransition;

try {
        mOverridePendingTransition = Activity.class.getMethod(
                "overridePendingTransition", new Class[] { Integer.TYPE, Integer.TYPE } );
        /* success */
    } catch (NoSuchMethodException nsme) {
        /* failure, this version of Android doesn't have this method */
    } 

And then, we can apply our own transition, i.e. use this method if it exists:

if (UIConstants.mOverridePendingTransition != null) {
               try {
                   UIConstants.mOverridePendingTransition.invoke(MainActivity.this, R.anim.activity_fade_in, R.anim.activity_fade_out);
               } catch (InvocationTargetException e) {
                   e.printStackTrace();
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               }
            }

Here, as an example, simple fade-in and fade-out animations were used for transition demonstration..

Initializing a static std::map<int, int> in C++

Just wanted to share a pure C++ 98 work around:

#include <map>

std::map<std::string, std::string> aka;

struct akaInit
{
    akaInit()
    {
        aka[ "George" ] = "John";
        aka[ "Joe" ] = "Al";
        aka[ "Phil" ] = "Sue";
        aka[ "Smitty" ] = "Yando";
    }
} AkaInit;

How to add custom validation to an AngularJS form?

In AngularJS the best place to define Custom Validation is Cutsom directive. AngularJS provide a ngMessages module.

ngMessages is a directive that is designed to show and hide messages based on the state of a key/value object that it listens on. The directive itself complements error message reporting with the ngModel $error object (which stores a key/value state of validation errors).

For custom form validation One should use ngMessages Modules with custom directive.Here i have a simple validation which will check if number length is less then 6 display an error on screen

 <form name="myform" novalidate>
                <table>
                    <tr>
                        <td><input name='test' type='text' required  ng-model='test' custom-validation></td>
                        <td ng-messages="myform.test.$error"><span ng-message="invalidshrt">Too Short</span></td>
                    </tr>
                </table>
            </form>

Here is how to create custom validation directive

angular.module('myApp',['ngMessages']);
        angular.module('myApp',['ngMessages']).directive('customValidation',function(){
            return{
            restrict:'A',
            require: 'ngModel',
            link:function (scope, element, attr, ctrl) {// 4th argument contain model information 

            function validationError(value) // you can use any function and parameter name 
                {
                 if (value.length > 6) // if model length is greater then 6 it is valide state
                 {
                 ctrl.$setValidity('invalidshrt',true);
                 }
                 else
                 {
                 ctrl.$setValidity('invalidshrt',false) //if less then 6 is invalide
                 }

                 return value; //return to display  error 
                }
                ctrl.$parsers.push(validationError); //parsers change how view values will be saved in the model
            }
            };
        });

$setValidity is inbuilt function to set model state to valid/invalid

Get Element value with minidom with Python

It should just be

name[0].firstChild.nodeValue

How to align the text middle of BUTTON

Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem

<style type=text/css>

YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px; 
 padding-right:30px "to fix the text in the middle 
 without interfering with the text itself"}

</style>

It worked for me

How do I check if file exists in jQuery or pure JavaScript?

For a client computer this can be achieved by:

try
{
  var myObject, f;
  myObject = new ActiveXObject("Scripting.FileSystemObject");
  f =   myObject.GetFile("C:\\img.txt");
  f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
  alert("file does not exist")
}

This is my program to transfer a file to a specific location and shows alert if it does not exist

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

If we are using the UIImagePickerController as a property, then this warning will disappear. assume that we are not using the result from the UIImagePickerController , if we are instantiating the UIImagePickerController within a function.

HTML - how to make an entire DIV a hyperlink?

alternative would be javascript and forwarding via the onclick event

<div onclick="window.location.href='somewhere...';">...</div>

Moment.js transform to date object

let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();

nice and clean!!!!

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

What does 'public static void' mean in Java?

Public - means that the class (program) is available for use by any other class.

Static - creates a class. Can also be applied to variables and methods,making them class methods/variables instead of just local to a particular instance of the class.

Void - this means that no product is returned when the class completes processing. Compare this with helper classes that provide a return value to the main class,these operate like functions; these do not have void in the declaration.

What is the best way to calculate a checksum for a file that is on my machine?

Just use win32 Checksum api. MD5 is native in Win32.

Max length for client ip address

If you are just storing it for reference, you can store it as a string, but if you want to do a lookup, for example, to see if the IP address is in some table, you need a "canonical representation." Converting the entire thing to a (large) number is the right thing to do. IPv4 addresses can be stored as a long int (32 bits) but you need a 128 bit number to store an IPv6 address.

For example, all these strings are really the same IP address: 127.0.0.1, 127.000.000.001, ::1, 0:0:0:0:0:0:0:1

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

How to convert a Datetime string to a current culture datetime string

DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime.TryParse(datetimestring,culture, styles, out dateValue);

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

RuntimeError on windows trying python multiprocessing

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

So, in my case, ended like this:

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

HTTP Status 405 - Method Not Allowed Error for Rest API

You might be doing a PUT call for GET operation Please check once

Subprocess changing directory

What your code tries to do is call a program named cd ... What you want is call a command named cd.

But cd is a shell internal. So you can only call it as

subprocess.call('cd ..', shell=True) # pointless code! See text below.

But it is pointless to do so. As no process can change another process's working directory (again, at least on a UNIX-like OS, but as well on Windows), this call will have the subshell change its dir and exit immediately.

What you want can be achieved with os.chdir() or with the subprocess named parameter cwd which changes the working directory immediately before executing a subprocess.

For example, to execute ls in the root directory, you either can do

wd = os.getcwd()
os.chdir("/")
subprocess.Popen("ls")
os.chdir(wd)

or simply

subprocess.Popen("ls", cwd="/")

how to execute php code within javascript

May be this way:

    <?php 
     if($_SERVER['REQUEST_METHOD']=="POST") {
       echo 'asdasda';
     }
    ?>

    <form method="post">
    <button type="submit" id="okButton">Order now</button>
</form>

Save bitmap to file function

Two example works for me, for your reference.

Bitmap bitmap = Utils.decodeBase64(base64);
try {
    File file = new File(filePath);
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
}
catch (Exception e) {
    e.printStackTrace();
    LOG.i(null, "Save file error!");
    return false;
}

and this one

Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());

if (savePic != null) {
    try {
        // build directory
        if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
        }
        // output image to file
        FileOutputStream fos = new FileOutputStream(filePath);
        savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
        ret = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    LOG.i(TAG, "savePicture image parsing error");
}

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

My JDK is installed at C:\Program Files\Java\jdk1.8.0_144\.
I had set JAVA_HOME= C:\Program Files\Java\jdk1.8.0_144\, and I was getting this error:

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

When I changed the JAVA_HOME to C:\Program Files\Java\jdk1.8.0_144\jre, the issue got fixed.
I am not sure how.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

How to get the first 2 letters of a string in Python?

t = "your string"

Play with the first N characters of a string with

def firstN(s, n=2):
    return s[:n]

which is by default equivalent to

t[:2]

Spring Test & Security: How to mock authentication?

Short answer:

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
private Filter springSecurityFilterChain;

@Before
public void setUp() throws Exception {
    final MockHttpServletRequestBuilder defaultRequestBuilder = get("/dummy-path");
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
            .defaultRequest(defaultRequestBuilder)
            .alwaysDo(result -> setSessionBackOnRequestBuilder(defaultRequestBuilder, result.getRequest()))
            .apply(springSecurity(springSecurityFilterChain))
            .build();
}

private MockHttpServletRequest setSessionBackOnRequestBuilder(final MockHttpServletRequestBuilder requestBuilder,
                                                             final MockHttpServletRequest request) {
    requestBuilder.session((MockHttpSession) request.getSession());
    return request;
}

After perform formLogin from spring security test each of your requests will be automatically called as logged in user.

Long answer:

Check this solution (the answer is for spring 4): How to login a user with spring 3.2 new mvc testing

How to fix .pch file missing on build?

I know this topic is very old, but I was dealing with this in VS2015 recently and what helped was to deleted the build folders and re-build it. This may have happen due to trying to close the program or a program halting/freezing VS while building.

cast a List to a Collection

First Collection is class Interface and you can not instantiate. Collection API

List Ver APi is also an interface class.

It may be so

List list = Collections.synchronizedList(new ArrayList(...)); 

ver enter link description here

Collection collection= Collections.synchronizedList(new ArrayList(...)); 

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

Android – Listen For Incoming SMS Messages

Thank to @Vineet Shukla (the accepted answer) and @Ruchir Baronia (found the issue in the accepted answer), below is the Kotlin version:

Add permission:

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

Register BroadcastReceiver in AndroidManifest:

<receiver
    android:name=".receiver.SmsReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter android:priority="2332412">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add implementation for BroadcastReceiver:

class SmsReceiver : BroadcastReceiver() {
    private var mLastTimeReceived = System.currentTimeMillis()

    override fun onReceive(p0: Context?, intent: Intent?) {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - mLastTimeReceived > 200) {
            mLastTimeReceived = currentTimeMillis

            val pdus: Array<*>
            val msgs: Array<SmsMessage?>
            var msgFrom: String?
            var msgText: String?
            val strBuilder = StringBuilder()
            intent?.extras?.let {
                try {
                    pdus = it.get("pdus") as Array<*>
                    msgs = arrayOfNulls(pdus.size)
                    for (i in msgs.indices) {
                        msgs[i] = SmsMessage.createFromPdu(pdus[i] as ByteArray)
                        strBuilder.append(msgs[i]?.messageBody)
                    }

                    msgText = strBuilder.toString()
                    msgFrom = msgs[0]?.originatingAddress

                    if (!msgFrom.isNullOrBlank() && !msgText.isNullOrBlank()) {
                        //
                        // Do some thing here
                        //
                    }
                } catch (e: Exception) {
                }
            }
        }
    }
}

Sometime event fires twice so I add mLastTimeReceived = System.currentTimeMillis()

What is a Maven artifact?

An artifact is a file, usually a JAR, that gets deployed to a Maven repository.

A Maven build produces one or more artifacts, such as a compiled JAR and a "sources" JAR.

Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact.

A project's dependencies are specified as artifacts.

Android: How do I prevent the soft keyboard from pushing my view up?

Just a single line to be added...

Add android:windowSoftInputMode="stateHidden|adjustPan" in required activity of your manifest file.

I just got solved :) :)

for loop in Python

In C/C++, we can do the following, as you mentioned

for(int k = 1; k <= c ; k++)
for(int k = 1; k <= c ; k +=2)

We know that here k starts with 1 and go till (predefined) c with step value 1 or 2 gradually. We can do this in Python by following,

for k in range(1,c+1):
for k in range(1,c+1,2):

Check this for more in depth.

Fill Combobox from database

void Fillcombobox()
{

    con.Open();
    cmd = new SqlCommand("select ID From Employees",con);
    Sdr = cmd.ExecuteReader();
    while (Sdr.Read())
    {
        for (int i = 0; i < Sdr.FieldCount; i++)
        {
           comboID.Items.Add( Sdr.GetString(i));

        }
    }
    Sdr.Close();
    con.Close();

}

How to convert std::string to LPCWSTR in C++ (Unicode)

string  myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0); 
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
 std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();

Change the bullet color of list

You have to use image

.listStyle {
    list-style: none;
    background: url(bullet.jpg) no-repeat left center;
    padding-left: 40px;
}

How to select a schema in postgres when using psql?

if you in psql just type

set schema 'temp';

and after that \d shows all relations in "temp

SQL Data Reader - handling Null column values

By influencing from getpsyched's answer, I created a generic method which checks column value by its name

public static T SafeGet<T>(this System.Data.SqlClient.SqlDataReader reader, string nameOfColumn)
{
  var indexOfColumn = reader.GetOrdinal(nameOfColumn);
  return reader.IsDBNull(indexOfColumn) ? default(T) : reader.GetFieldValue<T>(indexOfColumn);
}

Usage:

var myVariable = SafeGet<string>(reader, "NameOfColumn")

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

How to right-align and justify-align in Markdown?

As mentioned here, markdown do not support right aligned text or blocks. But the HTML result does it, via Cascading Style Sheets (CSS).

On my Jekyll Blog is use a syntax which works in markdown as well. To "terminate" a block use two spaces at the end or two times new line.

Of course you can also add a css-class with {: .right } instead of {: style="text-align: right" }.

Text to right

{: style="text-align: right" }
This text is on the right

Text as block

{: style="text-align: justify" }
This text is a block

Java Swing revalidate() vs repaint()

revalidate() just request to layout the container, when you experienced simply call revalidate() works, it could be caused by the updating of child components bounds triggers the repaint() when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint() is "accidentally" triggered.

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

we had this same issue starting this morning and goti it solved... hope this helps...

SSL on IIS 8

  1. Everything was working fine yesterday and last night our SSL was updated on the IIS site.
  2. While checking out the site Bindings to the SSL noticed that IIS8 has a new checkbox Require Server Name Indication, it was not checked so preceded to enable it.
  3. That triggered the problem.
  4. Went back to IIS, disabled the checkbox.... Problem Solved!!!!

Hope this helps!!!

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

Java Code for calculating Leap Year

With the course of : TestMyCode Programming assignment evaluator, that one of the exercises was this kind of issue, I wrote this answer:

import java.util.Scanner;

public class LeapYear {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Type a year: ");

        int year = Integer.parseInt(reader.nextLine());

        if (year % 400 == 0 && year % 100 == 0 && year % 4 == 0) {
            System.out.println("The year is a leap year");
        } else
         if (year % 4 == 0 && year%100!=0 ) {
            System.out.println("The year is a leap year");
        } else 
        {
            System.out.println("The year is not a leap year");
        }

    }
}

How do I URl encode something in Node.js?

The built-in module querystring is what you're looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'

NSURLErrorDomain error codes description

The NSURLErrorDomain error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.

How to convert the following json string to java object?

Check out Google's Gson: http://code.google.com/p/google-gson/

From their website:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.

How to delete a file via PHP?

The following should help

  • realpath — Returns canonicalized absolute pathname
  • is_writable — Tells whether the filename is writable
  • unlink — Deletes a file

Run your filepath through realpath, then check if the returned path is writable and if so, unlink it.

What's the simplest way of detecting keyboard input in a script from the terminal?

You can use methods from http://docs.python.org/2/library/msvcrt.html if you are on Windows.

import msvcrt
....
while True:
    print "Doing a function"
    if msvcrt.kbhit():
        print "Key pressed: %s" % msvcrt.getch()

How to create a cron job using Bash automatically without the interactive editor?

So, in Debian, Ubuntu, and many similar Debian based distros...

There is a cron task concatenation mechanism that takes a config file, bundles them up and adds them to your cron service running.

You can put a file under the /etc/cron.d/somefilename where somefilename is whatever you want.

sudo echo "0,15,30,45 * * * * ntpdate -u time.nist.gov" >> /etc/cron.d/vmclocksync

Let's disassemble this:

sudo - because you need elevated privileges to change cron configs under the /etc directory

echo - a vehicle to create output on std out. printf, cat... would work as well

" - use a doublequote at the beginning of your string, you're a professional

0,15,30,45 * * * * - the standard cron run schedule, this one runs every 15 minutes

ntpdate -u time.nist.gov - the actual command I want to run

" - because my first double quotes needs a buddy to close the line being output

>> - the double redirect appends instead of overwrites*

/etc/cron.d/vmclocksync - vmclocksync is the filename I've chosen, it goes in /etc/cron.d/


* if we used the > redirect, we could guarantee we only had one task entry. But, we would be at risk of blowing away any other rules in an existing file. You can decide for yourself if possible destruction with > is right or possible duplicates with >> are for you. Alternatively, you could do something convoluted or involved to check if the file name exists, if there is anything in it, and whether you are adding any kind of duplicate-- but, I have stuff to do and I can't do that for you right now.

Size of Matrix OpenCV

A complete C++ code example, may be helpful for the beginners

#include <iostream>
#include <string>
#include "opencv/highgui.h"

using namespace std;
using namespace cv;

int main()
{
    cv:Mat M(102,201,CV_8UC1);
    int rows = M.rows;
    int cols = M.cols;

    cout<<rows<<" "<<cols<<endl;

    cv::Size sz = M.size();
    rows = sz.height;
    cols = sz.width;

    cout<<rows<<" "<<cols<<endl;
    cout<<sz<<endl;
    return 0;
}

Get value from hidden field using jQuery

Closing the quotes in var hv = $('#h_v).text(); would help I guess

How do you calculate program run time in python?

I don't know if this is a faster alternative, but I have another solution -

from datetime import datetime
start=datetime.now()

#Statements

print datetime.now()-start

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

Regex expressions in Java, \\s vs. \\s+

First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.

However x.replaceAll("\\s+", ""); will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+ matches 1 or more spaces at once and replaces them with empty string.

So even though you get the same output from both it is better to use:

x.replaceAll("\\s+", "");

JavaScript alert box with timer

If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.

Add views in UIStackView programmatically

In my case the thing that was messing with I would expect was that I was missing this line:

stackView.translatesAutoresizingMaskIntoConstraints = false;

After that no need to set constraints to my arranged subviews whatsoever, the stackview is taking care of that.

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

What are the differences between a superkey and a candidate key?

One candidate key is chosen as the primary key. Other candidate keys are called alternate keys.

Detect If Browser Tab Has Focus

Surprising to see nobody mentioned document.hasFocus

if (document.hasFocus()) console.log('Tab is active')

MDN has more information.

Convert NaN to 0 in javascript

Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?

If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.

The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.

NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.

A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}

How to set up a cron job to run an executable every hour?

0 * * * * cd folder_containing_exe && ./exe_name

should work unless there is something else that needs to be setup for the program to run.

Which characters make a URL invalid?

I came up with a couple regular expressions for PHP that will convert urls in text to anchor tags. (First it converts all www. urls to http:// then converts all urls with https?:// to a href=... html links

$string = preg_replace('/(https?:\/\/)([!#$&-;=?\-\[\]_a-z~%]+)/sim', '<a href="$1$2">$2</a>', preg_replace('/(\s)((www\.)([!#$&-;=?\-\[\]_a-z~%]+))/sim', '$1http://$2', $string) );

jQuery autohide element after 5 seconds

I think, you could also do something like...

setTimeout(function(){
    $(".message-class").trigger("click");
}, 5000);

and do your animated effects on the event-click...

$(".message-class").click(function() {
    //your event-code
});

Greetings,

jQuery window scroll event does not fire up

  1. Declare your jQuery between <script> and </script> in the <head>,
  2. Wrap your .scroll() event within
$(document).ready(function(){
  //do something
});

How to use group by with union in t-sql

You need to alias the subquery. Thus, your statement should be:

Select Z.id
From    (
        Select id, time
        From dbo.tablea
        Union All
        Select id, time
        From dbo.tableb
        ) As Z
Group By Z.id

Warning as error - How to get rid of these

To treat all compiler warnings as compilation errors

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Treat all warnings as errors check box. (or select the build setting and change the “treat warnings as errors” settings to true.)

and if you want to get rid of it

To disable all compiler warnings

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Disable all warnings check box. (or select the build setting and change the “treat warnings as errors” settings to false.)

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

How to use both onclick and target="_blank"

Instead use window.open():

The syntax is:

window.open(strUrl, strWindowName[, strWindowFeatures]);

Your code should have:

window.open('Prosjektplan.pdf');

Your code should be:

<p class="downloadBoks"
   onclick="window.open('Prosjektplan.pdf')">Prosjektbeskrivelse</p>

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

Salt and hash a password in Python

For this to work in Python 3 you'll need to UTF-8 encode for example:

hashed_password = hashlib.sha512(password.encode('utf-8') + salt.encode('utf-8')).hexdigest()

Otherwise you'll get:

Traceback (most recent call last):
File "", line 1, in
hashed_password = hashlib.sha512(password + salt).hexdigest()
TypeError: Unicode-objects must be encoded before hashing

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

Just wanted to add -- apparently this can also be caused by installing Instant Client for 10, then realizing you want the full install and installing it again in a parallel directory. I don't know why this broke it.

Multi-line string with extra space (preserved indentation)

in a bash script the following works:

#!/bin/sh

text="this is line one\nthis is line two\nthis is line three"
echo -e $text > filename

alternatively:

text="this is line one
this is line two
this is line three"
echo "$text" > filename

cat filename gives:

this is line one
this is line two
this is line three

CSS – why doesn’t percentage height work?

You need to give it a container with a height. width uses the viewport as the default width

How to SHA1 hash a string in Android?

You don't need andorid for this. You can just do it in simple java.

Have you tried a simple java example and see if this returns the right sha1.

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AeSimpleSHA1 {
    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] textBytes = text.getBytes("iso-8859-1");
        md.update(textBytes, 0, textBytes.length);
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
}

Also share what your expected sha1 should be. Maybe ObjectC is doing it wrong.

Tri-state Check box in HTML?

You can use an indeterminate state: http://css-tricks.com/indeterminate-checkboxes/. It's supported by the browsers out of the box and don't require any external js libraries.

How do I prompt a user for confirmation in bash script?

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    # do dangerous stuff
fi

I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.

Also, the negated form might look like this:

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi

However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if should be used.

Explanation:

The read command outputs the prompt (-p "prompt") then accepts one character (-n 1) and accepts backslashes literally (-r) (otherwise read would see the backslash as an escape and wait for a second character). The default variable for read to store the result in is $REPLY if you don't supply a name like this: read -p "my prompt" -n 1 -r my_var

The if statement uses a regular expression to check if the character in $REPLY matches (=~) an upper or lower case "Y". The regular expression used here says "a string starting (^) and consisting solely of one of a list of characters in a bracket expression ([Yy]) and ending ($)". The anchors (^ and $) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read command.

The negated form uses the logical "not" operator (!) to match (=~) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]

How to drop a database with Mongoose?

If you modify @hellslam's solution like this then it will work

I use this technique to drop the Database after my integration tests

//CoffeeScript
mongoose = require "mongoose"
conn = mongoose.connect("mongodb://localhost/mydb")

conn.connection.db.dropDatabase()

//JavaScript
var conn, mongoose;
mongoose = require("mongoose");
conn = mongoose.connect("mongodb://localhost/mydb");

conn.connection.db.dropDatabase();

HTH at least it did for me, so I decided to share =)

How to convert FormData (HTML5 object) to JSON

Easy To Use Function

I Have Created A Function For This

function FormDataToJSON(FormElement){    
    var formData = new FormData(FormElement);
    var ConvertedJSON= {};
    for (const [key, value]  of formData.entries())
    {
        ConvertedJSON[key] = value;
    }

    return ConvertedJSON
}

Example Usage

var ReceivedJSON = FormDataToJSON(document.getElementById('FormId');)

In this code I have created empty JSON variable using for loop I have used keys from formData Object to JSON Keys in every Itration.

You Find This Code In My JS Library On GitHub Do Suggest Me If It Needs Improvement I Have Placed Code Here https://github.com/alijamal14/Utilities/blob/master/Utilities.js

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

Add padding and elevation:

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

Count(*) vs Count(1) - SQL Server

Clearly, COUNT(*) and COUNT(1) will always return the same result. Therefore, if one were slower than the other it would effectively be due to an optimiser bug. Since both forms are used very frequently in queries, it would make no sense for a DBMS to allow such a bug to remain unfixed. Hence you will find that the performance of both forms is (probably) identical in all major SQL DBMSs.

How to do INSERT into a table records extracted from another table

Remove both VALUES and the parenthesis.

INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1

how to bold words within a paragraph in HTML/CSS?

Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.

  1. Create a class for making any item bold. So for paragraph text it would be
span.bold(This name can be anything do not include parenthesis) {
   font-weight: bold;
}
  1. In your html you can access that class like by using the span tags and adding a class of bold or whatever name you have chosen

Defining TypeScript callback type

I'm a little late, but, since some time ago in TypeScript you can define the type of callback with

type MyCallback = (KeyboardEvent) => void;

Example of use:

this.addEvent(document, "keydown", (e) => {
    if (e.keyCode === 1) {
      e.preventDefault();
    }
});

addEvent(element, eventName, callback: MyCallback) {
    element.addEventListener(eventName, callback, false);
}

Protect .NET code from reverse engineering?

There's Salamander, which is a native .NET compiler and linker from Remotesoft that can deploy applications without the .NET framework. I don't know how well it lives up to its claims.

Get everything after and before certain character in SQL Server

use the following function

left(@test, charindex('/', @test) - 1)

What's the difference between .bashrc, .bash_profile, and .environment?

I have used Debian-family distros which appear to execute .profile, but not .bash_profile, whereas RHEL derivatives execute .bash_profile before .profile.

It seems to be a mess when you have to set up environment variables to work in any Linux OS.

How can I change column types in Spark SQL's DataFrame?

First, if you wanna cast type, then this:

import org.apache.spark.sql
df.withColumn("year", $"year".cast(sql.types.IntegerType))

With same column name, the column will be replaced with new one. You don't need to do add and delete steps.

Second, about Scala vs R.
This is the code that most similar to R I can come up with:

val df2 = df.select(
   df.columns.map {
     case year @ "year" => df(year).cast(IntegerType).as(year)
     case make @ "make" => functions.upper(df(make)).as(make)
     case other         => df(other)
   }: _*
)

Though the code length is a little longer than R's. That is nothing to do with the verbosity of the language. In R the mutate is a special function for R dataframe, while in Scala you can easily ad-hoc one thanks to its expressive power.
In word, it avoid specific solutions, because the language design is good enough for you to quickly and easy build your own domain language.


side note: df.columns is surprisingly a Array[String] instead of Array[Column], maybe they want it look like Python pandas's dataframe.

java Compare two dates

You equals(Object o) comparison is correct.

Yet, you should use after(Date d) and before(Date d) for date comparison.

How can I simulate an array variable in MySQL?

Both versions using sets didn't work for me (tested with MySQL 5.5). The function ELT() returns the whole set. Considering the WHILE statement is only avaible in PROCEDURE context i added it to my solution:

DROP PROCEDURE IF EXISTS __main__;

DELIMITER $
CREATE PROCEDURE __main__()
BEGIN
    SET @myArrayOfValue = '2,5,2,23,6,';

    WHILE (LOCATE(',', @myArrayOfValue) > 0)
    DO
        SET @value = LEFT(@myArrayOfValue, LOCATE(',',@myArrayOfValue) - 1);    
        SET @myArrayOfValue = SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);
    END WHILE;
END;
$
DELIMITER ;

CALL __main__;

To be honest, i don't think this is a good practice. Even if its realy necessary, this is barely readable and quite slow.

concatenate two database columns into one resultset column

Normal behaviour with NULL is that any operation including a NULL yields a NULL...

- 9 * NULL  = NULL  
- NULL + '' = NULL  
- etc  

To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..

SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

When to use "ON UPDATE CASCADE"

The ON UPDATE and ON DELETE specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION, CASCADE, SET NULL, and SET DEFAULT.

Delete actions of rows in the parent table

If you delete one or more rows in the parent table, you can set one of the following actions:

  • ON DELETE NO ACTION: SQL Server raises an error and rolls back the delete action on the row in the parent table.
  • ON DELETE CASCADE: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.
  • ON DELETE SET NULL: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.
  • ON DELETE SET DEFAULT: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified. By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.

Update action of rows in the parent table

If you update one or more rows in the parent table, you can set one of the following actions:

  • ON UPDATE NO ACTION: SQL Server raises an error and rolls back the update action on the row in the parent table.
  • ON UPDATE CASCADE: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.
  • ON UPDATE SET NULL: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.
  • ON UPDATE SET DEFAULT: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.
FOREIGN KEY (foreign_key_columns)
    REFERENCES parent_table(parent_key_columns)
    ON UPDATE <action> 
    ON DELETE <action>;

See the reference tutorial.

Can I dynamically add HTML within a div tag from C# on load event?

Remember using

myDiv.InnerHtml = "something";

will replace all HTML elements in myDIV. you need to append text to avoid that.In that this may help

myDiv.InnerHtml = "something" + myDiv.InnerText;

any html control in myDiv but not ASP html controls(as they are not rendered yet).

How to compile Go program consisting of multiple files?

You can use

go build *.go 
go run *.go

both will work also you may use

go build .
go run .

what is the use of Eval() in asp.net

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

Changing the row height of a datagridview

dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
}

The total number of locks exceeds the lock table size

in windows: if you have mysql workbench. Go to server status. find the location of running server file in my case it was:

C:\ProgramData\MySQL\MySQL Server 5.7

open my.ini file and find the buffer_pool_size. Set the value high. default value is 8M. This is how i fixed this problem

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

How to auto adjust the <div> height according to content in it?

For me after trying everything the below css worked:

float: left; width: 800px;

Try in chrome by inspecting element before putting it in css file.

omp parallel vs. omp parallel for

Here is example of using separated parallel and for here. In short it can be used for dynamic allocation of OpenMP thread-private arrays before executing for cycle in several threads. It is impossible to do the same initializing in parallel for case.

UPD: In the question example there is no difference between single pragma and two pragmas. But in practice you can make more thread aware behavior with separated parallel and for directives. Some code for example:

#pragma omp parallel
{ 
    double *data = (double*)malloc(...); // this data is thread private

    #pragma omp for
    for(1...100) // first parallelized cycle
    {
    }

    #pragma omp single 
    {} // make some single thread processing

    #pragma omp for // second parallelized cycle
    for(1...100)
    {
    }

    #pragma omp single 
    {} // make some single thread processing again

    free(data); // free thread private data
}

Python: CSV write by column rather than row

As an alternate streaming approach:

  • dump each col into a file
  • use python or unix paste command to rejoin on tab, csv, whatever.

Both steps should handle steaming just fine.

Pitfalls:

  • if you have 1000s of columns, you might run into the unix file handle limit!

What is the best way to measure execution time of a function?

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

Git cli: get user info from username

git config user.name
git config user.email

I believe these are the commands you are looking for.

Here is where I found them: http://alvinalexander.com/git/git-show-change-username-email-address

Android - Dynamically Add Views into View

To make @Mark Fisher's answer more clear, the inserted view being inflated should be a xml file under layout folder but without a layout (ViewGroup) like LinearLayout etc. inside. My example:

res/layout/my_view.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/i_am_id"
    android:text="my name"
    android:textSize="17sp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"/>

Then, the insertion point should be a layout like LinearLayout:

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/aaa"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/insert_point"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </LinearLayout>

</RelativeLayout>

Then the code should be

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shopping_cart);

    LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.my_view, null);
    ViewGroup main = (ViewGroup) findViewById(R.id.insert_point);
    main.addView(view, 0);
}

The reason I post this very similar answer is that when I tried to implement Mark's solution, I got stuck on what xml file should I use for insert_point and the child view. I used layout in the child view firstly and it was totally not working, which took me several hours to figure out. So hope my exploration can save others' time.

HTML text-overflow ellipsis detection

I think the better way to detect it is use getClientRects(), it seems each rect has the same height, so we can caculate lines number with the number of different top value.

getClientRects work like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

getRowRects work like this

you can detect like this

How to install Java 8 on Mac

brew cask commands were disabled on 2020-12-21 with the release of Homebrew 2.7.0.

Use the below commands to install JDK

brew install --cask adoptopenjdk/openjdk/adoptopenjdk8

Change the default base url for axios

From axios docs you have baseURL and url

baseURL will be prepended to url when making requests. So you can define baseURL as http://127.0.0.1:8000 and make your requests to /url

 // `url` is the server URL that will be used for the request
 url: '/user',

 // `baseURL` will be prepended to `url` unless `url` is absolute.
 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
 // to methods of that instance.
 baseURL: 'https://some-domain.com/api/',

What exactly does stringstream do?

From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

I come across some cases where it is both convenient and concise to use stringstream.

case 1

It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    }
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 
 }

Without the use of stringstream, it would be difficult to write such concise code.

How to delete or add column in SQLITE?

As others have pointed out, sqlite's ALTER TABLE statement does not support DROP COLUMN, and the standard recipe to do this does not preserve constraints & indices.

Here's some python code to do this generically, while maintaining all the key constraints and indices.

Please back-up your database before using! This function relies on doctoring the original CREATE TABLE statement and is potentially a bit unsafe - for instance it will do the wrong thing if an identifier contains an embedded comma or parenthesis.

If anyone would care to contribute a better way to parse the SQL, that would be great!

UPDATE I found a better way to parse using the open-source sqlparse package. If there is any interest I will post it here, just leave a comment asking for it ...

import re
import random

def DROP_COLUMN(db, table, column):
    columns = [ c[1] for c in db.execute("PRAGMA table_info(%s)" % table) ]
    columns = [ c for c in columns if c != column ]
    sql = db.execute("SELECT sql from sqlite_master where name = '%s'" 
        % table).fetchone()[0]
    sql = format(sql)
    lines = sql.splitlines()
    findcol = r'\b%s\b' % column
    keeplines = [ line for line in lines if not re.search(findcol, line) ]
    create = '\n'.join(keeplines)
    create = re.sub(r',(\s*\))', r'\1', create)
    temp = 'tmp%d' % random.randint(1e8, 1e9)
    db.execute("ALTER TABLE %(old)s RENAME TO %(new)s" % { 
        'old': table, 'new': temp })
    db.execute(create)
    db.execute("""
        INSERT INTO %(new)s ( %(columns)s ) 
        SELECT %(columns)s FROM %(old)s
    """ % { 
        'old': temp,
        'new': table,
        'columns': ', '.join(columns)
    })  
    db.execute("DROP TABLE %s" % temp)

def format(sql):
    sql = sql.replace(",", ",\n")
    sql = sql.replace("(", "(\n")
    sql = sql.replace(")", "\n)")
    return sql

Angular 2 execute script after template render

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

java.lang.IllegalArgumentException: contains a path separator

I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {    

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");  
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

Is there any standard for JSON API response format?

JSON-RPC 2.0 defines a standard request and response format, and is a breath of fresh air after working with REST APIs.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

Unknown column in 'field list' error on MySQL Update query

Just sharing my experience on this. I was having this same issue. My query was like:

select table1.column2 from table1

However, table1 did not have column2 column.

TypeError: 'list' object cannot be interpreted as an integer

Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.

So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.

Hashing with SHA1 Algorithm in C#

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
    byte[] data = UTF8Encoding.UTF8.GetBytes (str);
    data = data.Sha1Hash ();
    return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
    using (SHA1Managed sha1 = new SHA1Managed ()) {
    return sha1.ComputeHash (data);
}

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01 to 9999-12-31.

DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59.

TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.

TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59 to 838:59:59. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

Java - Convert int to Byte Array of 4 Bytes?

This should work:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

Code taken from here.

Edit An even simpler solution is given in this thread.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

The first suggestion in latkin's answer seems good, although I would suggest the less long-winded way below.

PS c:\temp> $global:test="one"

PS c:\temp> $test
one

PS c:\temp> function changet() {$global:test="two"}

PS c:\temp> changet

PS c:\temp> $test
two

His second suggestion however about being bad programming practice, is fair enough in a simple computation like this one, but what if you want to return a more complicated output from your variable? For example, what if you wanted the function to return an array or an object? That's where, for me, PowerShell functions seem to fail woefully. Meaning you have no choice other than to pass it back from the function using a global variable. For example:

PS c:\temp> function changet([byte]$a,[byte]$b,[byte]$c) {$global:test=@(($a+$b),$c,($a+$c))}

PS c:\temp> changet 1 2 3

PS c:\temp> $test
3
3
4

PS C:\nb> $test[2]
4

I know this might feel like a bit of a digression, but I feel in order to answer the original question we need to establish whether global variables are bad programming practice and whether, in more complex functions, there is a better way. (If there is one I'd be interested to here it.)

Java string replace and the NUL (NULL, ASCII 0) character?

I think it should be the case. To erase the character, you should use replace(".", "") instead.

List of enum values in java

It is possible but you should use EnumSet instead

enum MyEnum {
    ONE, TWO;
    public static final EnumSet<MyEnum> all = EnumSet.of(ONE, TWO);
}

How do I run a program with a different working directory from current, from Linux shell?

If you want to perform this inside your program then I would do something like:

#include <unistd.h>
int main()
{
  if(chdir("/c") < 0 )  
  {
     printf("Failed\n");
     return -1 ;
  }

  // rest of your program...

}

How to Create a real one-to-one relationship in SQL Server

There is one way I know how to achieve a strictly* one-to-one relationship without using triggers, computed columns, additional tables, or other 'exotic' tricks (only foreign keys and unique constraints), with one small caveat.

I will borrow the chicken-and-the-egg concept from the accepted answer to help me explain the caveat.

It is a fact that either a chicken or an egg must come first (in current DBs anyway). Luckily this solution does not get political and does not prescribe which has to come first - it leaves it up to the implementer.

The caveat is that the table which allows a record to 'come first' technically can have a record created without the corresponding record in the other table; however, in this solution, only one such record is allowed. When only one record is created (only chicken or egg), no more records can be added to any of the two tables until either the 'lonely' record is deleted or a matching record is created in the other table.

Solution:

Add foreign keys to each table, referencing the other, add unique constraints to each foreign key, and make one foreign key nullable, the other not nullable and also a primary key. For this to work, the unique constrain on the nullable column must only allow one null (this is the case in SQL Server, not sure about other databases).

CREATE TABLE dbo.Egg (
    ID int identity(1,1) not null,
    Chicken int null,
    CONSTRAINT [PK_Egg] PRIMARY KEY CLUSTERED ([ID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE dbo.Chicken (
    Egg int not null,
    CONSTRAINT [PK_Chicken] PRIMARY KEY CLUSTERED ([Egg] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE dbo.Egg  WITH NOCHECK ADD  CONSTRAINT [FK_Egg_Chicken] FOREIGN KEY([Chicken]) REFERENCES [dbo].[Chicken] ([Egg])
GO
ALTER TABLE dbo.Chicken  WITH NOCHECK ADD  CONSTRAINT [FK_Chicken_Egg] FOREIGN KEY([Egg]) REFERENCES [dbo].[Egg] ([ID])
GO
ALTER TABLE dbo.Egg WITH NOCHECK ADD CONSTRAINT [UQ_Egg_Chicken] UNIQUE([Chicken])
GO
ALTER TABLE dbo.Chicken WITH NOCHECK ADD CONSTRAINT [UQ_Chicken_Egg] UNIQUE([Egg])
GO

To insert, first an egg must be inserted (with null for Chicken). Now, only a chicken can be inserted and it must reference the 'unclaimed' egg. Finally, the added egg can be updated and it must reference the 'unclaimed' chicken. At no point can two chickens be made to reference the same egg or vice-versa.

To delete, the same logic can be followed: update egg's Chicken to null, delete the newly 'unclaimed' chicken, delete the egg.

This solution also allows swapping easily. Interestingly, swapping might be the strongest argument for using such a solution, because it has a potential practical use. Normally, in most cases, a one-to-one relationship of two tables is better implemented by simply refactoring the two tables into one; however, in a potential scenario, the two tables may represent truly distinct entities, which require a strict one-to-one relationship, but need to frequently swap 'partners' or be re-arranged in general, while still maintaining the one-to-one relationship after re-arrangement. If the more common solution were used, all data columns of one of the entities would have to be updated/overwritten for all pairs being re-arranged, as opposed to this solution, where only one column of foreign keys need to be re-arranged (the nullable foreign key column).

Well, this is the best I could do using standard constraints (don't judge :) Maybe someone will find it useful.

How do I enumerate the properties of a JavaScript object?

If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually.

Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values.

var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
Object.toJSON(data);
//-> '{"name": "Violet", "occupation": "character", "age": 25, "pets": ["frog","rabbit"]}'

http://www.prototypejs.org/api/object/tojson

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

If you are using bootstrap that will be the problem. If you want to use same bootstrap file in two locations use it below the header section .(example - inside body)

Note : "specially when you use html editors. "

Thank you.

Javascript Date: next month

If you are able to get your hands on date-fns library v2+, you can import the function addMonths, and use that to get the next month

_x000D_
_x000D_
<script type="module">
  import { addMonths } from 'https://cdn.jsdelivr.net/npm/date-fns/+esm'; 
  
  const current = new Date();
  const nextMonth = addMonths(current, 1);
  console.log(`Next month is ${nextMonth}`);
</script>
_x000D_
_x000D_
_x000D_

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

Using Bootstrap Tooltip with AngularJS

I wrote a simple Angular Directive that's been working well for us.

Here's a demo: http://jsbin.com/tesido/edit?html,js,output

Directive (for Bootstrap 3):

// registers native Twitter Bootstrap 3 tooltips
app.directive('bootstrapTooltip', function() {
  return function(scope, element, attrs) {
    attrs.$observe('title',function(title){
      // Destroy any existing tooltips (otherwise new ones won't get initialized)
      element.tooltip('destroy');
      // Only initialize the tooltip if there's text (prevents empty tooltips)
      if (jQuery.trim(title)) element.tooltip();
    })
    element.on('$destroy', function() {
      element.tooltip('destroy');
      delete attrs.$$observers['title'];
    });
  }
});

Note: If you're using Bootstrap 4, on lines 6 & 11 above you'll need to replace tooltip('destroy') with tooltip('dispose') (Thanks to user1191559 for this upadate)

Simply add bootstrap-tooltip as an attribute to any element with a title. Angular will monitor for changes to the title but otherwise pass the tooltip handling over to Bootstrap.

This also allows you to use any of the native Bootstrap Tooltip Options as data- attributes in the normal Bootstrap way.

Markup:

<div bootstrap-tooltip data-placement="left" title="Tooltip on left">
        Tooltip on left
</div>

Clearly this doesn't have all the elaborate bindings & advanced integration that AngularStrap and UI Bootstrap offer, but it's a good solution if you're already using Bootstrap's JS in your Angular app and you just need a basic tooltip bridge across your entire app without modifying controllers or managing mouse events.

Fitting a density curve to a histogram in R

Such thing is easy with ggplot2

library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5), 
                            rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..)) + 
  geom_density()

or to mimic the result from Dirk's solution

ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..), binwidth = 5) + 
  geom_density()

Hide Text with CSS, Best Practice?

Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

It is accessible, an has better performance than -99999px.

Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.

How to make a phone call programmatically?

Solved..! September 5, 2020.

It is working very well. In this way, you do not need to have permission from user. You can open directly phone calling part.

Trick point, use ACTION_DIAL instead of ACTION_CALL.

private void callPhoneNumber() {
    String phone = "03131693169";
    Intent callIntent = new Intent(Intent.ACTION_DIAL);
    callIntent.setData(Uri.parse("tel:" + phone));
    startActivity(callIntent);
}

For more question, ask me on Instagram: @canerkaseler

Spring: How to get parameters from POST body?

You can bind the json to a POJO using MappingJacksonHttpMessageConverter . Thus your controller signature can read :-

  public ResponseEntity<Boolean> saveData(@RequestBody RequestDTO req) 

Where RequestDTO needs to be a bean appropriately annotated to work with jackson serializing/deserializing. Your *-servlet.xml file should have the Jackson message converter registered in RequestMappingHandler as follows :-

  <list >
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

  </list>
</property>
</bean>

Checking the equality of two slices

And for now, here is https://github.com/google/go-cmp which

is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.

package main

import (
    "fmt"

    "github.com/google/go-cmp/cmp"
)

func main() {
    a := []byte{1, 2, 3}
    b := []byte{1, 2, 3}

    fmt.Println(cmp.Equal(a, b)) // true
}

How do I check two or more conditions in one <c:if>?

If you are using JSP 2.0 and above It will come with the EL support: so that you can write in plain english and use and with empty operators to write your test:

<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">

How do I return the SQL data types from my query?

I use a simple case statement to render results I can use in technical specification documents. This example does not contain every condition you will run into with a database, but it gives you a good template to work with.

SELECT
     TABLE_NAME          AS 'Table Name',
     COLUMN_NAME         AS 'Column Name',
     CASE WHEN DATA_TYPE LIKE '%char'
          THEN DATA_TYPE + '(' + CONVERT(VARCHAR, CHARACTER_MAXIMUM_LENGTH) + ')'
          WHEN DATA_TYPE IN ('bit', 'int', 'smallint', 'date')
          THEN DATA_TYPE
          WHEN DATA_TYPE = 'datetime'
          THEN DATA_TYPE + '(' + CONVERT(VARCHAR, DATETIME_PRECISION) + ')'
          WHEN DATA_TYPE = 'float'
          THEN DATA_TYPE
          WHEN DATA_TYPE IN ('numeric', 'money')
          THEN DATA_TYPE + '(' + CONVERT(VARCHAR, NUMERIC_PRECISION) + ', ' + CONVERT(VARCHAR, NUMERIC_PRECISION_RADIX) + ')'
     END                 AS 'Data Type',
     CASE WHEN IS_NULLABLE = 'NO'
          THEN 'NOT NULL'
          ELSE 'NULL'
     END                 AS 'PK/LK/NOT NULL'
FROM INFORMATION_SCHEMA.COLUMNS 
ORDER BY 
     TABLE_NAME, ORDINAL_POSITION

JQuery - Set Attribute value

Seriously, just don't use jQuery for this. disabled is a boolean property of form elements that works perfectly in every major browser since 1997, and there is no possible way it could be simpler or more intuitive to change whether or not a form element is disabled.

The simplest way of getting a reference to the checkbox would be to give it an id. Here's my suggested HTML:

<input type="hidden" name="chk0" value="">
<input type="checkbox" name="chk0" id="chk0_checkbox" value="true" disabled>

And the line of JavaScript to make the check box enabled:

document.getElementById("chk0_checkbox").disabled = false;

If you prefer, you can instead use jQuery to get hold of the checkbox:

$("#chk0_checkbox")[0].disabled = false;

Find and replace words/lines in a file

You can use Java's Scanner class to parse words of a file and process them in your application, and then use a BufferedWriter or FileWriter to write back to the file, applying the changes.

I think there is a more efficient way of getting the iterator's position of the scanner at some point, in order to better implement editting. But since files are either open for reading, or writing, I'm not sure regarding that.

In any case, you can use libraries already available for parsing of XML files, which have all of this implemented already and will allow you to do what you want easily.

How to read data from excel file using c#

Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

Finding median of list in Python

Here what I came up with during this exercise in Codecademy:

def median(data):
    new_list = sorted(data)
    if len(new_list)%2 > 0:
        return new_list[len(new_list)/2]
    elif len(new_list)%2 == 0:
        return (new_list[(len(new_list)/2)] + new_list[(len(new_list)/2)-1]) /2.0

print median([1,2,3,4,5,9])

How to check if a string is numeric?

Simple method:

public boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}


public boolean isOnlyNumber(String value) {
    boolean ret = false;
    if (!isBlank(value)) {
        ret = value.matches("^[0-9]+$");
    }
    return ret;
}