Programs & Examples On #Intellisense documentati

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

If you are using CMS like Drupal or Wordpress - just install jQuery Update module and error no longer persists.

How do you reverse a string in place in JavaScript?

There are many ways you can reverse a string in JavaScript. I'm jotting down three ways I prefer.

Approach 1: Using reverse function:

function reverse(str) {
  return str.split('').reverse().join('');
}

Approach 2: Looping through characters:

function reverse(str) {
  let reversed = '';

  for (let character of str) {
    reversed = character + reversed;
  }

  return reversed;
}

Approach 3: Using reduce function:

function reverse(str) {
  return str.split('').reduce((rev, char) => char + rev, '');
}

I hope this helps :)

gem install: Failed to build gem native extension (can't find header files)

Red Hat, Fedora:

yum -y install gcc mysql-devel ruby-devel rubygems
gem install -y mysql -- --with-mysql-config=/usr/bin/mysql_config

Debian, Ubuntu:

apt-get install libmysqlclient-dev ruby-dev
gem install mysql

Arch Linux:

pacman -S libmariadbclient
gem install mysql

Persist javascript variables across pages?

You can use http://rhaboo.org as a wrapper around localStorage. It stores complex objects but doesn't merely stringify and parse the whole thing like most such libraries do. That's really inefficient if you want to store a lot of data and add to it or change it in small chunks. Also, JSON discards a lot of important stuff like non-numerical properties of arrays.

In rhaboo you can write things like this:

var store = Rhaboo.persistent('Some name');

store.write('count', store.count ? store.count+1 : 1);

var laststamp = store.stamp ? store.stamp.toString() : "never";
store.write('stamp', new Date());

store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});

store.somethingfancy.went[1].mow.write(1, 'lawn');
console.log( store.somethingfancy.went[1].mow[1] ); //says lawn

BTW, I wrote rhaboo

connect to host localhost port 22: Connection refused

  1. Before installing/reinstalling anything check the status of sshd . . .
sudo systemctl status sshd
  1. You should see something like . . .
? sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; disabled; vendor prese>
   Active: inactive (dead)
     Docs: man:sshd(8)
           man:sshd_config(5)
  1. Just enable and start sshd
sudo systemctl enable sshd
sudo systemctl start sshd

What is the opposite of :hover (on mouse leave)?

If I understand correctly you could do the same thing by moving your transitions to the link rather than the hover state:

ul li a {
    color:#999;       
    transition: color 0.5s linear; /* vendorless fallback */
    -o-transition: color 0.5s linear; /* opera */
    -ms-transition: color 0.5s linear; /* IE 10 */
    -moz-transition: color 0.5s linear; /* Firefox */
    -webkit-transition: color 0.5s linear; /*safari and chrome */
}

ul li a:hover {
    color:black;
    cursor: pointer;
}

http://jsfiddle.net/spacebeers/sELKu/3/

The definition of hover is:

The :hover selector is used to select elements when you mouse over them.

By that definition the opposite of hover is any point at which the mouse is not over it. Someone far smarter than me has done this article, setting different transitions on both states - http://css-tricks.com/different-transitions-for-hover-on-hover-off/

#thing {
   padding: 10px;
   border-radius: 5px;

  /* HOVER OFF */
   -webkit-transition: padding 2s;
}

#thing:hover {
   padding: 20px;
   border-radius: 15px;

  /* HOVER ON */
   -webkit-transition: border-radius 2s;
}

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Confused by python file mode "w+"

The file is truncated, so you can call read() (no exceptions raised, unlike when opened using 'w') but you'll get an empty string.

Can Android do peer-to-peer ad-hoc networking?

I don't think it provides a multi-hop wireless packet routing environment. However you can try to integrate a simple routing mechanism. Just check out Wi-Share to get an idea how it can be done.

Delaying AngularJS route change until model loaded to prevent flicker

Using AngularJS 1.1.5

Updating the 'phones' function in Justen's answer using AngularJS 1.1.5 syntax.

Original:

phones: function($q, Phone) {
    var deferred = $q.defer();

    Phone.query(function(phones) {
        deferred.resolve(phones);
    });

    return deferred.promise;
}

Updated:

phones: function(Phone) {
    return Phone.query().$promise;
}

Much shorter thanks to the Angular team and contributors. :)

This is also the answer of Maximilian Hoffmann. Apparently that commit made it into 1.1.5.

Using CSS in Laravel views?

Copy the css or js file that you want to include, to public folder or you may want to store those in public/css or public/js folders.

Eg. you are using style.css file from css folder in public directory then you can use

<link rel="stylesheet" href="{{ url() }}./css/style.css" type="text/css"/>

But in Laravel 5.2 you will have to use

<link rel="stylesheet" href="{{ url('/') }}./css/style.css" type="text/css"/>

and if you want to include javascript files from public/js folder, it's fairly simple too

<script src="{{ url() }}./js/jquery.min.js"></script>

and in Laravel 5.2 you wll have to use

<script src="{{ url('/') }}./js/jquery.min.js"></script>

the function url() is a laravel helper function which will generate fully qualified URL to given path.

refresh leaflet map: map container is already initialized

I had same problem.then i set globally map variable e.g var map= null and then for display map i check

if(map==null)then map=new L.Map('idopenstreet').setView();

By this solution your map will be initialize only first time after that map will be fill by L.Map then it will not be null. so no error will be there like map container already initialize.

How to remove components created with Angular-CLI

There's the --dry-run flag which will allow you to preview the changes, and/or you can use the Angular Console App to generate the cli flags for you, using their easy GUI. It auto-previews everything before you commit to it.

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

how to use json file in html code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

My JSON file:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

Kill detached screen session

For me a simple

exit

works. This is from within the screen session.

How do I hide an element on a click event anywhere outside of the element?

This doesn't work - it hides the .myDIV when you click inside of it.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

Spring JPA selecting specific columns

I guess the easy way may be is using QueryDSL, that comes with the Spring-Data.

Using to your question the answer can be

JPAQuery query = new JPAQuery(entityManager);
List<Tuple> result = query.from(projects).list(project.projectId, project.projectName);
for (Tuple row : result) {
 System.out.println("project ID " + row.get(project.projectId));
 System.out.println("project Name " + row.get(project.projectName)); 
}}

The entity manager can be Autowired and you always will work with object and clases without use *QL language.

As you can see in the link the last choice seems, almost for me, more elegant, that is, using DTO for store the result. Apply to your example that will be:

JPAQuery query = new JPAQuery(entityManager);
QProject project = QProject.project;
List<ProjectDTO> dtos = query.from(project).list(new QProjectDTO(project.projectId, project.projectName));

Defining ProjectDTO as:

class ProjectDTO {

 private long id;
 private String name;
 @QueryProjection
 public ProjectDTO(long projectId, String projectName){
   this.id = projectId;
   this.name = projectName;
 }
 public String getProjectId(){ ... }
 public String getProjectName(){....}
}

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

WAMP Server doesn't load localhost

I faced a similar problem. I tried everything with ports, hosts and config files.But nothing helped.

I checked apache error logs. They showed the following error

(OS 10038)An operation was attempted on something that is not a socket.  : AH00332: winnt_accept: getsockname error on listening socket, is IPv6 available?

Finally this is what solved my problem.

1) Goto command prompt and run it in administrative mode. In windows 7 you can do it by typing cmd in run and then pressing ctrl+shift+enter

2) run the following command: netsh winsock reset

3) Restart the system

Get the value in an input text box

There is one important thing to mention:

$("#txt_name").val();

will return the current real value of a text field, for example if the user typed something there after a page load.

But:

$("#txt_name").attr('value')

will return value from DOM/HTML.

How can I stop float left?

Sometimes clear will not work. Use float: none as an override

Angular 2 change event - model changes

This worked for me

<input 
  (input)="$event.target.value = toSnakeCase($event.target.value)"
  [(ngModel)]="table.name" />

In Typescript

toSnakeCase(value: string) {
  if (value) {
    return value.toLowerCase().replace(/[\W_]+/g, "");
  }
}

bootstrap jquery show.bs.modal event won't fire

use this:

$(document).on('show.bs.modal','#myModal', function () {
  alert('hi');
})

How to make fixed header table inside scrollable div?

use StickyTableHeaders.js for this.

Header was transparent . so try to add this css .

thead {
    border-top: none;
    border-bottom: none;
    background-color: #FFF;
}

jQuery AutoComplete Trigger Change Event

The simplest, most robust way is to use the internal ._trigger() to fire the autocomplete change event.

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

$("#CompanyList").data("ui-autocomplete")._trigger("change");

Note, jQuery UI 1.9 changed from .data("autocomplete") to .data("ui-autocomplete"). You may also see some people using .data("uiAutocomplete") which indeed works in 1.9 and 1.10, but "ui-autocomplete" is the official preferred form. See http://jqueryui.com/upgrade-guide/1.9/#changed-naming-convention-for-data-keys for jQuery UI namespaecing on data keys.

Initialising an array of fixed size in python

An easy solution is x = [None]*length, but note that it initializes all list elements to None. If the size is really fixed, you can do x=[None,None,None,None,None] as well. But strictly speaking, you won't get undefined elements either way because this plague doesn't exist in Python.

Android view layout_width - how to change programmatically?

I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.

View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);

angular-cli server - how to specify default port

You can now specify the port in the .angular-cli.json under the defaults:

"defaults": {
  "styleExt": "scss",
  "serve": {
    "port": 8080
  },
  "component": {}
}

Tested in angular-cli v1.0.6

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

Iterate through a C++ Vector using a 'for' loop

I was surprised nobody mentioned that iterating through an array with an integer index makes it easy for you to write faulty code by subscripting an array with the wrong index. For example, if you have nested loops using i and j as indices, you might incorrectly subscript an array with j rather than i and thus introduce a fault into the program.

In contrast, the other forms listed here, namely the range based for loop, and iterators, are a lot less error prone. The language's semantics and the compiler's type checking mechanism will prevent you from accidentally accessing an array using the wrong index.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

You might have to re-check the order in which you are merging the files, it should be something like:

  1. jquery.min.js
  2. jquery-ui.js
  3. any third party plugins you loading
  4. your custom JS

implements Closeable or implements AutoCloseable

The try-with-resources Statement.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }

}

Please refer to the docs.

Val and Var in Kotlin

Simply think Val like final Variable in java

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

Convert Rows to columns using 'Pivot' in SQL Server

I'm writing an sp that could be useful for this purpose, basically this sp pivot any table and return a new table pivoted or return just the set of data, this is the way to execute it:

Exec dbo.rs_pivot_table @schema=dbo,@table=table_name,@column=column_to_pivot,@agg='sum([column_to_agg]),avg([another_column_to_agg]),',
        @sel_cols='column_to_select1,column_to_select2,column_to_select1',@new_table=returned_table_pivoted;

please note that in the parameter @agg the column names must be with '[' and the parameter must end with a comma ','

SP

Create Procedure [dbo].[rs_pivot_table]
    @schema sysname=dbo,
    @table sysname,
    @column sysname,
    @agg nvarchar(max),
    @sel_cols varchar(max),
    @new_table sysname,
    @add_to_col_name sysname=null
As
--Exec dbo.rs_pivot_table dbo,##TEMPORAL1,tip_liq,'sum([val_liq]),sum([can_liq]),','cod_emp,cod_con,tip_liq',##TEMPORAL1PVT,'hola';
Begin

    Declare @query varchar(max)='';
    Declare @aggDet varchar(100);
    Declare @opp_agg varchar(5);
    Declare @col_agg varchar(100);
    Declare @pivot_col sysname;
    Declare @query_col_pvt varchar(max)='';
    Declare @full_query_pivot varchar(max)='';
    Declare @ind_tmpTbl int; --Indicador de tabla temporal 1=tabla temporal global 0=Tabla fisica

    Create Table #pvt_column(
        pivot_col varchar(100)
    );

    Declare @column_agg table(
        opp_agg varchar(5),
        col_agg varchar(100)
    );

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@table) AND type in (N'U'))
        Set @ind_tmpTbl=0;
    ELSE IF OBJECT_ID('tempdb..'+ltrim(rtrim(@table))) IS NOT NULL
        Set @ind_tmpTbl=1;

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@new_table) AND type in (N'U')) OR 
        OBJECT_ID('tempdb..'+ltrim(rtrim(@new_table))) IS NOT NULL
    Begin
        Set @query='DROP TABLE '+@new_table+'';
        Exec (@query);
    End;

    Select @query='Select distinct '+@column+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+@schema+'.'+@table+' where '+@column+' is not null;';
    Print @query;

    Insert into #pvt_column(pivot_col)
    Exec (@query)

    While charindex(',',@agg,1)>0
    Begin
        Select @aggDet=Substring(@agg,1,charindex(',',@agg,1)-1);

        Insert Into @column_agg(opp_agg,col_agg)
        Values(substring(@aggDet,1,charindex('(',@aggDet,1)-1),ltrim(rtrim(replace(substring(@aggDet,charindex('[',@aggDet,1),charindex(']',@aggDet,1)-4),')',''))));

        Set @agg=Substring(@agg,charindex(',',@agg,1)+1,len(@agg))

    End

    Declare cur_agg cursor read_only forward_only local static for
    Select 
        opp_agg,col_agg
    from @column_agg;

    Open cur_agg;

    Fetch Next From cur_agg
    Into @opp_agg,@col_agg;

    While @@fetch_status=0
    Begin

        Declare cur_col cursor read_only forward_only local static for
        Select 
            pivot_col 
        From #pvt_column;

        Open cur_col;

        Fetch Next From cur_col
        Into @pivot_col;

        While @@fetch_status=0
        Begin

            Select @query_col_pvt='isnull('+@opp_agg+'(case when '+@column+'='+quotename(@pivot_col,char(39))+' then '+@col_agg+
            ' else null end),0) as ['+lower(Replace(Replace(@opp_agg+'_'+convert(varchar(100),@pivot_col)+'_'+replace(replace(@col_agg,'[',''),']',''),' ',''),'&',''))+
                (case when @add_to_col_name is null then space(0) else '_'+isnull(ltrim(rtrim(@add_to_col_name)),'') end)+']'
            print @query_col_pvt
            Select @full_query_pivot=@full_query_pivot+@query_col_pvt+', '

            --print @full_query_pivot

            Fetch Next From cur_col
            Into @pivot_col;        

        End     

        Close cur_col;
        Deallocate cur_col;

        Fetch Next From cur_agg
        Into @opp_agg,@col_agg; 
    End

    Close cur_agg;
    Deallocate cur_agg;

    Select @full_query_pivot=substring(@full_query_pivot,1,len(@full_query_pivot)-1);

    Select @query='Select '+@sel_cols+','+@full_query_pivot+' into '+@new_table+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+
    @schema+'.'+@table+' Group by '+@sel_cols+';';

    print @query;
    Exec (@query);

End;
GO

This is an example of execution:

Exec dbo.rs_pivot_table @schema=dbo,@table=##TEMPORAL1,@column=tip_liq,@agg='sum([val_liq]),avg([can_liq]),',@sel_cols='cod_emp,cod_con,tip_liq',@new_table=##TEMPORAL1PVT;

then Select * From ##TEMPORAL1PVT would return:

enter image description here

matplotlib get ylim values

Leveraging from the good answers above and assuming you were only using plt as in

import matplotlib.pyplot as plt

then you can get all four plot limits using plt.axis() as in the following example.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

The above code should produce the following output plot. enter image description here

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

Date format Mapping to JSON Jackson

To add characters such as T and Z in your date

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private Date currentTime;

output

{
    "currentTime": "2019-12-11T11:40:49Z"
}

How to kill a thread instantly in C#?

C# Thread.Abort is NOT guaranteed to abort the thread instantaneously. It will probably work when a thread calls Abort on itself but not when a thread calls on another.

Please refer to the documentation: http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx

I have faced this problem writing tools that interact with hardware - you want immediate stop but it is not guaranteed. I typically use some flags or other such logic to prevent execution of parts of code running on a thread (and which I do not want to be executed on abort - tricky).

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

git remove merge commit from history

Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more. The reason that your rebase wasn't working was that you weren't going back far enough.

WARNING: You are rewriting history doing this. Doing this with changes that have been pushed to a remote repo will cause issues. I recommend only doing this with commits that are local.

How can I loop through a C++ map of maps?

Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:

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

for(auto const &ent1 : mymap) {
  // ent1.first is the first key
  for(auto const &ent2 : ent1.second) {
    // ent2.first is the second key
    // ent2.second is the data
  }
}

this should be much cleaner than the earlier versions, and avoids unnecessary copies.

Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):

for(auto const &ent1 : mymap) {
  auto const &outer_key = ent1.first;
  auto const &inner_map = ent1.second;
  for(auto const &ent2 : inner_map) {
    auto const &inner_key   = ent2.first;
    auto const &inner_value = ent2.second;
  }
}

CSS Animation onClick

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

List all sequences in a Postgres db 8.1 with SQL

Here is another one which has the schema name beside the sequence name

select nspname,relname from pg_class c join pg_namespace n on c.relnamespace=n.oid where relkind = 'S' order by nspname

Javascript - sort array based on another array

Use the $.inArray() method from jQuery. You then could do something like this

var sortingArr = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
var newSortedArray = new Array();

for(var i=sortingArr.length; i--;) {
 var foundIn = $.inArray(sortingArr[i], itemsArray);
 newSortedArray.push(itemsArray[foundIn]);
}

Store an array in HashMap

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();

pick one, for example

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
    map.get("Something").add(coeficientUzura[i]); 
}

or just

HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);

fstream won't create a file

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out);

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/

What's the difference between HEAD^ and HEAD~ in Git?

^ BRANCH Selector
git checkout HEAD^2
Selects the 2nd branch of a (merge) commit by moving onto the selected branch (one step backwards on the commit-tree)

~ COMMIT Selector
git checkout HEAD~2
Moves 2 commits backwards on the default/selected branch


Defining both ~ and ^ relative refs as PARENT selectors is far the dominant definition published everywhere on the internet I have come across so far - including the official Git Book. Yes they are PARENT selectors, but the problem with this "explanation" is that it is completely against our goal: which is how to distinguish the two... :)

The other problem is when we are encouraged to use the ^ BRANCH selector for COMMIT selection (aka HEAD^ === HEAD~).
Again, yes, you can use it this way, but this is not its designed purpose. The ^ BRANCH selector's backwards move behaviour is a side effect not its purpose.

At merged commits only, can a number be assigned to the ^ BRANCH selector. Thus its full capacity can only be utilised where there is a need for selecting among branches. And the most straightforward way to express a selection in a fork is by stepping onto the selected path / branch - that's for the one step backwards on the commit-tree. It is a side effect only, not its main purpose.

CSS background opacity with rgba not working in IE 8

It is very simply you have to give first you have to give backgound as rgb because Internet Explorer 8 will support rgb instead rgba and then u have to give opacity like filter:alpha(opacity=50);

background:rgb(0,0,0);
filter:alpha(opacity=50);

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

How to do a HTTP HEAD request from the windows command line?

I'd download PuTTY and run a telnet session on port 80 to the webserver you want

HEAD /resource HTTP/1.1
Host: www.example.com

You could alternatively download Perl and try LWP's HEAD command. Or write your own script.

Python extract pattern matches

You can use groups (indicated with '(' and ')') to capture parts of the string. The match object's group() method then gives you the group's contents:

>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0)  # the entire match
'name my_user_name is valid'
>>> match.group(1)  # the first parenthesized subgroup
'my_user_name'

In Python 3.6+ you can also index into a match object instead of using group():

>>> match[0]  # the entire match 
'name my_user_name is valid'
>>> match[1]  # the first parenthesized subgroup
'my_user_name'

How can I check if a Perl array contains a particular value?

Method 1: grep (may careful while value is expected to be a regex).

Try to avoid using grep, if looking at resources.

if ( grep( /^$value$/, @badparams ) ) {
  print "found";
}

Method 2: Linear Search

for (@badparams) {
    if ($_ eq $value) {
       print "found";
       last;
    }
}

Method 3: Use a hash

my %hash = map {$_ => 1} @badparams;
print "found" if (exists $hash{$value});

Method 4: smartmatch

(added in Perl 5.10, marked is experimental in Perl 5.18).

use experimental 'smartmatch';  # for perl 5.18
print "found" if ($value ~~ @badparams);

Method 5: Use the module List::MoreUtils

use List::MoreUtils qw(any);
@badparams = (1,2,3);
$value = 1;
print "found" if any {$_ == $value} @badparams;

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

I made use of variables defined in :root inside CSS to modify the :after (the same applies to :before) pseudo-element, in particular to change the background-color value for a styled anchor defined by .sliding-middle-out:hover:after and the content value for another anchor (#reference) in the following demo that generates random colors by using JavaScript/jQuery:

HTML

<a href="#" id="changeColor" class="sliding-middle-out" title="Generate a random color">Change link color</a>
<span id="log"></span>
<h6>
  <a href="https://stackoverflow.com/a/52360188/2149425" id="reference" class="sliding-middle-out" target="_blank" title="Stack Overflow topic">Reference</a>
</h6>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/davidmerfield/randomColor/master/randomColor.js"></script>

CSS

:root {
    --anchorsFg: #0DAFA4;
}
a, a:visited, a:focus, a:active {
    text-decoration: none;
    color: var(--anchorsFg);
    outline: 0;
    font-style: italic;

    -webkit-transition: color 250ms ease-in-out;
    -moz-transition: color 250ms ease-in-out;
    -ms-transition: color 250ms ease-in-out;
    -o-transition: color 250ms ease-in-out;
    transition: color 250ms ease-in-out;
}
.sliding-middle-out {
    display: inline-block;
    position: relative;
    padding-bottom: 1px;
}
.sliding-middle-out:after {
    content: '';
    display: block;
    margin: auto;
    height: 1px;
    width: 0px;
    background-color: transparent;

    -webkit-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -moz-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -ms-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -o-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
}
.sliding-middle-out:hover:after {
    width: 100%;
    background-color: var(--anchorsFg);
    outline: 0;
}
#reference {
  margin-top: 20px;
}
.sliding-middle-out:before {
  content: attr(data-content);
  display: attr(data-display);
}

JS/jQuery

var anchorsFg = randomColor();
$( ".sliding-middle-out" ).hover(function(){
    $( ":root" ).css({"--anchorsFg" : anchorsFg});
});

$( "#reference" ).hover(
 function(){
    $(this).attr("data-content", "Hello World!").attr("data-display", "block").html("");
 },
 function(){
    $(this).attr("data-content", "Reference").attr("data-display", "inline").html("");
 }
);

How to jump to top of browser page

You can set the scrollTop, like this:

$('html,body').scrollTop(0);

Or if you want a little animation instead of a snap to the top:

$('html, body').animate({ scrollTop: 0 }, 'fast');

Laravel back button

One of the below solve your problem

URL::previous() 
URL::back()

other

URL::current()

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

how to make UITextView height dynamic according to text length?

Give this a try:

CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;

Edit- Here's the Swift:

var frame = self.textView.frame
frame.size.height = self.textView.contentSize.height
self.textView.frame = frame

Python multiprocessing PicklingError: Can't pickle <type 'function'>

When this problem comes up with multiprocessing a simple solution is to switch from Pool to ThreadPool. This can be done with no change of code other than the import-

from multiprocessing.pool import ThreadPool as Pool

This works because ThreadPool shares memory with the main thread, rather than creating a new process- this means that pickling is not required.

The downside to this method is that python isn't the greatest language with handling threads- it uses something called the Global Interpreter Lock to stay thread safe, which can slow down some use cases here. However, if you're primarily interacting with other systems (running HTTP commands, talking with a database, writing to filesystems) then your code is likely not bound by CPU and won't take much of a hit. In fact I've found when writing HTTP/HTTPS benchmarks that the threaded model used here has less overhead and delays, as the overhead from creating new processes is much higher than the overhead for creating new threads.

So if you're processing a ton of stuff in python userspace this might not be the best method.

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

JAXB Exception: Class not known to this context

Your ProfileDto class is not referenced in SearchResultDto. Try adding @XmlSeeAlso(ProfileDto.class) to SearchResultDto.

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

How to impose maxlength on textArea in HTML using JavaScript

I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.

Inspired by, but an improvement over Dana Woodman's answer:

Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

EDIT: Updated version for jQuery 1.7+, using on instead of live

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

Angularjs loading screen on ajax request

The best way to do this is to use response interceptors along with custom directive. And the process can further be improved using pub/sub mechanism using $rootScope.$broadcast & $rootScope.$on methods.

As the whole process is documented in a well written blog article, I'm not going to repeat that here again. Please refer to that article to come up with your needed implementation.

Relationship between hashCode and equals method in Java

Have a look at Hashtables, Hashmaps, HashSets and so forth. They all store the hashed key as their keys. When invoking get(Object key) the hash of the parameter is generated and lookup in the given hashes.

When not overwriting hashCode() and the instance of the key has been changed (for example a simple string that doesn't matter at all), the hashCode() could result in 2 different hashcodes for the same object, resulting in not finding your given key in map.get().

Windows batch: echo without new line

Echo with preceding space and without newline

As stated by Pedro earlier, echo without new line and with preceding space works (provided "9" is a true [BackSpace]).

<nul set /p=.9    Hello everyone

I had some issues getting it to work in Windows 10 with the new console but managed the following way.
In CMD type:

echo .?>bs.txt

I got "?" by pressing [Alt] + [8]
(the actual symbol may vary depending upon codepage).

Then it's easy to copy the result from "bs.txt" using Notepad.exe to where it's needed.

@echo off
<nul set /p "_s=.?    Hello everyone"
echo: here

How to list only the file names that changed between two commits?

Also note, if you just want to see the changed files between the last commit and the one before it. This works fine: git show --name-only

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

Limitations of SQL Server Express

Another limitation to consider is that SQL Server Express editions go into an idle mode after a period of disuse.

Understanding SQL Express behavior: Idle time resource usage, AUTO_CLOSE and User Instances:

When SQL Express is idle it aggressively trims back the working memory set by writing the cached data back to disk and releasing the memory.

But this is easily worked around: Is there a way to stop SQL Express 2008 from Idling?

react-native: command not found

I ran into this issue by being a bit silly. I use nvm to manage my different versions of node, and installed react-native into a version of node that was not my default. Upon opening a new shell, I lost my command. :) Switching back of course fixed things.

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

Running windows shell commands with python

Simple Import os package and run below command.

import os
os.system("python test.py")

Intellij idea subversion checkout error: `Cannot run program "svn"`

Disabling Use command-line client from the settings on IntelliJ Ultimate 14.0.3 works for me.

I checked IDEA's document, IDEA don't need a SVN client software anymore. see below description from https://www.jetbrains.com/idea/help/using-subversion-integration.html

=================================================================

Prerequisites

IntelliJ IDEA comes bundled with Subversion plugin. This plugin is turned on by default. If it is not, make sure that the plugin is enabled. IntelliJ IDEA's Subversion integration does not require a standalone Subversion client. All you need is an account in your Subversion repository. Subversion integration is enabled for the current project root or directory.

==================================================================

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

submit form on click event using jquery

it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.

How do I refresh a DIV content?

For div refreshing without creating div inside yours with same id, you should use this inside your function

$("#yourDiv").load(" #yourDiv > *");

How to convert JSON to a Ruby hash

What about the following snippet?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}

Bootstrap Alert Auto Close

Tiggers automatically and manually when needed

$(function () {
    TriggerAlertClose();
});

function TriggerAlertClose() {
    window.setTimeout(function () {
        $(".alert").fadeTo(1000, 0).slideUp(1000, function () {
            $(this).remove();
        });
    }, 5000);
}

PHP Fatal error: Cannot redeclare class

It means you've already created a class.

For instance:

class Foo {}

// some code here

class Foo {}

That second Foo would throw the error.

Right align and left align text in same HTML table cell

td style is not necessary but will make it easier to see this example in browser

<table>
 <tr>
  <td style="border: 1px solid black; width: 200px;">
  <div style="width: 50%; float: left; text-align: left;">left</div>
  <div style="width: 50%; float: left; text-align: right;">right</div>
  </td>
 </tr>
</table>

How to find the socket connection state in C?

There is an easy way to check socket connection state via poll call. First, you need to poll socket, whether it has POLLIN event.

  1. If socket is not closed and there is data to read then read will return more than zero.
  2. If there is no new data on socket, then POLLIN will be set to 0 in revents
  3. If socket is closed then POLLIN flag will be set to one and read will return 0.

Here is small code snippet:

int client_socket_1, client_socket_2;
if ((client_socket_1 = accept(listen_socket, NULL, NULL)) < 0)
{
    perror("Unable to accept s1");
    abort();
}
if ((client_socket_2 = accept(listen_socket, NULL, NULL)) < 0)
{
    perror("Unable to accept s2");
    abort();
}
pollfd pfd[]={{client_socket_1,POLLIN,0},{client_socket_2,POLLIN,0}};
char sock_buf[1024]; 
while (true)
{
    poll(pfd,2,5);
    if (pfd[0].revents & POLLIN)
    {
        int sock_readden = read(client_socket_1, sock_buf, sizeof(sock_buf));
        if (sock_readden == 0)
            break;
        if (sock_readden > 0)
            write(client_socket_2, sock_buf, sock_readden);
    }
    if (pfd[1].revents & POLLIN)
    {
        int sock_readden = read(client_socket_2, sock_buf, sizeof(sock_buf));
        if (sock_readden == 0)
            break;
        if (sock_readden > 0)
            write(client_socket_1, sock_buf, sock_readden);
    }
}

sql ORDER BY multiple values in specific order?

@bobflux's answer is great. I would like to extend it by adding a complete query that uses proposed approach.

select tt.id, tt.x_field
from target_table as tt
-- Here we join our target_table with order_table to specify custom ordering.
left join
    (values ('f', 1), ('p', 2), ('i', 3), ('a', 4)) as order_table (x_field, order_num)
    on order_table.x_field = tt.x_field
order by
    order_table.order_num, -- Here we order values by our custom order.
    tt.x_field;            -- Other values can be ordered alphabetically, for example.

Here is complete demo.

@font-face not working

This is probably due to CORS (or not quoting paths) and is expected behaviour. I know it sounds confusing, but the reason is due to the source of your fonts and not the web page itself.

A good explanation and numerous solutions for Apache, NGINX, IIS or PHP available in multiple languages can be found here:

https://www.hirehop.com/blog/cross-domain-fonts-cors-font-face-issue/

No increment operator (++) in Ruby?

From a posting by Matz:

(1) ++ and -- are NOT reserved operator in Ruby.

(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.

(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

                      matz.

How do I concatenate two strings in Java?

You can concatenate Strings using the + operator:

System.out.println("Your number is " + theNumber + "!");

theNumber is implicitly converted to the String "42".

Why rgb and not cmy?

The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).

The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK

A bit more information from the extract about them:

Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.

Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.

How to read a string one letter at a time in python

Why not just iterate through the string?

a_string="abcd"
for letter in a_string:
    print letter

returns

a
b
c
d

So, in pseudo-ish code, I would do this:

user_string = raw_input()
list_of_output = []
for letter in user_string:
   list_of_output.append(morse_code_ify(letter))

output_string = "".join(list_of_output)

Note: the morse_code_ify function is pseudo-code.

You definitely want to make a list of the characters you want to output rather than just concatenating on them on the end of some string. As stated above, it's O(n^2): bad. Just append them onto a list, and then use "".join(the_list).

As a side note: why are you removing the spaces? Why not just have morse_code_ify(" ") return a "\n"?

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.

Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.

Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md

Using request.setAttribute in a JSP page

i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.

Open source face recognition for Android

Here are some links that I found on face recognition libraries.

Image Identification links:

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

In my case neither M or G helped, so I have converted allocated memory to bytes using: https://www.gbmb.org/mb-to-bytes

4096M = 4294967296

php.ini:

memory_limit = 4294967296

How to make in CSS an overlay over an image?

Putting this answer here as it is the top result in Google.

If you want a quick and simple way:

    filter: brightness(0.2);

*Not compatible with IE

Get class list for element with jQuery

javascript provides a classList attribute for a node element in dom. Simply using

  element.classList

will return a object of form

  DOMTokenList {0: "class1", 1: "class2", 2: "class3", length: 3, item: function, contains: function, add: function, remove: function…}

The object has functions like contains, add, remove which you can use

Do C# Timers elapse on a separate thread?

For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.

    static System.Timers.Timer DummyTimer = null;

    static void Main(string[] args)
    {
        try
        {

            Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);

            DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
            DummyTimer.Enabled = true;
            DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
            DummyTimer.AutoReset = true;

            DummyTimer.Start();

            Console.WriteLine("Hit any key to exit");
            Console.ReadLine();
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.Message);
        }

        return;
    }

    static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
        return;
    }

Output you'd see if DummyTimer fired on 5 seconds interval:

Main Thread Id: 9
   12
   12
   12
   12
   12
   ... 

So, as seen, OnDummyTimerFired is executed on Workers thread.

No, further complication - If you reduce interval to say 10 ms,

Main Thread Id: 9
   11
   13
   12
   22
   17
   ... 

This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.

Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx#S2

What is “assert” in JavaScript?

If the assertion is false, the message is displayed. Specifically, if the first argument is false, the second argument (the string message) will be be logged in the developer tools console. If the first argument is true, basically nothing happens. A simple example – I’m using Google Developer Tools:

var isTrue = true;
var isFalse = false;
console.assert(isTrue, 'Equals true so will NOT log to the console.');
console.assert(isFalse, 'Equals false so WILL log to the console.');

matching query does not exist Error in Django

I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)

To resolve this during development, I used

request.session.flush()

How to convert a Map to List in Java?

List<Value> list = new ArrayList<Value>(map.values());

assuming:

Map<Key,Value> map;

Android Studio SDK location

I tried the accepted solution but it didn't resolve the issue for me.

I had already installed Android Studio 2-3 years ago, but I uninstalled it at some point. Installing the latest version was giving me an error. I did multiple uninstalls/reinstallations, but the issue persisted.

I found an SDK was available on my machine in %LocalAppData%. I opened the environment variable and deleted all the references of Android like Android Home /Path. I performed the uninstallation of Android Studio and then reinstalled.

This time it worked and installed properly; it is even downloading the other SDK-related files.

How to connect to mysql with laravel?

Laravel makes it very easy to manage your database connections through app/config/database.php.

As you noted, it is looking for a database called 'database'. The reason being that this is the default name in the database configuration file.

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database', <------ Default name for database
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Change this to the name of the database that you would like to connect to like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'my_awesome_data', <------ change name for database
    'username'  => 'root',            <------ remember credentials
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Once you have this configured correctly you will easily be able to access your database!

Happy Coding!

Get safe area inset top and bottom heights

None of the other answers here worked for me, but this did.

var topSafeAreaHeight: CGFloat = 0
var bottomSafeAreaHeight: CGFloat = 0

  if #available(iOS 11.0, *) {
    let window = UIApplication.shared.windows[0]
    let safeFrame = window.safeAreaLayoutGuide.layoutFrame
    topSafeAreaHeight = safeFrame.minY
    bottomSafeAreaHeight = window.frame.maxY - safeFrame.maxY
  }

Is there a TRY CATCH command in Bash

There are so many similar solutions which probably work. Below is a simple and working way to accomplish try/catch, with explanation in the comments.

#!/bin/bash

function a() {
  # do some stuff here
}
function b() {
  # do more stuff here
}

# this subshell is a scope of try
# try
(
  # this flag will make to exit from current subshell on any error
  # inside it (all functions run inside will also break on any error)
  set -e
  a
  b
  # do more stuff here
)
# and here we catch errors
# catch
errorCode=$?
if [ $errorCode -ne 0 ]; then
  echo "We have an error"
  # We exit the all script with the same error, if you don't want to
  # exit it and continue, just delete this line.
  exit $errorCode
fi

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Pro JavaScript programmer interview questions (with answers)

(I'm assuming you mean browser-side JavaScript)

Ask him why, despite his infinite knowledge of JavaScript, it is still a good idea to use existing frameworks such as jQuery, Mootools, Prototype, etc.

Answer: Good coders code, great coders reuse. Thousands of man hours have been poured into these libraries to abstract DOM capabilities away from browser specific implementations. There's no reason to go through all of the different browser DOM headaches yourself just to reinvent the fixes.

Sum up a column from a specific row down

If you don't mind using OFFSET(), which is a volatile function that recalculates everytime a cell is changed, then this is a good solution that is both dynamic and reusable:

=OFFSET($COL:$COL, ROW(), 1, 1048576 - ROW(), 1)

where $COL is the letter of the column you are going to operate upon, and ROW() is the row function that dynamically selects the same row as the cell containing this formula. You could also replace the ROW() function with a static number ($ROW).

=OFFSET($COL:$COL, $ROW, 1, 1048576 - $ROW, 1)

You could further clean up the formula by defining a named constant for the 1048576 as 'maxRows'. This can be done in the 'Define Name' menu of the Formulas tab.

=OFFSET($COL:$COL, $ROW, 1, maxRows - $ROW, 1)

A quick example: to Sum from C6 to the end of column C, you could do:

=SUM(OFFSET(C:C, 6, 1, maxRows - 6, 1))

or =SUM(OFFSET(C:C, ROW(), 1, maxRows - ROW(),1))

What's the difference between UTF-8 and UTF-8 without BOM?

I look at this from a different perspective. I think UTF-8 with BOM is better as it provides more information about the file. I use UTF-8 without BOM only if I face problems.

I am using multiple languages (even Cyrillic) on my pages for a long time and when the files are saved without BOM and I re-open them for editing with an editor (as cherouvim also noted), some characters are corrupted.

Note that Windows' classic Notepad automatically saves files with a BOM when you try to save a newly created file with UTF-8 encoding.

I personally save server side scripting files (.asp, .ini, .aspx) with BOM and .html files without BOM.

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

Error after upgrading pip: cannot import name 'main'

you can simply fix the pip and pip3 paths using update-alternatives

first thing you should check is your current $PATH run echo $PATH and see is you can find /usr/local/bin which is where pip3 and pip usually are

there is a change your system is looking here /bin/pip and /bin/pip3 so i will say fix the PATH by adding to your ~/.bash_profile file so it persists

export PATH=$PATH:/usr/local/bin and then check is its fixed with which pip and which pip3

if not then use update-alternatives to fix it finally

update-alternatives --install /bin/pip3 pip3 /usr/local/bin/pip3 30

and if you want to point pip to pip3 then

update-alternatives --install /bin/pip pip /usr/local/bin/pip3 30

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

The above solutions like run a query

SET session wait_timeout=600;

Will only work until mysql is restarted. For a persistant solution, edit mysql.conf and add after [mysqld]:

wait_timeout=300
interactive_timeout = 300

Where 300 is the number of seconds you want.

How to sort in-place using the merge sort algorithm?

I just tried in place merge algorithm for merge sort in JAVA by using the insertion sort algorithm, using following steps.
1) Two sorted arrays are available.
2) Compare the first values of each array; and place the smallest value into the first array.
3) Place the larger value into the second array by using insertion sort (traverse from left to right).
4) Then again compare the second value of first array and first value of second array, and do the same. But when swapping happens there is some clue on skip comparing the further items, but just swapping required.

I have made some optimization here; to keep lesser comparisons in insertion sort.
The only drawback i found with this solutions is it needs larger swapping of array elements in the second array.

e.g)

First___Array : 3, 7, 8, 9

Second Array : 1, 2, 4, 5

Then 7, 8, 9 makes the second array to swap(move left by one) all its elements by one each time to place himself in the last.

So the assumption here is swapping items is negligible compare to comparing of two items.

https://github.com/skanagavelu/algorithams/blob/master/src/sorting/MergeSort.java

package sorting;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
    int[] array = { 5, 6, 10, 3, 9, 2, 12, 1, 8, 7 };
    mergeSort(array, 0, array.length -1);
    System.out.println(Arrays.toString(array));

    int[] array1 = {4, 7, 2};
    System.out.println(Arrays.toString(array1));
    mergeSort(array1, 0, array1.length -1);
    System.out.println(Arrays.toString(array1));
    System.out.println("\n\n");

    int[] array2 = {4, 7, 9};
    System.out.println(Arrays.toString(array2));
    mergeSort(array2, 0, array2.length -1);
    System.out.println(Arrays.toString(array2));
    System.out.println("\n\n");

    int[] array3 = {4, 7, 5};
    System.out.println(Arrays.toString(array3));
    mergeSort(array3, 0, array3.length -1);
    System.out.println(Arrays.toString(array3));
    System.out.println("\n\n");

    int[] array4 = {7, 4, 2};
    System.out.println(Arrays.toString(array4));
    mergeSort(array4, 0, array4.length -1);
    System.out.println(Arrays.toString(array4));
    System.out.println("\n\n");

    int[] array5 = {7, 4, 9};
    System.out.println(Arrays.toString(array5));
    mergeSort(array5, 0, array5.length -1);
    System.out.println(Arrays.toString(array5));
    System.out.println("\n\n");

    int[] array6 = {7, 4, 5};
    System.out.println(Arrays.toString(array6));
    mergeSort(array6, 0, array6.length -1);
    System.out.println(Arrays.toString(array6));
    System.out.println("\n\n");

    //Handling array of size two
    int[] array7 = {7, 4};
    System.out.println(Arrays.toString(array7));
    mergeSort(array7, 0, array7.length -1);
    System.out.println(Arrays.toString(array7));
    System.out.println("\n\n");

    int input1[] = {1};
    int input2[] = {4,2};
    int input3[] = {6,2,9};
    int input4[] = {6,-1,10,4,11,14,19,12,18};
    System.out.println(Arrays.toString(input1));
    mergeSort(input1, 0, input1.length-1);
    System.out.println(Arrays.toString(input1));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input2));
    mergeSort(input2, 0, input2.length-1);
    System.out.println(Arrays.toString(input2));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input3));
    mergeSort(input3, 0, input3.length-1);
    System.out.println(Arrays.toString(input3));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input4));
    mergeSort(input4, 0, input4.length-1);
    System.out.println(Arrays.toString(input4));
    System.out.println("\n\n");
}

private static void mergeSort(int[] array, int p, int r) {
    //Both below mid finding is fine.
    int mid = (r - p)/2 + p;
    int mid1 = (r + p)/2;
    if(mid != mid1) {
        System.out.println(" Mid is mismatching:" + mid + "/" + mid1+ "  for p:"+p+"  r:"+r);
    }

    if(p < r) {
        mergeSort(array, p, mid);
        mergeSort(array, mid+1, r);
//      merge(array, p, mid, r);
        inPlaceMerge(array, p, mid, r);
        }
    }

//Regular merge
private static void merge(int[] array, int p, int mid, int r) {
    int lengthOfLeftArray = mid - p + 1; // This is important to add +1.
    int lengthOfRightArray = r - mid;

    int[] left = new int[lengthOfLeftArray];
    int[] right = new int[lengthOfRightArray];

    for(int i = p, j = 0; i <= mid; ){
        left[j++] = array[i++];
    }

    for(int i = mid + 1, j = 0; i <= r; ){
        right[j++] = array[i++];
    }

    int i = 0, j = 0;
    for(; i < left.length && j < right.length; ) {
        if(left[i] < right[j]){
            array[p++] = left[i++];
        } else {
            array[p++] = right[j++];
        }
    }
    while(j < right.length){
        array[p++] = right[j++];
    } 
    while(i < left.length){
        array[p++] = left[i++];
    }
}

//InPlaceMerge no extra array
private static void inPlaceMerge(int[] array, int p, int mid, int r) {
    int secondArrayStart = mid+1;
    int prevPlaced = mid+1;
    int q = mid+1;
    while(p < mid+1 && q <= r){
        boolean swapped = false;
        if(array[p] > array[q]) {
            swap(array, p, q);
            swapped = true;
        }   
        if(q != secondArrayStart && array[p] > array[secondArrayStart]) {
            swap(array, p, secondArrayStart);
            swapped = true;
        }
        //Check swapped value is in right place of second sorted array
        if(swapped && secondArrayStart+1 <= r && array[secondArrayStart+1] < array[secondArrayStart]) {
            prevPlaced = placeInOrder(array, secondArrayStart, prevPlaced);
        }
        p++;
        if(q < r) {     //q+1 <= r) {
            q++;
        }
    }
}

private static int placeInOrder(int[] array, int secondArrayStart, int prevPlaced) {
    int i = secondArrayStart;
    for(; i < array.length; i++) {
        //Simply swap till the prevPlaced position
        if(secondArrayStart < prevPlaced) {
            swap(array, secondArrayStart, secondArrayStart+1);
            secondArrayStart++;
            continue;
        }
        if(array[i] < array[secondArrayStart]) {
            swap(array, i, secondArrayStart);
            secondArrayStart++;
        } else if(i != secondArrayStart && array[i] > array[secondArrayStart]){
            break;
        }
    }
    return secondArrayStart;
}

private static void swap(int[] array, int m, int n){
    int temp = array[m];
    array[m] = array[n];
    array[n] = temp;
}
}

How to get HTTP response code for a URL in Java?

you can use java http/https url connection to get the response code from the website and other information as well here is a sample code.

 try {

            url = new URL("https://www.google.com"); // create url object for the given string  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if(https_url.startsWith("https")){
                 connection = (HttpsURLConnection) url.openConnection();
            }

            ((HttpURLConnection) connection).setRequestMethod("HEAD");
            connection.setConnectTimeout(50000); //set the timeout
            connection.connect(); //connect
            String responseMessage = connection.getResponseMessage(); //here you get the response message
             responseCode = connection.getResponseCode(); //this is http response code
            System.out.println(obj.getUrl()+" is up. Response Code : " + responseMessage);
            connection.disconnect();`
}catch(Exception e){
e.printStackTrace();
}

Maven plugins can not be found in IntelliJ

I just delete all my maven plugins stored in .m2\repository\org\apache\maven\plugins, and IntelliJ downloaded all the plugins again a it solve my problem and it worked fine for me!!!

message box in jquery

Do you mean just? alert()

function hello_world(){ alert("hello world"); }

How do I convert a list into a string with spaces in Python?

For Non String list we can do like this as well

" ".join(map(str, my_list))

shell script to remove a file if it already exist

If you want to ignore the step to check if file exists or not, then you can use a fairly easy command, which will delete the file if exists and does not throw an error if it is non-existing.

 rm -f xyz.csv

Set CFLAGS and CXXFLAGS options using CMake

On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")

It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.

Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

This maybe not a usefull solution for OP but it concerns the same "error" message.

We are hosting PHP pages on IIS8.5 with .NET 4.5 installed correctly.

We make use of the preload functionality to make sure our application is always responsive across the board.

After a while we started getting this error at random.

In the web.config : I put skipManagedModules to true, -> don't do this!

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
<applicationInitialization skipManagedModules="false" doAppInitAfterRestart="true">
  <add initializationPage="/" />
</applicationInitialization>
...

Although website is php, the routing to the paging is managed by the modules!!!

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

What's the difference between a mock & stub?

Plus useful answers, One of the most powerful point of using Mocks than Subs

If the collaborator [which the main code depend on it] is not under our control (e.g. from a third-party library),
In this case, stub is more difficult to write rather than mock.

Code for a simple JavaScript countdown timer?

_x000D_
_x000D_
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Nov 13 2017 22:05:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
  now = new Date();_x000D_
  seconds = (theevent - now) / 1000;_x000D_
  seconds = Math.round(seconds);_x000D_
  minutes = seconds / 60;_x000D_
  minutes = Math.round(minutes);_x000D_
  hours = minutes / 60;_x000D_
  hours = Math.round(hours);_x000D_
  days = hours / 24;_x000D_
  days = Math.round(days);_x000D_
  document.form1.days.value = days;_x000D_
  document.form1.hours.value = hours;_x000D_
  document.form1.minutes.value = minutes;_x000D_
  document.form1.seconds.value = seconds;_x000D_
  ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
  <p>Days_x000D_
    <input type="text" name="days" value="0" size="3">Hours_x000D_
    <input type="text" name="hours" value="0" size="4">Minutes_x000D_
    <input type="text" name="minutes" value="0" size="7">Seconds_x000D_
    <input type="text" name="seconds" value="0" size="7">_x000D_
  </p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to check if an element is visible with WebDriver

element instanceof RenderedWebElement should work.

How to insert element as a first child?

Use: $("<p>Test</p>").prependTo(".inner"); Check out the .prepend documentation on jquery.com

How to replace url parameter with javascript/jquery?

Nowdays that's possible with native JS

var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.

submitting a form when a checkbox is checked

Use JavaScript by adding an onChange attribute to your input tags

<input onChange="this.form.submit()" ... />

Detect HTTP or HTTPS then force HTTPS in JavaScript

Not a Javascript way to answer this but if you use CloudFlare you can write page rules that redirect the user much faster to HTTPS and it's free. Looks like this in CloudFlare's Page Rules:

enter image description here

Encoding conversion in java

CharsetDecoder should be what you are looking for, no ?

Many network protocols and files store their characters with a byte-oriented character set such as ISO-8859-1 (ISO-Latin-1).
However, Java's native character encoding is Unicode UTF16BE (Sixteen-bit UCS Transformation Format, big-endian byte order).

See Charset. That doesn't mean UTF16 is the default charset (i.e.: the default "mapping between sequences of sixteen-bit Unicode code units and sequences of bytes"):

Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets.
[US-ASCII, ISO-8859-1 a.k.a. ISO-LATIN-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16]
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.

This example demonstrates how to convert ISO-8859-1 encoded bytes in a ByteBuffer to a string in a CharBuffer and visa versa.

// Create the encoder and decoder for ISO-8859-1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

try {
    // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
    // The new ByteBuffer is ready to be read.
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));

    // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    // The new ByteBuffer is ready to be read.
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
} catch (CharacterCodingException e) {
}

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

I got this error because I have installed "Eclipse IDE for Enterprise Java Developers", I uninstalled this and installed "Eclipse IDE for Java Developers". Problem solved for me.

EF LINQ include multiple and nested entities

In Entity Framework Core (EF.core) you can use .ThenInclude for including next levels.

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
    .ToList();

More information: https://docs.microsoft.com/en-us/ef/core/querying/related-data

Note: Say you need multiple ThenInclude() on blog.Posts, just repeat the Include(blog => blog.Posts) and do another ThenInclude(post => post.Other).

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Other)
 .ToList();

How to check if C string is empty

Typically speaking, you're going to have a hard time getting an empty string here, considering %s ignores white space (spaces, tabs, newlines)... but regardless, scanf() actually returns the number of successful matches...

From the man page:

the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

so if somehow they managed to get by with an empty string (ctrl+z for example) you can just check the return result.

int count = 0;
do {
  ...
  count = scanf("%62s", url);  // You should check return values and limit the 
                               // input length
  ...
} while (count <= 0)

Note you have to check less than because in the example I gave, you'd get back -1, again detailed in the man page:

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

There is a chance...
You might be missing @Service, @Repository annotation on your respective implementation classes.

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

Delete column from SQLite table

I've made a Python function where you enter the table and column to remove as arguments:

def removeColumn(table, column):
    columns = []
    for row in c.execute('PRAGMA table_info(' + table + ')'):
        columns.append(row[1])
    columns.remove(column)
    columns = str(columns)
    columns = columns.replace("[", "(")
    columns = columns.replace("]", ")")
    for i in ["\'", "(", ")"]:
        columns = columns.replace(i, "")
    c.execute('CREATE TABLE temptable AS SELECT ' + columns + ' FROM ' + table)
    c.execute('DROP TABLE ' + table)
    c.execute('ALTER TABLE temptable RENAME TO ' + table)
    conn.commit()

As per the info on Duda's and MeBigFatGuy's answers this won't work if there is a foreign key on the table, but this can be fixed with 2 lines of code (creating a new table and not just renaming the temporary table)

How can I export data to an Excel file

Have you ever hear NPOI, a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop. Github Page

This is my Excel Export class

/*
 * User: TMPCSigit [email protected]
 * Date: 25/11/2019
 * Time: 11:28
 * 
 */
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Employee_Manager
{
    public static class ExportHelper
    {       
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, string value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, double value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, DateTime value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteStyle( ISheet sheet, int columnIndex, int rowIndex, ICellStyle style )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.CellStyle = style;
        }

        public static IWorkbook CreateNewBook( string filePath )
        {
            IWorkbook book;
            var extension = Path.GetExtension( filePath );

            // HSSF => Microsoft Excel(xls??)(excel 97-2003)
            // XSSF => Office Open XML Workbook??(xlsx??)(excel 2007??)
            if( extension == ".xls" ) {
                book = new HSSFWorkbook();
            }
            else if( extension == ".xlsx" ) {
                book = new XSSFWorkbook();
            }
            else {
                throw new ApplicationException( "CreateNewBook: invalid extension" );
            }

            return book;
        }
        public static void createXls(DataGridView dg){
            try {
                string filePath = "";
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel XLS (*.xls)|*.xls";
                sfd.FileName = "Export.xls";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    filePath = sfd.FileName;
                    var book = CreateNewBook( filePath );
                    book.CreateSheet( "Employee" );
                    var sheet = book.GetSheet( "Employee" );
                    int columnCount = dg.ColumnCount;
                    string columnNames = "";
                    string[] output = new string[dg.RowCount + 1];
                    for (int i = 0; i < columnCount; i++)
                    {
                        WriteCell( sheet, i, 0, SplitCamelCase(dg.Columns[i].Name.ToString()) );
                    }
                    for (int i = 0; i < dg.RowCount; i++)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            var celData =  dg.Rows[i].Cells[j].Value;
                            if(celData == "" || celData == null){
                                celData = "-";
                            }
                            if(celData.ToString() == "System.Drawing.Bitmap"){
                                celData = "Ada";
                            }
                            WriteCell( sheet, j, i+1, celData.ToString() );
                        }
                    }
                    var style = book.CreateCellStyle();
                    style.DataFormat = book.CreateDataFormat().GetFormat( "yyyy/mm/dd" );
                    WriteStyle( sheet, 0, 4, style );
                    using( var fs = new FileStream( filePath, FileMode.Create ) ) {
                        book.Write( fs );
                    }
                }
            }
            catch( Exception ex ) {
                Console.WriteLine( ex );
            }
        }
        public static string SplitCamelCase(string input)
        {
            return Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
        }
    }
}

Find the max of 3 numbers in Java with different data types

Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so

public static double max(double... n) {
    int i = 0;
    double max = n[i];

    while (++i < n.length)
        if (n[i] > max)
            max = n[i];

    return max;
}

In your example, max could be used like this

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

public static void main(String[] args) {
    double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Android Studio - How to Change Android SDK Path

Though many of the above answers serve the purpose, there is one straight forward thing we can do in project itself.

In Eclipse, go to Window->Preferences, select "Android" from left side menu. On the right panel you will see "SDK Location". Provide the path here.

Good luck.

Fatal error: Call to undefined function mb_strlen()

In case Google search for this error

Call to undefined function mb_ereg_match()

takes somebody to this thread. Installing php-mbstring resolves it too.

Ubuntu 18.04.1, PHP 7.2.10

sudo apt-get install php7.2-mbstring

Software Design vs. Software Architecture

Architecture is high level, abstract and logical design whereas software design is low level,detailed and physical design.

Deleting an element from an array in PHP

To avoid doing a search one can play around with array_diff:

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

In this case one doesn't have to search/use the key.

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

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

Make sure that you have added ojdbc14.jar into your library.

For oracle 11g, usie ojdbc6.jar.

Java - Search for files in a directory

you can try something like this:

import java.io.*;
import java.util.*;
class FindFile 
{
    public void findFile(String name,File file)
    {
        File[] list = file.listFiles();
        if(list!=null)
        for (File fil : list)
        {
            if (fil.isDirectory())
            {
                findFile(name,fil);
            }
            else if (name.equalsIgnoreCase(fil.getName()))
            {
                System.out.println(fil.getParentFile());
            }
        }
    }
    public static void main(String[] args) 
    {
        FindFile ff = new FindFile();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the file to be searched.. " );
        String name = scan.next();
        System.out.println("Enter the directory where to search ");
        String directory = scan.next();
        ff.findFile(name,new File(directory));
    }
}

Here is the output:

J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load

Why do we have to override the equals() method in Java?

This should be enough to answer your question: http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html

The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.

(Partial quote - click through to read examples.)

How to empty a char array?

Don't bother trying to zero-out your char array if you are dealing with strings. Below is a simple way to work with the char strings.

Copy (assign new string):

strcpy(members, "hello");

Concatenate (add the string):

strcat(members, " world");

Empty string:

members[0] = 0;

Simple like that.

How to resize the jQuery DatePicker control

open ui.all.css

at the end put

@import "ui.base.css";
@import "ui.theme.css";

div.ui-datepicker {
font-size: 62.5%; 
}

and go !

How to copy directory recursively in python and overwrite all?

Have a look at the shutil package, especially rmtree and copytree. You can check if a file / path exists with os.paths.exists(<path>).

import shutil
import os

def copy_and_overwrite(from_path, to_path):
    if os.path.exists(to_path):
        shutil.rmtree(to_path)
    shutil.copytree(from_path, to_path)

Vincent was right about copytree not working, if dirs already exist. So distutils is the nicer version. Below is a fixed version of shutil.copytree. It's basically copied 1-1, except the first os.makedirs() put behind an if-else-construct:

import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst): # This one line does the trick
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

How can I compare strings in C using a `switch` statement?

If it is a 2 byte string you can do something like in this concrete example where I switch on ISO639-2 language codes.

    LANIDX_TYPE LanCodeToIdx(const char* Lan)
    {
      if(Lan)
        switch(Lan[0]) {
          case 'A':   switch(Lan[1]) {
                        case 'N': return LANIDX_AN;
                        case 'R': return LANIDX_AR;
                      }
                      break;
          case 'B':   switch(Lan[1]) {
                        case 'E': return LANIDX_BE;
                        case 'G': return LANIDX_BG;
                        case 'N': return LANIDX_BN;
                        case 'R': return LANIDX_BR;
                        case 'S': return LANIDX_BS;
                      }
                      break;
          case 'C':   switch(Lan[1]) {
                        case 'A': return LANIDX_CA;
                        case 'C': return LANIDX_CO;
                        case 'S': return LANIDX_CS;
                        case 'Y': return LANIDX_CY;
                      }
                      break;
          case 'D':   switch(Lan[1]) {
                        case 'A': return LANIDX_DA;
                        case 'E': return LANIDX_DE;
                      }
                      break;
          case 'E':   switch(Lan[1]) {
                        case 'L': return LANIDX_EL;
                        case 'N': return LANIDX_EN;
                        case 'O': return LANIDX_EO;
                        case 'S': return LANIDX_ES;
                        case 'T': return LANIDX_ET;
                        case 'U': return LANIDX_EU;
                      }
                      break;
          case 'F':   switch(Lan[1]) {
                        case 'A': return LANIDX_FA;
                        case 'I': return LANIDX_FI;
                        case 'O': return LANIDX_FO;
                        case 'R': return LANIDX_FR;
                        case 'Y': return LANIDX_FY;
                      }
                      break;
          case 'G':   switch(Lan[1]) {
                        case 'A': return LANIDX_GA;
                        case 'D': return LANIDX_GD;
                        case 'L': return LANIDX_GL;
                        case 'V': return LANIDX_GV;
                      }
                      break;
          case 'H':   switch(Lan[1]) {
                        case 'E': return LANIDX_HE;
                        case 'I': return LANIDX_HI;
                        case 'R': return LANIDX_HR;
                        case 'U': return LANIDX_HU;
                      }
                      break;
          case 'I':   switch(Lan[1]) {
                        case 'S': return LANIDX_IS;
                        case 'T': return LANIDX_IT;
                      }
                      break;
          case 'J':   switch(Lan[1]) {
                        case 'A': return LANIDX_JA;
                      }
                      break;
          case 'K':   switch(Lan[1]) {
                        case 'O': return LANIDX_KO;
                      }
                      break;
          case 'L':   switch(Lan[1]) {
                        case 'A': return LANIDX_LA;
                        case 'B': return LANIDX_LB;
                        case 'I': return LANIDX_LI;
                        case 'T': return LANIDX_LT;
                        case 'V': return LANIDX_LV;
                      }
                      break;
          case 'M':   switch(Lan[1]) {
                        case 'K': return LANIDX_MK;
                        case 'T': return LANIDX_MT;
                      }
                      break;
          case 'N':   switch(Lan[1]) {
                        case 'L': return LANIDX_NL;
                        case 'O': return LANIDX_NO;
                      }
                      break;
          case 'O':   switch(Lan[1]) {
                        case 'C': return LANIDX_OC;
                      }
                      break;
          case 'P':   switch(Lan[1]) {
                        case 'L': return LANIDX_PL;
                        case 'T': return LANIDX_PT;
                      }
                      break;
          case 'R':   switch(Lan[1]) {
                        case 'M': return LANIDX_RM;
                        case 'O': return LANIDX_RO;
                        case 'U': return LANIDX_RU;
                      }
                      break;
          case 'S':   switch(Lan[1]) {
                        case 'C': return LANIDX_SC;
                        case 'K': return LANIDX_SK;
                        case 'L': return LANIDX_SL;
                        case 'Q': return LANIDX_SQ;
                        case 'R': return LANIDX_SR;
                        case 'V': return LANIDX_SV;
                        case 'W': return LANIDX_SW;
                      }
                      break;
          case 'T':   switch(Lan[1]) {
                        case 'R': return LANIDX_TR;
                      }
                      break;
          case 'U':   switch(Lan[1]) {
                        case 'K': return LANIDX_UK;
                        case 'N': return LANIDX_UN;
                      }
                      break;
          case 'W':   switch(Lan[1]) {
                        case 'A': return LANIDX_WA;
                      }
                      break;
          case 'Z':   switch(Lan[1]) {
                        case 'H': return LANIDX_ZH;
                      }
                      break;
        }
      return LANIDX_UNDEFINED;
    }

LANIDX_* being constant integers used to index in arrays.

How can I check if an argument is defined when starting/calling a batch file?

A more-advanced example:

? unlimited arguments.

? exist on file system (either file or directory?) or a generic string.

? specify if is a file

? specify is a directory

? no extensions, would work in legacy scripts!

? minimal code ?

@echo off

:loop
      ::-------------------------- has argument ?
      if ["%~1"]==[""] (
        echo done.
        goto end
      )
      ::-------------------------- argument exist ?
      if not exist %~s1 (
        echo not exist
      ) else (
        echo exist
        if exist %~s1\NUL (
          echo is a directory
        ) else (
          echo is a file
        )
      )
      ::--------------------------
      shift
      goto loop
      
      
:end

pause

? other stuff..?

¦ in %~1 - the ~ removes any wrapping " or '.

¦ in %~s1 - the s makes the path be DOS 8.3 naming, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "s.

¦ the ["%~1"]==[""] "can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1 (just without the " wrapping, if any..)

if there were no arguments of if we've used shift and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""].

¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)

¦ execution examples

save it as identifier.cmd

it can identify an unlimited arguments (normally you are limited to %1-%9), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).


this allows you to run the following commands:

?identifier.cmd c:\windows and to get

exist
is a directory
done

?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE" and to get

exist
is a file
done

? and multiple arguments (of course this is the whole-deal..)

identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world

and to get

exist
is a directory
exist
is a file
exist
is a file
not exist
done.

naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)

Hope it helps anyone :)

published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory

and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax

Check if Cookie Exists

Sorry, not enough rep to add a comment, but from zmbq's answer:

Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:

bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;

How to delete SQLite database from Android programmatically

It's easy just type from your shell:

adb shell
cd /data/data
cd <your.application.java.package>
cd databases
su rm <your db name>.db

How can I make text appear on next line instead of overflowing?

Well, you can stick one or more "soft hyphens" (&#173;) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.

Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.

What is the easiest way to get the current day of the week in Android?

you can use that code for Kotlin which you will use calendar class from java into Kotlin

    val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)

    fun dayOfWeek() {
    println("What day is it today?")
    val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
    println( when (day) {
      1 -> "Sunday"
      2 -> "Monday"
      3 -> "Tuesday"
      4 -> "Wednesday"
      5 -> "Thursday"
      6 -> "Friday"
      7 -> "Saturday"
      else -> "Time has stopped"
   })
 }

How to serialize a JObject without the formatting?

You can also do the following;

string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

memory error in python

check program with this input:abc/if you got something like ab ac bc abc program works well and you need a stronger RAM otherwise the program is wrong.

Usage of MySQL's "IF EXISTS"

I found the example RichardTheKiwi quite informative.

Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

-- what I might write in MSSQL

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
    SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
    INSERT INTO TABLE(FieldValue) VALUES('')
    SELECT SCOPE_IDENTITY() AS TableID
END

-- rewritten for MySQL

IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
    SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
    INSERT INTO Table (FieldValue) VALUES('');
    SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;

The activity must be exported or contain an intent-filter

Sometimes if you change the starting activity you have to click edit in the run dropdown play button and in app change the Launch Options Activity to the one you have set the LAUNCHER intent filter in the manifest.

how to access the command line for xampp on windows

Thank you guys for this answers. But I think the accepted answer needs more clarity, As i found difficulty in getting the solution.

  1. We may set the environment variable as mentioned in the answer by w0rldart .

    In this case(after seting envmnt var) we may run the phpFile by opening start >> CMD and typing commands like,

    php.exe <path to file location>

    or

    php <path to file location>

    example:

    php.exe C:\xampp\htdocs\test.php
    
  2. you can open Start >> CMD as administrator and write like

    <path to php.exe in xampp's php folder> <path to file location>

    example:

    C:\xampp\php\php.exe C:\xampp\htdocs\test.php
    

    or

    C:\xampp\php\php C:\xampp\htdocs\test.php
    

Hopes this will help somebody.

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Split string with string as delimiter

I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).

@echo off
setlocal

set "str=string1&with spaces by string2&with spaces.txt"

set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"

echo "%string1%"
echo "%string2%"

For further details on the split method, see this post.

Left align and right align within div in Bootstrap

We can achieve by Bootstrap 4 Flexbox:

<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>

d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%

Example: JSFiddle

How to show particular image as thumbnail while implementing share on Facebook?

Facebook uses og:tags and the Open Graph Protocol to decipher what information to display when previewing your URL in a share dialog or in a news feed on facebook.

The og:tags contain information such as :

  • The title of the page
  • The type of page
  • The URL
  • The websites name
  • A description of the page
  • Facebook user_id's of administrators of the page ( on facebook )

Here is an example ( taken from the facebook documentation ) of some og:tags

<meta property="og:title" content="The Rock"/>
<meta property="og:type" content="movie"/>
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>

Once you have implemented the correct markup of the og:tags and set their values, you can test how facebook will view your URL by using the Facebook Debugger. The debugger tool will also highlight any problems it finds with the og:tags on the page or lack there-of.

One thing to keep in mind is that facebook does do some caching with regard to this information, so in order for changes to take effect your page will have t be scraped as stated in the documentation :

Editing Meta Tags

You can update the attributes of your page by updating your page's tags. Note that og:title and og:type are only editable initially - after your page receives 50 likes the title becomes fixed, and after your page receives 10,000 likes the type becomes fixed. These properties are fixed to avoid surprising users who have liked the page already. Changing the title or type tags after these limits are reached does nothing, your page retains the original title and type.

For the changes to be reflected on Facebook, you must force your page to be scraped. The page is scraped when an admin for the page clicks the Like button or when the URL is entered into the Facebook URL Linter Facebook Debugger...

How to run cron job every 2 hours

Just do:

0 */2 * * *  /home/username/test.sh 

The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)

Don't forget, you can check syslog to see if it ever actually ran!

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

Get Absolute Position of element within the window in wpf

Since .NET 3.0, you can simply use *yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*).

This will give you the point 0, 0 of your button, but towards the container. (You can also give an other point that 0, 0)

Check here for the doc.

CodeIgniter: How to use WHERE clause and OR clause

You can use this :

$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);

How to merge two files line by line in Bash

here's non-paste methods

awk

awk 'BEGIN {OFS=" "}{
  getline line < "file2"
  print $0,line
} ' file1

Bash

exec 6<"file2"
while read -r line
do
    read -r f2line <&6
    echo "${line}${f2line}"
done <"file1"
exec 6<&-

Python JSON encoding

Try:

import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"

simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon

NB: Based on Paolo's answer.

Showing the same file in both columns of a Sublime Text window

Yes, you can. When a file is open, click on File -> New View Into File. You can then drag the new tab to the other pane and view the file twice.

There are several ways to create a new pane. As described in other answers, on Linux and Windows, you can use AltShift2 (Option ?Command ?2 on OS X), which corresponds to View ? Layout ? Columns: 2 in the menu. If you have the excellent Origami plugin installed, you can use View ? Origami ? Pane ? Create ? Right, or the CtrlK, Ctrl? chord on Windows/Linux (replace Ctrl with ? on OS X).

Print list without brackets in a single row

This is what you need

", ".join(names)

How can I get the full/absolute URL (with domain) in Django?

Use handy request.build_absolute_uri() method on request, pass it the relative url and it'll give you full one.

By default, the absolute URL for request.get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

UITableView load more when scrolling to bottom like Facebook application

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

NSInteger sectionsAmount = [tableView numberOfSections];
NSInteger rowsAmount = [tableView numberOfRowsInSection:[indexPath section]];
if ([indexPath section] == sectionsAmount - 1 && [indexPath row] == rowsAmount - 1) {
    //get last row
    if (!isSearchActive && !isFilterSearchActive) {
        if (totalRecords % 8 == 0) {
            int64_t delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {


            [yourTableView beginUpdates];
            [yourTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
            [yourTableView endUpdates];
            });
        }
    }
}
}

What are these ^M's that keep showing up in my files in emacs?

^M at the end of line in Emacs is indicating a carriage return (\r) followed by a line feed (\n). You'll often see this if one person edits files on Windows (where end of line is the combination of carriage return and newline characters) and you edit in Unix or Linux (where end of line is only a newline character).

The combination of characters is usually not harmful. If you're using source control, you may be able to configure the text file checkin format so that lines are magically adjusted for you. Alternatively, you may be able to use checkin and checkout triggers that will automatically "fix" the files for you. Or, you might just use a tool like dos2unix to manually adjust things.

Specifying content of an iframe instead of the src attribute to a page

You can use data: URL in the src:

_x000D_
_x000D_
var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';_x000D_
var iframe = document.querySelector('iframe');_x000D_
iframe.src = 'data:text/html,' + encodeURIComponent(html);
_x000D_
<iframe></iframe>
_x000D_
_x000D_
_x000D_

Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.

Convert HTML to data:text/html link using JavaScript.

When do you use the "this" keyword?

I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)

But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.

Loop through an array of strings in Bash?

Yes

for Item in Item1 Item2 Item3 Item4 ;
  do
    echo $Item
  done

Output:

Item1
Item2
Item3
Item4

To preserve spaces; single or double quote list entries and double quote list expansions.

for Item in 'Item 1' 'Item 2' 'Item 3' 'Item 4' ;
  do
    echo "$Item"
  done

Output:

Item 1
Item 2
Item 3
Item 4

To make list over multiple lines

for Item in Item1 \
            Item2 \
            Item3 \
            Item4
  do
    echo $Item
  done

Output:

Item1
Item2
Item3
Item4

Simple list variable
List=( Item1 Item2 Item3 )

or

List=(
      Item1 
      Item2 
      Item3
     )

Display the list variable:

echo ${List[*]}

Output:

Item1 Item2 Item3

Loop through the list:

for Item in ${List[*]} 
  do
    echo $Item 
  done

Output:

Item1
Item2
Item3

Create a function to go through a list:

Loop(){
  for item in ${*} ; 
    do 
      echo ${item} 
    done
}
Loop ${List[*]}

Using the declare keyword (command) to create the list, which is technically called an array:

declare -a List=(
                 "element 1" 
                 "element 2" 
                 "element 3"
                )
for entry in "${List[@]}"
   do
     echo "$entry"
   done

Output:

element 1
element 2
element 3

Creating an associative array. A dictionary:

declare -A continent

continent[Vietnam]=Asia
continent[France]=Europe
continent[Argentina]=America

for item in "${!continent[@]}"; 
  do
    printf "$item is in ${continent[$item]} \n"
  done

Output:

 Argentina is in America
 Vietnam is in Asia
 France is in Europe

CSV variables or files in to a list.
Changing the internal field separator from a space, to what ever you want.
In the example below it is changed to a comma

List="Item 1,Item 2,Item 3"
Backup_of_internal_field_separator=$IFS
IFS=,
for item in $List; 
  do
    echo $item
  done
IFS=$Backup_of_internal_field_separator

Output:

Item 1
Item 2
Item 3

If need to number them:

` 

this is called a back tick. Put the command inside back ticks.

`command` 

It is next to the number one on your keyboard and or above the tab key, on a standard American English language keyboard.

List=()
Start_count=0
Step_count=0.1
Stop_count=1
for Item in `seq $Start_count $Step_count $Stop_count`
    do 
       List+=(Item_$Item)
    done
for Item in ${List[*]}
    do 
        echo $Item
    done

Output is:

Item_0.0
Item_0.1
Item_0.2
Item_0.3
Item_0.4
Item_0.5
Item_0.6
Item_0.7
Item_0.8
Item_0.9
Item_1.0

Becoming more familiar with bashes behavior:

Create a list in a file

cat <<EOF> List_entries.txt
Item1
Item 2 
'Item 3'
"Item 4"
Item 7 : *
"Item 6 : * "
"Item 6 : *"
Item 8 : $PWD
'Item 8 : $PWD'
"Item 9 : $PWD"
EOF

Read the list file in to a list and display

List=$(cat List_entries.txt)
echo $List
echo '$List'
echo "$List"
echo ${List[*]}
echo '${List[*]}'
echo "${List[*]}"
echo ${List[@]}
echo '${List[@]}'
echo "${List[@]}"

BASH commandline reference manual: Special meaning of certain characters or words to the shell.

SQL Last 6 Months

Try this one

where datediff(month, datetime_column, getdate()) <= 6

To exclude or filter out future dates

where datediff(month, datetime_column, getdate()) between 0 and 6


This part datediff(month, datetime_column, getdate()) will get the month difference in number of current date and Datetime_Column and will return Rows like:

Result
1
2
3
4
5
6
7
8
9
10

This is Our final condition to get last 6 months data

where result <= 6

C++ Compare char array with string

You're not working with strings. You're working with pointers. var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.

So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.

IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

The C way of doing this is to use the strcmp function:

strcmp(var1, "dev");

This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

So to compare for equality you need to do one of these:

if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}

However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

std::string var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

String in function parameter

char *arr; above statement implies that arr is a character pointer and it can point to either one character or strings of character

& char arr[]; above statement implies that arr is strings of character and can store as many characters as possible or even one but will always count on '\0' character hence making it a string ( e.g. char arr[]= "a" is similar to char arr[]={'a','\0'} )

But when used as parameters in called function, the string passed is stored character by character in formal arguments making no difference.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

What's the fastest way of checking if a point is inside a polygon in python

Your test is good, but it measures only some specific situation: we have one polygon with many vertices, and long array of points to check them within polygon.

Moreover, I suppose that you're measuring not matplotlib-inside-polygon-method vs ray-method, but matplotlib-somehow-optimized-iteration vs simple-list-iteration

Let's make N independent comparisons (N pairs of point and polygon)?

# ... your code...
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]

M = 10000
start_time = time()
# Ray tracing
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside1 = ray_tracing_method(x,y, polygon)
print "Ray Tracing Elapsed time: " + str(time()-start_time)

# Matplotlib mplPath
start_time = time()
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside2 = path.contains_points([[x,y]])
print "Matplotlib contains_points Elapsed time: " + str(time()-start_time)

Result:

Ray Tracing Elapsed time: 0.548588991165
Matplotlib contains_points Elapsed time: 0.103765010834

Matplotlib is still much better, but not 100 times better. Now let's try much simpler polygon...

lenpoly = 5
# ... same code

result:

Ray Tracing Elapsed time: 0.0727779865265
Matplotlib contains_points Elapsed time: 0.105288982391

android.os.NetworkOnMainThreadException with android 4.2

Use StrictMode Something like this:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }

How should I do integer division in Perl?

The lexically scoped integer pragma forces Perl to use integer arithmetic in its scope:

print 3.0/2.1 . "\n";    # => 1.42857142857143
{
  use integer;
  print 3.0/2.1 . "\n";  # => 1
}
print 3.0/2.1 . "\n";    # => 1.42857142857143

How to find a user's home directory on linux or unix?

To find the home directory for user FOO on a UNIX-ish system, use ~FOO. For the current user, use ~.

Finding the mode of a list

Here is how you can find mean,median and mode of a list:

import numpy as np
from scipy import stats

#to take input
size = int(input())
numbers = list(map(int, input().split()))

print(np.mean(numbers))
print(np.median(numbers))
print(int(stats.mode(numbers)[0]))

get all characters to right of last dash

I created a string extension for this, hope it helps.

public static string GetStringAfterChar(this string value, char substring)
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            var index = value.LastIndexOf(substring);
            return index > 0 ? value.Substring(index + 1) : value;
        }

        return string.Empty;
    }

Compare two files and write it to "match" and "nomatch" files

//STEP01   EXEC SORT90MB                        
//SORTJNF1 DD DSN=INPUTFILE1,   
//            DISP=SHR                          
//SORTJNF2 DD DSN=INPUTFILE2,   
//            DISP=SHR                          
//SORTOUT  DD DSN=MISMATCH_OUTPUT_FILE, 
//            DISP=(,CATLG,DELETE),             
//            UNIT=TAPE,                        
//            DCB=(RECFM=FB,BLKSIZE=0),         
//            DSORG=PS                          
//SYSOUT   DD SYSOUT=*                          
//SYSIN    DD *                                 
  JOINKEYS FILE=F1,FIELDS=(1,79,A)              
  JOINKEYS FILE=F2,FIELDS=(1,79,A)              
  JOIN UNPAIRED,F1,ONLY                         
  SORT FIELDS=COPY                              
/*                                              

Clearing all cookies with JavaScript

You can get a list by looking into the document.cookie variable. Clearing them all is just a matter of looping over all of them and clearing them one by one.

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

How to send a html email with the bash command "sendmail"?

It's simpler to use, the -a option :

cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]

Convert negative data into positive data in SQL Server

UPDATE mytbl
SET a = ABS(a)
where a < 0

ImportError: No module named site on Windows

For me it happened because I had 2 versions of python installed - python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.

How can I iterate over an enum?

The typical way is as follows:

enum Foo {
  One,
  Two,
  Three,
  Last
};

for ( int fooInt = One; fooInt != Last; fooInt++ )
{
   Foo foo = static_cast<Foo>(fooInt);
   // ...
}

Please note, the enum Last is meant to be skipped by the iteration. Utilizing this "fake" Last enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum. If you want to add more enums later, just add them before Last. The loop in this example will still work.

Of course, this breaks down if the enum values are specified:

enum Foo {
  One = 1,
  Two = 9,
  Three = 4,
  Last
};

This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.

switch ( foo )
{
    case One:
        // ..
        break;
    case Two:  // intentional fall-through
    case Three:
        // ..
        break;
    case Four:
        // ..
        break;
     default:
        assert( ! "Invalid Foo enum value" );
        break;
}

If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.

How can I read numeric strings in Excel cells as string (not numbers)?

Yes, this works perfectly

recommended:

        DataFormatter dataFormatter = new DataFormatter();
        String value = dataFormatter.formatCellValue(cell);

old:

cell.setCellType(Cell.CELL_TYPE_STRING);

even if you have a problem with retrieving a value from cell having formula, still this works.

Can I nest a <button> element inside an <a> using HTML5?

It is illegal in HTML5 to embed a button element inside a link.

Better to use CSS on the default and :active (pressed) states:

_x000D_
_x000D_
body{background-color:#F0F0F0} /* JUST TO MAKE THE BORDER STAND OUT */_x000D_
a.Button{padding:.1em .4em;color:#0000D0;background-color:#E0E0E0;font:normal 80% sans-serif;font-weight:700;border:2px #606060 solid;text-decoration:none}_x000D_
a.Button:not(:active){border-left-color:#FFFFFF;border-top-color:#FFFFFF}_x000D_
a.Button:active{border-right-color:#FFFFFF;border-bottom-color:#FFFFFF}
_x000D_
<p><a class="Button" href="www.stackoverflow.com">Click me<a>
_x000D_
_x000D_
_x000D_