Programs & Examples On #Or designer

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

Cannot find vcvarsall.bat when running a Python script

Note that there is a very simple solution.

  1. Download the software from http://www.microsoft.com/en-us/download/details.aspx?id=44266 and install it.

  2. Find the installing directory, it is something like "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python"

  3. Change the directory name "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0" to "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC"

  4. Add a new environment variable "VS90COMNTOOLS" and its value is "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC\VC"

Now everything is OK.

PHP array: count or sizeof?

Please use count function, Here is a example how to count array in a element

$cars = array("Volvo","BMW","Toyota");
echo count($cars);

The count() function returns the number of elements in an array.

The sizeof() function returns the number of elements in an array.

The sizeof() function is an alias of the count() function.

is there any alternative for ng-disabled in angular2?

Here is a solution am using with anular 6.

[readonly]="DateRelatedObject.bool_DatesEdit ? true : false"

plus above given answer

[attr.disabled]="valid == true ? true : null"

did't work for me plus be aware of using null cause it's expecting bool.

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

Correct way to create rounded corners in Twitter Bootstrap

In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:

For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom" 
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"

To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.

*Note that the bottom tag of the three is the same as the first tag in the first link path.

A full working example, could be :

<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">

In the above example, the image is centered by using the Bootstrap auto margin on left and right.

Count number of records returned by group by

A CTE worked for me:

with cte as (
  select 1 col1
  from temptable
  group by column_1
)

select COUNT(col1)
from cte;

Excel SUMIF between dates

I found another way to work around this issue that I thought I would share.

In my case I had a years worth of daily columns (i.e. Jan-1, Jan-2... Dec-31), and I had to extract totals for each month. I went about it this way: Sum the entire year, Subtract out the totals for the dates prior and the dates after. It looks like this for February's totals:

=SUM($P3:$NP3)-(SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3)+SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3))

Where $P$2:$NP$2 contained my date values and $P3:$NP3 was the first row of data I am totaling. So SUM($P3:$NP3) is my entire year's total and I subtract (the sum of two sumifs):

SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3), which totals all the months after February and SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3), which totals all the months before February.

How to implement the Java comparable interface?

Emp class needs to implement Comaparable interface so we need to Override its compateTo method.

import java.util.ArrayList;
import java.util.Collections;


class Emp implements Comparable< Emp >{

    int empid;
    String name;

    Emp(int empid,String name){
         this.empid = empid;  
         this.name = name;

    }


    @Override
    public String toString(){
        return empid+" "+name;
    }

    @Override
    public int compareTo(Emp o) {

     if(this.empid==o.empid){
       return 0; 
     } 
     else if(this.empid < o.empid){
     return 1;
     }
     else{
       return -1;
     }
    }
}

public class JavaApplication1 {


    public static void main(String[] args) {

    ArrayList<Emp> a= new ArrayList<Emp>();

    a.add(new Emp(10,"Mahadev"));
      a.add(new Emp(50,"Ashish"));
      a.add(new Emp(40,"Amit"));
      Collections.sort(a);
      for(Emp id:a){
      System.out.println(id);
      }
    }

}

How to set a JavaScript breakpoint from code in Chrome?

There are many ways to debug JavaScript code. Following two approaches are widely used to debug JavaScript via code

  1. Using console.log() to print out the values in the browser console. (This will help you understand the values at certain points of your code)

  2. Debugger keyword. Add debugger; to the locations you want to debug, and open the browser's developer console and navigate to the sources tab.

For more tools and ways in which you debug JavaScript Code, are given in this link by W3School.

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

This expression will check if the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,

^[A-Za-z][A-Za-z0-9@#%&\*]*$

How to check list A contains any value from list B?

If you didn't care about performance, you could try:

a.Any(item => b.Contains(item))
// or, as in the column using a method group
a.Any(b.Contains)

But I would try this first:

a.Intersect(b).Any()

Get the number of rows in a HTML table

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
<!--
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');
//-->
</script>

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.

select constraint_name from all_cons_columns where table_name = [TABLE_NAME] and column_name = [COLUMN_NAME];

Sublime Text 2: How to delete blank/empty lines

Their is a more easily way to do that without regex. you have just to select the whole text. then go to: Edit--> Permute Lines --> Unique.

That's all. and all blank lines will be deleted.

Correct way to detach from a container without stopping it

In Docker container atleast one process must be run, then only the container will be running the docker image(ubuntu,httd..etc, whatever it is) at background without exiting

For example in ubuntu docker image ,

To create a new container with detach mode (running background atleast on process),

docker run -d -i -t f63181f19b2f /bin/bash

it will create a new contain for this image(ubuntu) id f63181f19b2f . The container will run in the detached mode (running in background) at that time a small process tty bash shell will be running at background. so, container will keep on running untill the bash shell process will killed.

To attach to the running background container,use

docker attach  b1a0873a8647

if you want to detach from container without exiting(without killing the bash shell), By default , you can use ctrl-p,q. it will come out of container without exiting from the container(running background. that means without killing the bash shell).

You can pass the custom command during attach time to container,

docker attach --detach-keys="ctrl-s" b1a0873a8647

this time ctrl-p,q escape sequence won't work. instead, ctrl-s will work for exiting from container. you can pass any key eg, (ctrl-*)

jQuery: how to get which button was clicked upon form submission?

You can simply get the event object when you submit the form. From that, get the submitter object. As below:

$(".review-form").submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        let submitter_btn = $(e.originalEvent.submitter);
        
        console.log(submitter_btn.attr("name"));
}

In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -

$(".review-form").submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        let form = $(this);
        let newForm = new FormData($(form)[0]);
        let submitter_btn = $(e.originalEvent.submitter);
        
        console.log(submitter_btn.attr("name"));

        if (submitter_btn.attr("name") == "approve_btn") {
            newForm.set("action_for", submitter_btn.attr("name"));
        } else if (submitter_btn.attr("name") == "reject_btn") {
            newForm.set("action_for", submitter_btn.attr("name"));
        } else {
            console.log("there is some error!");
            return;
        }
}

I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task. My HTML form is something like this -

<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
    class="review-form">
    {% csrf_token %}
    <input type="hidden" name="product_id" value="{{product.product_id}}" />
    <input type="hidden" name="task_id" value="{{product.task_id_id}}" />
    <button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
        <i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
    </button>
    <button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
            <i class="fa fa-times" style="color: red;"></i>
    </button>
</form>

Let me know if you have any doubts.

Node Version Manager (NVM) on Windows

The first thing that we need to do is install NVM.

  1. Uninstall existing version of node since we won’t be using it anymore
  2. Delete any existing nodejs installation directories. e.g. “C:\Program Files\nodejs”) that might remain. NVM’s generated symlink will not overwrite an existing (even empty) installation directory.
  3. Delete the npm install directory at C:\Users[Your User]\AppData\Roaming\npm We are now ready to install nvm. Download the installer from https://github.com/coreybutler/nvm/releases

To upgrade, run the new installer. It will safely overwrite the files it needs to update without touching your node.js installations. Make sure you use the same installation and symlink folder. If you originally installed to the default locations, you just need to click “next” on each window until it finishes.

Credits Directly copied from : https://digitaldrummerj.me/windows-running-multiple-versions-of-node/

Convert objective-c typedef to its string equivalent

the following provides a solution such that to add a new enum requires only a one-line edit, similar work to adding a single line in an enum {} list.

//------------------------------------------------------------------------------
// enum to string example
#define FOR_EACH_GENDER(tbd) \
        tbd(GENDER_MALE) \
        tbd(GENDER_FEMALE) \
        tbd(GENDER_INTERSEX) \

#define ONE_GENDER_ENUM(name) name,
enum
{
    FOR_EACH_GENDER(ONE_GENDER_ENUM)
    MAX_GENDER
};

#define ONE_GENDER(name) #name,
static const char *enumGENDER_TO_STRING[] = 
{
    FOR_EACH_GENDER(ONE_GENDER)
};

// access string name with enumGENDER_TO_STRING[value]
// or, to be safe converting from a untrustworthy caller
static const char *enumGenderToString(unsigned int value)
{
    if (value < MAX_GENDER)
    {
        return enumGENDER_TO_STRING[value];
    }
    return NULL;
}

static void printAllGenders(void)
{
    for (int ii = 0;  ii < MAX_GENDER;  ii++)
    {
        printf("%d) gender %s\n", ii, enumGENDER_TO_STRING[ii]);
    }
}

//------------------------------------------------------------------------------
// you can assign an arbitrary value and/or information to each enum,
#define FOR_EACH_PERSON(tbd) \
        tbd(2, PERSON_FRED,     "Fred",     "Weasley", GENDER_MALE,   12) \
        tbd(4, PERSON_GEORGE,   "George",   "Weasley", GENDER_MALE,   12) \
        tbd(6, PERSON_HARRY,    "Harry",    "Potter",  GENDER_MALE,   10) \
        tbd(8, PERSON_HERMIONE, "Hermione", "Granger", GENDER_FEMALE, 10) \

#define ONE_PERSON_ENUM(value, ename, first, last, gender, age) ename = value,
enum
{
    FOR_EACH_PERSON(ONE_PERSON_ENUM)
};

typedef struct PersonInfoRec
{
    int value;
    const char *ename;
    const char *first;
    const char *last;
    int gender;
    int age;
} PersonInfo;

#define ONE_PERSON_INFO(value, ename, first, last, gender, age) \
                     { ename, #ename, first, last, gender, age },
static const PersonInfo personInfo[] = 
{
    FOR_EACH_PERSON(ONE_PERSON_INFO)
    { 0, NULL, NULL, NULL, 0, 0 }
};
// note: if the enum values are not sequential, you need another way to lookup
// the information besides personInfo[ENUM_NAME]

static void printAllPersons(void)
{
    for (int ii = 0;  ;  ii++)
    {
        const PersonInfo *pPI = &personInfo[ii];
        if (!pPI->ename)
        {
            break;
        }
        printf("%d) enum %-15s  %8s %-8s %13s %2d\n",
            pPI->value, pPI->ename, pPI->first, pPI->last,
            enumGenderToString(pPI->gender), pPI->age);
    }
}

PHP, Get tomorrows date from date

<? php 

//1 Day = 24*60*60 = 86400

echo date("d-m-Y", time()+86400); 

?>

Concatenate two slices in Go

append( ) function and spread operator

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation. So we need to use ...

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

output of the above code is: [1 2 3 4 5 6]

How to see the changes in a Git commit?

From the man page for git-diff(1):

git diff [options] [<commit>] [--] [<path>…]
git diff [options] --cached [<commit>] [--] [<path>…]
git diff [options] <commit> <commit> [--] [<path>…]
git diff [options] <blob> <blob>
git diff [options] [--no-index] [--] <path> <path>

Use the 3rd one in the middle:

git diff [options] <parent-commit> <commit>

Also from the same man page, at the bottom, in the Examples section:

$ git diff HEAD^ HEAD      <3>

Compare the version before the last commit and the last commit.

Admittedly it's worded a little confusingly, it would be less confusing as

Compare the most recent commit with the commit before it.

Mysql - How to quit/exit from stored procedure

I think this solution is handy if you can test the value of the error field later. This is also applicable by creating a temporary table and returning a list of errors.

DROP PROCEDURE IF EXISTS $procName;
DELIMITER //
CREATE PROCEDURE $procName($params)
BEGIN
    DECLARE error INT DEFAULT 0;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET error = 1;
    SELECT
       $fields
    FROM $tables
    WHERE $where
    ORDER BY $sorting LIMIT 1
    INTO $vars;
    IF error = 0 THEN
       SELECT $vars;
    ELSE
       SELECT 1 AS error;
       SET @error = 0;
    END IF;
END//
CALL $procName($effp);

window.open target _self v window.location.href?

As others have said, the second approach is usually preferred.

The two code snippets are not exactly equivalent however: the first one actually sets window.opener to the window object itself, whereas the second will leave it as it is, at least under Firefox.

Setting Windows PATH for Postgres tools

Incase any one still wondering how to add environment variables then please use this link to add variables. Link: https://sqlbackupandftp.com/blog/setting-windows-path-for-postgres-tools

Empty an array in Java / processing

I was able to do that with the following 2 lines, I had an array called selected_items used to get all selected items on a dataTable

selected_items = null;
selected_items = [];

How to search contents of multiple pdf files?

If You want to see file names with pdftotext use following command:

find . -name '*.pdf' -exec echo {} \; -exec pdftotext {} - \; | grep "pattern\|pdf" 

View array in Visual Studio debugger?

Hover your mouse cursor over the name of the array, then hover over the little (+) icon that appears.

ERROR! MySQL manager or server PID file could not be found! QNAP

Just run mysqld (don't run as root) from your terminal. Your mysql server will restart and reset everything like shown in the picture below:

enter image description here

And use a command like so:

mysql -u root -h 127.0.0.1

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Make Https call using HttpClient

There is a non-global setting at the level of HttpClientHandler:

var handler = new HttpClientHandler()
{
    SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
};

var client = new HttpClient(handler);

Thus one enables latest TLS versions.

Note, that the default value SslProtocols.Default is actually SslProtocols.Ssl3 | SslProtocols.Tls (checked for .Net Core 2.1 and .Net Framework 4.7.1).

"Could not find a version that satisfies the requirement opencv-python"

Install it by using this command:

pip install opencv-contrib-python

Elastic Search: how to see the indexed data

A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.

Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.

Installing python module within code

You can also use something like:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

How do I generate a random number between two variables that I have stored?

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber

connecting MySQL server to NetBeans

I just had the same issue with Netbeans 8.2 and trying to connect to mySQL server on a Mac OS machine. The only thing that worked for me was to add the following to the url of the connection string: &serverTimezone=UTC (or if you are connecting via Hibernate.cfg.xml then escape the & as &) Not surprisingly I found the solution on this stack overflow post also:

MySQL JDBC Driver 5.1.33 - Time Zone Issue

Best Regards, Claudio

tsql returning a table from a function or store procedure

You can't access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:

ALTER FUNCTION FnGetCompanyIdWithCategories()
RETURNS  @rtnTable TABLE 
(
    -- columns returned by the function
    ID UNIQUEIDENTIFIER NOT NULL,
    Name nvarchar(255) NOT NULL
)
AS
BEGIN
DECLARE @TempTable table (id uniqueidentifier, name nvarchar(255)....)

insert into @myTable 
select from your stuff

--This select returns data
insert into @rtnTable
SELECT ID, name FROM @mytable 
return
END

Edit

Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.

declare @table as table (id int, name nvarchar(50),templateid int,account nvarchar(50))

insert into @table
execute industry_getall

select * 
from @table 
inner join [user] 
    on account=[user].loginname

In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let's look at how you would do this if you were using a UDF

select *
from fn_Industry_GetAll()
inner join [user] 
    on account=[user].loginname

As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you're not using the secondary temporary table (performance is a complete guess on my part).

If you're going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you're indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.

How to disable an input box using angular.js

You need to use ng-disabled directive

<input data-ng-model="userInf.username" 
       class="span12 editEmail" 
       type="text" 
       placeholder="[email protected]" 
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="<expression to disable>" />

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

using namespaces and subqueries You can do it:

declare @data table (RequestID varchar(20), CreatedDate datetime, HistoryStatus varchar(20))
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','For Review');
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','Completed');  
insert into @data values ('CF-0000112','8/26/2009 1:07:01 PM','For Review');   
insert into @data values ('CF-0000113','8/26/2009 1:07:01 PM','For Review');  
insert into @data values ('CF-0000114','8/26/2009 1:07:01 PM','Completed');  
insert into @data values ('CF-0000115','8/26/2009 1:07:01 PM','Completed');

select d1.RequestID,d1.CreatedDate,d1.HistoryStatus 
from @data d1 
where d1.HistoryStatus = 'Completed'
union all 
select d2.RequestID,d2.CreatedDate,d2.HistoryStatus 
from @data d2 
where d2.HistoryStatus = 'For Review' 
    and d2.RequestID not in (
        select RequestID 
        from @data 
        where HistoryStatus = 'Completed' 
            and CreatedDate = d2.CreatedDate
    )

Above query returns

CF-0000001, 2009-08-26 13:07:01.000,    Completed
CF-0000114, 2009-08-26 13:07:01.000,    Completed
CF-0000115, 2009-08-26 13:07:01.000,    Completed
CF-0000112, 2009-08-26 13:07:01.000,    For Review
CF-0000113, 2009-08-26 13:07:01.000,    For Review

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

Swift apply .uppercaseString to only the first letter of a string

Swift 2.0 (Single line):

String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst())

How to lazy load images in ListView in Android

Novoda also has a great lazy image loading library and many apps like Songkick, Podio, SecretDJ and ImageSearch use their library.

Their library is hosted here on Github and they have a pretty active issues tracker as well. Their project seems to be pretty active too, with over 300+ commits at the time of writing this reply.

I want to load another HTML page after a specific amount of time

<meta http-equiv="refresh" content="5;URL='form2.html'">

Is there a way to create key-value pairs in Bash script?

If you can use a simple delimiter, a very simple oneliner is this:

for i in a,b c_s,d ; do 
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Hereby i is filled with character sequences like "a,b" and "c_s,d". each separated by spaces. After the do we use parameter substitution to extract the part before the comma , and the part after it.

How to list records with date from the last 10 days?

My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:

SELECT Table.date
  FROM Table 
  WHERE date > current_date - interval '10 day';

Demonstrated here (you should be able to run this on any Postgres db):

SELECT DISTINCT current_date, 
                current_date - interval '10' day, 
                current_date - interval '10 days' 
  FROM pg_language;

Result:

2013-03-01  2013-03-01 00:00:00 2013-02-19 00:00:00

Deleting an SVN branch

You can also delete the branch on the remote directly. Having done that, the next update will remove it from your working copy.

svn rm "^/reponame/branches/name_of_branch" -m "cleaning up old branch name_of_branch"

The ^ is short for the URL of the remote, as seen in 'svn info'. The double quotes are necessary on Windows command line, because ^ is a special character.

This command will also work if you have never checked out the branch.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

  1. Right-click on your project
  2. Click Properties
  3. Click the "Java Compiler" option on the left menu
  4. Under JDK compliance section on the right, change it to "1.7"
  5. Run a Maven clean and then Maven build.

Is there a way to specify a max height or width for an image?

editied to add support for ie6:

Try

<img style="height:725px;max-width:500px;width: expression(this.width > 500 ? 500: true);" id="img_DocPreview" src="Images/empty.jpg" />

This should set the height to 725px but prevent the width from exceeding 500px. The width expression works around ie6 and is ignored by other browsers.

How to parse SOAP XML?

One of the simplest ways to handle namespace prefixes is simply to strip them from the XML response before passing it through to simplexml such as below:

$your_xml_response = '<Your XML here>';
$clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $your_xml_response);
$xml = simplexml_load_string($clean_xml);

This would return the following:

SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
            [PaymentNotification] => SimpleXMLElement Object
                (
                    [payment] => SimpleXMLElement Object
                        (
                            [uniqueReference] => ESDEUR11039872
                            [epacsReference] => 74348dc0-cbf0-df11-b725-001ec9e61285
                            [postingDate] => 2010-11-15T15:19:45
                            [bankCurrency] => EUR
                            [bankAmount] => 1.00
                            [appliedCurrency] => EUR
                            [appliedAmount] => 1.00
                            [countryCode] => ES
                            [bankInformation] => Sean Wood
                            [merchantReference] => ESDEUR11039872
                        )

                )

        )

)

Map with Key as String and Value as List in Groovy

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

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

You can do the following:

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

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

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

Map -> withDefault(Closure)

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:

<table align='center' style='text-align:center'>
  <tr>
    <td align='center' style='text-align:center'>
      <!-- AMAZING CONTENT! -->
    </td>
  </tr>
</table>

I only listed some of the key things that resolved my Microsoft email issues.

Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/

It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.

"Cannot GET /" with Connect on Node.js

var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect(); 
app.use(serveStatic('../angularjs'),  {default: 'angular.min.js'}); app.listen(3000); 

finished with non zero exit value

Looks like it could be caused by different root causes. While in my case, it's caused by "Windows OS cannot handle the path which is too long", so the "aapt.exe" reported that error message:

http://start-coding.blogspot.com/2015/07/android-development-in-windows-using.html

ICommand MVVM implementation

@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel

First implement ICommand

public class Command : ICommand
{
    public delegate void ICommandOnExecute();
    public delegate bool ICommandOnCanExecute();

    private ICommandOnExecute _execute;
    private ICommandOnCanExecute _canExecute;

    public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
    {
        _execute = onExecuteMethod;
        _canExecute = onCanExecuteMethod;
    }

    #region ICommand Members

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke() ?? true;
    }

    public void Execute(object parameter)
    {
        _execute?.Invoke();
    }

    #endregion
}

Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor

Then to use in the ViewModel

public Command CommandToRun_WithCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        }, () =>
        {
            // Code to check to see if we can run 
            // Return true or false
        });
    }
}

public Command CommandToRun_NoCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        });
    }
}

I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.

How To Set Text In An EditText

String text = "Example";
EditText edtText = (EditText) findViewById(R.id.edtText);
edtText.setText(text);

Check it out EditText accept only String values if necessary convert it to string.

If int, double, long value, do:

String.value(value);

Tesseract OCR simple example

Try updating the line to:

ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

Permissions error when connecting to EC2 via SSH on Mac OSx

If the issue is consistent and happened about 10-15 times in a row even after changing file permissions to 400 or 600, then it is most certainly something is wrong on the ec2 instance, so to make sure:

  1. Check the logs when you try to ssh to the instance by adding -v at the end and see either it gives out anything specific.

  2. Make sure you use the correct name for ssh, like Ubuntu. Perhaps that depends on Linux distribution and users you added and either you've given permission for "root user" ssh.

Then if nothing helps, follow the documentation here https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#TroubleshootingInstancesConnectingMindTerm to fix that. It helped in my case, and it happened because of messed up directories/files permissions.

How do I set multipart in axios with react?

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

Convert hex string (char []) to int?

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

unsigned hexdec (const char *hex, const int s_hex);

Before the first conversion intialize the array used for conversion with :

void init_hexdec ();

Here the link on github : https://github.com/kevmuret/libhex/

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

How to style readonly attribute with CSS?

Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

Same behavior in Firefox 14 and Chrome 20.

To be on the safe side, i use both selectors.

textarea[readonly="readonly"], textarea[readonly] {
...
}

Where do I find the definition of size_t?

In minimalistic programs where a size_t definition was not loaded "by chance" in some include but I still need it in some context (for example to access std::vector<double>), then I use that context to extract the correct type. For example typedef std::vector<double>::size_type size_t.

(Surround with namespace {...} if necessary to make the scope limited.)

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

Strip / trim all strings of a dataframe

If you really want to use regex, then

>>> df.replace('(^\s+|\s+$)', '', regex=True, inplace=True)
>>> df
   0   1
0  a  10
1  c   5

But it should be faster to do it like this:

>>> df[0] = df[0].str.strip()

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

How to get rid of the "No bootable medium found!" error in Virtual Box?

Follow the steps below:

1) Select your VM Instance. Go to Settings->Storage

2) Under the storage tree select the default image or "Empty"(which ever is present)

3) Under the attributes frame, click on the CD image and select "Choose a virtual CD/DVD disk file"

4) Browse and select the image file(iso or what ever format) from the system

5) Select OK.

Abishek's solution is correct. But the highlighted area in 2nd image could be misleading.

How can I configure Logback to log different levels for a logger to different destinations?

okay, here is my favorite xml way of doing it. I do this for the eclipse version so I can

  • click on stuff to take me to the log statements and
  • see info and below in black and warn/severe in red

and for some reason SO is not showing this all properly but most seems to be there...

<configuration scan="true" scanPeriod="30 seconds">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      
          <evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator"> 
            <expression>
               e.level.toInt() &lt;= INFO.toInt()
            </expression>
          </evaluator>
          <OnMismatch>DENY</OnMismatch>
          <OnMatch>NEUTRAL</OnMatch>
        </filter>

        <encoder>
            <pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> 
            <level>warn</level>
        </filter>

        <encoder>
            <pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
        </encoder>
        <target>System.err</target>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STDERR"/>
    </root>
</configuration>

How to solve SyntaxError on autogenerated manage.py?

Make sure which python version you connect the django with (Make sure to activate the virtual env if you are using any).

When you install django using just

pip install django 

then you have to run

python manage.py startapp <yourApp name>

else if you have used:

pip3 install django

then you have to run

python3 manage.py startapp <yourapp name>

Refer:
enter image description here

How do I view events fired on an element in Chrome DevTools?

For jQuery (at least version 1.11.2) the following procedure worked for me.

  1. Right click on the element and open 'Chrome Developer Tools'
  2. Type $._data(($0), 'events'); in the 'Console'
  3. Expand the attached objects and double click the handler: value.
  4. This shows the source code of the attached function, search for part of that using the 'Search' tab.

And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)

how-to-find-jquery-click-handler-function

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

sizing div based on window width

Try absolute positioning:

<div style="position:relative;width:100%;">
    <div id="help" style="
    position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index:1;">
        <img src="/portfolio/space_1_header.png" border="0" style="width:100%;">
    </div>
</div>

Graphviz: How to go from .dot to a graph?

You can also output your file in xdot format, then render it in a browser using canviz, a JavaScript library.

Canviz on code.google.com:

To see an example, there is a "Canviz Demo" link on the page above as of November 2, 2014.

Executing multiple commands from a Windows cmd script

When you call another .bat file, I think you need "call" in front of the call:

call otherCommand.bat

Convert varchar into datetime in SQL Server

The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilà.

Wampserver icon not going green fully, mysql services not starting up?

I had the same problem. Mysql didn't start.

  1. go to services.
  2. right click the wampmysqld go to properties.
  3. startup type select manual.
  4. right click and click start service.

worked for me.

How do I enable MSDTC on SQL Server?

Can also see here on how to turn on MSDTC from the Control Panel's services.msc.

On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.

How to align content of a div to the bottom

Relative+absolute positioning is your best bet:

_x000D_
_x000D_
#header {_x000D_
  position: relative;_x000D_
  min-height: 150px;_x000D_
}_x000D_
_x000D_
#header-content {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
#header, #header * {_x000D_
  background: rgba(40, 40, 100, 0.25);_x000D_
}
_x000D_
<div id="header">_x000D_
  <h1>Title</h1>_x000D_
  <div id="header-content">Some content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But you may run into issues with that. When I tried it I had problems with dropdown menus appearing below the content. It's just not pretty.

Honestly, for vertical centering issues and, well, any vertical alignment issues with the items aren't fixed height, it's easier just to use tables.

Example: Can you do this HTML layout without using tables?

Fatal error: Class 'ZipArchive' not found in

On ubuntu desktop, I had to do.

sudo apt-get install php5.6-zip

This installed the library but I still kept on getting the same error, so I had to restart apache using:

sudo service apache2 restart

and it worked.

How can I know if a process is running?

This is a way to do it with the name:

Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("nothing");
else
  MessageBox.Show("run");

You can loop all process to get the ID for later manipulation:

Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}

can not find module "@angular/material"

I followed each of the suggestions here (I'm using Angular 7), but nothing worked. My app refused to acknowledge that @angular/material existed, so it showed an error on this line:

import { MatCheckboxModule } from '@angular/material';

Even though I was using the --save parameter to add Angular Material to my project:

npm install --save @angular/material @angular/cdk

...it refused to add anything to my "package.json" file.

I even tried deleting the package-lock.json file, as some articles suggest that this causes problems, but this had no effect.

To fix this issue, I had to manually add these two lines to my "package.json" file.

{
    "devDependencies": {
        ...
        "@angular/material": "~7.2.2",
        "@angular/cdk": "~7.2.2",
        ...

What I can't tell is whether this is an issue related to using Angular 7, or if it's been around for years....

Shell script "for" loop syntax

There's more than one way to do it.

max=10
for i in `eval "echo {2..$max}"`
do
    echo "$i"
done

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I had this problem, and on a hunch I removed the Qt Configs from my environment. I.e.,

rm -rf ~/.config/Qt*

Then I started qtcreator and it reconfigured itself with the existing state of the machine. It no longer remembered where my projects were, but that just meant I had to browse to them "for the first time" again.

But more importantly it built itself a coherent set of library paths, so I could rebuild and run my project executables again without the xcb or qxcb libraries going missing.

how to add key value pair in the JSON object already declared

Please try following simple operations on a json, insert/update/push:

var movie_json = {
                    "id": 100,
                 };

//to insert new key/value to movie_json
movie_json['name'] = 'Harry Potter';
console.log("new key: " + movie_json);

//to update a key/value in movie_json
movie_json['id'] = 101;
console.log("updated key: " +movie_json);

//adding a json array to movie_json and push a new item.
movie_json['movies']=["The Philosopher's Stone"];
movie_json['movies'].push('The Chamber of Secrets');
console.log(movie_json);

How can I scroll a web page using selenium webdriver in python?

element=find_element_by_xpath("xpath of the li you are trying to access")

element.location_once_scrolled_into_view

this helped when I was trying to access a 'li' that was not visible.

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

Create an enum with string values

A hacky way to this is: -

CallStatus.ts

enum Status
{
    PENDING_SCHEDULING,
    SCHEDULED,
    CANCELLED,
    COMPLETED,
    IN_PROGRESS,
    FAILED,
    POSTPONED
}

export = Status

Utils.ts

static getEnumString(enum:any, key:any):string
{
    return enum[enum[key]];
}

How to use

Utils.getEnumString(Status, Status.COMPLETED); // = "COMPLETED"

How to attach a file using mail command on Linux?

There are a lot of answers here using mutt or mailx or people saying mail doesn't support "-a"

First, Ubuntu 14.0.4 mail from mailutils supports this:

mail -A filename -s "subject" [email protected]

Second, I found that by using the "man mail" command and searching for "attach"

How to sync with a remote Git repository?

Generally git pull is enough, but I'm not sure what layout you have chosen (or has github chosen for you).

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

Photoshop text tool adds punctuation to the beginning of text

This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.

How to update a claim in ASP.NET Identity?

Here you go:

            var user = User as ClaimsPrincipal;
            var identity = user.Identity as ClaimsIdentity;
            var claim = (from c in user.Claims
                         where c.Type == ClaimTypes.UserData
                         select c).Single();
            identity.RemoveClaim(claim);

taken from here.

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

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

I got tired of waiting for this to get built into SVN. I was using tortoiseSVN with ignore-on-commit, but that pops up a user dialog box that you can't suppress from the command line, and when I run my build script and go and make a cup of tea, I hate it when I come back to discover it's waiting for user input 10% of the way through.

So here's a windows powershell script that commits only files that aren't in a changelist:

# get list of changed files into targets
[XML]$svnStatus = svn st -q --xml C:\SourceCode\Monad
# select the nodes that aren't in a changelist
$fileList = $svnStatus.SelectNodes('/status/target/entry[wc-status/@item != "unversioned"]') | Foreach-Object {$_.path};
# create a temp file of targets
$fileListPath =  [IO.Path]::GetTempFileName();
$fileList | out-file $fileListPath -Encoding ASCII
# do the commit
svn commit --targets $fileListPath -m "Publish $version" --keep-changelists 
# remove the temp file
Remove-Item $filelistPath

How to fill a datatable with List<T>

Try this

static DataTable ConvertToDatatable(List<Item> list)
{
    DataTable dt = new DataTable();

    dt.Columns.Add("Name");
    dt.Columns.Add("Price");
    dt.Columns.Add("URL");
    foreach (var item in list)
    {
        var row = dt.NewRow();

        row["Name"] = item.Name;
        row["Price"] = Convert.ToString(item.Price);
        row["URL"] = item.URL;

        dt.Rows.Add(row);
    }

    return dt;
}

Installation of SQL Server Business Intelligence Development Studio

http://msdn.microsoft.com/en-us/library/ms173767.aspx

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

Change mysql user password using command line

Your login root should be /usr/local/directadmin/conf/mysql.conf. Then try following

UPDATE mysql.user SET password=PASSWORD('$w0rdf1sh') WHERE user='tate256' AND Host='10.10.2.30';
FLUSH PRIVILEGES;

Host is your mysql host.

jquery drop down menu closing by clicking outside

how to have a click event outside of the dropdown menu so that it close the dropdown menu ? Heres the code

$(document).click(function (e) {
    e.stopPropagation();
    var container = $(".dropDown");

    //check if the clicked area is dropDown or not
    if (container.has(e.target).length === 0) {
        $('.subMenu').hide();
    }
})

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

HTTP vs HTTPS performance

The current top answer is not fully correct.

As others have pointed out here, https requires handshaking and therefore does more TCP/IP roundtrips.

In a WAN environment typically then the latency becomes the limiting factor and not the increased CPU usage on the server.

Just keep in mind that the latency from Europe to the US can be around 200 ms (torundtrip time).

You can easily measure this (for the single user case) with HTTPWatch.

How to change an application icon programmatically in Android?

AndroidManifest.xml example:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name="com.pritesh.resourceidentifierexample.MainActivity"
                  android:label="@string/app_name"
                  android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <!--<category android:name="android.intent.category.LAUNCHER"/>-->
            </intent-filter>
        </activity>

        <activity-alias android:label="RED"
                        android:icon="@drawable/ic_android_red"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Red"
                        android:enabled="true"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="GREEN"
                        android:icon="@drawable/ic_android_green"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Green"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="BLUE"
                        android:icon="@drawable/ic_android_blue"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Blue"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

    </application>

Then follow below given code in MainActivity:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
            int imageResourceId;
            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
            int hours = new Time(System.currentTimeMillis()).getHours();
            Log.d("DATE", "onCreate: "  + hours);

            getPackageManager().setComponentEnabledSetting(
                    getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

            if(hours == 13)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_red", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Red"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }else if(hours == 14)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_green", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Green"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }else
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_blue", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Blue"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }

            imageView.setImageResource(imageResourceId);

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.

Example:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

How to show soft-keyboard when edittext is focused

In your onResume() section of the Activity you can do call the method bringKeyboard();

 onResume() {
     EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
     bringKeyboard(yourEditText);
 }


  protected boolean bringKeyboard(EditText view) {
    if (view == null) {
        return false;
    }
    try {
      // Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
        String value = view.getText().toString();
        if (value == null) {
            InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            return true;
        }
    } catch (Exception e) {
        Log.e(TAG, "decideFocus. Exception", e);
    }
    return false;
  }

How can I listen for a click-and-hold in jQuery?

Try this:

var thumbnailHold;

    $(".image_thumb").mousedown(function() {
        thumbnailHold = setTimeout(function(){
             checkboxOn(); // Your action Here

         } , 1000);
     return false;
});

$(".image_thumb").mouseup(function() {
    clearTimeout(thumbnailHold);
});

Objective-C: Calling selectors with multiple arguments

Your method signature is:

- (void) myTest:(NSString *)

withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).

If you call the function in this manner:

[self performSelector:@selector(myTest:) withObject:myString];

It will work.

But, as the other posters have suggested, you may want to rename the method:

- (void)myTestWithAString:(NSString*)aString;

And call:

[self performSelector:@selector(myTestWithAString:) withObject:myString];

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I know already answered but who looking for 'Fri' like this

for Fri -

SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);

and who wants full date string they can use 4E for Friday

For Friday-

SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);

Enjoy...

Clearing a text field on button click

If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!

Here I have used jQuery function, it can be done by simple JavaScript also...

        <form id="form_data">
           <input type="anything"  name="anything" />
           <input type="anything"  name="anything" />

             <!-- Save and Reset button -->
           <button type="button" id="btn_submit">Save</button>
           <button type="reset" id="btn_reset" style="display: none;"></button>
        </form>

<script type="text/javascript">
$(function(){
    $('#btn_submit').click(function(){
        // Do what ever you want
       $('#btn_reset').click();  // Clicking reset button
    });
});
</script>

Right pad a string with variable number of spaces

The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.

SELECT CAST('Test' AS CHAR(20))

This returns the value 'Test '.

Detect encoding and make everything UTF-8

A little heads up. You said that the "ß" should be displayed as "Ÿ" in your database.

This is probably because you're using a database with Latin-1 character encoding or possibly your PHP-MySQL connection is set wrong, this is, P believes your MySQL is set to use UTF-8, so it sends data as UTF-8, but your MySQL believes PHP is sending data encoded as ISO 8859-1, so it may once again try to encode your sent data as UTF-8, causing this kind of trouble.

Take a look at mysql_set_charset. It may help you.

Does Eclipse have line-wrap

As mentioned in the post by VonC on this same page. Eclipse now has this capability as of 06/2016 Neon.

Try this plugin Eclipse platform plugin

It looks like eclipse only has the ability to do it manually on its own and here are the commands. At that point you must reformat the highlighted text manually.

It's not terribly obvious how to control Eclipse line width and line wrapping in your Java source files. Here's how and where:

Comment width and line wrapping is set in Preferences->Java->Code Style->Formatter, then click on the Edit button and select the Comments tab. I like Line Width for Comments to be 120.

Code line wrapping is set nearby, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Line Wrapping tab. I like a line width of 120 and indent size of 4.

Indentation is set separately, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Indentation tab. I like an indent size of 4, consistent with the Line Wrapping indent setting.

As if that's not enough, you can also set printer margins, tab size, etc, in Preferences>General>Editors>Text Editors where I set the Displayed Tab Width to 4 and Print Margin Column to 120 or more.

You can also check the Show Print Margin box to get a faint vertical line at the printer margin column

Javascript checkbox onChange

Pure javascript:

_x000D_
_x000D_
const checkbox = document.getElementById('myCheckbox')

checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checked');
  } else {
    alert('not checked');
  }
})
_x000D_
My Checkbox: <input id="myCheckbox" type="checkbox" />
_x000D_
_x000D_
_x000D_

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Get time difference between two dates in seconds

You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.

const start = new Date().getTime();
const end = new Date().getTime();

const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

Merging Cells in Excel using C#

oSheet.get_Range("A1", "AS1").Merge();

HTML <select> selected option background-color CSS style

I realise this is an old post, but in case it helps, you can apply this CSS to have IE11 draw a dotted outline for the focus indication of a <select> element so that it resembles Firefox's focus indication: select:focus::-ms-value { background: transparent; color: inherit; outline-style: dotted; outline-width: thin; }

How to find index of all occurrences of element in array?

More simple way with es6 style.

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);


//Examples:
var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
indexOfAll(cars, "Nano"); //[0, 3, 5]
indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []

Error: No module named psycopg2.extensions

This one worked for me

python manage.py migrate

How to get a value from the last inserted row?

Use sequences in postgres for id columns:

INSERT mytable(myid) VALUES (nextval('MySequence'));

SELECT currval('MySequence');

currval will return the current value of the sequence in the same session.

(In MS SQL, you would use @@identity or SCOPE_IDENTITY())

How can I display a messagebox in ASP.NET?

The best solution is a minimal use of java directly in the visualstudio GUI

here it is: On a button go to the "OnClientClick" property (its not into events*) overthere type:

return confirm('are you sure?')

it will put a dialog with cancel ok buttons transparent over current page if cancel is pressed no postback will ocure. However if you want only ok button type:

alert ('i told you so')

The events like onclick work server side they execute your code, while OnClientClick runs in the browser side. the come most close to a basic dialog

Find rows that have the same value on a column in MySQL

Thanks guys :-) I used the below because I only cared about those two columns and not so much about the rest. Worked great

  select email, login_id from table
    group by email, login_id
    having COUNT(email) > 1

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

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

Convert float to string with precision & number of decimal digits specified?

A typical way would be to use stringstream:

#include <iomanip>
#include <sstream>

double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();

See fixed

Use fixed floating-point notation

Sets the floatfield format flag for the str stream to fixed.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

and setprecision.


For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.

Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:

#include <array>
#include <charconv>

double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
                               std::chars_format::fixed, 2);
if (ec == std::errc{}) {
    std::string s(buffer.data(), ptr);
    // ....
}
else {
    // error handling
}

Java ArrayList clear() function

it's not true the clear() function clear the Arraylist and start from index 0

JQuery post JSON object to a server

It is also possible to use FormData(). But you need to set contentType as false:

var data = new FormData();
data.append('name', 'Bob'); 

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: false,
        data: data,
        dataType: 'json'
    });
}

Php - testing if a radio button is selected and get the value

I suggest you do it through the GET request: for example, index.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="result.php" method="post">
  Answer 1 <input type="radio" name="ans" value="ans1" /><br />
  Answer 2 <input type="radio" name="ans" value="ans2"  /><br />
  Answer 3 <input type="radio" name="ans" value="ans3"  /><br />
  Answer 4 <input type="radio" name="ans" value="ans4"  /><br />
  <input type="button" value="submit" onclick="sendPost()" />
 </form>
 <script type="text/javascript">
    function sendPost(){
        var value = $('input[name="ans"]:checked').val();
        window.location.href = "sendpost.php?ans="+value;
    };
 </script>

this is sendpost.php:

<?php
if(isset($_GET["ans"]) AND !empty($_GET["ans"])){
    echo $_GET["ans"];
}
?>

Is it possible to use jQuery .on and hover?

None of these solutions worked for me when mousing over/out of objects created after the document has loaded as the question requests. I know this question is old but I have a solution for those still looking:

$("#container").on('mouseenter', '.selector', function() {
    //do something
});
$("#container").on('mouseleave', '.selector', function() {
    //do something
});

This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.

Convert SVG to image (JPEG, PNG, etc.) in the browser

I wrote this ES6 Class which does the Job.

class SvgToPngConverter {
  constructor() {
    this._init = this._init.bind(this);
    this._cleanUp = this._cleanUp.bind(this);
    this.convertFromInput = this.convertFromInput.bind(this);
  }

  _init() {
    this.canvas = document.createElement("canvas");
    this.imgPreview = document.createElement("img");
    this.imgPreview.style = "position: absolute; top: -9999px";

    document.body.appendChild(this.imgPreview);
    this.canvasCtx = this.canvas.getContext("2d");
  }

  _cleanUp() {
    document.body.removeChild(this.imgPreview);
  }

  convertFromInput(input, callback) {
    this._init();
    let _this = this;
    this.imgPreview.onload = function() {
      const img = new Image();
      _this.canvas.width = _this.imgPreview.clientWidth;
      _this.canvas.height = _this.imgPreview.clientHeight;
      img.crossOrigin = "anonymous";
      img.src = _this.imgPreview.src;
      img.onload = function() {
        _this.canvasCtx.drawImage(img, 0, 0);
        let imgData = _this.canvas.toDataURL("image/png");
        if(typeof callback == "function"){
            callback(imgData)
        }
        _this._cleanUp();
      };
    };

    this.imgPreview.src = input;
  }
}

Here is how you use it

let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
    // You now have your png data in base64 (imgData). 
    // Do what ever you wish with it here.
});

If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.

How to print variables in Perl

You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.

print $ids should be a fairly hard statement to mess up, but it is possible. Possible reasons:

  1. $ids is undefined. Gives the warning undefined value in print
  2. $ids is out of scope. With use strict, gives fatal warning Global variable $ids needs explicit package name, and otherwise the undefined warning from above.
  3. You forgot a semi-colon at the end of the line.
  4. You tried to do print $ids $nIds, in which case perl thinks that $ids is supposed to be a filehandle, and you get an error such as print to unopened filehandle.

Explanations

1: Should not happen. It might happen if you do something like this (assuming you are not using strict):

my $var;
while (<>) {
    $Var .= $_;
}
print $var;

Gives the warning for undefined value, because $Var and $var are two different variables.

2: Might happen, if you do something like this:

if ($something) {
    my $var = "something happened!";
}
print $var;

my declares the variable inside the current block. Outside the block, it is out of scope.

3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings.

4: Also a common mistake. There are a number of ways to correctly print two variables in the same print statement:

print "$var1 $var2";  # concatenation inside a double quoted string
print $var1 . $var2;  # concatenation
print $var1, $var2;   # supplying print with a list of args

Lastly, some perl magic tips for you:

use strict;
use warnings;

# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;

# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;

my $ids  = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";

Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.

Variations:

  • print "@file" is equivalent to $ids = join(' ',@file); print $ids;
  • $#file will return the last index in @file. Since arrays usually start at 0, $#file + 1 is equivalent to scalar @file.

You can also do:

my $ids;
do {
    local $/;
    $ids = <$fh>;
}

By temporarily "turning off" $/, the input record separator, i.e. newline, you will make <$fh> return the entire file. What <$fh> really does is read until it finds $/, then return that string. Note that this will preserve the newlines in $ids.

Line-by-line solution:

open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
    chomp;
    $ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.

Git: "please tell me who you are" error

Update your bootstrap process to create a ${HOME}/.gitconfig with the proper contents, or to copy an existing one from somewhere.

How do I convert a numpy array to (and display) an image?

You could use PIL to create (and display) an image:

from PIL import Image
import numpy as np

w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()

Built in Python hash() function

Use hashlib as hash() was designed to be used to:

quickly compare dictionary keys during a dictionary lookup

and therefore does not guarantee that it will be the same across Python implementations.

How to force a WPF binding to refresh?

MultiBinding friendly version...

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}

Get refresh token google api

Hi I followed following steps and I had been able to get the refresh token.

Authorization flow has two steps.

  1. Is to obtain the authorization code using https://accounts.google.com/o/oauth2/auth? URL.

    For that a post request is sent providing following parameters. 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE + '&access_type=offline' Providing above will receive a authorization code.

  2. Retrieving AcessToken and RefreshToken using https://accounts.google.com/o/oauth2/token? URL. For that a post request is sent providing following parameters.

    "code" : code, "client_id" : CID, "client_secret" : CSECRET, "redirect_uri" : REDIRECT, "grant_type" : "authorization_code",

So in your first attempt once you authorize the permissions you will be able to get the Refresh token. Subsequent attempts will not provide the refresh token. If you want the token again the revoke the access in you application.

Hope this will help someone cheers :)

How to check whether dynamically attached event listener exists or not?

It seems odd that this method doesn't exist. Is it time to add it finally?

If you wanted to you could something like the following:

var _addEventListener = EventTarget.prototype.addEventListener;
var _removeEventListener = EventTarget.prototype.removeEventListener;
EventTarget.prototype.events = {};
EventTarget.prototype.addEventListener = function(name, listener, etc) {
  var events = EventTarget.prototype.events;
  if (events[name] == null) {
    events[name] = [];
  }

  if (events[name].indexOf(listener) == -1) {
    events[name].push(listener);
  }

  _addEventListener(name, listener);
};
EventTarget.prototype.removeEventListener = function(name, listener) {
  var events = EventTarget.prototype.events;

  if (events[name] != null && events[name].indexOf(listener) != -1) {
    events[name].splice(events[name].indexOf(listener), 1);
  }

  _removeEventListener(name, listener);
};
EventTarget.prototype.hasEventListener = function(name) {
  var events = EventTarget.prototype.events;
  if (events[name] == null) {
    return false;
  }

  return events[name].length;
};

Difference between AutoPostBack=True and AutoPostBack=False?

The AutoPostBack property is used to set or return whether or not an automatic post back occurs when the user presses "ENTER" or "TAB" in the TextBox control.

If this property is set to TRUE the automatic post back is enabled, otherwise FALSE. Default is FALSE.

Tomcat is not running even though JAVA_HOME path is correct

I had Win 8 x86 installed. My Path variable had entry C:\Program Files\Java\jdk1.6.0_31\bin and I also had following variables:

  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_31;
  • JRE_HOME : C:\Program Files\Java\jre6;

My tomcat is installed at C:\Program Files\Apache Software Foundation\apache-tomcat-7.0.41

And still it did not worked for me.

I tried by replacing Program Files in those paths with Progra~1. I also tried by moving JAVA to another folder so that full path to it does not contain any spaces. But nothing worked.

Finally environment variables that worked for me are:

  • Kept path variable as is with full Program Files i.e. C:\Program Files\Java\jdk1.6.0_31\bin
  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_31
  • Deleted JRE_HOME

So what I did is removed JRE_HOME and removed semicolon at the end of JAVA_HOME. I think semicolon should not be an issue, though I removed it. I am giving these settings, since after a lot of googling nothing worked for me and suddenly these seem to work. You can replicate and see if it works for you.

This also worked for Win 7 x64, where

  • Path variable contained C:\Program Files (x86)\Java\jdk1.7.0_17\bin
  • JAVA_HOME is set to C:\Program Files (x86)\Java\jdk1.7.0_17 (without semicoln)

Please tell me why this worked, I know removing JRE_HOME was weird solution, but any guesses what difference it makes?

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

sql: check if entry in table A exists in table B

The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

dropzone.js - how to do something after ALL files are uploaded

Just use queuecomplete that's what its there for and its so so simple. Check the docs http://www.dropzonejs.com/

queuecomplete > Called when all files in the queue finished uploading.

      this.on("queuecomplete", function (file) {
          alert("All files have uploaded ");
      });

SQL, How to convert VARCHAR to bigint?

an alternative would be to do something like:

SELECT
   CAST(P0.seconds as bigint) as seconds
FROM
   (
   SELECT
      seconds
   FROM
      TableName
   WHERE
      ISNUMERIC(seconds) = 1
   ) P0

Uninstall mongoDB from ubuntu

In my case mongodb packages are named mongodb-org and mongodb-org-*

So when I type sudo apt purge mongo then tab (for auto-completion) I can see all installed packages that start with mongo.

Another option is to run the following command (which will list all packages that contain mongo in their names or their descriptions):

dpkg -l | grep mongo

In summary, I would do (to purge all packages that start with mongo):

sudo apt purge mongo*

and then (to make sure that no mongo packages are left):

dpkg -l | grep mongo

Of course, as mentioned by @alicanozkara, you will need to manually remove some directories like /var/log/mongodb and /var/lib/mongodb

Running the following find commands:

sudo find /etc/ -name "*mongo*" and sudo find /var/ -name "*mongo*"

may also show some files that you may want to remove, like:

/etc/systemd/system/mongodb.service
/etc/apt/sources.list.d/mongodb-org-3.2.list

and:

/var/lib/apt/lists/repo.mongodb.*

You may also want to remove user and group mongodb, to do so you need to run:

sudo userdel -r mongodb
sudo groupdel mongodb

To check whether mongodb user/group exists or not, try:

cut -d: -f1 /etc/passwd | grep mongo
cut -d: -f1 /etc/group | grep mongo

Redirect echo output in shell script to logfile

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error

Render a string in HTML and preserve spaces and linebreaks

There is a simple way to do it. I tried it on my app and it worked pretty well.

Just type: $text = $row["text"]; echo nl2br($text);

Facebook how to check if user has liked page and show content?

You need to write a little PHP code. When user first click tab you can check is he like the page or not. Below is the sample code

include_once("facebook.php");

    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => FACEBOOK_APP_ID,
      'secret' => FACEBOOK_SECRET,
      'cookie' => true,
    ));

$signed_request = $facebook->getSignedRequest();

// Return you the Page like status
$like_status = $signed_request["page"]["liked"];

if($like_status)
{
    echo 'User Liked the page';
    // Place some content you wanna show to user

}else{
    echo 'User do not liked the page';
    // Place some content that encourage user to like the page
}

How to add a new project to Github using VS Code

This feature was added in 1.45, demoed here.

Launch the command palette Ctrl+Shift+P, run Publish to Github, and follow the prompt. You will be given the choice between a private and public repository, so be careful that you choose the right one.

running from command palette

It may ask you to login to github. It will then prompt for the repo name (defaults to the name of the folder), and for creating a .gitignore file (defaults to empty .gitignore). Just hit enter if you are fine with the defaults. When you are done it should give you a popup notification in the bottom right with a link to the repo https://github.com/<username>/<reponame>

Minor warning: if your project already has a .gitignore file in it this process will overwrite it

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How do I install SciPy on 64 bit Windows?

Unofficial 64-bit installers for NumPy and SciPy are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/

Make sure that you download & install the packages (aka. wheels) that match your CPython version and bitness (ie. cp35 = Python v3.5; win_amd64 = x86_64).

You'll want to install NumPy first; From a CMD prompt with administrator privileges for a system-wide (aka. Program Files) install:

C:\>pip install numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl

Or include the --user flag to install to the current user's application folder (Typically %APPDATA%\Python on Windows) from a non-admin CMD prompt:

C:\>pip install --user numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl

Then do the same for SciPy:

C:\>pip install [--user] scipy-<version>-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl

Don't forget to replace <version>, <ver-spec>, and <cpu-build> appropriately if you copy & paste any of these examples. And also that you must use the numpy & scipy packages from the ifd.uci.edu link above (or else you will get errors if you try to mix & match incompatible packages -- uninstall any conflicting packages first [ie. pip list]).

Software Design vs. Software Architecture

Software design has a longer history while the term software architecture is barely 20 years old. Hence, it is going through growing pains right now.

Academics tend to see Architecture as part of the larger field of software design. Although there is growing recognition that Arch is a field within it's own.

Practitioners tend to see Arch as high-level design decisions that are strategic and can be costly in a project to undo.

The exact line between Arch and design depends on the software domain. For instance, in the domain of Web Applications, the layered architecture is gaining the most popularity currently (Biz Logic Layer, Data Access Layer, etc.) The lower level parts of this Arch are considered design (class diagrams, method signatures, etc.) This would be defined differently in the domains of embedded systems, operating systems, compilers, etc.

How do I delete specific lines in Notepad++?

You can try doing a replace of #region with \n, turning extended search mode on.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

For me the accepted answer did not yet work. I started off as suggested here:

ln -s /usr/bin/nodejs /usr/bin/node

After doing this I was getting the following error:

/usr/local/lib/node_modules/npm/bin/npm-cli.js:85 let notifier = require('update-notifier')({pkg}) ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3

The solution was to download the most recent version of node from https://nodejs.org/en/download/ .

Then I did:

sudo tar -xf node-v10.15.0-linux-x64.tar.xz --directory /usr/local --strip-components 1

Now the update was finally successful: npm -v changed from 3.2.1 to 6.4.1

Is there more to an interface than having the correct methods

Here is my understanding of interface advantage. Correct me if I am wrong. Imagine we are developing OS and other team is developing the drivers for some devices. So we have developed an interface StorageDevice. We have two implementations of it (FDD and HDD) provided by other developers team.

Then we have a OperatingSystem class which can call interface methods such as saveData by just passing an instance of class implemented the StorageDevice interface.

The advantage here is that we don't care about the implementation of the interface. The other team will do the job by implementing the StorageDevice interface.

package mypack;

interface StorageDevice {
    void saveData (String data);
}


class FDD implements StorageDevice {
    public void saveData (String data) {
        System.out.println("Save to floppy drive! Data: "+data);
    }
}

class HDD implements StorageDevice {
    public void saveData (String data) {
        System.out.println("Save to hard disk drive! Data: "+data);
    }
}

class OperatingSystem {
    public String name;
    StorageDevice[] devices;
    public OperatingSystem(String name, StorageDevice[] devices) {

        this.name = name;
        this.devices = devices.clone();

        System.out.println("Running OS " + this.name);
        System.out.println("List with storage devices available:");
        for (StorageDevice s: devices) {
            System.out.println(s);
        }

    }

    public void saveSomeDataToStorageDevice (StorageDevice storage, String data) {
        storage.saveData(data);
    }
}

public class Main {

    public static void main(String[] args) {

        StorageDevice fdd0 = new FDD();
        StorageDevice hdd0 = new HDD();     
        StorageDevice[] devs = {fdd0, hdd0};        
        OperatingSystem os = new OperatingSystem("Linux", devs);
        os.saveSomeDataToStorageDevice(fdd0, "blah, blah, blah...");    
    }
}

Specifying width and height as percentages without skewing photo proportions in HTML

Given the lack of information regarding the original image size, specifying percentages for the width and height would result in highly erratic results. If you are trying to ensure that an image will fit within a specific location on your page then you'll need to use some server side code to manage that rescaling.

Select NOT IN multiple columns

I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:

SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)

How to obtain a Thread id in Python?

Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()) and use something like below not to depend on particular numbers and being amd64-only:

---- 8< ---- (xos.pyx)
"""module xos complements standard module os""" 

cdef extern from "<sys/syscall.h>":                                                             
    long syscall(long number, ...)                                                              
    const int SYS_gettid                                                                        

# gettid returns current OS thread identifier.                                                  
def gettid():                                                                                   
    return syscall(SYS_gettid)                                                                  

and

---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos

...

print 'my tid: %d' % xos.gettid()

this depends on Cython though.

How to restrict UITextField to take only numbers in Swift?

//Only accept decimal numbers as input, [ SWIFT 3.0 ]

func textField(_ shouldChangeCharactersIntextField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
        let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

        let components = string.components(separatedBy: inverseSet)

        let filtered = components.joined(separator: "")

        return string == filtered
}

PHP - remove <img> tag from string

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

How to determine previous page URL in Angular?

Create a injectable service:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';

 /** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {

  private previousUrl: string = undefined;
  private currentUrl: string = undefined;

  constructor(private router : Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl(){
    return this.previousUrl;
  }    
}

Then use it everywhere you need. To store the current variable as soon as possible, it's necessary to use the service in the AppModule.

// AppModule
export class AppModule {
  constructor(private routerExtService: RouterExtService){}

  //...

}

// Using in SomeComponent
export class SomeComponent implements OnInit {

  constructor(private routerExtService: RouterExtService, private location: Location) { } 

  public back(): void {
    this.location.back();
  }

  //Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
  public goToPrevious(): void {
    let previous = this.routerExtService.getPreviousUrl();

    if(previous)
      this.routerExtService.router.navigateByUrl(previous);
  }

  //...

}

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

How to use both onclick and target="_blank"

The window.open method is prone to cause popup blockers to complain

A better approach is:

Put a form in the webpage with an id

<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName"> </form>

Then use:

function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");
theForm.submit();

}

and

onclick="Javascript: openYourRequiredPage()"

You can use

method="post"

or

method="get"

As you wish

How to use HTML Agility pack

Getting Started - HTML Agility Pack

// From File
var doc = new HtmlDocument();
doc.Load(filePath);

// From String
var doc = new HtmlDocument();
doc.LoadHtml(html);

// From Web
var url = "http://html-agility-pack.net/";
var web = new HtmlWeb();
var doc = web.Load(url);

fatal: Not a valid object name: 'master'

copying Superfly Jon's comment into an answer:

To create a new branch without committing on master, you can use:

git checkout -b <branchname>

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

There are two ways to resolve this issue.Try option 1 first, if it doesn't work try option 2, and your problem is solved.

1) On the top right corner of your console, there is a red button, to stop the spring boot application which is already running on this port just click on the red button to terminate.

2) If the red button is not activated you need to right click on the console and select terminate/disconnect all. Hope this helps.

Bonus tip:- If you want to run your server on a different port of your choice, create a file named application.properties in resource folder of your maven project and write server.port=3000 to run your application on port 3000

jQuery: enabling/disabling datepicker

You can replace form field with its copy:

var copy = $('#from').clone(); $('#from').replaceWith(copy);

And after that initialize datetimepicker again.

Clean out Eclipse workspace metadata

In my case eclipse is not showing parent class function on $this, so I perform below mention points and it starts works:-

I go to my /var/www/ folder and check for .metadata folder (Here check the .log file and it shows) Resource is out of sync with the file system: 1. Go to Eclipse --> Project --> Clean 2. Windows -- preferences --> General --> Workspace --> And set it to "Refresh Automatically"

After that boom - things gets start working :)

If you want to load variables from other files too then ado this :- Eclipse-->Windows-->Preferences-->Php-->Editor-->Content Assist --> and check "show variable from other files"

Then it will show element , variables and other functions also.

White spaces are required between publicId and systemId

The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.

You'll get the error with (for instance):

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

You won't with:

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">

Notice "" at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.

By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.

Navigation bar show/hide

In Swift 4.2 and Xcode 10

self.navigationController?.isNavigationBarHidden = true  //Hide
self.navigationController?.isNavigationBarHidden = false  //Show

If you don't want to display Navigation bar only in 1st VC, but you want display in 2nd VC onword's

In your 1st VC write this code.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true  //Hide
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = false  //Show
}

Creating an array of objects in Java

For generic class it is necessary to create a wrapper class. For Example:

Set<String>[] sets = new HashSet<>[10]

results in: "Cannot create a generic array"

Use instead:

        class SetOfS{public Set<String> set = new HashSet<>();}
        SetOfS[] sets = new SetOfS[10];  

how to clear JTable

If we use tMOdel.setRowCount(0); we can get Empty table.

DefaultTableModel tMOdel = (DefaultTableModel) jtableName.getModel();
tMOdel.setRowCount(0);

Fragment onCreateView and onActivityCreated called twice

I was scratching my head about this for a while too, and since Dave's explanation is a little hard to understand I'll post my (apparently working) code:

private class TabListener<T extends Fragment> implements ActionBar.TabListener {
    private Fragment mFragment;
    private Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    public TabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
        mFragment=mActivity.getFragmentManager().findFragmentByTag(mTag);
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            ft.replace(android.R.id.content, mFragment, mTag);
        } else {
            if (mFragment.isDetached()) {
                ft.attach(mFragment);
            }
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}

As you can see it's pretty much like the Android sample, apart from not detaching in the constructor, and using replace instead of add.

After much headscratching and trial-and-error I found that finding the fragment in the constructor seems to make the double onCreateView problem magically go away (I assume it just ends up being null for onTabSelected when called through the ActionBar.setSelectedNavigationItem() path when saving/restoring state).

net::ERR_INSECURE_RESPONSE in Chrome

I was getting this error on amazon.ca, meetup.com, and the Symantec homepage.

I went to the update page in the Chrome browser (it was at 53.*) and checked for an upgrade, and it showed there was no updates available. After asking around my office, it turns out the latest version was 55 but I was stuck on 53 for some reason.

After upgrading (had to manually download from the Chrome website) the issues were gone!

Read/write to file using jQuery

Use javascript's execCommand('SaveAs', false, filename); functionality

Edit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.

Now this code is an rare antique zero day collectible.

// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename);
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function like this:

msg =  "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");

hardcoded string "row three", should use @string resource

You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I tried changing the Internal Testers option, tried changing other items on the app details page, and tried uploading several new binaries (with the same code, only changing the build number) over a 2-day period to no effect. I also contacted Apple through the iTunes Connect support link; they replied in less than 24 hours, but only to ask for more info (most of which I had already provided).

Finally, the fifth build I uploaded, two days later, went through in the normal few minutes and I was finally able to submit my app for review.

In Visual Basic how do you create a block comment

In Visual Studio .NET you can do Ctrl + K then C to comment, Crtl + K then U to uncomment a block.

Finding absolute value of a number without using Math.abs()

If you look inside Math.abs you can probably find the best answer:

Eg, for floats:

    /*
     * Returns the absolute value of a {@code float} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     * Special cases:
     * <ul><li>If the argument is positive zero or negative zero, the
     * result is positive zero.
     * <li>If the argument is infinite, the result is positive infinity.
     * <li>If the argument is NaN, the result is NaN.</ul>
     * In other words, the result is the same as the value of the expression:
     * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static float abs(float a) {
        return (a <= 0.0F) ? 0.0F - a : a;
    }

Download/Stream file from URL - asp.net

If you are looking for a .NET Core version of @Dallas's answer, use the below.

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

What's the best way to get the last element of an array without deleting it?

How about:

current(array_slice($array, -1))
  • works for associative arrays
  • works when $array == [] (returns false)
  • doesn't affect the original array

How do you run a crontab in Cygwin on Windows?

You have two options:

  1. Install cron as a windows service, using cygrunsrv:

    cygrunsrv -I cron -p /usr/sbin/cron -a -n
    
    net start cron
    

    Note, in (very) old versions of cron you need to use -D instead of -n

  2. The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:

    C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
    

What's a good (free) visual merge tool for Git? (on windows)

I don't know a good free tool but winmerge is ok(ish). I've been using the beyond compare tools since 1999 and can't rate it enough - it costs about 50 USD and this investment has paid for it self in time savings more than I can possible imagine.

Sometimes tools should be paid for if they are very very good.

My docker container has no internet

I've had a similar problem for the last few days. For me the cause was a combination of systemd, docker and my hosting provider. I'm running up-to-date CentOS (7.7.1908).

My hosting provider automatically generates a config file for systemd-networkd. Starting with systemd 219 which is the current version for CentOS 7, systemd-networkd took control of network-related sysctl parameters. Docker seems to be incompatible with this version and will reset the IP-Forwarding flags everytime a container is launched.

My solution was to add IPForward=true in the [Network]-section of my provider-generated config file. This file might be in several places, most likely in /etc/systemd/network.

The process is also described in the official docker docs: https://docs.docker.com/v17.09/engine/installation/linux/linux-postinstall/#ip-forwarding-problems

How do I pass multiple attributes into an Angular.js attribute directive?

You do it exactly the same way as you would with an element directive. You will have them in the attrs object, my sample has them two-way binding via the isolate scope but that's not required. If you're using an isolated scope you can access the attributes with scope.$eval(attrs.sample) or simply scope.sample, but they may not be defined at linking depending on your situation.

app.directive('sample', function () {
    return {
        restrict: 'A',
        scope: {
            'sample' : '=',
            'another' : '='
        },
        link: function (scope, element, attrs) {
            console.log(attrs);
            scope.$watch('sample', function (newVal) {
                console.log('sample', newVal);
            });
            scope.$watch('another', function (newVal) {
                console.log('another', newVal);
            });
        }
    };
});

used as:

<input type="text" ng-model="name" placeholder="Enter a name here">
<input type="text" ng-model="something" placeholder="Enter something here">
<div sample="name" another="something"></div>

What is @ModelAttribute in Spring MVC?

Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.

public String add(@ModelAttribute("specified") Model model) {
    ...
}

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

How to send a POST request from node.js Express?

As described here for a post request :

var http = require('http');

var options = {
  host: 'www.host.com',
  path: '/',
  port: '80',
  method: 'POST'
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

How do I programmatically click a link with javascript?

Many of the above methods have been deprecated. It is now recommended to use the constructor found here

function clickAnchorTag() {
    var event = document.createEvent('MouseEvent');
    event = new CustomEvent('click');
    var a = document.getElementById('nameOfID');
    a.dispatchEvent(event);
}

This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

it worked for me after deleting and adding the server back.

Check if string contains a value in array

If your $string is always consistent (ie. the domain name is always at the end of the string), you can use explode() with end(), and then use in_array() to check for a match (as pointed out by @Anand Solanki in their answer).

If not, you'd be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.

$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);

if (empty($matches[1])) {
  // no domain name was found in $string
} else {
  if (in_array($matches[1], $owned_urls)) {
    // exact match found
  } else {
    // exact match not found
  }
}

The expression above could probably be improved (I'm not particularly knowledgeable in this area)

Here's a demo

How to push JSON object in to array using javascript

can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data

 var my_json;
    $.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
    console.log(json1);
        var data = [];
    json1.feeds.forEach(function(feed,i){
        console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
        my_json = feed;
        console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
        data.push(my_json);
    }); 

Commands out of sync; you can't run this command now

to solve this problem you have to store result data before use it

$numRecords->execute();

$numRecords->store_result();

that's all

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

You may get day, month and year and may concatenate them or may use MM-dd-yyyy format as given below.

Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);



Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1   = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1  = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);



LocalDateTime ldt1 = LocalDateTime.now();  
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy3 = ldt1.format(format1);  
System.out.println("Formatted Date 3: " + mmddyyyy3);  



LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);



LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy5 = ldt3.format(format2);   
System.out.println("Formatted Date 5: " + mmddyyyy5); 



Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3  = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);



Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4  = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);



Date date4 = new Date();
int day5   = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5  = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);



Date date5 = new Date();
int day6   = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6  = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);`enter code here`
System.out.println("Formatted Date 9: " + mmddyyyy9);

jquery function val() is not equivalent to "$(this).value="?

$(this).value is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val().