Programs & Examples On #Sdcc

SDCC is a retargettable, optimizing ANSI - C compiler suite that targets the Intel MCS51 based microprocessors (8031, 8032, 8051, 8052, etc.), Maxim (formerly Dallas) DS80C390 variants, Freescale (formerly Motorola) HC08 based (hc08, s08) and Zilog Z80 based MCUs (z80, z180, gbz80, Rabbit 2000/3000, Rabbit 3000A). Work is in progress on supporting the Microchip PIC16 and PIC18 targets. It can be retargeted for other microprocessors.

Using Chrome's Element Inspector in Print Preview Mode?

As of Chrome 48 (and perhaps a few versions earlier), the function seems to have moved yet again:

The first few steps are unchanged:

  1. Press F12 to bring up the developer tools

  2. Press ESC to open the console

According to the previous answers, the setting could then be found under the "Emulation" tab. As shown in the images below, it has now been moved to the "Rendering" tab, which can be brought up by clicking on the three dots to the left of the "Console" tab.

Tab selection

Setting selection

How to "git clone" including submodules?

Try this.

git clone -b <branch_name> --recursive <remote> <directory>

If you have added the submodule in a branch make sure that you add it to the clone command.

How to pass a function as a parameter in Java?

Lambda Expressions

To add on to jk.'s excellent answer, you can now pass a method more easily using Lambda Expressions (in Java 8). First, some background. A functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

Without lambda expressions:

obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});

With lambda expressions:

obj.aMethod(i -> i == 982);

Here is an excerpt from the Java tutorial on Lambda Expressions:

Syntax of Lambda Expressions

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.

    Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

    p -> p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    
  • The arrow token, ->

  • A body, which consists of a single expression or a statement block. This example uses the following expression:

    p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

    p -> {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }
    

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)
    

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.


Here is how you can "pass a method" using a lambda expression:

Note: this uses a new standard functional interface, java.util.function.IntConsumer.

class A {
    public static void methodToPass(int i) { 
        // do stuff
    }
}
import java.util.function.IntConsumer;

class B {
    public void dansMethod(int i, IntConsumer aMethod) {
        /* you can now call the passed method by saying aMethod.accept(i), and it
        will be the equivalent of saying A.methodToPass(i) */
    }
}
class C {
    B b = new B();

    public C() {
        b.dansMethod(100, j -> A.methodToPass(j));   //Lambda Expression here
    }
}

The above example can be shortened even more using the :: operator.

public C() {
    b.dansMethod(100, A::methodToPass);
}

Stop MySQL service windows

I'm on XP. I've installed MySQL-5.6.10 manually from .zip, no Windows auto-installer provided by MySQL site. The /bin directory of my MySQL is in my PATH. So I start the server with mysqld --console command, like this:

C:\Documents and Settings\User>mysqld --console
2013-04-12 14:39:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_times
tamp server option (see documentation for more details).

From now on it is running. And that cmd window is occupied. I open and use another one.

I've tried to use the answers from above but none of them can stop the server. Only errors are throw. So I stop the server with mysqladmin -u root shutdown on the other cmd window or with Ctrl + C on the cmd window it is running in. The latter works not so good as the former, sometimes I have to click Ctrl + C twice or more.

The log of the shutdown process is like this:

2013-04-12 17:55:29 3968 [Note] Giving 0 client threads a chance to die gracefully
2013-04-12 17:55:29 3968 [Note] Event Scheduler: Purging the queue. 0 events
2013-04-12 17:55:29 3968 [Note] Shutting down slave threads
2013-04-12 17:55:29 3968 [Note] Forcefully disconnecting 0 remaining clients
2013-04-12 17:55:29 3968 [Note] Binlog end
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'partition'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INSERTED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_METRICS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCKS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_TRX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'InnoDB'
2013-04-12 17:55:29 3968 [Note] InnoDB: FTS optimize thread exiting.
2013-04-12 17:55:29 3968 [Note] InnoDB: Starting shutdown...
2013-04-12 17:55:30 3968 [Note] InnoDB: Shutdown completed; log sequence number 1719777
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'BLACKHOLE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'ARCHIVE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MRG_MYISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MyISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MEMORY'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'CSV'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'sha256_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_old_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_native_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'binlog'
2013-04-12 17:55:30 3968 [Note] mysqld: Shutdown complete

And I still don't know if it is 100% right way to shutdown the server, but it works :)

How can I initialize base class member variables in derived class constructor?

You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass of A) to initialize them:

class A 
{
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
    // Change "protected" to "public" to allow others to instantiate A.
private:
    int a, b; // Keep these variables private in A
};

class B : public A 
{
public:
    B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
    {
    } 
};

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

The meaning of NoInitialContextException error

The javax.naming package comprises the JNDI API. Since it's just an API, rather than an implementation, you need to tell it which implementation of JNDI to use. The implementations are typically specific to the server you're trying to talk to.

To specify an implementation, you pass in a Properties object when you construct the InitialContext. These properties specify the implementation to use, as well as the location of the server. The default InitialContext constructor is only useful when there are system properties present, but the properties are the same as if you passed them in manually.

As to which properties you need to set, that depends on your server. You need to hunt those settings down and plug them in.

Can you create nested WITH clauses for Common Table Expressions?

These answers are pretty good, but as far as getting the items to order properly, you'd be better off looking at this article http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge

Here's an example of his query.

WITH paths AS ( 
    SELECT 
        EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath 
    FROM EmployeeHierarchyWide 
    WHERE ManagerID IS NULL

    UNION ALL

    SELECT 
        ehw.EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath 
    FROM paths AS p 
        JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID 
) 
SELECT * FROM paths order by FullPath

What are the differences between JSON and JSONP?

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
  alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

Reset all the items in a form

I recently had to do this for Textboxes and Checkboxes but using JavaScript ...

How to reset textbox and checkbox controls in an ASP.net document

Here is the code ...

<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>

<script type="text/javascript">
      function ResetForm() {
          //get the all the Input type elements in the document
          var AllInputsElements = document.getElementsByTagName('input');
          var TotalInputs = AllInputsElements.length;

          //we have to find the checkboxes and uncheck them
          //note: <asp:checkbox renders to <input type="checkbox" after compiling, which is why we use 'input' above
          for(var i=0;i< TotalInputs ; i++ )
          {
            if(AllInputsElements[i].type =='checkbox')
            {
                AllInputsElements[i].checked = false;
            }
          }

          //reset all textbox controls
          $('input[type=text], textarea').val('');

          Page_ClientValidateReset();
          return false;
      }

      //This function resets all the validation controls so that they don't "fire" up
      //during a post-back.
      function Page_ClientValidateReset() {
          if (typeof (Page_Validators) != "undefined") {
              for (var i = 0; i < Page_Validators.length; i++) {
                  var validator = Page_Validators[i];
                  validator.isvalid = true;
                  ValidatorUpdateDisplay(validator);
              }
          }
      }
</script>

And call it with a button or any other method ...

<asp:button id="btnRESET" runat="server" onclientclick="return ResetForm();" text="RESET" width="100px"></asp:button>

If you don't use ValidationControls on your website, just remove all the code refering to it above and the call Page_ClientValidateReset();

I am sure you can expand it for any other control using the DOM. And since there is no post to the server, it's faster and no "flashing" either.

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

If you want to check syntax error for any nginx files, you can use the -c option.

[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]# 

Conda: Installing / upgrading directly from github

There's better support for this now through conda-env. You can, for example, now do:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It's more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

CSS - make div's inherit a height

As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.

Usually inherited height has to come from either an element which has an explicit height or if height: 100%; has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -

This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support

I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!

proof of concept example is here

Simple check for SELECT query empty result

SELECT count(*) as CountThis ....

Then you can compare it as string like so:

IF CHECKROW_RS("CountThis")="0" THEN ...

CHECKROW_RS is an object

Create table variable in MySQL

If you don't want to store table in database then @Evan Todd already has been provided temporary table solution.

But if you need that table for other users and want to store in db then you can use below procedure.

Create below ‘stored procedure’:

————————————

DELIMITER $$

USE `test`$$

DROP PROCEDURE IF EXISTS `sp_variable_table`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN

SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;

SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0', paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8");
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ‘Table has been created’;
END$$

DELIMITER ;

———————————————–

Now you can execute this procedure to create a variable name table as per below-

call sp_variable_table();

You can check new table after executing below command-

use test;show tables like ‘%zafar%’; — test is here ‘database’ name.

You can also check more details at below path-

http://mydbsolutions.in/how-can-create-a-table-with-variable-name/

Are iframes considered 'bad practice'?

As with all technologies, it has its ups and downs. If you are using an iframe to get around a properly developed site, then of course it is bad practice. However sometimes an iframe is acceptable.

One of the main problems with an iframe has to do with bookmarks and navigation. If you are using it to simply embed a page inside your content, I think that is fine. That is what an iframe is for.

However I've seen iframes abused as well. It should never be used as an integral part of your site, but as a piece of content within a site.

Usually, if you can do it without an iframe, that is a better option. I'm sure others here may have more information or more specific examples, it all comes down to the problem you are trying to solve.

With that said, if you are limited to HTML and have no access to a backend like PHP or ASP.NET etc, sometimes an iframe is your only option.

Possible to make labels appear when hovering over a point in matplotlib?

If you use jupyter notebook, my solution is as simple as:

%pylab
import matplotlib.pyplot as plt
import mplcursors
plt.plot(...)
mplcursors.cursor(hover=True)
plt.show()

YOu can get something like enter image description here

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Using import fs from 'fs'

It's not supported just yet... If you want to use it you will have to install Babel.

Is there a Python Library that contains a list of all the ascii characters?

You can do this without a module:

    characters = list(map(chr, range(97,123)))

Type characters and it should print ["a","b","c", ... ,"x","y","z"]. For uppercase use:

    characters=list(map(chr,range(65,91)))

Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range() to add more characters to the list.
map() calls chr() every iteration of the range().

How can you dynamically create variables via a while loop?

Stuffing things into the global and/or local namespaces is not a good idea. Using a dict is so some-other-language-ish ... d['constant-key'] = value just looks awkward. Python is OO. In the words of a master: """Namespaces are one honking great idea -- let's do more of those!"""

Like this:

>>> class Record(object):
...     pass
...
>>> r = Record()
>>> r.foo = 'oof'
>>> setattr(r, 'bar', 'rab')
>>> r.foo
'oof'
>>> r.bar
'rab'
>>> names = 'id description price'.split()
>>> values = [666, 'duct tape', 3.45]
>>> s = Record()
>>> for name, value in zip(names, values):
...     setattr(s, name, value)
...
>>> s.__dict__ # If you are suffering from dict withdrawal symptoms
{'price': 3.45, 'id': 666, 'description': 'duct tape'}
>>>

Include CSS,javascript file in Yii Framework

Easy in your conf/main.php. This is my example with bootstrap. You can see that here

'components'=>array(
    'clientScript' => array(
        'scriptMap' => array(
            'jquery.js'=>false,  //disable default implementation of jquery
            'jquery.min.js'=>false,  //desable any others default implementation
            'core.css'=>false, //disable
            'styles.css'=>false,  //disable
            'pager.css'=>false,   //disable
            'default.css'=>false,  //disable
        ),
        'packages'=>array(
            'jquery'=>array(                             // set the new jquery
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/jquery-1.7.2.min.js'),
            ),
            'bootstrap'=>array(                       //set others js libraries
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/bootstrap.min.js'),
                'css'=>array(                        // and css
                    'css/bootstrap.min.css',
                    'css/custom.css',
                    'css/bootstrap-responsive.min.css',
                ),
                'depends'=>array('jquery'),         // cause load jquery before load this.
            ),
        ),
    ),
),

How to list processes attached to a shared memory segment in linux?

Use ipcs -a: it gives detailed information of all resources [semaphore, shared-memory etc]

Here is the image of the output:

image

Writing a dictionary to a text file?

You can do as follow :

import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))

https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

Grouping functions (tapply, by, aggregate) and the *apply family

In the collapse package recently released on CRAN, I have attempted to compress most of the common apply functionality into just 2 functions:

  1. dapply (Data-Apply) applies functions to rows or (default) columns of matrices and data.frames and (default) returns an object of the same type and with the same attributes (unless the result of each computation is atomic and drop = TRUE). The performance is comparable to lapply for data.frame columns, and about 2x faster than apply for matrix rows or columns. Parallelism is available via mclapply (only for MAC).

Syntax:

dapply(X, FUN, ..., MARGIN = 2, parallel = FALSE, mc.cores = 1L, 
       return = c("same", "matrix", "data.frame"), drop = TRUE)

Examples:

# Apply to columns:
dapply(mtcars, log)
dapply(mtcars, sum)
dapply(mtcars, quantile)
# Apply to rows:
dapply(mtcars, sum, MARGIN = 1)
dapply(mtcars, quantile, MARGIN = 1)
# Return as matrix:
dapply(mtcars, quantile, return = "matrix")
dapply(mtcars, quantile, MARGIN = 1, return = "matrix")
# Same for matrices ...
  1. BY is a S3 generic for split-apply-combine computing with vector, matrix and data.frame method. It is significantly faster than tapply, by and aggregate (an also faster than plyr, on large data dplyr is faster though).

Syntax:

BY(X, g, FUN, ..., use.g.names = TRUE, sort = TRUE,
   expand.wide = FALSE, parallel = FALSE, mc.cores = 1L,
   return = c("same", "matrix", "data.frame", "list"))

Examples:

# Vectors:
BY(iris$Sepal.Length, iris$Species, sum)
BY(iris$Sepal.Length, iris$Species, quantile)
BY(iris$Sepal.Length, iris$Species, quantile, expand.wide = TRUE) # This returns a matrix 
# Data.frames
BY(iris[-5], iris$Species, sum)
BY(iris[-5], iris$Species, quantile)
BY(iris[-5], iris$Species, quantile, expand.wide = TRUE) # This returns a wider data.frame
BY(iris[-5], iris$Species, quantile, return = "matrix") # This returns a matrix
# Same for matrices ...

Lists of grouping variables can also be supplied to g.

Talking about performance: A main goal of collapse is to foster high-performance programming in R and to move beyond split-apply-combine alltogether. For this purpose the package has a full set of C++ based fast generic functions: fmean, fmedian, fmode, fsum, fprod, fsd, fvar, fmin, fmax, ffirst, flast, fNobs, fNdistinct, fscale, fbetween, fwithin, fHDbetween, fHDwithin, flag, fdiff and fgrowth. They perform grouped computations in a single pass through the data (i.e. no splitting and recombining).

Syntax:

fFUN(x, g = NULL, [w = NULL,] TRA = NULL, [na.rm = TRUE,] use.g.names = TRUE, drop = TRUE)

Examples:

v <- iris$Sepal.Length
f <- iris$Species

# Vectors
fmean(v)             # mean
fmean(v, f)          # grouped mean
fsd(v, f)            # grouped standard deviation
fsd(v, f, TRA = "/") # grouped scaling
fscale(v, f)         # grouped standardizing (scaling and centering)
fwithin(v, f)        # grouped demeaning

w <- abs(rnorm(nrow(iris)))
fmean(v, w = w)      # Weighted mean
fmean(v, f, w)       # Weighted grouped mean
fsd(v, f, w)         # Weighted grouped standard-deviation
fsd(v, f, w, "/")    # Weighted grouped scaling
fscale(v, f, w)      # Weighted grouped standardizing
fwithin(v, f, w)     # Weighted grouped demeaning

# Same using data.frames...
fmean(iris[-5], f)                # grouped mean
fscale(iris[-5], f)               # grouped standardizing
fwithin(iris[-5], f)              # grouped demeaning

# Same with matrices ...

In the package vignettes I provide benchmarks. Programming with the fast functions is significantly faster than programming with dplyr or data.table, especially on smaller data, but also on large data.

Show and hide divs at a specific time interval using jQuery

Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval so theres no cleanup that has to be done.

Having this HTML

<section id="testimonials">
    <h2>My testimonial spinner</h2>
    <div class="testimonial">
      <p>First content</p>
    </div>
    <div class="testimonial">
      <p>Second content</p>
    </div>
    <div class="testimonial">
       <p>Third content</p>
    </div>
</section>

Using ES2016

Here you call the function recursively and update the arguments.

  const testimonials = $('#testimonials')
      .children()
      .filter('div.testimonial');

  const showTestimonial = index => {

    testimonials.hide();
    $(testimonials[index]).fadeIn();

    return index === testimonials.length
      ? showTestimonial(0)
      : setTimeout(() => { showTestimonial(index + 1); }, 10000);
   }

showTestimonial(0); // id of the first element you want to show.

Laravel Eloquent - Get one Row

Using Laravel Eloquent you can get one row using first() method,

it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

Syntax:

Model::where('fieldname',$value)->first();

Example:

$user = User::where('email',$email)->first(); 
//OR
//$user = User::whereEmail($email)->first();

How to sum all column values in multi-dimensional array?

Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.

function array_add_by_key( $array1, $array2 ) {
    foreach ( $array2 as $k => $a ) {
        if ( array_key_exists( $k, $array1 ) ) {
            $array1[$k] += $a;
        } else {
            $array1[$k] = $a;
        }
    }
    return $array1;
}

sys.argv[1], IndexError: list index out of range

sys.argv is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.

But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.

The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot

Given a class, see if instance has method (Ruby)

I don't know why everyone is suggesting you should be using instance_methods and include? when method_defined? does the job.

class Test
  def hello; end
end

Test.method_defined? :hello #=> true

NOTE

In case you are coming to Ruby from another OO language OR you think that method_defined means ONLY methods that you defined explicitly with:

def my_method
end

then read this:

In Ruby, a property (attribute) on your model is basically a method also. So method_defined? will also return true for properties, not just methods.

For example:

Given an instance of a class that has a String attribute first_name:

<instance>.first_name.class #=> String

<instance>.class.method_defined?(:first_name) #=> true

since first_name is both an attribute and a method (and a string of type String).

Java ArrayList for integers

you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work

Convert True/False value read from file to boolean

you can use distutils.util.strtobool

>>> from distutils.util import strtobool

>>> strtobool('True')
1
>>> strtobool('False')
0

True values are y, yes, t, true, on and 1; False values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

How to find MySQL process list and to kill those processes?

Here is the solution:

  1. Login to DB;
  2. Run a command show full processlist;to get the process id with status and query itself which causes the database hanging;
  3. Select the process id and run a command KILL <pid>; to kill that process.

Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:

  1. Login to MySQL;
  2. Run a query Select concat('KILL ',id,';') from information_schema.processlist where user='user'; to print all processes with KILL command;
  3. Copy the query result, paste and remove a pipe | sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.

How to import a csv file into MySQL workbench?

It seems a little tricky since it really had bothered me for a long time.

You just need to open the table (right click the "Select Rows- Limit 10000") and you will open a new window. In this new window, you will find "import icon".

Laravel 5 – Remove Public from URL

There is always a reason to have a public folder in the Laravel setup, all public related stuffs should be present inside the public folder,

Don't Point your ip address/domain to the Laravel's root folder but point it to the public folder. It is unsafe pointing the server Ip to the root folder., because unless you write restrictions in .htaccess, one can easily access the other files.,

Just write rewrite condition in the .htaccess file and install rewrite module and enable the rewrite module, the problem which adds public in the route will get solved.

What are the differences between B trees and B+ trees?

B+Trees are much easier and higher performing to do a full scan, as in look at every piece of data that the tree indexes, since the terminal nodes form a linked list. To do a full scan with a B-Tree you need to do a full tree traversal to find all the data.

B-Trees on the other hand can be faster when you do a seek (looking for a specific piece of data by key) especially when the tree resides in RAM or other non-block storage. Since you can elevate commonly used nodes in the tree there are less comparisons required to get to the data.

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.

EDIT

Based on your comment, the following code:

namespace Ui
{
    class MainWindowClass;
}

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
{
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;
}

class MainWindow : public QMainWindow
{
    private:

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;
};

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
{
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass
    {};
}


class MainWindow : public QMainWindow
{
    private:

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;
};

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

How to properly ignore exceptions

try:
      doSomething()
except Exception: 
    pass
else:
      stuffDoneIf()
      TryClauseSucceeds()

FYI the else clause can go after all exceptions and will only be run if the code in the try doesn't cause an exception.

CakePHP select default value in SELECT input

In CakePHP 1.3, use 'default'=>value to select the default value in a select input:

$this->Form->input('Leaf.id', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));

JavaScript - Getting HTML form values

<input type="text" id="note_text" />

let value = document.getElementById("note_text").value;

Class file for com.google.android.gms.internal.zzaja not found

If you are using more than one libraries of firebase then make sure that the version are same.

Before:
  compile 'com.google.firebase:firebase-database:9.2.0'
    compile 'com.google.firebase:firebase-storage:9.2.0'
    compile 'com.firebaseui:firebase-ui-database:0.4.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.firebase:firebase-auth:9.0.2'

After:  compile 'com.google.firebase:firebase-database:9.2.0'
    compile 'com.google.firebase:firebase-storage:9.2.0'
    compile 'com.firebaseui:firebase-ui-database:0.4.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.firebase:firebase-auth:9.2.0'

in my case i have used auth with 9.0.2 .So i changed to 9.2.0

Install .ipa to iPad with or without iTunes

There were 3 ways to do this:

Method 1: Using iTunes. Yes, you can install .ipa in iPad, first you have to import that .ipa to your iTunes. Connect your iPad to iTunes then install application just by click on Install and then Sync.

Method 2: iFunbox

Method 3: Diawi

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

ssh : Permission denied (publickey,gssapi-with-mic)

I had the same issue while using vagrant. So from my Mac I was trying to ssh to a vagrant box (CentOS 7)

Solved it by amending the /etc/ssh/sshd_config PasswordAuthentication yes then re-started the service using sudo systemctl restart sshd

Hope this helps.

How can I display a messagebox in ASP.NET?

@freelancer If you are using ScriptManager then try this code for message..

string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(), 
                      "ServerControlScript", script, true);

Auto-click button element on page load using jQuery

You can use that and adjust the time you want to launch 1= onload 2000= 2 sec

_x000D_
_x000D_
$(document).ready(function(){
 $('#click').click(function(){
        alert('button clicked');
    });
  // set time out 2 sec
     setTimeout(function(){
        $('#click').trigger('click');
    }, 2000);
});
_x000D_
.container{
padding-top:50px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="col text-center">
<button id="click" class="btn btn-danger">Jquery Auto Click</button>
  </div>
   </div>
_x000D_
_x000D_
_x000D_

jQuery first child of "this"

If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):

element.children(":first").toggleClass("redClass");

How to install a python library manually

You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.

The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:

$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install. (Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )

If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:

$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz 
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

Why use Select Top 100 Percent?

The error says it all...

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Don't use TOP 100 PERCENT, use TOP n, where N is a number

The TOP 100 PERCENT (for reasons I don't know) is ignored by SQL Server VIEW (post 2012 versions), but I think MS kept it for syntax reasons. TOP n is better and will work inside a view and sort it the way you want when a view is used initially, but be careful.

Jquery, Clear / Empty all contents of tbody element?

You probably have found this out already, but for someone stuck with this problem:

$("#tableId > tbody").html("");

How to Sort Date in descending order From Arraylist Date in android?

If date in string format convert it to date format for each object :

String argmodifiledDate = "2014-04-06 22:26:15";
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            try
            {
                this.modifiledDate = format.parse(argmodifiledDate);
            }
            catch (ParseException e)
            {

                e.printStackTrace();
            }

Then sort the arraylist in descending order :

ArrayList<Document> lstDocument= this.objDocument.getArlstDocuments();
        Collections.sort(lstDocument, new Comparator<Document>() {
              public int compare(Document o1, Document o2) {
                  if (o1.getModifiledDate() == null || o2.getModifiledDate() == null)
                    return 0;     
                  return o2.getModifiledDate().compareTo(o1.getModifiledDate());
              }
            });

How to convert IPython notebooks to PDF and HTML?

You can use this simple online service. It supports both HTML and PDF.

Gray out image with CSS?

If you don't mind using a bit of JavaScript, jQuery's fadeTo() works nicely in every browser I've tried.

jQuery(selector).fadeTo(speed, opacity);

Embedding a media player in a website using HTML

You can use plenty of things.

  • If you're a standards junkie, you can use the HTML5 <audio> tag:

Here is the official W3C specification for the audio tag.

Usage:

<audio controls>
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
         type='audio/mp4'>
 <!-- The next two lines are only executed if the browser doesn't support MP4 files -->
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
         type='audio/ogg; codecs=vorbis'>
 <!-- The next line will only be executed if the browser doesn't support the <audio> tag-->
 <p>Your user agent does not support the HTML5 Audio element.</p>
</audio>

jsFiddle here.

Note: I'm not sure which are the best ones, as I have never used one (yet).


UPDATE: As mentioned in another answer's comment, you are using XHTML 1.0 Transitional. You might be able to get <audio> to work with some hack.


UPDATE 2: I just remembered another way to do play audio. This will work in XHTML!!! This is fully standards-compliant.

You use this JavaScript:

var aud = document.createElement("iframe");
aud.setAttribute('src', "http://yoursite.com/youraudio.mp4"); // replace with actual file path
aud.setAttribute('width', '1px');
aud.setAttribute('height', '1px');
aud.setAttribute('scrolling', 'no');
aud.style.border = "0px";
document.body.appendChild(aud);

This is my answer to another question.


UPDATE 3: To customise the controls, you can use something like this.

How can I filter a date of a DateTimeField in Django?

person = Profile.objects.get(id=1)

tasks = Task.objects.filter(assigned_to=person, time_stamp__year=person.time_stamp.utcnow().year)

all my model do have time_stamp so I used the person objects to obtain the current year

How to Upload Image file in Retrofit 2

@Multipart
@POST(Config.UPLOAD_IMAGE)
Observable<Response<String>> uploadPhoto(@Header("Access-Token") String header, @Part MultipartBody.Part imageFile);

And you can call this api like this:

   public void uploadImage(File file) {
     // create multipart
     RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

    // upload
    getViewInteractor().showProfileUploadingProgress();

    Observable<Response<String>> observable = api.uploadPhoto("",body);

    // on Response
    subscribeForNetwork(observable, new ApiObserver<Response<String>>() {
        @Override
        public void onError(Throwable e) {
            getViewInteractor().hideProfileUploadingProgress();
        }

        @Override
        public void onResponse(Response<String> response) {

            if (response.code() != 200) {
                Timber.d("error " + response.code());
                return;
            }
            getViewInteractor().hideProfileUploadingProgress();
            getViewInteractor().onProfileImageUploadSuccess(response.body());

        }
    });

}

jQuery DataTables: control table width

This works fine.

#report_container {
   float: right;
   position: relative;
   width: 100%;
}

ASP.NET MVC3 - textarea with @Html.EditorFor

You could use the [DataType] attribute on your view model like this:

public class MyViewModel
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}

and then you could have a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}

and a view which does what you want:

@model AppName.Models.MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Text)
    <input type="submit" value="OK" />
}

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :

var objResponse1 = 
    JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

In my case, there was something wrong with the .NET Core Windows Hosting Bundle installation.

I had that installed and had restarted IIS using ("net stop was /y" and "net start w3svc") after installation, but I would get that 500.19 error with Error Code 0x8007000d and Config Source -1: 0:.

I managed to resolve the issue by repairing the .NET Core Windows Hosting Bundle installation and restarting IIS using the commands I mentioned above.

Hope this helps someone!

Remap values in pandas column with a dict

As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:

df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))

The .transform() processes each column as a series. Contrary to .apply()which passes the columns aggregated in a DataFrame.

Consequently you can apply the Series method map().

Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map() method

App installation failed due to application-identifier entitlement

I had the same error and I solved it by changing Bundle Identifier to something new. After that it build project with no problem.

My steps:

  • Open Xcode
  • Go to General tab
  • Find Identity
  • Change Bundle Identifier to something new.

Bundle identifier change

Convert java.util.date default format to Timestamp in Java

Best one

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

How to display a loading screen while site content loads

First, set up a loading image in a div. Next, get the div element. Then, set a function that edits the css to make the visibility to "hidden". Now, in the <body>, put the onload to the function name.

How to redirect output to a file and stdout

< command > |& tee filename # this will create a file "filename" with command status as a content, If a file already exists it will remove existed content and writes the command status.

< command > | tee >> filename # this will append status to the file but it doesn't print the command status on standard_output (screen).

I want to print something by using "echo" on screen and append that echoed data to a file

echo "hi there, Have to print this on screen and append to a file" 

jQuery - Dynamically Create Button and Attach Event Handler

Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.

$("#myButton").click(function () {
    var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
        alert('hi');
    }).end();

    $("#nodeAttributeHeader").attr('style', 'display: table-row;');
    $("#addNodeTable tr:last").before(test);
});

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

"No cached version... available for offline mode."

Since you mention you have a proxy connection I will tell you what worked for me: I went to properties (as friedrich mentioned) ensuring the Offline Work was unchecked. I opened up the gradle.properties file in the IDE and added my proxy settings. Here's a generic version:

systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Then at the top of the properties file in the IDE there was a "Try Again" link which I clicked. That did it.

contenteditable change events

This thread was very helpful while I was investigating the subject.

I've modified some of the code available here into a jQuery plugin so it is in a re-usable form, primarily to satisfy my needs but others may appreciate a simpler interface to jumpstart using contenteditable tags.

https://gist.github.com/3410122

Update:

Due to its increasing popularity the plugin has been adopted by Makesites.org

Development will continue from here:

https://github.com/makesites/jquery-contenteditable

How to fast get Hardware-ID in C#?

The following approach was inspired by this answer to a related (more general) question.

The approach is to read the MachineGuid value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography. This value is generated during OS installation.

There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid value.

However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.

public string GetMachineGuid()
{
   string location = @"SOFTWARE\Microsoft\Cryptography";
   string name = "MachineGuid";

   using (RegistryKey localMachineX64View = 
       RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
   {
       using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
       {
           if (rk == null)
               throw new KeyNotFoundException(
                   string.Format("Key Not Found: {0}", location));

           object machineGuid = rk.GetValue(name);
           if (machineGuid == null)
               throw new IndexOutOfRangeException(
                   string.Format("Index Not Found: {0}", name));

           return machineGuid.ToString();
       }
   }
}

check if a file is open in Python

I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?

This is how you could do that:

while True:   # repeat until the try statement succeeds
    try:
        myfile = open("myfile.csv", "r+") # or "a+", whatever you need
        break                             # exit the loop
    except IOError:
        input("Could not open file! Please close Excel. Press Enter to retry.")
        # restart the loop

with myfile:
    do_stuff()

What is the difference between for and foreach?

You can use foreach if the object you want to iterate over implements the IEnumerable interface. You need to use for if you can access the object only by index.

Regular expressions in C: examples?

This is an example of using REG_EXTENDED. This regular expression

"^(-)?([0-9]+)((,|.)([0-9]+))?\n$"

Allows you to catch decimal numbers in Spanish system and international. :)

#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
regex_t regex;
int reti;
char msgbuf[100];

int main(int argc, char const *argv[])
{
    while(1){
        fgets( msgbuf, 100, stdin );
        reti = regcomp(&regex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
        if (reti) {
            fprintf(stderr, "Could not compile regex\n");
            exit(1);
        }

        /* Execute regular expression */
        printf("%s\n", msgbuf);
        reti = regexec(&regex, msgbuf, 0, NULL, 0);
        if (!reti) {
            puts("Match");
        }
        else if (reti == REG_NOMATCH) {
            puts("No match");
        }
        else {
            regerror(reti, &regex, msgbuf, sizeof(msgbuf));
            fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            exit(1);
        }

        /* Free memory allocated to the pattern buffer by regcomp() */
        regfree(&regex);
    }

}

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

How can I work with command line on synology?

for my example:

Windows XP ---> Synology:DS218+

  • Step1:
        > DNS: Control Panel (???)
             > Terminal & SNMP(??? & SNMP)
  • Step2:
        Enable Telnet service (?? Telnet ??)
        or Enable SSH Service (?? SSH ??)


    enter image description here
    enter image description here


  • Step3: Launch the terminal on Windows (or via executing

        cmd
    to launch the terminal)
    enter image description here


  • Step4: type: telnet your_nas_ip_or_domain_name, like below

        telnet 192.168.1.104
    enter image description here



  • Step5:
    demo a terminal application, like compiling the Java code

    Fzz login: tsungjung411

    Password:

    # shows the current working directory (?????????)
    $ pwd
    /var/services/homes/tsungjung411


    # edit a Java file (via vi), then compile and run it 
    # (?? vi ?? Java ??,???????)
    $ vi Main.java

    # show the file content (??????)
    $ cat Main.java
    public class Main {
        public static void main(String [] args) {
            System.out.println("hello, World!");
        }
    }

    # compiles the Java file (?? Java ??)
    javac Main.java

    # executes the Java file (?? Java ??)
    $ java Main
    hello, World!

    # shows the file list (??????)
    $ ls
    CloudStation  Main.class  Main.java  www

enter image description here


    # shows the JRE version on this Synology Disk Station
    $ java -version
    openjdk version "1.8.0_151"
    OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12)
    OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)




  • Step6:
    demo another terminal application, like running the Python code

    $ python
    Python 2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import sys
    >>>
    >>> # shows the the python version
    >>> print(sys.version)
    2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)]
    >>>
    >>> import os
    >>>
    >>> # shows the current working directory
    >>> print(os.getcwd())
    /volume1/homes/tsungjung411

enter image description here


    $ # launch Python 3
    $ python3
    Python 3.5.1 (default, Dec  9 2016, 00:20:03)
    [GCC 4.9.3 20150311 (prerelease)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>




How to get current domain name in ASP.NET

www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..

Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.

Personally, I'd suggest special-casing www. for this.

string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;

if (host.StartsWith("www."))
    return host.Substring(4);
else
    return host;

Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.

string host = ...;

int lastDot = host.LastIndexOf('.');

int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');

if (secondToLastDot > -1)
    return host.Substring(secondToLastDot + 1);
else
    return host;

Getting the port is just like other people have said.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

If you installed it using the PKG installer, you can do:

pkgutil --pkgs

or better:

pkgutil --pkgs | grep org.python.Python

which will output something like:

org.python.Python.PythonApplications-2.7
org.python.Python.PythonDocumentation-2.7
org.python.Python.PythonFramework-2.7
org.python.Python.PythonProfileChanges-2.7
org.python.Python.PythonUnixTools-2.7

you can now select which packages you will unlink (remove).

This is the unlink documentation:

 --unlink package-id
             Unlinks (removes) each file referenced by package-id. WARNING: This command makes no attempt to perform reference counting or dependency analy-
             sis. It can easily remove files required by your system. It may include unexpected files due to package tainting. Use the --files command first
             to double check.

In my example you will type

pkgutil --unlink org.python.Python.PythonApplications-2.7
pkgutil --unlink org.python.Python.PythonDocumentation-2.7
pkgutil --unlink org.python.Python.PythonFramework-2.7
pkgutil --unlink org.python.Python.PythonProfileChanges-2.7
pkgutil --unlink org.python.Python.PythonUnixTools-2.7

or in one single line:

pkgutil --pkgs | grep org.python.Python | xargs -L1 pkgutil -f --unlink

Important: --unlink is not available anymore starting with Lion (as of Q1`2014 that would include Lion, Mountain Lion, and Mavericks). If anyone that comes to this instructions try to use it with lion, should try instead to adapt it with what this post is saying: https://wincent.com/wiki/Uninstalling_packages_(.pkg_files)_on_Mac_OS_X

Allow anything through CORS Policy

Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.

I am running Nginx and it was simple enough to just modify the my_app.conf file (where my_app is your app name). You can find this file in /etc/nginx/conf.d

If you do not have location / {} already you can just add it under server {}, then add add_header 'Access-Control-Allow-Origin' '*'; under location / {}.

The final format should look something like this:

server {
    server_name ...;
    listen ...;
    root ...;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
    }
}

How can I exit from a javascript function?

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

How to keep :active css style after clicking an element

Combine JS & CSS :

button{
  /* 1st state */
}

button:hover{
  /* hover state */
}

button:active{
  /* click state */
}

button.active{
  /* after click state */
}


jQuery('button').click(function(){
   jQuery(this).toggleClass('active');
});

What is the difference between And and AndAlso in VB.NET?

AndAlso is much like And, except it works like && in C#, C++, etc.

The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".

This is sometimes very useful, e.g. in an expression such as:

If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
   ...
End If

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

How do I get the domain originating the request in express.js?

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

How to print last two columns using awk

Please try this out to take into account all possible scenarios:

awk '{print $(NF-1)"\t"$NF}'  file

or

awk 'BEGIN{OFS="\t"}' file

or

awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file

How to have an automatic timestamp in SQLite?

you can use triggers. works very well

CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME);


CREATE TRIGGER insert_Timestamp_Trigger
AFTER INSERT ON MyTable
BEGIN
   UPDATE MyTable SET Timestamp =STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;

CREATE TRIGGER update_Timestamp_Trigger
AFTER UPDATE On MyTable
BEGIN
   UPDATE MyTable SET Timestamp = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;

Dots in URL causes 404 with ASP.NET mvc and IIS

Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.

  @Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |

How do I change the default port (9000) that Play uses when I execute the "run" command?

Play 2.0-RC4

It is important to include quotes around the play command you want to run. In my case without the quotes play would still run on port 9000.

play "run 8080"

Alternatively you could run the following from the play console (type 'play' to get to the console)

run 8080

Java escape JSON String?

org.json.simple.JSONObject.escape() escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.

import org.json.simple.JSONValue;
JSONValue.escape("test string");

Add pom.xml when using maven

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <scope>test</scope>
</dependency>

How to customize the background color of a UITableViewCell?

vlado.grigorov has some good advice - the best way is to create a backgroundView, and give that a colour, setting everything else to the clearColor. Also, I think that way is the only way to correctly clear the colour (try his sample - but set 'clearColor' instead of 'yellowColor'), which is what I was trying to do.

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I am amazed to see so many string replace ideas of UUID. How about this:

UUID temp = UUID.randomUUID();
String uuidString = Long.toHexString(temp.getMostSignificantBits())
     + Long.toHexString(temp.getLeastSignificantBits());

This is the fasted way of doing it since the whole toString() of UUID is already more expensive not to mention the regular expression which has to be parsed and executed or the replacing with empty string.

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

PHP equivalent of .NET/Java's toString()

PHP is dynamically typed, so like Chris Fournier said, "If you use it like a string it becomes a string". If you're looking for more control over the format of the string then printf is your answer.

How to use the ProGuard in Android Studio?

Here is Some of Most Common Proguard Rules that you need to add in proguard-rules.pro file in Android Sutdio.

ButterKnife

 -keep class butterknife.** { *; }
 -dontwarn butterknife.internal.**
 -keep class **$$ViewBinder { *; }
 -keepclasseswithmembernames class * {
        @butterknife.* <fields>;
  }
 -keepclasseswithmembernames class * {
        @butterknife.* <methods>;
  }

Retrofit

 -dontwarn retrofit.**
 -keep class retrofit.** { *; }
 -keepattributes Signature
 -keepattributes Exceptions

OkHttp3

 -keepattributes Signature
 -keepattributes *Annotation*
 -keep class okhttp3.** { *; }
 -keep interface okhttp3.** { *; }
 -dontwarn okhttp3.** 
 -keep class sun.misc.Unsafe { *; }
 -dontwarn java.nio.file.*
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 

Gson

 -keep class sun.misc.Unsafe { *; }
 -keep class com.google.gson.stream.** { *; }

Code obfuscation

-keepclassmembers class com.yourname.models** { <fields>; }

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

Starting iPhone app development in Linux?

You can use Tersus (open source), and it lets you export the app as an Xcode project.

Resize command prompt through commands

I know, that's a 8 years old question, but that can still happen today.

Powershell ca be used for that. An example is shown here. The shortest command for the cmd is:

powershell -command "&{(get-host).ui.rawui.windowsize=@{width=100;height=55};}"

Set your wanted window size to the width and hight vars. However, this short line has two limitations:

  • Be sure that the window size is not larger than the predefined buffer sizes. Otherwise there occur an error message.
  • Depending on the system, loading and processing of Powershell takes 2...4 seconds. Sometimes this is a long time to wait.

To avoid that, in the command below the buffer size is defined. In addition, the process runs parallel to the other following cmd commands:

start /b powershell -command "&{$w=(get-host).ui.rawui;$w.buffersize=@{width=177;height=999};$w.windowsize=@{width=155;height=55};}"

The width and height values to the buffersize object, here 177 and 999, must be bigger or equal to the window size values.

Mapping list in Yaml to list of objects in Spring Boot

  • You don't need constructors
  • You don't need to annotate inner classes
  • RefreshScope have some problems when using with @Configuration. Please see this github issue

Change your class like this:

@ConfigurationProperties(prefix = "available-payment-channels-list")
@Configuration
public class AvailableChannelsConfiguration {

    private String xyz;
    private List<ChannelConfiguration> channelConfigurations;

    // getters, setters

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;

        // getters, setters
    }

}

.gitignore is ignored by Git

Mine wasn't working because I've literaly created a text document called .gitignore

Instead, create a text document, open it in Notepad++ then save as .gitignore

Make sure to pick All types (*.*) from the dropdown when you save it.


Or in gitbash, simply use touch .gitignore

How can I convert my Java program to an .exe file?

UPDATE: GCJ is dead. It was officially removed from the GCC project in 2016. Even before that, it was practically abandoned for seven years, and in any case it was never sufficiently complete to serve as a viable alternative Java implementation.

Go find another Java AOT compiler.

GCJ: The GNU Compiler for Java can compile Java source code into native machine code, including Windows executables.

Although not everything in Java is supported under GCJ, especially the GUI components (see What Java API's are supported? How complete is the support? question from the FAQ). I haven't used GCJ much, but from the limited testing I've done with console applications, it seems fine.

One downside of using GCJ to create an standalone executable is that the size of the resulting EXE can be quite large. One time I compiled a trivial console application in GCJ and the result was an executable about 1 MB. (There may be ways around this that I am not aware of. Another option would be executable compression programs.)

In terms of open-source installers, the Nullsoft Scriptable Install System is a scriptable installer. If you're curious, there are user contributed examples on how to detect the presence of a JRE and install it automatically if the required JRE is not installed. (Just to let you know, I haven't used NSIS before.)

For more information on using NSIS for installing Java applications, please take a look at my response for the question "What's the best way to distribute Java applications?"

How to use HttpWebRequest (.NET) asynchronously?

public static async Task<byte[]> GetBytesAsync(string url) {
    var request = (HttpWebRequest)WebRequest.Create(url);
    using (var response = await request.GetResponseAsync())
    using (var content = new MemoryStream())
    using (var responseStream = response.GetResponseStream()) {
        await responseStream.CopyToAsync(content);
        return content.ToArray();
    }
}

public static async Task<string> GetStringAsync(string url) {
    var bytes = await GetBytesAsync(url);
    return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}

Why can't variables be declared in a switch statement?

The entire section of the switch is a single declaration context. You can't declare a variable in a case statement like that. Try this instead:

switch (val)  
{  
case VAL:
{
  // This will work
  int newVal = 42;
  break;
}
case ANOTHER_VAL:  
  ...
  break;
}

How can I copy the output of a command directly into my clipboard?

For mac this is an example way to copy (into clipboard) paste (from clipboard) using command line

Copy the result of pwd command to clipboard as

$ pwd | pbcopy

Use the content in the clipboard as

$ cd $(pbpaste)

Is there a cross-browser onload event when clicking the back button?

I thought this would be for "onunload", not page load, since aren't we talking about firing an event when hitting "Back"? $document.ready() is for events desired on page load, no matter how you get to that page (i.e. redirect, opening the browser to the URL directly, etc.), not when clicking "Back", unless you're talking about what to fire on the previous page when it loads again. And I'm not sure the page isn't getting cached as I've found that Javascripts still are, even when $document.ready() is included in them. We've had to hit Ctrl+F5 when editing our scripts that have this event whenever we revise them and we want test the results in our pages.

$(window).unload(function(){ alert('do unload stuff here'); }); 

is what you'd want for an onunload event when hitting "Back" and unloading the current page, and would also fire when a user closes the browser window. This sounded more like what was desired, even if I'm outnumbered with the $document.ready() responses. Basically the difference is between an event firing on the current page while it's closing or on the one that loads when clicking "Back" as it's loading. Tested in IE 7 fine, can't speak for the other browsers as they aren't allowed where we are. But this might be another option.

Hashset vs Treeset

HashSet is O(1) to access elements, so it certainly does matter. But maintaining order of the objects in the set isn't possible.

TreeSet is useful if maintaining an order(In terms of values and not the insertion order) matters to you. But, as you've noted, you're trading order for slower time to access an element: O(log n) for basic operations.

From the javadocs for TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

How to change visibility of layout programmatically

TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);

How can I specify system properties in Tomcat configuration on startup?

This question is addressed in the Apache wiki.

Question: "Can I set Java system properties differently for each webapp?"

Answer: No. If you can edit Tomcat's startup scripts (or better create a setenv.sh file), you can add "-D" options to Java. But there is no way in Java to have different values of system properties for different classes in the same JVM. There are some other methods available, like using ServletContext.getContextPath() to get the context name of your web application and locate some resources accordingly, or to define elements in WEB-INF/web.xml file of your web application and then set the values for them in Tomcat context file (META-INF/context.xml). See http://tomcat.apache.org/tomcat-7.0-doc/config/context.html .

http://wiki.apache.org/tomcat/HowTo#Can_I_set_Java_system_properties_differently_for_each_webapp.3F

How to convert .pfx file to keystore with private key?

If you work with JDK 1.5 or below the keytool utility will not have the -importkeystore option (see JDK 1.5 keytool documentation) and the solution by MikeD will be available only by transferring the .pfx on a machine with a newer JDK (1.6 or above).

Another option in JDK 1.5 or below (if you have Oracle WebLogic product), is to follow the instructions from this Oracle document: Using PFX and PEM Certificate Formats with Keystores. It describes the conversion into .pem format, how to extract certificates information from this textual format, and import it into .jks format with java utils.ImportPrivateKey utility (this is an utility included with WebLogic product).

Preloading CSS Images

The only way is to Base64 encode the image and place it inside the HTML code so that it doesn't need to contact the server to download the image.

This will encode an image from url so you can copy the image file code and insert it in your page like so...

body {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);
}

Make a div fill the height of the remaining screen space

I wresteled with this for a while and ended up with the following:

Since it is easy to make the content DIV the same height as the parent but apparently difficult to make it the parent height minus the header height I decided to make content div full height but position it absolutely in the top left corner and then define a padding for the top which has the height of the header. This way the content displays neatly under the header and fills the whole remaining space:

body {
    padding: 0;
    margin: 0;
    height: 100%;
    overflow: hidden;
}

#header {
    position: absolute;
    top: 0;
    left: 0;
    height: 50px;
}

#content {
    position: absolute;
    top: 0;
    left: 0;
    padding-top: 50px;
    height: 100%;
}

OnclientClick and OnClick is not working at the same time?

There are two issues here:

Disabling the button on the client side prevents the postback

To overcome this, disable the button after the JavaScript onclick event. An easy way to do this is to use setTimeout as suggested by this answer.

Also, the OnClientClick code runs even if ASP.NET validation fails, so it's probably a good idea to add a check for Page_IsValid. This ensures that the button will not be disabled if validation fails.

OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"

It's neater to put all of this JavaScript code in its own function as the question shows:

OnClientClick="disable(this);"

function disable(button) {
    setTimeout(function () {
        if (Page_IsValid)
            button.disabled = true;
    }, 0);
}

Disabling the button on the client side doesn't disable it on the server side

To overcome this, disable the button on the server side. For example, in the OnClick event handler:

OnClick="Button1_Click"

protected void Button1_Click(object sender, EventArgs e)
{
    ((Button)sender).Enabled = false;
}

Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.

How does Trello access the user's clipboard?

Something very similar can be seen on http://goo.gl when you shorten the URL.

There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.

When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)

How do I print uint32_t and uint16_t variables value?

You need to include inttypes.h if you want all those nifty new format specifiers for the intN_t types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d or %u in case the sizes are different to what you think.

It includes stdint.h and extends it with quite a few other things, such as the macros that can be used for the printf/scanf family of calls. This is covered in section 7.8 of the ISO C99 standard.

For example, the following program:

#include <stdio.h>
#include <inttypes.h>
int main (void) {
    uint32_t a=1234;
    uint16_t b=5678;
    printf("%" PRIu32 "\n",a);
    printf("%" PRIu16 "\n",b);
    return 0;
}

outputs:

1234
5678

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

Converting Array to List

Old way but still working!

 int[] values = {1,2,3,4};
 List<Integer> list = new ArrayList<>(values.length);

 for(int valor : values) {
     list.add(valor);
 }

TypeError: '<=' not supported between instances of 'str' and 'int'

If you're using Python3.x input will return a string,so you should use int method to convert string to integer.

Python3 Input

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

By the way,it's a good way to use try catch if you want to convert string to int:

try:
  i = int(s)
except ValueError as err:
  pass 

Hope this helps.

jQuery select change event get selected option

See official API documentation https://api.jquery.com/selected-selector/

This good works:

$( "select" ).on('change',function() {
  var str = "";
  // For multiple choice
  $( "select option:selected" ).each(function() {
    str += $( this ).val() + " "; 
  });
});

and

$( "select" ).on('change',function() {
  // For unique choice
  var selVal = $( "select option:selected" ).val(); 
});

and be easy for unique choice

var SelVal = $( "#idSelect option:selected" ).val();

IOError: [Errno 13] Permission denied

I had a similar problem. I was attempting to have a file written every time a user visits a website.

The problem ended up being twofold.

1: the permissions were not set correctly

2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)

After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)

A process crashed in windows .. Crash dump location

a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).

If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP

jQuery $.ajax(), pass success data into separate function

this is how I do it

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

AngularJS ng-class if-else expression

This is the best and reliable way to do this. Here is a simple example and after that you can develop your custom logic:

//In .ts
public showUploadButton:boolean = false;

if(some logic)
{
    //your logic
    showUploadButton = true;
}

//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>

iOS Launching Settings -> Restrictions URL Scheme

In iOS 9 it works again!

To open Settings > General > Keyboard, I use:

prefs:root=General&path=Keyboard

Moreover, it is possible to go farther to Keyboards:

prefs:root=General&path=Keyboard/KEYBOARDS

Using PowerShell credentials without being prompted for a password

Regarding storing credentials, I use two functions(that are normally in a module that is loaded from my profile):

#=====================================================================
# Get-MyCredential
#=====================================================================
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = @"

    Get-MyCredential
    Usage:
    Get-MyCredential -CredPath `$CredPath

    If a credential is stored in $CredPath, it will be used.
    If no credential is found, Export-Credential will start and offer to
    Store a credential at the location specified.

"@
    if($Help -or (!($CredPath))){write-host $Helptext; Break}
    if (!(Test-Path -Path $CredPath -PathType Leaf)) {
        Export-Credential (Get-Credential) $CredPath
    }
    $cred = Import-Clixml $CredPath
    $cred.Password = $cred.Password | ConvertTo-SecureString
    $Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
    Return $Credential
}

And this one:

#=====================================================================
# Export-Credential
# Usage: Export-Credential $CredentialObject $FileToSaveTo
#=====================================================================
function Export-Credential($cred, $path) {
      $cred = $cred | Select-Object *
      $cred.password = $cred.Password | ConvertFrom-SecureString
      $cred | Export-Clixml $path
}

You use it like this:

$Credentials = Get-MyCredential (join-path ($PsScriptRoot) Syncred.xml)

If the credential file doesnt exist, you will be prompted the first time, at that point it will store the credentials in an encrypted string inside an XML file. The second time you run that line, the xmlfile is there and will be opened automatically.

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

How to left align a fixed width string?

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

on a side note you can make the width variable with *-s

>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple                    something                     '

Restart container within pod

kubectl exec -it POD_NAME -c CONTAINER_NAME bash - then kill 1

Assuming the container is run as root which is not recommended.

In my case when I changed the application config, I had to reboot the container which was used in a sidecar pattern, I would kill the PID for the spring boot application which is owned by the docker user.

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

I came across the same issue recently. I had to insert new rows in a document with hidden rows and faced the same issues with you. After some search and some emails in apache poi list, it seems like a bug in shiftrows() when a document has hidden rows.

Typescript es6 import module "File is not a module error"

Above answers are correct. But just in case... Got same error in VS Code. Had to re-save/recompile file that was throwing error.

Label points in geom_point

Use geom_text , with aes label. You can play with hjust, vjust to adjust text position.

ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)

enter image description here

EDIT: Label only values above a certain threshold:

  ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +
  geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)

chart with conditional labels

jQuery get an element by its data-id

This worked for me, in my case I had a button with a data-id attribute:

$("a").data("item-id");

Fiddle

AngularJS ui-router login authentication

The easiest solution is to use $stateChangeStart and event.preventDefault() to cancel the state change when the user is not authenticated and redirect him to the auth state that is the login page.

angular
  .module('myApp', [
    'ui.router',
  ])
    .run(['$rootScope', 'User', '$state',
    function ($rootScope, User, $state) {
      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.name !== 'auth' && !User.authenticaded()) {
          event.preventDefault();
          $state.go('auth');
        }
      });
    }]
  );

Appending the same string to a list of strings in Python

list2 = ['%sbar' % (x,) for x in list]

And don't use list as a name; it shadows the built-in type.

How do I get the current absolute URL in Ruby on Rails?

I think that the Ruby on Rails 3.0 method is now request.fullpath.

Create numpy matrix filled with NaNs

I compared the suggested alternatives for speed and found that, for large enough vectors/matrices to fill, all alternatives except val * ones and array(n * [val]) are equally fast.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot

val = 42.0


def fill(n):
    a = numpy.empty(n)
    a.fill(val)
    return a


def colon(n):
    a = numpy.empty(n)
    a[:] = val
    return a


def full(n):
    return numpy.full(n, val)


def ones_times(n):
    return val * numpy.ones(n)


def list(n):
    return numpy.array(n * [val])


perfplot.show(
    setup=lambda n: n,
    kernels=[fill, colon, full, ones_times, list],
    n_range=[2 ** k for k in range(20)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

How to set gradle home while importing existing project in Android studio

For Ubuntu default version is /usr/lib/gradle/default. In case of update, you don't need to reassign link in idea/studio.

How to remove extension from string (only real extension!)

Recommend use: pathinfo with PATHINFO_FILENAME

$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);

Combine Multiple child rows into one row MYSQL

What you want is called a pivot, and it's not directly supported in MySQL, check this answer out for the options you've got:

How to pivot a MySQL entity-attribute-value schema

How can I update the current line in a C# Windows Console App?

So far we have three competing alternatives for how to do this:

Console.Write("\r{0}   ", value);                      // Option 1: carriage return
Console.Write("\b\b\b\b\b{0}", value);                 // Option 2: backspace
{                                                      // Option 3 in two parts:
    Console.SetCursorPosition(0, Console.CursorTop);   // - Move cursor
    Console.Write(value);                              // - Rewrite
}

I've always used Console.CursorLeft = 0, a variation on the third option, so I decided to do some tests. Here's the code I used:

public static void CursorTest()
{
    int testsize = 1000000;

    Console.WriteLine("Testing cursor position");
    Stopwatch sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < testsize; i++)
    {
        Console.Write("\rCounting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using \\r: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    int top = Console.CursorTop;
    for (int i = 0; i < testsize; i++)
    {
        Console.SetCursorPosition(0, top);        
        Console.Write("Counting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using CursorLeft: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    Console.Write("Counting:          ");
    for (int i = 0; i < testsize; i++)
    {        
        Console.Write("\b\b\b\b\b\b\b\b{0,8}", i);
    }

    sw.Stop();
    Console.WriteLine("\nTime using \\b: {0}", sw.ElapsedMilliseconds);
}

On my machine, I get the following results:

  • Backspaces: 25.0 seconds
  • Carriage Returns: 28.7 seconds
  • SetCursorPosition: 49.7 seconds

Additionally, SetCursorPosition caused noticeable flicker that I didn't observe with either of the alternatives. So, the moral is to use backspaces or carriage returns when possible, and thanks for teaching me a faster way to do this, SO!


Update: In the comments, Joel suggests that SetCursorPosition is constant with respect to the distance moved while the other methods are linear. Further testing confirms that this is the case, however constant time and slow is still slow. In my tests, writing a long string of backspaces to the console is faster than SetCursorPosition until somewhere around 60 characters. So backspace is faster for replacing portions of the line shorter than 60 characters (or so), and it doesn't flicker, so I'm going to stand by my initial endorsement of \b over \r and SetCursorPosition.

Verifying a specific parameter with Moq

I believe that the problem in the fact that Moq will check for equality. And, since XmlElement does not override Equals, it's implementation will check for reference equality.

Can't you use a custom object, so you can override equals?

How to use regex in XPath "contains" function

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

Uncomment this line (in /conf/logging.properties)

org.apache.jasper.compiler.TldLocationsCache.level = FINE

Work's for me in tomcat 7.0.53!

How to change the name of an iOS app?

The best way I like in xcode5 is to change product name in building settings. Search "product name" in "building settings", and change it.

enter image description here

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to get summary statistics by group

Besides describeBy, the doBy package is an another option. It provides much of the functionality of SAS PROC SUMMARY. Details: http://www.statmethods.net/stats/descriptives.html

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

Select statement to find duplicates on certain fields

Try this query to find duplicate records on multiple fields

SELECT a.column1, a.column2
FROM dbo.a a
JOIN (SELECT column1, 
       column2, count(*) as countC
FROM dbo.a 
GROUP BY column4, column5
HAVING count(*) > 1 ) b
ON a.column1 = b.column1
AND a.column2 = b.column2

The request was rejected because no multipart boundary was found in springboot

This worked for me: Uploading a file via Postman, to a SpringMVC backend webapp:

Backend: Endpoint controller definition

Postman: Headers setup POST Body setup

how to create a list of lists

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]

Hibernate openSession() vs getCurrentSession()

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.

login to remote using "mstsc /admin" with password

Save your username, password and sever name in an RDP file and run the RDP file from your script

Display images in asp.net mvc

Make sure you image is a relative path such as:

@Url.Content("~/Content/images/myimage.png")

MVC4

<img src="~/Content/images/myimage.png" />

You could convert the byte[] into a Base64 string on the fly.

string base64String = Convert.ToBase64String(imageBytes);

<img src="@String.Format("data:image/png;base64,{0}", base64string)" />

"This project is incompatible with the current version of Visual Studio"

In case you came here looking for the issue with ".smproj" file, it is because you are missing SQL Server Analysis Services(SSAS). To over come this, install SQL Server Data Tools(SSDT) in your system, restart your Visual Studio and it will work.

Thanks.

Why would I use dirname(__FILE__) in an include or include_once statement?

Let's say I have a (fake) directory structure like:

.../root/
        /app
            bootstrap.php
        /scripts
            something/
                somescript.php
        /public
            index.php

Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.

Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.

There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.

(Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)

Now, why not just use include 'init.php';?

As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).

Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?

Evaluate a string with a switch in C++

what about just have the option number:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    int op;

    cin >> s >> op;
    switch (op) {
    case 1: break;
    case 2: break;
    default:
    }

    return 0;
}  

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.

See this example: Creating a Real-Time Chat App with PHP and Node.js

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How to make sure that a certain Port is not occupied by any other process

You can use "netstat" to check whether a port is available or not.

Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

You have to put : before port number to get the actual output

Ex netstat -anp | find ":8080"

How do I autoindent in Netbeans?

To format all the code in NetBeans, press Alt + Shift + F. If you want to indent lines, select the lines and press Alt + Shift + right arrow key, and to unindent, press Alt + Shift + left arrow key.

How do I get the Session Object in Spring?

i made my own utils. it is handy. :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * SpringMVC????
 * 
 * @author ??([email protected])
 *
 */
public final class WebContextHolder {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;
    }

    private WebContextHolder() {
        super();
    }

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public HttpSession getSession() {
        return getSession(true);
    }

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
    }

}

Set keyboard caret position in html textbox

Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.

Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera

Cross-browser caret positioning technique (example: moving the cursor to the END)

// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)

setCaretPosition('IDHERE', 10); // example

The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0), in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.

In chrome the biggest issue was that just giving it .focus() wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value; before calling our function, and now it has a grasp & position with the input to use selectionStart.

function setCaretPosition(elemId, caretPos) {
    var el = document.getElementById(elemId);

    el.value = el.value;
    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);

Spark java.lang.OutOfMemoryError: Java heap space

Broadly speaking, spark Executor JVM memory can be divided into two parts. Spark memory and User memory. This is controlled by property spark.memory.fraction - the value is between 0 and 1. When working with images or doing memory intensive processing in spark applications, consider decreasing the spark.memory.fraction. This will make more memory available to your application work. Spark can spill, so it will still work with less memory share.

The second part of the problem is division of work. If possible, partition your data into smaller chunks. Smaller data possibly needs less memory. But if that is not possible, you are sacrifice compute for memory. Typically a single executor will be running multiple cores. Total memory of executors must be enough to handle memory requirements of all concurrent tasks. If increasing executor memory is not a option, you can decrease the cores per executor so that each task gets more memory to work with. Test with 1 core executors which have largest possible memory you can give and then keep increasing cores until you find the best core count.

Android Push Notifications: Icon not displaying in notification, white square shown instead

I just converted my png to a transparent png and then the icon was the same shape as the picture, but not the same color

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

For me the issue was caused by com.google.android.exoplayer conflicting with com.facebook.android:audience-network-sdk.

I fixed the problem by excluding the exoplayer library from the audience-network-sdk :

compile ('com.facebook.android:audience-network-sdk:4.24.0') {
    exclude group: 'com.google.android.exoplayer'
}

How to return a value from pthread threads in C?

You've returned a pointer to a local variable. That's bad even if threads aren't involved.

The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:

#include <pthread.h>
#include <stdio.h>

int something_worked(void) {
    /* thread operation might fail, so here's a silly example */
    void *p = malloc(10);
    free(p);
    return p ? 1 : 0;
}

void *myThread(void *result)
{
   if (something_worked()) {
       *((int*)result) = 42;
       pthread_exit(result);
   } else {
       pthread_exit(0);
   }
}

int main()
{
   pthread_t tid;
   void *status = 0;
   int result;

   pthread_create(&tid, NULL, myThread, &result);
   pthread_join(tid, &status);

   if (status != 0) {
       printf("%d\n",result);
   } else {
       printf("thread failed\n");
   }

   return 0;
}

If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

Stop and Start a service via batch or cmd file?

Instead of checking codes, this works too

net start "Apache tomcat" || goto ExitError

:End  
exit 0  

:ExitError  
echo An error has occurred while starting the tomcat services  
exit 1  

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

I ran into the same issue and solved it by downloading api level 20 using sdk manager and changing every string that points to android-L. I did it because I dont have a kitkat device and don't want to use emulator. See the image download the marked one.

Here's my build config:

apply plugin: 'com.android.application'

android {
compileSdkVersion 20//changed this from default
buildToolsVersion "20.0.0"

defaultConfig {
    applicationId "com.example.subash.test"
    minSdkVersion 12//changed this from default
    targetSdkVersion 20//changed this from default
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

How to make Apache serve index.php instead of index.html?

As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

root@host:/etc/apache2/mods-enabled$ vi dir.conf 

And change the order of that line, bringing index.php to the first position:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

Using @property versus getters and setters

[TL;DR? You can skip to the end for a code example.]

I actually prefer to use a different idiom, which is a little involved for using as a one off, but is nice if you have a more complex use case.

A bit of background first.

Properties are useful in that they allow us to handle both setting and getting values in a programmatic way but still allow attributes to be accessed as attributes. We can turn 'gets' into 'computations' (essentially) and we can turn 'sets' into 'events'. So let's say we have the following class, which I've coded with Java-like getters and setters.

class Example(object):
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

    def getX(self):
        return self.x or self.defaultX()

    def getY(self):
        return self.y or self.defaultY()

    def setX(self, x):
        self.x = x

    def setY(self, y):
        self.y = y

    def defaultX(self):
        return someDefaultComputationForX()

    def defaultY(self):
        return someDefaultComputationForY()

You may be wondering why I didn't call defaultX and defaultY in the object's __init__ method. The reason is that for our case I want to assume that the someDefaultComputation methods return values that vary over time, say a timestamp, and whenever x (or y) is not set (where, for the purpose of this example, "not set" means "set to None") I want the value of x's (or y's) default computation.

So this is lame for a number of reasons describe above. I'll rewrite it using properties:

class Example(object):
    def __init__(self, x=None, y=None):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self.x or self.defaultX()

    @x.setter
    def x(self, value):
        self._x = value

    @property
    def y(self):
        return self.y or self.defaultY()

    @y.setter
    def y(self, value):
        self._y = value

    # default{XY} as before.

What have we gained? We've gained the ability to refer to these attributes as attributes even though, behind the scenes, we end up running methods.

Of course the real power of properties is that we generally want these methods to do something in addition to just getting and setting values (otherwise there is no point in using properties). I did this in my getter example. We are basically running a function body to pick up a default whenever the value isn't set. This is a very common pattern.

But what are we losing, and what can't we do?

The main annoyance, in my view, is that if you define a getter (as we do here) you also have to define a setter.[1] That's extra noise that clutters the code.

Another annoyance is that we still have to initialize the x and y values in __init__. (Well, of course we could add them using setattr() but that is more extra code.)

Third, unlike in the Java-like example, getters cannot accept other parameters. Now I can hear you saying already, well, if it's taking parameters it's not a getter! In an official sense, that is true. But in a practical sense there is no reason we shouldn't be able to parameterize an named attribute -- like x -- and set its value for some specific parameters.

It'd be nice if we could do something like:

e.x[a,b,c] = 10
e.x[d,e,f] = 20

for example. The closest we can get is to override the assignment to imply some special semantics:

e.x = [a,b,c,10]
e.x = [d,e,f,30]

and of course ensure that our setter knows how to extract the first three values as a key to a dictionary and set its value to a number or something.

But even if we did that we still couldn't support it with properties because there is no way to get the value because we can't pass parameters at all to the getter. So we've had to return everything, introducing an asymmetry.

The Java-style getter/setter does let us handle this, but we're back to needing getter/setters.

In my mind what we really want is something that capture the following requirements:

  • Users define just one method for a given attribute and can indicate there whether the attribute is read-only or read-write. Properties fail this test if the attribute writable.

  • There is no need for the user to define an extra variable underlying the function, so we don't need the __init__ or setattr in the code. The variable just exists by the fact we've created this new-style attribute.

  • Any default code for the attribute executes in the method body itself.

  • We can set the attribute as an attribute and reference it as an attribute.

  • We can parameterize the attribute.

In terms of code, we want a way to write:

def x(self, *args):
    return defaultX()

and be able to then do:

print e.x     -> The default at time T0
e.x = 1
print e.x     -> 1
e.x = None
print e.x     -> The default at time T1

and so forth.

We also want a way to do this for the special case of a parameterizable attribute, but still allow the default assign case to work. You'll see how I tackled this below.

Now to the point (yay! the point!). The solution I came up for for this is as follows.

We create a new object to replace the notion of a property. The object is intended to store the value of a variable set to it, but also maintains a handle on code that knows how to calculate a default. Its job is to store the set value or to run the method if that value is not set.

Let's call it an UberProperty.

class UberProperty(object):

    def __init__(self, method):
        self.method = method
        self.value = None
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def clearValue(self):
        self.value = None
        self.isSet = False

I assume method here is a class method, value is the value of the UberProperty, and I have added isSet because None may be a real value and this allows us a clean way to declare there really is "no value". Another way is a sentinel of some sort.

This basically gives us an object that can do what we want, but how do we actually put it on our class? Well, properties use decorators; why can't we? Let's see how it might look (from here on I'm going to stick to using just a single 'attribute', x).

class Example(object):

    @uberProperty
    def x(self):
        return defaultX()

This doesn't actually work yet, of course. We have to implement uberProperty and make sure it handles both gets and sets.

Let's start with gets.

My first attempt was to simply create a new UberProperty object and return it:

def uberProperty(f):
    return UberProperty(f)

I quickly discovered, of course, that this doens't work: Python never binds the callable to the object and I need the object in order to call the function. Even creating the decorator in the class doesn't work, as although now we have the class, we still don't have an object to work with.

So we're going to need to be able to do more here. We do know that a method need only be represented the one time, so let's go ahead and keep our decorator, but modify UberProperty to only store the method reference:

class UberProperty(object):

    def __init__(self, method):
        self.method = method

It is also not callable, so at the moment nothing is working.

How do we complete the picture? Well, what do we end up with when we create the example class using our new decorator:

class Example(object):

    @uberProperty
    def x(self):
        return defaultX()

print Example.x     <__main__.UberProperty object at 0x10e1fb8d0>
print Example().x   <__main__.UberProperty object at 0x10e1fb8d0>

in both cases we get back the UberProperty which of course is not a callable, so this isn't of much use.

What we need is some way to dynamically bind the UberProperty instance created by the decorator after the class has been created to an object of the class before that object has been returned to that user for use. Um, yeah, that's an __init__ call, dude.

Let's write up what we want our find result to be first. We're binding an UberProperty to an instance, so an obvious thing to return would be a BoundUberProperty. This is where we'll actually maintain state for the x attribute.

class BoundUberProperty(object):
    def __init__(self, obj, uberProperty):
        self.obj = obj
        self.uberProperty = uberProperty
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def getValue(self):
        return self.value if self.isSet else self.uberProperty.method(self.obj)

    def clearValue(self):
        del self.value
        self.isSet = False

Now we the representation; how do get these on to an object? There are a few approaches, but the easiest one to explain just uses the __init__ method to do that mapping. By the time __init__ is called our decorators have run, so just need to look through the object's __dict__ and update any attributes where the value of the attribute is of type UberProperty.

Now, uber-properties are cool and we'll probably want to use them a lot, so it makes sense to just create a base class that does this for all subclasses. I think you know what the base class is going to be called.

class UberObject(object):
    def __init__(self):
        for k in dir(self):
            v = getattr(self, k)
            if isinstance(v, UberProperty):
                v = BoundUberProperty(self, v)
                setattr(self, k, v)

We add this, change our example to inherit from UberObject, and ...

e = Example()
print e.x               -> <__main__.BoundUberProperty object at 0x104604c90>

After modifying x to be:

@uberProperty
def x(self):
    return *datetime.datetime.now()*

We can run a simple test:

print e.x.getValue()
print e.x.getValue()
e.x.setValue(datetime.date(2013, 5, 31))
print e.x.getValue()
e.x.clearValue()
print e.x.getValue()

And we get the output we wanted:

2013-05-31 00:05:13.985813
2013-05-31 00:05:13.986290
2013-05-31
2013-05-31 00:05:13.986310

(Gee, I'm working late.)

Note that I have used getValue, setValue, and clearValue here. This is because I haven't yet linked in the means to have these automatically returned.

But I think this is a good place to stop for now, because I'm getting tired. You can also see that the core functionality we wanted is in place; the rest is window dressing. Important usability window dressing, but that can wait until I have a change to update the post.

I'll finish up the example in the next posting by addressing these things:

  • We need to make sure UberObject's __init__ is always called by subclasses.

    • So we either force it be called somewhere or we prevent it from being implemented.
    • We'll see how to do this with a metaclass.
  • We need to make sure we handle the common case where someone 'aliases' a function to something else, such as:

      class Example(object):
          @uberProperty
          def x(self):
              ...
    
          y = x
    
  • We need e.x to return e.x.getValue() by default.

    • What we'll actually see is this is one area where the model fails.
    • It turns out we'll always need to use a function call to get the value.
    • But we can make it look like a regular function call and avoid having to use e.x.getValue(). (Doing this one is obvious, if you haven't already fixed it out.)
  • We need to support setting e.x directly, as in e.x = <newvalue>. We can do this in the parent class too, but we'll need to update our __init__ code to handle it.

  • Finally, we'll add parameterized attributes. It should be pretty obvious how we'll do this, too.

Here's the code as it exists up to now:

import datetime

class UberObject(object):
    def uberSetter(self, value):
        print 'setting'

    def uberGetter(self):
        return self

    def __init__(self):
        for k in dir(self):
            v = getattr(self, k)
            if isinstance(v, UberProperty):
                v = BoundUberProperty(self, v)
                setattr(self, k, v)


class UberProperty(object):
    def __init__(self, method):
        self.method = method

class BoundUberProperty(object):
    def __init__(self, obj, uberProperty):
        self.obj = obj
        self.uberProperty = uberProperty
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def getValue(self):
        return self.value if self.isSet else self.uberProperty.method(self.obj)

    def clearValue(self):
        del self.value
        self.isSet = False

    def uberProperty(f):
        return UberProperty(f)

class Example(UberObject):

    @uberProperty
    def x(self):
        return datetime.datetime.now()

[1] I may be behind on whether this is still the case.

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

How to select Python version in PyCharm?

I think you are saying that you have python2 and python3 installed and have added a reference to each version under Pycharm > Settings > Project Interpreter

What I think you are asking is how do you have some projects run with Python 2 and some projects running with Python 3.

If so, you can look under Run > Edit Configurations

PyCharm Run > Edit Configurations

How to round an average to 2 decimal places in PostgreSQL?

Try casting your column to a numeric like:

SELECT ROUND(cast(some_column as numeric),2) FROM table

How to import local packages in go?

Import paths are relative to your $GOPATH and $GOROOT environment variables. For example, with the following $GOPATH:

GOPATH=/home/me/go

Packages located in /home/me/go/src/lib/common and /home/me/go/src/lib/routers are imported respectively as:

import (
    "lib/common"
    "lib/routers"
)

How to Compare two strings using a if in a stored procedure in sql server 2008?

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This is ridiculous but I just have rebooted my machine (mac) and the problem was gone like it has never happened. I hate to sound like a support guy...

Vertical Alignment of text in a table cell

Just add vertical-align:top for first td alone needed not for all td.

_x000D_
_x000D_
tr>td:first-child {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<tr>_x000D_
  <td>Description</td>_x000D_
  <td>more text</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

getResourceAsStream returns null

So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.

The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.

Methods

  1. ClassLoader.getResourceAsStream().

Format: "/"-separated names; no leading "/" (all names are absolute).

Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

  1. Class.getResourceAsStream()

Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package

Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");

Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)

How to always show scrollbar

Try android:scrollbarAlwaysDrawVerticalTrack="true" for vertical. and Try android:scrollbarAlwaysDrawHorizontalTrack="true" for horizontal

Is there a no-duplicate List implementation out there?

I just made my own UniqueList in my own little library like this:

package com.bprog.collections;//my own little set of useful utilities and classes

import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Jonathan
*/
public class UniqueList {

private HashSet masterSet = new HashSet();
private ArrayList growableUniques;
private Object[] returnable;

public UniqueList() {
    growableUniques = new ArrayList();
}

public UniqueList(int size) {
    growableUniques = new ArrayList(size);
}

public void add(Object thing) {
    if (!masterSet.contains(thing)) {
        masterSet.add(thing);
        growableUniques.add(thing);
    }
}

/**
 * Casts to an ArrayList of unique values
 * @return 
 */
public List getList(){
    return growableUniques;
}

public Object get(int index) {
    return growableUniques.get(index);
}

public Object[] toObjectArray() {
    int size = growableUniques.size();
    returnable = new Object[size];
    for (int i = 0; i < size; i++) {
        returnable[i] = growableUniques.get(i);
    }
    return returnable;
    }
}

I have a TestCollections class that looks like this:

package com.bprog.collections;
import com.bprog.out.Out;
/**
*
* @author Jonathan
*/
public class TestCollections {
    public static void main(String[] args){
        UniqueList ul = new UniqueList();
        ul.add("Test");
        ul.add("Test");
        ul.add("Not a copy");
        ul.add("Test"); 
        //should only contain two things
        Object[] content = ul.toObjectArray();
        Out.pl("Array Content",content);
    }
}

Works fine. All it does is it adds to a set if it does not have it already and there's an Arraylist that is returnable, as well as an object array.

Visual Studio move project to a different folder

I wanted the changes in Git to be shown as moves/renames instead of delete & adds. So I did a combo of the above and this post.

mkdir subdirectory
git mv -k ./* ./subdirectory
# check to make sure everything moved (see below)
git commit

And adjust the paths of the projects and of the assemblies from the nuget Pkg's in the sln file via a text editor.

How can I show an element that has display: none in a CSS rule?

try setting the display to block in your javascript instead of a blank value.

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

H.264 file size for 1 hr of HD video

For a good quality x264 encoding of 1060i, done by a computer, not a mobile device, not in real time, you could use a bitrate at about 5 MBps. That means 2250 MB/hour of encoded material. Recommend you deinterlace the footage and compress as progressive.

Pandas - How to flatten a hierarchical index in columns

A bit late maybe, but if you are not worried about duplicate column names:

df.columns = df.columns.tolist()

How do you enable mod_rewrite on any OS?

if it related to hosting site then ask to your hosting or if you want to enable it in local machine then check this youtube step by step tutorial related to enabling rewrite module in wamp apache https://youtu.be/xIspOX9FuVU?t=1m43s
Wamp server icon -> Apache -> Apache Modules and check the rewrite module option it should be checked but after that wamp require restart all services

Why do I get a warning icon when I add a reference to an MEF plugin project?

For both of (or all of) the projects that you want to use together:

Right click on the project > Properties > Application > Target .NET framework

Make sure that both of (or all of) your projects are using the same .NET framework version.

How to process each output line in a loop?

You can do the following while read loop, that will be fed by the result of the grep command using the so called process substitution:

while IFS= read -r result
do
    #whatever with value $result
done < <(grep "xyz" abc.txt)

This way, you don't have to store the result in a variable, but directly "inject" its output to the loop.


Note the usage of IFS= and read -r according to the recommendations in BashFAQ/001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

The -r option to read prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters). Without this option, any unescaped backslashes in the input will be discarded. You should almost always use the -r option with read.

In the scenario above IFS= prevents trimming of leading and trailing whitespace. Remove it if you want this effect.

Regarding the process substitution, it is explained in the bash hackers page:

Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.

Mysql: Select rows from a table that are not in another

This worked for me in Oracle:

SELECT a.* 
    FROM tbl1 a 
MINUS 
SELECT b.* 
    FROM tbl2 b;

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

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

Increasing number of max-connections will not solve the problem.

We were experiencing the same situation on our servers. This is what happens

User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.

You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour

SET interactive_timeout=3600