Programs & Examples On #Indexed image

Very Simple, Very Smooth, JavaScript Marquee

Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:

First include :

<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>

and then:

//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;

$('.marquee').marquee({
    //speed in milliseconds of the marquee
    duration: duration, // for responsive/fluid use
    //duration: 8000, // for fixed container
    //gap in pixels between the tickers
    gap: $('.marquee').width(),
    //time in milliseconds before the marquee will start animating
    delayBeforeStart: 0,
    //'left' or 'right'
    direction: 'left',
    //true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true
});

If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin

How do I reference the input of an HTML <textarea> control in codebehind?

You should reference the textarea ID and include the runat="server" attribute to the textarea

message.Body = TextArea1.Text;  

What is test123?


Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

C char array initialization

Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.

Your code will result in compiler errors. Your first code fragment:

char buf[10] ; buf = ''

is doubly illegal. First, in C, there is no such thing as an empty char. You can use double quotes to designate an empty string, as with:

char* buf = ""; 

That will give you a pointer to a NUL string, i.e., a single-character string with only the NUL character in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NUL character, you have to specify it:

char buf = '\0';

The backslash is necessary to disambiguate from character '0'.

char buf = 0;

accomplishes the same thing, but the former is a tad less ambiguous to read, I think.

Secondly, you cannot initialize arrays after they have been defined.

char buf[10];

declares and defines the array. The array identifier buf is now an address in memory, and you cannot change where buf points through assignment. So

buf =     // anything on RHS

is illegal. Your second and third code fragments are illegal for this reason.

To initialize an array, you have to do it at the time of definition:

char buf [10] = ' ';

will give you a 10-character array with the first char being the space '\040' and the rest being NUL, i.e., '\0'. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0. There will not be any "random content".

If you declare and define the array but don't initialize it, as in the following:

char buf [10];

you will have random content in all the elements.

App not setup: This app is still in development mode

This is an answer I haven't seen much around (this it was in a comment somewhere) although yes taking the app off development mode will work this can be bad for security or really annoying if the app isn't ready yet but you need to submit the app for review on account of needing access to special permissions (e.g. user_birthday).

What I did instead to fix the error was go to https://developers.facebook.com/sa/apps/{appId}/roles/ or from the app dashboard click roles on the left side

Then add the user account(s) to either developer or tester. Developers will need to be verified by mobile and will get access to the app to make changes but a tester will only need to be verified by email (not sure if even this is necessary but it probably is) and will only be able to use the API instead of make changes to settings.

If the app is ready for the public, obviously just take the app off development mode.

How to check if a function exists on a SQL database

I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:

IF OBJECTPROPERTY (object_id('schemaname.scalarfuncname'), 'IsScalarFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.tablefuncname'), 'IsTableFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.procname'), 'IsProcedure') = 1

This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.

The OBJECTPROPERTY function uses the following signature:

OBJECTPROPERTY ( id , property ) 

You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.

PHP Echo a large block of text

One option is to get out of the php block and just write HTML.

With your code, after the opening curly brace of your if statement, end the PHP:

if (is_single()) { ?>

Then remove the echo ' and the ';

After all your html and css, before the closing }, write:

<? } else {

If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.

How to generate a random number in C++?

Here is a solution. Create a function that returns the random number and place it outside the main function to make it global. Hope this helps

#include <iostream>
#include <cstdlib>
#include <ctime>
int rollDie();
using std::cout;
int main (){
    srand((unsigned)time(0));
    int die1;
    int die2;
    for (int n=10; n>0; n--){
    die1 = rollDie();
    die2 = rollDie();
    cout << die1 << " + " << die2 << " = " << die1 + die2 << "\n";
}
system("pause");
return 0;
}
int rollDie(){
    return (rand()%6)+1;
}

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

jQuery hide and show toggle div with plus and minus icon

Toggle the text Show and Hide and move your backgroundPosition Y axis

LIVE DEMO

$(function(){ // DOM READY shorthand

    $(".slidingDiv").hide();

    $('.show_hide').click(function( e ){
        // e.preventDefault(); // If you use anchors
        var SH = this.SH^=1; // "Simple toggler"
        $(this).text(SH?'Hide':'Show')
               .css({backgroundPosition:'0 '+ (SH?-18:0) +'px'})
               .next(".slidingDiv").slideToggle();
    });

});

CSS:

.show_hide{
  background:url(plusminus.png) no-repeat;
  padding-left:20px;  
}

Entity Framework Query for inner join

You could use a navigation property if its available. It produces an inner join in the SQL.

from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s

How to detect when facebook's FB.init is complete

Here's a simpler method, that requires neither events or timeouts. It does require jQuery, however.

Use jQuery.holdReady() (docs)

So, immediately after your jQuery script, delay the ready event.

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $.holdReady( true ); // don't fire ready until told (ie when FB loaded)
</script>

Then, in your Facebook init function, release it:

window.fbAsyncInit = function() {
    FB.init({
        appId: '11111111111111',
        cookie: true,
        xfbml: false,
        version: 'v2.4'
    });

    // release the ready event to execute
    $.holdReady( false );
};

Then you can use the ready event as normal:

$(document).ready( myApp.init );

How to use setInterval and clearInterval?

Use setTimeout(drawAll, 20) instead. That only executes the function once.

Egit rejected non-fast-forward

Open git view :

1- select your project and choose merge 2- Select remote tracking 3- click ok

Git will merge the remote branch with local repository

4- then push

Angular JS update input field after change

I wrote a directive you can use to bind an ng-model to any expression you want. Whenever the expression changes the model is set to the new value.

 module.directive('boundModel', function() {
      return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel) {
          var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
            if(newValue != oldValue) {
              ngModel.$setViewValue(newValue);
              ngModel.$render();
            }
          });

          // When $destroy is fired stop watching the change.
          // If you don't, and you come back on your state
          // you'll have two watcher watching the same properties
          scope.$on('$destroy', function() {
              boundModel$watcher();
          });
        }
    });

You can use it in your templates like this:

 <li>Total<input type="text" ng-model="total" bound-model="one * two"></li>      

How to stash my previous commit?

An alternative solution uses the stash:

Before:

~/dev/gitpro $git stash list

~/dev/gitpro $git log --oneline -3

* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
  1. git reset head~1 <--- head shifted one back to c222; working still contains c111 changes
  2. git stash push -m "commit 111" <--- staging/working (containing c111 changes) stashed; staging/working rolled back to revised head (containing c222 changes)
  3. git reset head~1 <--- head shifted one back to c333; working still contains c222 changes
  4. git stash push -m "commit 222" <--- staging/working (containing c222 changes) stashed; staging/working rolled back to revised head (containing c333 changes)
  5. git stash pop stash@{1} <--- oldest stash entry with c111 changes removed & applied to staging/working
  6. git commit -am "commit 111" <-- new commit with c111's changes becomes new head

note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).

note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)

After:

~/dev/gitpro $git stash list

stash@{0}: On master: c222

~/dev/gitpro $git log -2 --oneline

* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333

Import and insert sql.gz file into database with putty

The file is a gzipped (compressed) SQL file, almost certainly a plain text file with .sql as its extension. The first thing you need to do is copy the file to your database server via scp.. I think PuTTY's is pscp.exe

# Copy it to the server via pscp
C:\> pscp.exe numbers.sql.gz user@serverhostname:/home/user

Then SSH into your server and uncompress the file with gunzip

user@serverhostname$  gunzip numbers.sql.gz
user@serverhostname$  ls 

numbers.sql

Finally, import it into your MySQL database using the < input redirection operator:

user@serverhostname$  mysql -u mysqluser -p < numbers.sql

If the numbers.sql file doesn't create a database but expects one to be present already, you will need to include the database in the command as well:

user@serverhostname$  mysql -u mysqluser -p databasename < numbers.sql

If you have the ability to connect directly to your MySQL server from outside, then you could use a local MySQL client instead of having to copy and SSH. In that case, you would just need a utility that can decompress .gz files on Windows. I believe 7zip does so, or you can obtain the gzip/gunzip binaries for Windows.

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

How do I create a new line in Javascript?

For a string I just write "\n" to give me a new line. For example, typing console.log("First Name: Rex" + "\n" + "Last Name: Blythe"); Will type:

First Name: Rex

Last Name: Blythe

How to call multiple JavaScript functions in onclick event?

_x000D_
_x000D_
var btn = document.querySelector('#twofuns');_x000D_
btn.addEventListener('click',method1);_x000D_
btn.addEventListener('click',method2);_x000D_
function method2(){_x000D_
  console.log("Method 2");_x000D_
}_x000D_
function method1(){_x000D_
  console.log("Method 1");_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>Pramod Kharade-Javascript</title>_x000D_
</head>_x000D_
<body>_x000D_
<button id="twofuns">Click Me!</button>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can achieve/call one event with one or more methods.

How to read Data from Excel sheet in selenium webdriver

Your problem is that log4j has not been initialized. It does not affect the outcome of you application in any way, so it's safe to ignore or just initialize Log4J, see: How to initialize log4j properly?

How is using OnClickListener interface different via XML and Java code?

Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.

How do I set specific environment variables when debugging in Visual Studio?

You can set it at Property > Configuration Properties > Debugging > Environment enter image description here

Object of class stdClass could not be converted to string

I use codeignator and I got the error:

Object of class stdClass could not be converted to string.

for this post I get my result

I use in my model section

$query = $this->db->get('user', 10);
        return $query->result();

and from this post I use

$query = $this->db->get('user', 10);
        return $query->row();

and I solved my problem

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

It is late to answer this question but I thought It will add to the explanation.

It is happening because any where in your code you are returning two elements simultaneously.

e.g

return(
    <div id="div1"></div>
    <div id="div1"></div>
  )

It should be wrapped in a parent element. e.g

 return(
      <div id="parent">
        <div id="div1"></div>
        <div id="div1"></div>
      </div>
      )

**More Detailed Explanation**

Your below jsx code get transformed

class App extends React.Component {
  render(){
    return (
      <div>
        <h1>Welcome to React</h1>
      </div>
    );
  }
}

into this

_createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
        'div',
        null,
        React.createElement(
          'h1',
          null,
          'Welcome to React'
        )
      );
    }
  }]);

But if you do this

class App extends React.Component {
  render(){
    return (
        <h1>Welcome to React</h1>
        <div>Hi</div>
    );
  }
}

this gets converted into this(Just for illustration purpose, actually you will get error : Adjacent JSX elements must be wrapped in an enclosing tag)

_createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
        'div',
        null,
       'Hi'
      ); 
    return React.createElement(
          'h1',
          null,
          'Welcome to React'
        )
    }
  }]);

In the above code you can see that you are trying to return twice from a method call, which is obviously wrong.

Edit- Latest changes in React 16 and own-wards:

If you do not want to add extra div to wrap around and want to return more than one child components you can go with React.Fragments.

React.Fragments (<React.Fragments>)are little bit faster and has less memory usage (no need to create an extra DOM node, less cluttered DOM tree).

e.g (In React 16.2.0)

render() {
  return (
    <>
       React fragments.
      <h2>A heading</h2>
      More React fragments.
      <h2>Another heading</h2>
      Even more React fragments.
    </>
  );
}

or

render() {
  return (
    <React.Fragments>
       React fragments.
      <h2>A heading</h2>
      More React fragments.
      <h2>Another heading</h2>
      Even more React fragments.
    </React.Fragments>
  );
}

or

render() {
 return [
  "Some text.",
  <h2 key="heading-1">A heading</h2>,
  "More text.",
  <h2 key="heading-2">Another heading</h2>,
  "Even more text."
 ];
}

How to install sshpass on mac?

There are instructions on how to install sshpass here:

https://gist.github.com/arunoda/7790979

For Mac you will need to install xcode and command line tools then use the unofficial Homewbrew command:

brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

.includes() not working in Internet Explorer

includes() is not supported by most browsers. Your options are either to use

-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

or to use

-indexof()

var str = "abcde";
var n = str.indexOf("cd");

Which gives you n=2

This is widely supported.

What is wrong with my SQL here? #1089 - Incorrect prefix key

This

PRIMARY KEY (id (11))

is generated automatically by phpmyadmin, change to

PRIMARY KEY (id)

.

MySQL Select all columns from one table and some from another table

Using alias for referencing the tables to get the columns from different tables after joining them.

Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id

How to check type of variable in Java?

a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.

boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class. Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.

I took this information from: How do you know a variable type in java?

This can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.

By the way, this is known as Reflection. Here's some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/

How to download a Nuget package without nuget.exe or Visual Studio extension?

Based on Xavier's answer, I wrote a Google chrome extension NuTake to add links to the Nuget.org package pages.

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.

You can do this by using IPTABLES to redirect port 80 to 8080.

Multiple actions were found that match the request in Web Api

This solution worked for me.

Please place Route2 first in WebApiConfig. Also Add HttpGet and HttpPost before each method and include controller name and method name in the url.

WebApiConfig =>

config.Routes.MapHttpRoute(
           name: "MapByAction",
           routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional });

Controller =>

public class ValuesController : ApiController
{

    [HttpPost]
    public string GetCustomer([FromBody] RequestModel req)
    {
        return "Customer";
    }

    [HttpPost]
    public string GetCustomerList([FromBody] RequestModel req)
    {
        return "Customer List";
    }
}

Url =>

http://localhost:7050/api/Values/GetCustomer

http://localhost:7050/api/Values/GetCustomerList

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

Using ZXing to create an Android barcode scanning app

Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.

I highly recommend using this library: https://github.com/dm77/barcodescanner

It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Trying to handle "back" navigation button action in iOS

In Swift 4 or above:

override func didMove(toParent parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

Does IE9 support console.log, and is it a real function?

A simple solution to this console.log problem is to define the following at the beginning of your JS code:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.

/bin/sh: pushd: not found

add

SHELL := /bin/bash

at the top of your makefile I have found it on another question How can I use Bash syntax in Makefile targets?

Clear contents of cells in VBA using column reference

I just came up with this very simple method of clearing an entire sheet.

Sub ClearThisSheet()

ActiveSheet.UsedRange.ClearContents

End Sub

Converting a double to an int in Javascript without rounding

Just use parseInt() and be sure to include the radix so you get predictable results:

parseInt(d, 10);

Reverting to a previous revision using TortoiseSVN

In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)

Default passwords of Oracle 11g?

It is possible to connect to the database without specifying a password. Once you've done that you can then reset the passwords. I'm assuming that you've installed the database on your machine; if not you'll first need to connect to the machine the database is running on.

  1. Ensure your user account is a member of the dba group. How you do this depends on what OS you are running.

  2. Enter sqlplus / as sysdba in a Command Prompt/shell/Terminal window as appropriate. This should log you in to the database as SYS.

  3. Once you're logged in, you can then enter

    alter user SYS identified by "newpassword";
    

    to reset the SYS password, and similarly for SYSTEM.

(Note: I haven't tried any of this on Oracle 12c; I'm assuming they haven't changed things since Oracle 11g.)

Detecting a long press with Android

option: custom detector class

abstract public class
Long_hold
extends View.OnTouchListener
{
  public@Override boolean
  onTouch(View view, MotionEvent touch)
  {
    switch(touch.getAction())
    {
    case ACTION_DOWN: down(touch); return true;
    case ACTION_MOVE: move(touch);
    }
    return true;
  }

  private long
  time_0;
  private float
  x_0, y_0;

  private void
  down(MotionEvent touch)
  {
    time_0= touch.getEventTime();
    x_0= touch.getX();
    y_0= touch.getY();
  }

  private void
  move(MotionEvent touch)
  {
    if(held_too_short(touch) {return;}
    if(moved_too_much(touch)) {return;}

    long_press(touch);
  }
  abstract protected void
  long_hold(MotionEvent touch);
}

use

private double
moved_too_much(MotionEvent touch)
{
  return Math.hypot(
      x_0 -touch.getX(),
      y_0 -touch.getY()) >TOLERANCE;
}

private double
held_too_short(MotionEvent touch)
{
  return touch.getEventTime()-time_0 <DOWN_PERIOD;
}

where

  • TOLERANCE is the maximum tolerated movement

  • DOWN_PERIOD is the time one has to press

import

static android.view.MotionEvent.ACTION_MOVE;
static android.view.MotionEvent.ACTION_DOWN;

in code

setOnTouchListener(new Long_hold()
  {
  protected@Override boolean
  long_hold(MotionEvent touch)
  {
    /*your code on long hold*/
  }
});

data.frame rows to a list

Like this:

xy.list <- split(xy.df, seq(nrow(xy.df)))

And if you want the rownames of xy.df to be the names of the output list, you can do:

xy.list <- setNames(split(xy.df, seq(nrow(xy.df))), rownames(xy.df))

E: Unable to locate package mongodb-org

All steps are correct just change the Step 4 as below

  • Step 4: Install the last stable MongoDB version and all the necessary packages on our system

Command: sudo apt-get install mongodb

It has worked for me.

Which is the best IDE for Python For Windows

Python is dynamic language so the IDE can do only so much in terms of code intelligence and syntax checking but I personally recommend Komode IDE, it's pretty slick on OS/X and Windows. I've experienced high cpu use with Linux but not sure if it's caused by my VirtualBox environment.

You can also try Eclipse with PyDev plugin. It's heavier so performance might become a problem though.

How to keep indent for second line in ordered lists via CSS?

You can use CSS to select a range; in this case, you want list items 1-9:

ol li:nth-child(n+1):nth-child(-n+9) 

Then adjust margins on those first items appropriately:

ol li:nth-child(n+1):nth-child(-n+9) { margin-left: .55em; }
ol li:nth-child(n+1):nth-child(-n+9) em,
ol li:nth-child(n+1):nth-child(-n+9) span { margin-left: 19px; }

See it in action here: http://www.wortfm.org/wort-madison-charts-for-the-week-beginning-11192012/

How to sort an array of objects in Java?

Update for Java 8 constructs

Assuming a Book class with a name field getter, you can use Arrays.sort method by passing an additional Comparator specified using Java 8 constructs - Comparator default method & method references.

Arrays.sort(bookArray, Comparator.comparing(Book::getName));

Also, it's possible to compare on multiple fields using thenComparing methods.

Arrays.sort(bookArray, Comparator.comparing(Book::getName)
      .thenComparing(Book::getAuthor))
      .thenComparingInt(Book::getId));

How to use ConcurrentLinkedQueue?

This is largely a duplicate of another question.

Here's the section of that answer that is relevant to this question:

Do I need to do my own synchronization if I use java.util.ConcurrentLinkedQueue?

Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is not guaranteed thread-safe are any operations you perform on the collection that are non-atomic.

For example, this is threadsafe without any action on your part:

queue.add(obj);

or

queue.poll(obj);

However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are not automatically threadsafe:

if(!queue.isEmpty()) {
   queue.poll(obj);
}

That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this:

synchronized(queue) {
    if(!queue.isEmpty()) {
       queue.poll(obj);
    }
}

Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not.

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

Custom HTTP headers : naming conventions

The question bears re-reading. The actual question asked is not similar to vendor prefixes in CSS properties, where future-proofing and thinking about vendor support and official standards is appropriate. The actual question asked is more akin to choosing URL query parameter names. Nobody should care what they are. But name-spacing the custom ones is a perfectly valid -- and common, and correct -- thing to do.

Rationale:
It is about conventions among developers for custom, application-specific headers -- "data relevant to their account" -- which have nothing to do with vendors, standards bodies, or protocols to be implemented by third parties, except that the developer in question simply needs to avoid header names that may have other intended use by servers, proxies or clients. For this reason, the "X-Gzip/Gzip" and "X-Forwarded-For/Forwarded-For" examples given are moot. The question posed is about conventions in the context of a private API, akin to URL query parameter naming conventions. It's a matter of preference and name-spacing; concerns about "X-ClientDataFoo" being supported by any proxy or vendor without the "X" are clearly misplaced.

There's nothing special or magical about the "X-" prefix, but it helps to make it clear that it is a custom header. In fact, RFC-6648 et al help bolster the case for use of an "X-" prefix, because -- as vendors of HTTP clients and servers abandon the prefix -- your app-specific, private-API, personal-data-passing-mechanism is becoming even better-insulated against name-space collisions with the small number of official reserved header names. That said, my personal preference and recommendation is to go a step further and do e.g. "X-ACME-ClientDataFoo" (if your widget company is "ACME").

IMHO the IETF spec is insufficiently specific to answer the OP's question, because it fails to distinguish between completely different use cases: (A) vendors introducing new globally-applicable features like "Forwarded-For" on the one hand, vs. (B) app developers passing app-specific strings to/from client and server. The spec only concerns itself with the former, (A). The question here is whether there are conventions for (B). There are. They involve grouping the parameters together alphabetically, and separating them from the many standards-relevant headers of type (A). Using the "X-" or "X-ACME-" prefix is convenient and legitimate for (B), and does not conflict with (A). The more vendors stop using "X-" for (A), the more cleanly-distinct the (B) ones will become.

Example:
Google (who carry a bit of weight in the various standards bodies) are -- as of today, 20141102 in this slight edit to my answer -- currently using "X-Mod-Pagespeed" to indicate the version of their Apache module involved in transforming a given response. Is anyone really suggesting that Google should use "Mod-Pagespeed", without the "X-", and/or ask the IETF to bless its use?

Summary:
If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common, convention.

Should I put #! (shebang) in Python scripts, and what form should it take?

If you have different modules installed and need to use a specific python install, then shebang appears to be limited at first. However, you can do tricks like the below to allow the shebang to be invoked first as a shell script and then choose python. This is very flexible imo:

#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3

if [ -x $PREFERRED_PYTHON ]; then
    echo Using preferred python $PREFERRED_PYTHON
    exec $PREFERRED_PYTHON "$0" "$@"
elif [ -x $ALTERNATIVE_PYTHON ]; then
    echo Using alternative python $ALTERNATIVE_PYTHON
    exec $ALTERNATIVE_PYTHON "$0" "$@"
else
    echo Using fallback python $FALLBACK_PYTHON
    exec python3 "$0" "$@"
fi
exit 127
'''

__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())

Or better yet, perhaps, to facilitate code reuse across multiple python scripts:

#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[@]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$@"; exit 127; '''

and then select.sh has:

PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3

if [ -x $PREFERRED_PYTHON ]; then
    CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
    CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
    CHOSEN_PYTHON=$FALLBACK_PYTHON
fi

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

How to run a command in the background on Windows?

I believe the command you are looking for is start /b *command*

For unix, nohup represents 'no hangup', which is slightly different than a background job (which would be *command* &. I believe that the above command should be similar to a background job for windows.

Get file version in PowerShell

I prefer to install the PowerShell Community Extensions and just use the Get-FileVersionInfo function that it provides.

Like so:

Get-FileVersionInfo MyAssembly.dll

with output like:

ProductVersion   FileVersion      FileName
--------------   -----------      --------
1.0.2907.18095   1.0.2907.18095   C:\Path\To\MyAssembly.dll

I've used it against an entire directory of assemblies with great success.

Selection with .loc in python

pd.DataFrame.loc can take one or two indexers. For the rest of the post, I'll represent the first indexer as i and the second indexer as j.

If only one indexer is provided, it applies to the index of the dataframe and the missing indexer is assumed to represent all columns. So the following two examples are equivalent.

  1. df.loc[i]
  2. df.loc[i, :]

Where : is used to represent all columns.

If both indexers are present, i references index values and j references column values.


Now we can focus on what types of values i and j can assume. Let's use the following dataframe df as our example:

    df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['X', 'Y'])

loc has been written such that i and j can be

  1. scalars that should be values in the respective index objects

    df.loc['A', 'Y']
    
    2
    
  2. arrays whose elements are also members of the respective index object (notice that the order of the array I pass to loc is respected

    df.loc[['B', 'A'], 'X']
    
    B    3
    A    1
    Name: X, dtype: int64
    
    • Notice the dimensionality of the return object when passing arrays. i is an array as it was above, loc returns an object in which an index with those values is returned. In this case, because j was a scalar, loc returned a pd.Series object. We could've manipulated this to return a dataframe if we passed an array for i and j, and the array could've have just been a single value'd array.

      df.loc[['B', 'A'], ['X']]
      
         X
      B  3
      A  1
      
  3. boolean arrays whose elements are True or False and whose length matches the length of the respective index. In this case, loc simply grabs the rows (or columns) in which the boolean array is True.

    df.loc[[True, False], ['X']]
    
       X
    A  1
    

In addition to what indexers you can pass to loc, it also enables you to make assignments. Now we can break down the line of code you provided.

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
  1. iris_data['class'] == 'versicolor' returns a boolean array.
  2. class is a scalar that represents a value in the columns object.
  3. iris_data.loc[iris_data['class'] == 'versicolor', 'class'] returns a pd.Series object consisting of the 'class' column for all rows where 'class' is 'versicolor'
  4. When used with an assignment operator:

    iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
    

    We assign 'Iris-versicolor' for all elements in column 'class' where 'class' was 'versicolor'

MySQL Workbench not displaying query results

This is a known bug: link. Upcoming release 6.2.2 fixes this for OS X (Unfortunately, Linux version is still broken).

At least on my computer it's not dissapeared, just folded, and it's edge is almost merged with the edge of 'Action Output' block. When you move your mouse to that edge, the cursor starts looking like a dash with two arrows. Slowly move it couple of pixels higher until you catch the small 1px area where the cursor changes to a dash with a single arrow. Then catch it and pull : )

I've made a couple of photos to illustrate this.

Step 1 Step 2 Step 3

Dynamic SQL results into temp table in SQL Stored procedure

Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...

Collapse all methods in Visual Studio Code

Collapse All is Fold All in Visual Studio Code.

Press Ctrl + K + S for All Settings. Assign a key which you want for Fold All. By default it's Ctrl + K + 0.

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

How do I clear a C++ array?

Hey i think The fastest way to handle that kind of operation is to memset() the memory.

Example-

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

A similar C++ way would be to use std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

Change hover color on a button with Bootstrap customization

This is the correct way to change btn color.

 .btn-primary:not(:disabled):not(.disabled).active, 
    .btn-primary:not(:disabled):not(.disabled):active, 
    .show>.btn-primary.dropdown-toggle{
        color: #fff;
        background-color: #F7B432;
        border-color: #F7B432;
    }

How to select only date from a DATETIME field in MySQL?

Select * from table_name where date(datetime)

Is there a template engine for Node.js?

Check out the Node js modules wiki page. They have listed all the templating engines supporting node.js.

Why do access tokens expire?

This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?

  • Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.
  • Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.
  • The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.

What is the difference between window, screen, and document in Javascript?

The window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

How to not wrap contents of a div?

A combination of both float: left; white-space: nowrap; worked for me.

Each of them independently didn't accomplish the desired result.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Is there an equivalent for var_dump (PHP) in Javascript?

A bit of improvement on nickf's function for those that don't know the type of the variable coming in:

function dump(v) {
    switch (typeof v) {
        case "object":
            for (var i in v) {
                console.log(i+":"+v[i]);
            }
            break;
        default: //number, string, boolean, null, undefined 
            console.log(typeof v+":"+v);
            break;
    }
}

In .NET, which loop runs faster, 'for' or 'foreach'?

Unless you're in a specific speed optimization process, I would say use whichever method produces the easiest to read and maintain code.

If an iterator is already setup, like with one of the collection classes, then the foreach is a good easy option. And if it's an integer range you're iterating, then for is probably cleaner.

403 Forbidden vs 401 Unauthorized HTTP responses

Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.

Brief and Terse

Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.

Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.

Detailed and In-Depth

From RFC2616

10.4.2 401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).

and

10.4.4 403 Forbidden The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.

The first thing to keep in mind is that "Authentication" and "Authorization" in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use "login" to refer to authentication and authorization by methods other than RFC2617

So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.

401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let's give it a try and see what happens.

403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help - that is outside the RFC2616 standards and definition.


Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.

How do I turn a String into a InputStreamReader in java?

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

Where can I get a list of Ansible pre-defined variables?

There is lot of variables defined as Facts -- http://docs.ansible.com/ansible/playbooks_variables.html#information-discovered-from-systems-facts

"ansible_all_ipv4_addresses": [
    "REDACTED IP ADDRESS"
],
"ansible_all_ipv6_addresses": [
    "REDACTED IPV6 ADDRESS"
],
"ansible_architecture": "x86_64",
"ansible_bios_date": "09/20/2012",
"ansible_bios_version": "6.00",
"ansible_cmdline": {
    "BOOT_IMAGE": "/boot/vmlinuz-3.5.0-23-generic",
    "quiet": true,
    "ro": true,
    "root": "UUID=4195bff4-e157-4e41-8701-e93f0aec9e22",
    "splash": true
},
"ansible_date_time": {
    "date": "2013-10-02",
    "day": "02",
    "epoch": "1380756810",
    "hour": "19",
    "iso8601": "2013-10-02T23:33:30Z",
    "iso8601_micro": "2013-10-02T23:33:30.036070Z",
    "minute": "33",
    "month": "10",
    "second": "30",
    "time": "19:33:30",
    "tz": "EDT",
    "year": "2013"
},
"ansible_default_ipv4": {
    "address": "REDACTED",
    "alias": "eth0",
    "gateway": "REDACTED",
    "interface": "eth0",
    "macaddress": "REDACTED",
    "mtu": 1500,
    "netmask": "255.255.255.0",
    "network": "REDACTED",
    "type": "ether"
},
"ansible_default_ipv6": {},
"ansible_devices": {
    "fd0": {
        "holders": [],
        "host": "",
        "model": null,
        "partitions": {},
        "removable": "1",
        "rotational": "1",
        "scheduler_mode": "deadline",
        "sectors": "0",
        "sectorsize": "512",
        "size": "0.00 Bytes",
        "support_discard": "0",
        "vendor": null
    },
    "sda": {
        "holders": [],
        "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
        "model": "VMware Virtual S",
        "partitions": {
            "sda1": {
                "sectors": "39843840",
                "sectorsize": 512,
                "size": "19.00 GB",
                "start": "2048"
            },
            "sda2": {
                "sectors": "2",
                "sectorsize": 512,
                "size": "1.00 KB",
                "start": "39847934"
            },
            "sda5": {
                "sectors": "2093056",
                "sectorsize": 512,
                "size": "1022.00 MB",
                "start": "39847936"
            }
        },
        "removable": "0",
        "rotational": "1",
        "scheduler_mode": "deadline",
        "sectors": "41943040",
        "sectorsize": "512",
        "size": "20.00 GB",
        "support_discard": "0",
        "vendor": "VMware,"
    },
    "sr0": {
        "holders": [],
        "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
        "model": "VMware IDE CDR10",
        "partitions": {},
        "removable": "1",
        "rotational": "1",
        "scheduler_mode": "deadline",
        "sectors": "2097151",
        "sectorsize": "512",
        "size": "1024.00 MB",
        "support_discard": "0",
        "vendor": "NECVMWar"
    }
},
"ansible_distribution": "Ubuntu",
"ansible_distribution_release": "precise",
"ansible_distribution_version": "12.04",
"ansible_domain": "",
"ansible_env": {
    "COLORTERM": "gnome-terminal",
    "DISPLAY": ":0",
    "HOME": "/home/mdehaan",
    "LANG": "C",
    "LESSCLOSE": "/usr/bin/lesspipe %s %s",
    "LESSOPEN": "| /usr/bin/lesspipe %s",
    "LOGNAME": "root",
    "LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:",
    "MAIL": "/var/mail/root",
    "OLDPWD": "/root/ansible/docsite",
    "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "PWD": "/root/ansible",
    "SHELL": "/bin/bash",
    "SHLVL": "1",
    "SUDO_COMMAND": "/bin/bash",
    "SUDO_GID": "1000",
    "SUDO_UID": "1000",
    "SUDO_USER": "mdehaan",
    "TERM": "xterm",
    "USER": "root",
    "USERNAME": "root",
    "XAUTHORITY": "/home/mdehaan/.Xauthority",
    "_": "/usr/local/bin/ansible"
},
"ansible_eth0": {
    "active": true,
    "device": "eth0",
    "ipv4": {
        "address": "REDACTED",
        "netmask": "255.255.255.0",
        "network": "REDACTED"
    },
    "ipv6": [
        {
            "address": "REDACTED",
            "prefix": "64",
            "scope": "link"
        }
    ],
    "macaddress": "REDACTED",
    "module": "e1000",
    "mtu": 1500,
    "type": "ether"
},
"ansible_form_factor": "Other",
"ansible_fqdn": "ubuntu2.example.com",
"ansible_hostname": "ubuntu2",
"ansible_interfaces": [
    "lo",
    "eth0"
],
"ansible_kernel": "3.5.0-23-generic",
"ansible_lo": {
    "active": true,
    "device": "lo",
    "ipv4": {
        "address": "127.0.0.1",
        "netmask": "255.0.0.0",
        "network": "127.0.0.0"
    },
    "ipv6": [
        {
            "address": "::1",
            "prefix": "128",
            "scope": "host"
        }
    ],
    "mtu": 16436,
    "type": "loopback"
},
"ansible_lsb": {
    "codename": "precise",
    "description": "Ubuntu 12.04.2 LTS",
    "id": "Ubuntu",
    "major_release": "12",
    "release": "12.04"
},
"ansible_machine": "x86_64",
"ansible_memfree_mb": 74,
"ansible_memtotal_mb": 991,
"ansible_mounts": [
    {
        "device": "/dev/sda1",
        "fstype": "ext4",
        "mount": "/",
        "options": "rw,errors=remount-ro",
        "size_available": 15032406016,
        "size_total": 20079898624
    }
],
"ansible_nodename": "ubuntu2.example.com",
"ansible_os_family": "Debian",
"ansible_pkg_mgr": "apt",
"ansible_processor": [
    "Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz"
],
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_threads_per_core": 1,
"ansible_processor_vcpus": 1,
"ansible_product_name": "VMware Virtual Platform",
"ansible_product_serial": "REDACTED",
"ansible_product_uuid": "REDACTED",
"ansible_product_version": "None",
"ansible_python_version": "2.7.3",
"ansible_selinux": false,
"ansible_ssh_host_key_dsa_public": "REDACTED KEY VALUE"
"ansible_ssh_host_key_ecdsa_public": "REDACTED KEY VALUE"
"ansible_ssh_host_key_rsa_public": "REDACTED KEY VALUE"
"ansible_swapfree_mb": 665,
"ansible_swaptotal_mb": 1021,
"ansible_system": "Linux",
"ansible_system_vendor": "VMware, Inc.",
"ansible_user_id": "root",
"ansible_userspace_architecture": "x86_64",
"ansible_userspace_bits": "64",
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "VMware"

Unit testing private methods in C#

You can use PrivateObject Class

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(expectedVal, retVal);

Note: PrivateObject and PrivateType are not available for projects targeting netcoreapp2.0 - GitHub Issue 366

Spring Boot - inject map from application.yml

Below solution is a shorthand for @Andy Wilkinson's solution, except that it doesn't have to use a separate class or on a @Bean annotated method.

application.yml:

input:
  name: raja
  age: 12
  somedata:
    abcd: 1 
    bcbd: 2
    cdbd: 3

SomeComponent.java:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "input")
class SomeComponent {

    @Value("${input.name}")
    private String name;

    @Value("${input.age}")
    private Integer age;

    private HashMap<String, Integer> somedata;

    public HashMap<String, Integer> getSomedata() {
        return somedata;
    }

    public void setSomedata(HashMap<String, Integer> somedata) {
        this.somedata = somedata;
    }

}

We can club both @Value annotation and @ConfigurationProperties, no issues. But getters and setters are important and @EnableConfigurationProperties is must to have the @ConfigurationProperties to work.

I tried this idea from groovy solution provided by @Szymon Stepniak, thought it will be useful for someone.

How to use SQL Select statement with IF EXISTS sub query?

Use a CASE statement and do it like this:

SELECT 
    T1.Id [Id]
    ,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2]
FROM
    TABLE1 [T1]
    LEFT OUTER JOIN
        TABLE2 [T2]
        ON
        T2.Id = T1.Id

How to fix ReferenceError: primordials is not defined in node

Fix it in 1 minute:

Just follow these steps. I'm on windows 10 and it worked perfectly for me!

  1. In the same directory where you have package.json create a npm-shrinkwrap.json file with the following contents:
    {
      "dependencies": {
        "graceful-fs": {
            "version": "4.2.2"
         }
      }
    }
  1. Run npm install, and don't worry, it will update npm-shrinkwrap.json with a bunch of content.

  2. Run gulp to start the project.

How to turn off the Eclipse code formatter for certain sections of Java code?

Instead of turning the formatting off, you can configure it not to join already wrapped lines. Similar to Jitter's response, here's for Eclipse STS:

Properties ? Java Code Style ? Formatter ? Enable project specific settings OR Configure Workspace Settings ? Edit ? Line Wrapping (tab) ? check "Never join already wrapped lines"

Save, apply.

enter image description here

How to change Visual Studio 2012,2013 or 2015 License Key?

For me, with Visual Studio 2013, it wasn't enough to remove the license key and perform a repair (the repair restored the license key instead of reverting to a trial, and running it without the repair (after deleting the key) claimed the license had expired but wouldn't let me enter a new key).

I had to:

  • Discover what license key Visual Studio was looking for in the registry with Process Monitor (it was HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C)
  • Completely uninstall Visual Studio 2013 (save CurrentSettings.vssettings first)
  • Delete the license key from the registry by hand in regedit
  • Install Visual Studio using the publicly available web installer (which doesn't have any baked-in license key -- it installs a 30-day trial)
  • Enter my new license key
  • (Re-)install updates (Update 1 at this time)
  • Restore settings by importing the backup I made of CurrentSettings.vssettings

How to split page into 4 equal parts?

If you want to have control over where they are placed separate from source code order:

Demo: http://jsfiddle.net/NmL2W/

<div id="NW"></div>
<div id="NE"></div>
<div id="SE"></div>?
<div id="SW"></div>
html, body { height:100%; margin:0; padding:0 }
div { position:fixed; width:50%; height:50% }
#NW { top:0;   left:0;   background:orange  }
#NE { top:0;   left:50%; background:blue    }
#SW { top:50%; left:0;   background:green   }
#SE { top:50%; left:50%; background:red     }    ?

Note: if you want padding on your regions, you'll need to set the box-sizing to border-box:

div {
  /* ... */
  padding:1em;
  box-sizing:border-box;
  -moz-box-sizing:border-box;
  -webkit-box-sizing:border-box;
}

…otherwise your "50%" width and height become "50% + 2em", which will lead to visual overlaps.

Convert a matrix to a 1 dimensional array

you can use as.vector(). It looks like it is the fastest method according to my little benchmark, as follows:

library(microbenchmark)
x=matrix(runif(1e4),100,100) # generate a 100x100 matrix
microbenchmark(y<-as.vector(x),y<-x[1:length(x)],y<-array(x),y<-c(x),times=1e4)

The first solution uses as.vector(), the second uses the fact that a matrix is stored as a contiguous array in memory and length(m) gives the number of elements in a matrix m. The third instantiates an array from x, and the fourth uses the concatenate function c(). I also tried unmatrix from gdata, but it's too slow to be mentioned here.

Here are some of the numerical results I obtained:

> microbenchmark(
        y<-as.vector(x),
        y<-x[1:length(x)],
        y<-array(x),
        y<-c(x),
        times=1e4)

Unit: microseconds
                expr    min      lq     mean  median      uq       max neval
   y <- as.vector(x)  8.251 13.1640 29.02656 14.4865 15.7900 69933.707 10000
 y <- x[1:length(x)] 59.709 70.8865 97.45981 73.5775 77.0910 75042.933 10000
       y <- array(x)  9.940 15.8895 26.24500 17.2330 18.4705  2106.090 10000
           y <- c(x) 22.406 33.8815 47.74805 40.7300 45.5955  1622.115 10000

Flattening a matrix is a common operation in Machine Learning, where a matrix can represent the parameters to learn but one uses an optimization algorithm from a generic library which expects a vector of parameters. So it is common to transform the matrix (or matrices) into such a vector. It's the case with the standard R function optim().

How do I hide a menu item in the actionbar?

You are trying to access a menu item from an activity, which dont have the access to scope. The call to find the menu item will return null, because the view is not binded with neither the activity nor the layout you are calling from.

The menu items are binded with items such as "Navigation Bar" which in turn are binded with the corresponding activity.

So initialize those views in activity (), and then access the menu items withing that views.

Navigation navView;
navView = findViewById(R.id.navigationView);

MenuItem item = navView.getMenu().findItem(R.id.item_hosting);
item.setVisible(false);

How can I reset eclipse to default settings?

Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.

Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.

Cannot find Microsoft.Office.Interop Visual Studio

If you have installed latest Visual studio and want to To locate library of Microsoft.Office.Interop.Outlook or any other Microsoft.Office.Interop library then you should look into below 2 folders:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15

Please note that folder could be C:\Program Files\

Running multiple AsyncTasks at the same time -- not possible?

Making @sulai suggestion more generic :

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}   

Where does PostgreSQL store the database?

Under my Linux installation, it's here: /var/lib/postgresql/8.x/

You can change it with initdb -D "c:/mydb/"

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Unordered List (<ul>) default indent

When reseting the "Indent" of the list you have to keep in mind that browsers might have different defaults. To make life a lot easier always start off with a "Normalize" file.

The purpose of using these CSS "Normalize" files is to set everything to a know set of values and not relying on what the browser's defaults. Chrome might have a different set of defaults to say FireFox. This way you know that your pages will always display the same no matter what browser you are using, and you know the values to "Reset" your elements.

Now if you are only concerned about lists in particular I would not simply set the padding to 0, this will put your bullets "Outside" of the list not inside like you would expect.

Another thing to keep in mind is not to use the "px" or pixel unit of measurement, you want to use the "em" unit instead. The "em" unit is based on font-size, this way no matter what the font-size is you are guaranteed that the bullet will be on the inside of the list, if you use a pixel offset then on larger font sizes the bullets will be on the outside of the list.

So here is a snippet of the "Normalize" script I use. First set everything to a known value so you know what to set it back to.

ul{
   margin: 0;
   padding: 1em; /* Set the distance from the list edge to 1x the font size */
   list-style-type: disc;
   list-style-position: outside;
   list-style-image: none;
}

What is the instanceof operator in JavaScript?

I just found a real-world application and will use it more often now, I think.

If you use jQuery events, sometimes you want to write a more generic function which may also be called directly (without event). You can use instanceof to check if the first parameter of your function is an instance of jQuery.Event and react appropriately.

var myFunction = function (el) {                
    if (el instanceof $.Event) 
        // event specific code
    else
        // generic code
};

$('button').click(recalc);    // Will execute event specific code
recalc('myParameter');  // Will execute generic code

In my case, the function needed to calculate something either for all (via click event on a button) or only one specific element. The code I used:

var recalc = function (el) { 
    el = (el == undefined || el instanceof $.Event) ? $('span.allItems') : $(el);
    // calculate...
};

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Bootstrap 3 modal vertical position center

i have downloaded bootstrap3-dialog from bellow link and modified the open function in bootstrap-dialog.js

https://github.com/nakupanda/bootstrap3-dialog

Code

open: function () {
            !this.isRealized() && this.realize();
            this.updateClosable();
            //Custom To Vertically centering Bootstrap 
            var $mymodal = this.getModal();
            $mymodal = $mymodal.append('<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td align="center" valign="middle" class="centerModal"></td></tr></table>');
            $mymodal = $mymodal.find(".modal-dialog").appendTo($mymodal.find(".centerModal"));
            //END
            this.getModal().modal('show');
            return this;
        }

Css

.centerModal .modal-header{
    text-align:left;
}
.centerModal .modal-body{
    text-align:left;
} 

sqlalchemy filter multiple columns

There are number of ways to do it:

Using filter() (and operator)

query = meta.Session.query(User).filter(
    User.firstname.like(search_var1),
    User.lastname.like(search_var2)
    )

Using filter_by() (and operator)

query = meta.Session.query(User).filter_by(
    firstname.like(search_var1),
    lastname.like(search_var2)
    )

Chaining filter() or filter_by() (and operator)

query = meta.Session.query(User).\
    filter_by(firstname.like(search_var1)).\
    filter_by(lastname.like(search_var2))

Using or_(), and_(), and not()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(
    and_(
        User.firstname.like(search_var1),
        User.lastname.like(search_var2)
    )
)

Getting XML Node text value with Java DOM

I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

Perhaps iterate the children of your tag node and see what types are there?

Tried this code and it works for me:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

Output was:

#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

Connect to SQL Server database from Node.js

This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.

At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.

"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.

On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.

If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE

Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js

Just in case, if the above links are not working, I am including the source code here:

_x000D_
_x000D_
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
    server: "localhost\\SQL2K14",_x000D_
    database: "SampleDb",_x000D_
    user: "sa",_x000D_
    password: "sql2014",_x000D_
    port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
    var conn = new sql.Connection(dbConfig);_x000D_
    _x000D_
    conn.connect().then(function () {_x000D_
        var req = new sql.Request(conn);_x000D_
        req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
            console.log(recordset);_x000D_
            conn.close();_x000D_
        })_x000D_
        .catch(function (err) {_x000D_
            console.log(err);_x000D_
            conn.close();_x000D_
        });        _x000D_
    })_x000D_
    .catch(function (err) {_x000D_
        console.log(err);_x000D_
    });_x000D_
_x000D_
    //--> another way_x000D_
    //var req = new sql.Request(conn);_x000D_
    //conn.connect(function (err) {_x000D_
    //    if (err) {_x000D_
    //        console.log(err);_x000D_
    //        return;_x000D_
    //    }_x000D_
    //    req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
    //        if (err) {_x000D_
    //            console.log(err);_x000D_
    //        }_x000D_
    //        else { _x000D_
    //            console.log(recordset);_x000D_
    //        }_x000D_
    //        conn.close();_x000D_
    //    });_x000D_
    //});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
_x000D_
_x000D_

The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.

The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql

UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)

laravel 5 : Class 'input' not found

   #config/app.php
   'aliases' => [
        ...
        'Input' => Illuminate\Support\Facades\Input::class,
        ...
    ],

   #Use Controller file
   use Illuminate\Support\Facades\Input;
   ==OR==
   use Input;

Read full example: https://devnote.in/laravel-class-input-not-found

How can you undo the last git add?

You cannot undo the latest git add, but you can undo all adds since the last commit. git reset without a commit argument resets the index (unstages staged changes):

git reset

MVC pattern on Android

Android UI creation using layouts, resources, activities and intents is an implementation of the MVC pattern. Please see the following link for more on this - http://www.cs.otago.ac.nz/cosc346/labs/COSC346-lab2.2up.pdf

mirror for the pdf

Add property to an array of objects

You can use the forEach method to execute a provided function once for each element in the array. In this provided function you can add the Active property to the element.

Results.forEach(function (element) {
  element.Active = "false";
});

How to catch integer(0)?

Inspired by Andrie's answer, you could use identical and avoid any attribute problems by using the fact that it is the empty set of that class of object and combine it with an element of that class:

attr(a, "foo") <- "bar"

identical(1L, c(a, 1L))
#> [1] TRUE

Or more generally:

is.empty <- function(x, mode = NULL){
    if (is.null(mode)) mode <- class(x)
    identical(vector(mode, 1), c(x, vector(class(x), 1)))
}

b <- numeric(0)

is.empty(a)
#> [1] TRUE
is.empty(a,"numeric")
#> [1] FALSE
is.empty(b)
#> [1] TRUE
is.empty(b,"integer")
#> [1] FALSE

Convert object string to JSON

Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.

https://github.com/douglascrockford/JSON-js

Facebook API "This app is in development mode"

  • Development mode is for testing
  • Go to https://developers.facebook.com/apps, then App Review -> Select No for Your app is in development and unavailable to the public
  • Go to Roles -> Testers, enter the Facebook user Id of the users you want to enable testing

Why does Oracle not find oci.dll?

I was using SQLTool where I was getting oci.dll was not found then I downloaded instantclient-basic-nt-12.2.0.1.0 extracted it and added the folder till oci.dll file in path variable

eg.: Path: .;D:\Softwares\Oracle Instant Client\instantclient_12_2

It resolve my issue, now I am able to open the SQLTool

Is it possible to embed animated GIFs in PDFs?

I haven't tested it but apparently you can add quicktime animations to a pdf (no idea why). So the solution would be to export the animated gif to quicktime and add it to the pdf.

Here the solution that apparently works:

  1. Open the GIF in Quicktime and save as MOV (Apparently it works with other formats too, you'll have to try it out).
  2. Insert the MOV into the PDF (with Adobe InDesign (make sure to set Object> Interactive> film options > Embed in PDF) - It should work with Adobe Acrobat Pro DC too: see link
  3. Save the PDF.

See this link (German)

Determining image file size + dimensions via Javascript?

How about this:

var imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg';
var blob = null;
var xhr = new XMLHttpRequest(); 
xhr.open('GET', imageUrl, true); 
xhr.responseType = 'blob';
xhr.onload = function() 
{
    blob = xhr.response;
    console.log(blob, blob.size);
}
xhr.send();

http://qnimate.com/javascript-create-file-object-from-url/

due to Same Origin Policy, only work under same origin

How do I conditionally apply CSS styles in AngularJS?

One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:

ng-style="{backgroundColor:myColor}" 

SQL Server - Case Statement

Like so

DECLARE @t INT=1

SELECT CASE
            WHEN @t>0 THEN
                CASE
                    WHEN @t=1 THEN 'one'
                    ELSE 'not one'
                END
            ELSE 'less than one'
        END

EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.

What is the difference between g++ and gcc?

For c++ you should use g++.

It's the same compiler (e.g. the GNU compiler collection). GCC or G++ just choose a different front-end with different default options.

In a nutshell: if you use g++ the frontend will tell the linker that you may want to link with the C++ standard libraries. The gcc frontend won't do that (also it could link with them if you pass the right command line options).

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Importing JSON into an Eclipse project

Download json from java2s website then include in your project. In your class add these package java_basic;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

Parse date without timezone javascript

You can use this code

var stringDate = "2005-07-08T00:00:00+0000";
var dTimezone = new Date();
var offset = dTimezone.getTimezoneOffset() / 60;
var date = new Date(Date.parse(stringDate));
date.setHours(date.getHours() + offset);

Begin, Rescue and Ensure in Ruby?

If you want to ensure a file is closed you should use the block form of File.open:

File.open("myFile.txt", "w") do |file|
  begin
    file << "#{content} \n"
  rescue
  #handle the error here
  end
end

Select DataFrame rows between two dates

There are two possible solutions:

  • Use a boolean mask, then use df.loc[mask]
  • Set the date column as a DatetimeIndex, then use df[start_date : end_date]

Using a boolean mask:

Ensure df['date'] is a Series with dtype datetime64[ns]:

df['date'] = pd.to_datetime(df['date'])  

Make a boolean mask. start_date and end_date can be datetime.datetimes, np.datetime64s, pd.Timestamps, or even datetime strings:

#greater than the start date and smaller than the end date
mask = (df['date'] > start_date) & (df['date'] <= end_date)

Select the sub-DataFrame:

df.loc[mask]

or re-assign to df

df = df.loc[mask]

For example,

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.random((200,3)))
df['date'] = pd.date_range('2000-1-1', periods=200, freq='D')
mask = (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
print(df.loc[mask])

yields

            0         1         2       date
153  0.208875  0.727656  0.037787 2000-06-02
154  0.750800  0.776498  0.237716 2000-06-03
155  0.812008  0.127338  0.397240 2000-06-04
156  0.639937  0.207359  0.533527 2000-06-05
157  0.416998  0.845658  0.872826 2000-06-06
158  0.440069  0.338690  0.847545 2000-06-07
159  0.202354  0.624833  0.740254 2000-06-08
160  0.465746  0.080888  0.155452 2000-06-09
161  0.858232  0.190321  0.432574 2000-06-10

Using a DatetimeIndex:

If you are going to do a lot of selections by date, it may be quicker to set the date column as the index first. Then you can select rows by date using df.loc[start_date:end_date].

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.random((200,3)))
df['date'] = pd.date_range('2000-1-1', periods=200, freq='D')
df = df.set_index(['date'])
print(df.loc['2000-6-1':'2000-6-10'])

yields

                   0         1         2
date                                    
2000-06-01  0.040457  0.326594  0.492136    # <- includes start_date
2000-06-02  0.279323  0.877446  0.464523
2000-06-03  0.328068  0.837669  0.608559
2000-06-04  0.107959  0.678297  0.517435
2000-06-05  0.131555  0.418380  0.025725
2000-06-06  0.999961  0.619517  0.206108
2000-06-07  0.129270  0.024533  0.154769
2000-06-08  0.441010  0.741781  0.470402
2000-06-09  0.682101  0.375660  0.009916
2000-06-10  0.754488  0.352293  0.339337

While Python list indexing, e.g. seq[start:end] includes start but not end, in contrast, Pandas df.loc[start_date : end_date] includes both end-points in the result if they are in the index. Neither start_date nor end_date has to be in the index however.


Also note that pd.read_csv has a parse_dates parameter which you could use to parse the date column as datetime64s. Thus, if you use parse_dates, you would not need to use df['date'] = pd.to_datetime(df['date']).

How can I remove text within parentheses with a regex?

>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'

test if display = none

You can use the following code to test if display is equivalent to none:

if ($(element).css('display') === 'none' ){
    // do the stuff
}

How do I disable "missing docstring" warnings at a file-level in Pylint?

In my case, with Pylint 2.6.0, the missing docstring messages wouldn't disappear, even after explicitly disabling missing-module-docstring, missing-class-docstring and missing-function-docstring in my .pylintrc file. Finally, the following configuration worked for me:

[MESSAGES CONTROL]

disable=missing-docstring,empty-docstring

Apparently, Pylint 2.6.0 still validates docstrings unless both checks are disabled.

What is the difference between function and procedure in PL/SQL?

In dead simple way it makes this meaning.

Functions :

These subprograms return a single value; mainly used to compute and return a value.

Procedure :

These subprograms do not return a value directly; mainly used to perform an action.

Example Program:

CREATE OR REPLACE PROCEDURE greetings

BEGIN 

dbms_output.put_line('Hello World!');

END ;
/

Executing a Standalone Procedure :

A standalone procedure can be called in two ways:

• Using the EXECUTE keyword • Calling the name of procedure from a PL/SQL block

The procedure can also be called from another PL/SQL block:

BEGIN 
greetings;
END;
/

Function:

CREATE OR REPLACE FUNCTION totalEmployees 
RETURN number IS
total number(3) := 0;
BEGIN 
SELECT count(*) into total 
FROM employees;
RETURN total; 
END;
/

Following program calls the function totalCustomers from an another block

DECLARE 
c number(3);
BEGIN 
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/

In Angular, how to redirect with $location.path as $http.post success callback

Instead of using success, I change it to then and it works.

here is the code:

lgrg.controller('login', function($scope, $window, $http) {
    $scope.loginUser = {};

    $scope.submitForm = function() {
        $scope.errorInfo = null

        $http({
            method  : 'POST',
            url     : '/login',
            headers : {'Content-Type': 'application/json'}
            data: $scope.loginUser
        }).then(function(data) {
            if (!data.status) {
                $scope.errorInfo = data.info
            } else {
                //page jump
                $window.location.href = '/admin';
            }
        });
    };
});

Convert byte to string in Java

String str = "0x63";
int temp = Integer.parseInt(str.substring(2, 4), 16);
char c = (char)temp;
System.out.print(c);

AVD Manager - Cannot Create Android Virtual Device

Launching the AVD Manager from Visual Studio 2015 resolved this issue for me.

I had (a lot of packages) all the required packages installed but hadn't used them for some time & had issues detecting them in the SDK manager. I attempted all the solutions provided above to no avail, including running the AVD after running the monitor.bat file in 'android/sdk/tools'.

I then launched the AVD from VS in 'Tools->Android->Android Emulator Manager' and it detected both 'Google APIs Intel Atom x86' & the ARM EABI v7a system Images right off the bat!

Target is set to API Level 23.

Casting interfaces for deserialization in JSON.NET

Use this class, for mapping abstract type to real type:

public class AbstractConverter<TReal, TAbstract> 
    : JsonConverter where TReal : TAbstract
{
    public override Boolean CanConvert(Type objectType)
        => objectType == typeof(TAbstract);

    public override Object ReadJson(JsonReader reader, Type type, Object value, JsonSerializer jser)
        => jser.Deserialize<TReal>(reader);

    public override void WriteJson(JsonWriter writer, Object value, JsonSerializer jser)
        => jser.Serialize(writer, value);
}

...and when deserialize:

var settings = new JsonSerializerSettings
{
    Converters = {
        new AbstractConverter<Thing, IThingy>(),
        new AbstractConverter<Thing2, IThingy2>()
    },
};

JsonConvert.DeserializeObject(json, type, settings);

Find and replace strings in vim on multiple lines

The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

:6,10s/<search_string>/<replace_string>/g | 14,18&&

If you have many ranges though, I'd rather use a loop:

:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor

Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

How to get date and time from server

You can use the "system( string $command[, int &$return_var] ) : string" function. For Windows system( "time" );, system( "time > output.txt" ); to put the response in the output.txt file. If you plan on deploying your website on someone else's server, then you may not want to hardcode the server time, as the server may move to an unknown timezone. Then it may be best to set the default time zone in the php.ini file. I use Hostinger and they allow you to configure that php.ini value.

align images side by side in html

Try using this format

<figure>
   <img src="img" alt="The Pulpit Rock" width="304" height="228">
   <figcaption>Fig1. - A view of the pulpit rock in Norway.</figcaption>
</figure>

This will give you a real caption (just add the 2nd and 3rd imgs using Float:left like others suggested)

Create a symbolic link of directory in Ubuntu

In script is usefull something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

Converting Go struct to JSON

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Not the answer for this question

I got this exception when trying to delete a folder where i deleted the file inside.

Example:

createFolder("folder");  
createFile("folder/file");  
deleteFile("folder/file");  
deleteFolder("folder"); // error here

While deleteFile("folder/file"); returned that it was deleted, the folder will only be considered empty after the program restart.

On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-

Explanation from dhke

Usage of \b and \r in C

As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.

I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc. enter image description here

Also, I am very curious what is the compiler that you were using. :)

Copy table without copying data

Try:

CREATE TABLE foo SELECT * FROM bar LIMIT 0

Or:

CREATE TABLE foo SELECT * FROM bar WHERE 1=0

How to use zIndex in react-native

I finally solved this by creating a second object that imitates B.

My schema now looks like this:

enter image description here

I now have B1 (within parent of A) and B2 outside of it.

B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.

Call child component method from parent class - Angular

Angular – Call Child Component’s Method in Parent Component’s Template

You have ParentComponent and ChildComponent that looks like this.

parent.component.html

enter image description here

parent.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

When serve, it looks like this:

enter image description here

When user focus on ParentComponent’s input element, you want to call ChildComponent’s doSomething() method.

Simply do this:

  1. Give app-child selector in parent.component.html a DOM variable name (prefix with # – hashtag), in this case we call it appChild.
  2. Assign expression value (of the method you want to call) to input element’s focus event.

enter image description here

The result:

enter image description here

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

For yet another concrete use case, use double brackets when you want to select a data frame created by the split() function. If you don't know, split() groups a list/data frame into subsets based on a key field. It's useful if when you want to operate on multiple groups, plot them, etc.

> class(data)
[1] "data.frame"

> dsplit<-split(data, data$id)
> class(dsplit)
[1] "list"

> class(dsplit['ID-1'])
[1] "list"

> class(dsplit[['ID-1']])
[1] "data.frame"

php how to go one level up on dirname(__FILE__)

To Whom, deailing with share hosting environment and still chance to have Current PHP less than 7.0 Who does not have dirname( __FILE__, 2 ); it is possible to use following.

function dirname_safe($path, $level = 0){
    $dir = explode(DIRECTORY_SEPARATOR, $path);
    $level = $level * -1;
    if($level == 0) $level = count($dir);
    array_splice($dir, $level);
    return implode($dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}

print_r(dirname_safe(__DIR__, 2));

C# - using List<T>.Find() with custom objects

It's easy, just use list.Find(x => x.name == "stringNameOfObjectToFind");

Show constraints on tables command

Simply query the INFORMATION_SCHEMA:

USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<your_database_name>" 
      AND TABLE_NAME = "<your_table_name>" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

How can I format bytes a cell in Excel as KB, MB, GB etc?

I don't know of a way to make it show you binary gigabytes (multiples of 1024*1024*1024) but you can make it show you decimal gigabytes using a format like:

0.00,,,"Gb"

Fatal error: Maximum execution time of 300 seconds exceeded

On Xampp, in php.ini you must check mysql.connect_timeout either. So, for example, change it to:

mysql.connect_timeout = 3600

That time will be always counted in seconds (so 1 hour in my example)

How to pass List<String> in post method using Spring MVC?

I had the same use case, You can change your method defination in the following way :

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody Map<String,List<String>> fruits) {
    ..
}

The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

How to do select from where x is equal to multiple values?

Put parentheses around the "OR"s:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND
(
    ads.county_id = 2
    OR ads.county_id = 5
    OR ads.county_id = 7
    OR ads.county_id = 9
)

Or even better, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)

Mix Razor and Javascript code

Use <text>:

<script type="text/javascript">

   var data = [];

   @foreach (var r in Model.rows)
   {
      <text>
            data.push([ @r.UnixTime * 1000, @r.Value ]);
      </text>
   }
</script>

Sending POST parameters with Postman doesn't work, but sending GET parameters does

I was having the same problem. To fix it I added the following headers:

Content-Type: application/json

I had to manually add the content type even though I also had the type of "json" in the raw post field parameters.

Encoding URL query parameters in Java

EDIT: URIUtil is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.


URIUtil of Apache httpclient is really useful, although there are some alternatives

URIUtil.encodeQuery(url);

For example, it encodes space as "+" instead of "%20"

Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

What is "origin" in Git?

origin is not the remote repository name. It is rather a local alias set as a key in place of the remote repository URL.

It avoids the user having to type the whole remote URL when prompting a push.

This name is set by default and for convention by Git when cloning from a remote for the first time.

This alias name is not hard coded and could be changed using following command prompt:

git remote rename origin mynewalias

Take a look at http://git-scm.com/docs/git-remote for further clarifications.

What is the correct way to do a CSS Wrapper?

<div class="wrapper">test test test</div>

.wrapper{
    width:100px;
    height:100px;
    margin:0 auto;
}

Check working example at http://jsfiddle.net/8wpYV/

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

Format numbers in django templates

Based on muhuk answer I did this simple tag encapsulating python string.format method.

  • Create a templatetags at your's application folder.
  • Create a format.py file on it.
  • Add this to it:

    from django import template
    
    register = template.Library()
    
    @register.filter(name='format')
    def format(value, fmt):
        return fmt.format(value)
    
  • Load it in your template {% load format %}
  • Use it. {{ some_value|format:"{:0.2f}" }}

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

How to move from one fragment to another fragment on click of an ImageView in Android?

you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.

You can call another fragment by writing the code below:

        FragmentTransaction t = this.getFragmentManager().beginTransaction();
        Fragment mFrag = new MyFragment();
        t.replace(R.id.content_frame, mFrag);
        t.commit();

here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.

you can also add the other fragment incase of replace.

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

See here for variations: https://en.cppreference.com/w/cpp/language/range-for

Using Google Text-To-Speech in Javascript

Very easy with responsive voice. Just include the js and voila!

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>

<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />

How do I enable Java in Microsoft Edge web browser?

Edge has dropped all support for plugins. This means that Java, ActiveX, Silverlight, and other plugins are no longer supported. For this reason Microsoft has included Internet Explorer 11, which does support these plugins, with non-mobile versions of Windows 10. If you are running Windows 10 and need plugin support Edge is not an option, but IE 11 is.

How to create a directive with a dynamic template in AngularJS?

You should move your switch into the template by using the 'ng-switch' directive:

module.directive('testForm', function() {
    return {
        restrict: 'E',
        controllerAs: 'form',
        controller: function ($scope) {
            console.log("Form controller initialization");
            var self = this;
            this.fields = {};
            this.addField = function(field) {
                console.log("New field: ", field);
                self.fields[field.name] = field;
            };
        }
    }
});

module.directive('formField', function () {
    return {
        require: "^testForm",
        template:
            '<div ng-switch="field.fieldType">' +
            '    <span>{{title}}:</span>' +
            '    <input' +
            '        ng-switch-when="text"' +
            '        name="{{field.name}}"' +
            '        type="text"' +
            '        ng-model="field.value"' +
            '    />' +
            '    <select' +
            '        ng-switch-when="select"' +
            '        name="{{field.name}}"' +
            '        ng-model="field.value"' +
            '        ng-options="option for option in options">' +
            '        <option value=""></option>' +
            '    </select>' +
            '</div>',
        restrict: 'E',
        replace: true,
        scope: {
            fieldType: "@",
            title: "@",
            name: "@",
            value: "@",
            options: "=",
        },
        link: function($scope, $element, $attrs, form) {
            $scope.field = $scope;
            form.addField($scope);
        }
    };
});

It can be use like this:

<test-form>
    <div>
        User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
    </div>
    <form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
    <form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
    <form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>

How do I hide an element when printing a web page?

You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):

<div id="printOption">
    <a href="javascript:void();" 
       onclick="document.getElementById('printOption').style.visibility = 'hidden'; 
       document.print(); 
       return true;">
       Print
    </a>
</div>

The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).

The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.

How do I search an SQL Server database for a string?

Here is how you can search the database in Swift using the FMDB library.

First, go to this link and add this to your project: FMDB. When you have done that, then here is how you do it. For example, you have a table called Person, and you have firstName and secondName and you want to find data by first name, here is a code for that:

    func loadDataByfirstName(firstName : String, completion: @escaping CompletionHandler){
    if isDatabaseOpened {
        let query = "select * from Person where firstName like '\(firstName)'"
        do {
            let results = try database.executeQuery(query, values: [firstName])
            while results.next() {
                let firstName = results.string(forColumn: "firstName") ?? ""
                let lastName = results.string(forColumn: "lastName") ?? ""
                let newPerson = Person(firstName: firstName, lastName: lastName)
                self.persons.append(newPerson)
            }
            completion(true)
        }catch let err {
            completion(false)
            print(err.localizedDescription)
        }
        database.close()
    }
}

Then in your ViewController you will write this to find the person detail you are looking for:

  override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)
      SQLManager.instance.openDatabase { (success) in
        if success {
            SQLManager.instance.loadDataByfirstName(firstName: "Hardi") { (success) in
                if success {
                    // You have your data Here
                }
            }
        }
    }
}

Using getline() in C++

If you only have a single newline in the input, just doing

std::cin.ignore();

will work fine. It reads and discards the next character from the input.

But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

See e.g. this reference of the ignore function.

To be even more safe, do the second alternative above in a loop until gcount returns zero.

TimeStamp on file name using PowerShell

Thanks for the above script. One little modification to add in the file ending correctly. Try this ...

$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**

Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat

Using a RegEx to match IP addresses in Python

You have to modify your regex in the following way

pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")

that's because . is a wildcard that stands for "every character"

How to remove gem from Ruby on Rails application?

You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.

Xcode 9 error: "iPhone has denied the launch request"

I just cleared the profiles with the Apple Configurator, restarted the iDevice and worked again as usual.

How do I find the PublicKeyToken for a particular dll?

Using PowerShell, you can execute this statement:

([system.reflection.assembly]::loadfile("C:\..\Full_Path\..\MyDLL.dll")).FullName

The output will provide the Version, Culture and PublicKeyToken as shown below:

MyDLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a

How do I close a single buffer (out of many) in Vim?

Close buffer without closing the window

If you want to close a buffer without destroying your window layout (current layout based on splits), you can use a Plugin like bbye. Based on this, you can just use

:Bdelete (instead of :bdelete)
:Bwipeout (instead of :bwipeout)

Or just create a mapping in your .vimrc for easier access like

:nnoremap <Leader>q :Bdelete<CR>

Advantage over vim's :bdelete and :bwipeout

From the plugin's documentation:

  • Close and remove the buffer.
  • Show another file in that window.
  • Show an empty file if you've got no other files open.
  • Do not leave useless [no file] buffers if you decide to edit another file in that window.
  • Work even if a file's open in multiple windows.
  • Work a-okay with various buffer explorers and tabbars.

:bdelete vs :bwipeout

From the plugin's documentation:

Vim has two commands for closing a buffer: :bdelete and :bwipeout. The former removes the file from the buffer list, clears its options, variables and mappings. However, it remains in the jumplist, so Ctrl-o takes you back and reopens the file. If that's not what you want, use :bwipeout or Bbye's equivalent :Bwipeout where you would've used :bdelete.

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

Explain why constructor inject is better than other options

A class that takes a required dependency as a constructor argument can only be instantiated if that argument is provided (you should have a guard clause to make sure the argument is not null.) A constructor therefore enforces the dependency requirement whether or not you're using Spring, making it container-agnostic.

If you use setter injection, the setter may or may not be called, so the instance may never be provided with its dependency. The only way to force the setter to be called is using @Required or @Autowired , which is specific to Spring and is therefore not container-agnostic.

So to keep your code independent of Spring, use constructor arguments for injection.

Update: Spring 4.3 will perform implicit injection in single-constructor scenarios, making your code more independent of Spring by potentially not requiring an @Autowired annotation at all.

html text input onchange event

onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:

<input
   type       = "text" 
   onchange   = "myHandler();"
   onkeypress = "this.onchange();"
   onpaste    = "this.onchange();"
   oninput    = "this.onchange();"
/>

display Java.util.Date in a specific format

You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

Using margin:auto to vertically-align a div

I think you can fix that with Flexbox

_x000D_
_x000D_
.black {
  height : 200px;
  width : 200px;
  background-color : teal;
  border: 5px solid rgb(0, 53, 53);
  /* This is the important part */
  display : flex;
  justify-content: center;
  align-items: center;
}

.message {
  background-color :  rgb(119, 128, 0);
  border: 5px solid rgb(0, 53, 53);
  height : 50%;
  width : 50%;
  padding : 5px;
}
_x000D_
<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>
_x000D_
_x000D_
_x000D_

Simplest way to merge ES6 Maps/Sets?

Based off of Asaf Katz's answer, here's a typescript version:

export function union<T> (...iterables: Array<Set<T>>): Set<T> {
  const set = new Set<T>()
  iterables.forEach(iterable => {
    iterable.forEach(item => set.add(item))
  })
  return set
}

Math functions in AngularJS bindings

Better option is to use :

{{(100*score/questionCounter) || 0 | number:0}}

It sets default value of equation to 0 in the case when values are not initialized.

How can I view an old version of a file with Git?

git log -p will show you not just the commit logs but also the diff of each commit (except merge commits). Then you can press /, enter filename and press enter. Press n or p to go to the next/previous occurrence. This way you will not just see the changes in the file but also the commit information.

Sorting an array of objects by property values

For sort on multiple array object field. Enter your field name in arrprop array like ["a","b","c"] then pass in second parameter arrsource actual source we want to sort.

function SortArrayobject(arrprop,arrsource){
arrprop.forEach(function(i){
arrsource.sort(function(a,b){
return ((a[i] < b[i]) ? -1 : ((a[i] > b[i]) ? 1 : 0));
});
});
return arrsource;
}

How to obtain Telegram chat_id for a specific user?

The message updates you receive via getUpdates or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id key.

This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.

I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.

File being used by another process after using File.Create()

File.Create returns a FileStream. You need to close that when you have written to the file:

using (FileStream fs = File.Create(path, 1024)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

You can use using for automatically closing the file.

Node.js check if file exists

fs.exists(path, callback) and fs.existsSync(path) are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.

To test the existence of a file synchronously one can use ie. fs.statSync(path). An fs.Stats object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.

var fs = require('fs'),
  path = '/path/to/my/file',
  stats;

try {
  stats = fs.statSync(path);
  console.log("File exists.");
}
catch (e) {
  console.log("File does not exist.");
}

Case insensitive access for generic dictionary

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

You can, however, create a case-insensitive dictionary in the first place using:-

var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);

Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-

var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);

This new dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase so comparer.GetHashCode("foo") and comparer.GetHashcode("FOO") give you the same value.

Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>> and just iterate over it:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;

Or if you prefer, without the LINQ:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
  if (String.Equals(element.Key, myKey, comparer))
  {
    value = element.Value;
    break;
  }
}

This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).

How to get the number of characters in a std::string?

When dealing with C++ strings (std::string), you're looking for length() or size(). Both should provide you with the same value. However when dealing with C-Style strings, you would use strlen().

#include <iostream>
#include <string.h>

int main(int argc, char **argv)
{
   std::string str = "Hello!";
   const char *otherstr = "Hello!"; // C-Style string
   std::cout << str.size() << std::endl;
   std::cout << str.length() << std::endl;
   std::cout << strlen(otherstr) << std::endl; // C way for string length
   std::cout << strlen(str.c_str()) << std::endl; // convert C++ string to C-string then call strlen
   return 0;
}

Output:

6
6
6
6

.gitignore for Visual Studio Projects and Solutions

On Visual Studio 2015 Update 3, and with Git extension updated as of today (2016-10-24), the .gitignore generated by Visual Studio is:

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/

# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# DNX
project.lock.json
artifacts/

*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding add-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml

# TODO: Un-comment the next line if you do not want to checkin 
# your web deploy settings because they may include unencrypted
# passwords
#*.pubxml
*.publishproj

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config

# Windows Store app package directory
AppPackages/
BundleArtifacts/

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm

# SQL Server files
*.mdf
*.ldf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# LightSwitch generated files
GeneratedArtifacts/
ModelManifest.xml

# Paket dependency manager
.paket/paket.exe

# FAKE - F# Make
.fake/

SQL - select distinct only on one column

You will use the following query:

SELECT * FROM [table] GROUP BY NUMBER;

Where [table] is the name of the table.

This provides a unique listing for the NUMBER column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.

How can I dismiss the on screen keyboard?

Just use:

Focus.of(context).unfocus();

All about Focus in Flutter here -> enter link description here

Structure padding and packing

Rules for padding:

  1. Every member of the struct should be at an address divisible by its size. Padding is inserted between elements or at the end of the struct to make sure this rule is met. This is done for easier and more efficient Bus access by the hardware.
  2. Padding at the end of the struct is decided based on the size of the largest member of the struct.

Why Rule 2: Consider the following struct,

Struct 1

If we were to create an array(of 2 structs) of this struct, No padding will be required at the end:

Struct1 array

Therefore, size of struct = 8 bytes

Assume we were to create another struct as below:

Struct 2

If we were to create an array of this struct, there are 2 possibilities, of the number of bytes of padding required at the end.

A. If we add 3 bytes at the end and align it for int and not Long:

Struct2 array aligned to int

B. If we add 7 bytes at the end and align it for Long:

Struct2 array aligned to Long

The start address of the second array is a multiple of 8(i.e 24). The size of the struct = 24 bytes

Therefore, by aligning the start address of the next array of the struct to a multiple of the largest member(i.e if we were to create an array of this struct, the first address of the second array must start at an address which is a multiple of the largest member of the struct. Here it is, 24(3 * 8)), we can calculate the number of padding bytes required at the end.

What are Covering Indexes and Covered Queries in SQL Server?

A covered query is a query where all the columns in the query's result set are pulled from non-clustered indexes.

A query is made into a covered query by the judicious arrangement of indexes.

A covered query is often more performant than a non-covered query in part because non-clustered indexes have more rows per page than clustered indexes or heap indexes, so fewer pages need to be brought into memory in order to satisfy the query. They have more rows per page because only part of the table row is part of the index row.

A covering index is an index which is used in a covered query. There is no such thing as an index which, in and of itself, is a covering index. An index may be a covering index with respect to query A, while at the same time not being a covering index with respect to query B.

Accessing a value in a tuple that is in a list

Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in DiveIntoPython3, for example). Here are a few points:

[x[1] for x in L]

  • Notice the []'s around the line of code. These are what define a list. This tells you that this code returns a list, so it's of the list type. Hence, this technique is called a "list comprehension."
  • L is your original list. So you should define L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)] prior to executing the above code.
  • x is a variable that only exists in the comprehension - try to access x outside of the comprehension, or type type(x) after executing the above line and it will tell you NameError: name 'x' is not defined, whereas type(L) returns <class 'list'>.
  • x[1] points to the second item in each of the tuples whereas x[0] would point to each of the first items.
  • So this line of code literally reads "return the second item in a tuple for all tuples in list L."

It's tough to tell how much you attempted the problem prior to asking the question, but perhaps you just weren't familiar with comprehensions? I would spend some time reading through Chapter 3 of DiveIntoPython, or any resource on comprehensions. Good luck.

How to resize images proportionally / keeping the aspect ratio?

This issue can be solved by CSS.

.image{
 max-width:*px;
}

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

How to delete Certain Characters in a excel 2010 cell

Another option: =MID(A1,2,LEN(A1)-2)

Or this (for fun): =RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)

Explicitly select items from a list or tuple

I just want to point out, even syntax of itemgetter looks really neat, but it's kinda slow when perform on large list.

import timeit
from operator import itemgetter
start=timeit.default_timer()
for i in range(1000000):
    itemgetter(0,2,3)(myList)
print ("Itemgetter took ", (timeit.default_timer()-start))

Itemgetter took 1.065209062149279

start=timeit.default_timer()
for i in range(1000000):
    myList[0],myList[2],myList[3]
print ("Multiple slice took ", (timeit.default_timer()-start))

Multiple slice took 0.6225321444745759

How to create PDFs in an Android app?

Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.

IOS 7 Navigation Bar text and arrow color

enter image description here

This one took me about half a day to figure out but this is what worked for me. Inside the rootViewController that initializes the navigationController, I put this code inside my viewDidAppear method:

//set bar color
[self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:85.0/255.0 green:143.0/255.0 blue:220.0/255.0 alpha:1.0]];
//optional, i don't want my bar to be translucent
[self.navigationController.navigationBar setTranslucent:NO];
//set title and title color
[self.navigationItem setTitle:@"Title"];
[self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor]];
//set back button color
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor,nil] forState:UIControlStateNormal];
//set back button arrow color
[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

My full post on this here

Accessing Google Account Id /username via Android

if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
  Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
  String userid=currentPerson.getId(); //BY THIS CODE YOU CAN GET CURRENT LOGIN USER ID
}

Call another rest api from my server in Spring-Boot

Does Retrofit have any method to achieve this? If not, how I can do that?

YES

Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

For more information refer the following link

https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial