Programs & Examples On #Fat client

What is the difference between instanceof and Class.isAssignableFrom(...)?

This thread provided me some insight into how instanceof differed from isAssignableFrom, so I thought I'd share something of my own.

I have found that using isAssignableFrom to be the only (probably not the only, but possibly the easiest) way to ask one's self if a reference of one class can take instances of another, when one has instances of neither class to do the comparison.

Hence, I didn't find using the instanceof operator to compare assignability to be a good idea when all I had were classes, unless I contemplated creating an instance from one of the classes; I thought this would be sloppy.

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

Check if a Postgres JSON array contains a string

You could use @> operator to do this something like

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

Newline in JLabel

Surround the string with <html></html> and break the lines with <br/>.

JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

How to set the size of a column in a Bootstrap responsive table

You could use inline styles and define the width in the <th> tag. Make it so that the sum of the widths = 100%.

    <tr>
        <th style="width:10%">Size</th>
        <th style="width:30%">Bust</th>
        <th style="width:50%">Waist</th>
        <th style="width:10%">Hips</th>
    </tr>

Bootply demo

Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.

How to effectively work with multiple files in Vim

I use the following, this gives you lots of features that you'd expect to have in other editors such as Sublime Text / Textmate

  1. Use buffers not 'tab pages'. Buffers are the same concept as tabs in almost all other editors.
  2. If you want the same look of having tabs you can use the vim-airline plugin with the following setting in your .vimrc: let g:airline#extensions#tabline#enabled = 1. This automatically displays all the buffers as tab headers when you have no tab pages opened
  3. Use Tim Pope's vim-unimpaired which gives [b and ]b for moving to previous/next buffers respectively (plus a whole host of other goodies)
  4. Have set wildmenu in your .vimrc then when you type :b <file part> + Tab for a buffer you will get a list of possible buffers that you can use left/right arrows to scroll through
  5. Use Tim Pope's vim-obsession plugin to store sessions that play nicely with airline (I had lots of pain with sessions and plugins)
  6. Use Tim Pope's vim-vinegar plugin. This works with the native :Explore but makes it much easier to work with. You just type - to open the explorer, which is the same key as to go up a directory in the explorer. Makes navigating faster (however with fzf I rarely use this)
  7. fzf (which can be installed as a vim plugin) is also a really powerful fuzzy finder that you can use for searching for files (and buffers too). fzf also plays very nicely with fd (a faster version of find)
  8. Use Ripgrep with vim-ripgrep to search through your code base and then you can use :cdo on the results to do search and replace

VBA: How to display an error message just like the standard error message which has a "Debug" button?

This answer does not address the Debug button (you'd have to design a form and use the buttons on that to do something like the method in your next question). But it does address this part:

now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured.

First, I'll assume you don't want this in production code - you want it either for debugging or for code you personally will be using. I use a compiler flag to indicate debugging; then if I'm troubleshooting a program, I can easily find the line that's causing the problem.

# Const IsDebug = True

Sub ProcA()
On Error Goto ErrorHandler
' Main code of proc

ExitHere:
    On Error Resume Next
    ' Close objects and stuff here
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & ": " & Err.Description, , ThisWorkbook.Name & ": ProcA"
    #If IsDebug Then
        Stop            ' Used for troubleshooting - Then press F8 to step thru code 
        Resume          ' Resume will take you to the line that errored out
    #Else
        Resume ExitHere ' Exit procedure during normal running
    #End If
End Sub

Note: the exception to Resume is if the error occurs in a sub-procedure without an error handling routine, then Resume will take you to the line in this proc that called the sub-procedure with the error. But you can still step into and through the sub-procedure, using F8 until it errors out again. If the sub-procedure's too long to make even that tedious, then your sub-procedure should probably have its own error handling routine.

There are multiple ways to do this. Sometimes for smaller programs where I know I'm gonna be stepping through it anyway when troubleshooting, I just put these lines right after the MsgBox statement:

    Resume ExitHere         ' Normally exits during production
    Resume                  ' Never will get here
Exit Sub

It will never get to the Resume statement, unless you're stepping through and set it as the next line to be executed, either by dragging the next statement pointer to that line, or by pressing CtrlF9 with the cursor on that line.

Here's an article that expands on these concepts: Five tips for handling errors in VBA. Finally, if you're using VBA and haven't discovered Chip Pearson's awesome site yet, he has a page explaining Error Handling In VBA.

How do I use a PriorityQueue?

In here, We can define user defined comparator:

Below code :

 import java.util.*;
 import java.util.Collections;
 import java.util.Comparator; 


 class Checker implements Comparator<String>
 {
    public int compare(String str1, String str2)
    {
        if (str1.length() < str2.length()) return -1;
        else                               return 1;
    }
 }


class Main
{  
   public static void main(String args[])
    {  
      PriorityQueue<String> queue=new PriorityQueue<String>(5, new Checker());  
      queue.add("india");  
      queue.add("bangladesh");  
      queue.add("pakistan");  
 
      while (queue.size() != 0)
      {
         System.out.printf("%s\n",queue.remove());
      }
   }  
}  

Output :

   india                                               
   pakistan                                         
   bangladesh

Difference between the offer and add methods : link

Remove a cookie

Just set the value of cookie to false in order to unset it,

setcookie('cookiename', false);

PS:- That's the easiest way to do it.

AJAX Mailchimp signup form integration

Use jquery.ajaxchimp plugin to achieve that. It's dead easy!

<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />        
  <p class="result"></p>
</form>

JavaScript:

$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})

How to read data when some numbers contain commas as thousand separator?

If number is separated by "." and decimals by "," (1.200.000,00) in calling gsub you must set fixed=TRUE as.numeric(gsub(".","",y,fixed=TRUE))

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Recursively counting files in a Linux directory

If you want to avoid error cases, don't allow wc -l to see files with newlines (which it will count as 2+ files)

e.g. Consider a case where we have a single file with a single EOL character in it

> mkdir emptydir && cd emptydir
> touch $'file with EOL(\n) character in it'
> find -type f
./file with EOL(?) character in it
> find -type f | wc -l
2

Since at least gnu wc does not appear to have an option to read/count a null terminated list (except from a file), the easiest solution would just be to not pass it filenames, but a static output each time a file is found, e.g. in the same directory as above

> find -type f -exec printf '\n' \; | wc -l
1

Or if your find supports it

> find -type f -printf '\n' | wc -l
1 

Join/Where with LINQ and Lambda

It could be something like

var myvar = from a in context.MyEntity
            join b in context.MyEntity2 on a.key equals b.key
            select new { prop1 = a.prop1, prop2= b.prop1};

How do I convert a String to an int in Java?

Google Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}

Java Project: Failed to load ApplicationContext

Looks like you are using maven (src/main/java). In this case put the applicationContext.xml file in the src/main/resources directory. It will be copied in the classpath directory and you should be able to access it with

@ContextConfiguration("/applicationContext.xml")

From the Spring-Documentation: A plain path, for example "context.xml", will be treated as a classpath resource from the same package in which the test class is defined. A path starting with a slash is treated as a fully qualified classpath location, for example "/org/example/config.xml".

So it's important that you add the slash when referencing the file in the root directory of the classpath.

If you work with the absolute file path you have to use 'file:C:...' (if I understand the documentation correctly).

How to decode JWT Token?

I found the solution, I just forgot to Cast the result:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

remove space between paragraph and unordered list

You can use CSS selectors in a way similar to the following:

p + ul {
    margin-top: -10px;
}

This could be helpful because p + ul means select any <ul> element after a <p> element.

You'll have to adapt this to how much padding or margin you have on your <p> tags generally.

Original answer to original question:

p, ul {
    padding: 0;
    margin: 0;
}

That will take any EXTRA white space away.

p, ul {
    display: inline;
}

That will make all the elements inline instead of blocks. (So, for instance, the <p> won't cause a line break before and after it.)

How can I preview a merge in git?

I've found that the solution the works best for me is to just perform the merge and abort it if there are conflicts. This particular syntax feels clean and simple to me. This is Strategy 2 below.

However, if you want to ensure you don't mess up your current branch, or you're just not ready to merge regardless of the existence of conflicts, simply create a new sub-branch off of it and merge that:

Strategy 1: The safe way – merge off a temporary branch:

git checkout mybranch
git checkout -b mynew-temporary-branch
git merge some-other-branch

That way you can simply throw away the temporary branch if you just want to see what the conflicts are. You don't need to bother "aborting" the merge, and you can go back to your work -- simply checkout 'mybranch' again and you won't have any merged code or merge conflicts in your branch.

This is basically a dry-run.

Strategy 2: When you definitely want to merge, but only if there aren't conflicts

git checkout mybranch
git merge some-other-branch

If git reports conflicts (and ONLY IF THERE ARE conflicts) you can then do:

git merge --abort

If the merge is successful, you cannot abort it (only reset).

If you're not ready to merge, use the safer way above.

[EDIT: 2016-Nov - I swapped strategy 1 for 2, because it seems to be that most people are looking for "the safe way". Strategy 2 is now more of a note that you can simply abort the merge if the merge has conflicts that you're not ready to deal with. Keep in mind if reading comments!]

How to set a bitmap from resource

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).

How to find lines containing a string in linux

/tmp/myfile

first line text
wanted text
other text

the command

$ grep -n "wanted text" /tmp/myfile | awk -F  ":" '{print $1}'
2

Handling ExecuteScalar() when no results are returned

this could help .. example::

using System;
using System.Data;
using System.Data.SqlClient;

class ExecuteScalar
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
    mySqlConnection.Open();

    int returnValue = (int) mySqlCommand.ExecuteScalar();
    Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

    mySqlConnection.Close();
  }
}

from this here

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Only one process can use port 80 at a time. Port 80 is the default port for web servers, so when you navigate to websites over HTTP, you are actually navigating to that server's port 80 by default (when you use HTTPS, the port is 443).

You can try to hunt down all the programs that are running on port 80, but there's an easier way that will work for development. When running XAMPP, click "Config" under "Apache". Replace Listen 80 with Listen 8080 and ServerName localhost:80 to ServerName localhost:8080.

Then, when you want to look at your masterpiece, navigate to http://localhost:8080 in your browser.

Windows batch script to move files

move c:\Sourcefoldernam\*.* e:\destinationFolder

^ This did not work for me for some reason

But when I tried using quotation marks, it suddenly worked:

move "c:\Sourcefoldernam\*.*" "e:\destinationFolder"

I think its because my directory had spaces in one of the folders. So if it doesn't work for you, try with quotation marks!

How do I remove blue "selected" outline on buttons?

This is an issue in the Chrome family and has been there forever.

A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208

It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse. You should see that outline only on keyboard tab-press.

I highly recommend using this fix: https://github.com/wicg/focus-visible.

Just do the following

npm install --save focus-visible

Add the script to your html:

<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>

or import into your main entry file if using webpack or something similar:

import 'focus-visible/dist/focus-visible.min';

then put this in your css file:

// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
  outline: magenta auto 5px;
}

You can just set:

button:focus {outline:0;}

but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.

Remove title in Toolbar in appcompat-v7

Try this...

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

    .....

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_landing_page);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    .....

 }

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

C# Creating and using Functions

The reason why you have the error is because your add function is defined after your using it in main if you were to create a function prototype before main up above it with public int Add(int x, int y); or you could just copy and paste your entire Add function above main cause main is where the compiler starts execution so doesn't it make sense to declare and define a function before you use it hope that helps. :D

Calling a php function by onclick event

Executing PHP functions by the onclick event is a cumbersome task and near impossible.

Instead you can redirect to another PHP page.

Say you are currently on a page one.php and you want to fetch some data from this php script process the data and show it in another page i.e. two.php you can do it by writing the following code <button onclick="window.location.href='two.php'">Click me</button>

How to increase memory limit for PHP over 2GB?

Input the following to your Apache configuration:

php_value memory_limit 2048M

Rails: How do I create a default value for attributes in Rails activerecord's model?

The solution depends on a few things.

Is the default value dependent on other information available at creation time? Can you wipe the database with minimal consequences?

If you answered the first question yes, then you want to use Jim's solution

If you answered the second question yes, then you want to use Daniel's solution

If you answered no to both questions, you're probably better off adding and running a new migration.

class AddDefaultMigration < ActiveRecord::Migration
  def self.up
     change_column :tasks, :status, :string, :default => default_value, :null => false
  end
end

:string can be replaced with any type that ActiveRecord::Migration recognizes.

CPU is cheap so the redefinition of Task in Jim's solution isn't going to cause many problems. Especially in a production environment. This migration is proper way of doing it as it is loaded it and called much less often.

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

Can a background image be larger than the div itself?

I do not believe that you can make a background image overflow its div. Images placed in Image tags can overflow their parent div, but background images are limited by the div for which they are the background.

Best practices for API versioning?

Put your version in the URI. One version of an API will not always support the types from another, so the argument that resources are merely migrated from one version to another is just plain wrong. It's not the same as switching format from XML to JSON. The types may not exist, or they may have changed semantically.

Versions are part of the resource address. You're routing from one API to another. It's not RESTful to hide addressing in the header.

Disabling tab focus on form elements

My case may not be typical but what I wanted to do was to have certain columns in a TABLE completely "inert": impossible to tab into them, and impossible to select anything in them. I had found class "unselectable" from other SO answers:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

This actually prevents the user using the mouse to put the focus in the TD ... but I couldn't find a way on SO to prevent tabbing into cells. The TDs in my TABLE actually each has a DIV as their sole child, and using console.log I found that in fact the DIVs would get the focus (without the focus first being obtained by the TDs).

My solution involves keeping track of the "previously focused" element (anywhere on the page):

window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
  window.prevFocus = window.currFocus;
  window.currFocus = document.activeElement;
});

I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...

The simplest answer is then just to do this (to the sole DIV child in every newly created TD):

...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
    window.prevFocus.focus();
});         

So far so good. It should be clear that this would work if you just have a TD (with no DIV child). Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.

SQL Add foreign key to existing column

Maybe you got your columns backwards??

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)           <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id)   <-- this needs to be a column of the ActiveDirectories table

Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?

Then your command should be:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 

Python: most idiomatic way to convert None to empty string?

If you know that the value will always either be a string or None:

xstr = lambda s: s or ""

print xstr("a") + xstr("b") # -> 'ab'
print xstr("a") + xstr(None) # -> 'a'
print xstr(None) + xstr("b") # -> 'b'
print xstr(None) + xstr(None) # -> ''

Calling remove in foreach loop in Java

Use

.remove() of Interator or

Use

CopyOnWriteArrayList

How to declare a type as nullable in TypeScript?

Nullable type can invoke runtime error. So I think it's good to use a compiler option --strictNullChecks and declare number | null as type. also in case of nested function, although input type is null, compiler can not know what it could break, so I recommend use !(exclamination mark).

function broken(name: string | null): string {
  function postfix(epithet: string) {
    return name.charAt(0) + '.  the ' + epithet; // error, 'name' is possibly null
  }
  name = name || "Bob";
  return postfix("great");
}

function fixed(name: string | null): string {
  function postfix(epithet: string) {
    return name!.charAt(0) + '.  the ' + epithet; // ok
  }
  name = name || "Bob";
  return postfix("great");
}

Reference. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

How to get folder path from file path with CMD

For the folder name and drive, you can use:

echo %~dp0

You can get a lot more information using different modifiers:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file

The modifiers can be combined to get compound results:
%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only

This is a copy paste from the "for /?" command on the prompt. Hope it helps.

Related

Top 10 DOS Batch tips (Yes, DOS Batch...) shows batchparams.bat (link to source as a gist):

C:\Temp>batchparams.bat c:\windows\notepad.exe
%~1     =      c:\windows\notepad.exe
%~f1     =      c:\WINDOWS\NOTEPAD.EXE
%~d1     =      c:
%~p1     =      \WINDOWS\
%~n1     =      NOTEPAD
%~x1     =      .EXE
%~s1     =      c:\WINDOWS\NOTEPAD.EXE
%~a1     =      --a------
%~t1     =      08/25/2005 01:50 AM
%~z1     =      17920
%~$PATHATH:1     =
%~dp1     =      c:\WINDOWS\
%~nx1     =      NOTEPAD.EXE
%~dp$PATH:1     =      c:\WINDOWS\
%~ftza1     =      --a------ 08/25/2005 01:50 AM 17920 c:\WINDOWS\NOTEPAD.EXE

How to set dropdown arrow in spinner?

Attach a Spinner Style using Java Code:

First, you need to a layout file such as below:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
android:minHeight="?android:attr/listPreferredItemHeight" />

Let us name it spinner_item.xml and place it inside res/layouts folder.

Next, Create a String ArrayList and put all the Spinner options inside it:

ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item No. 1");
spinnerArray.add("Item No. 2");
spinnerArray.add("Item No. 3");
spinnerArray.add("Item No. 4");

Finally, create the Spinner object and attach the style layout to it.

Spinner spinner = new Spinner(getActivity());
spinner.setTag("some_id");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);                  spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(spinnerArrayAdapter);

Note the Spinner(getActivity()) in the above line will be changed to Spinner(this) if you are writing this from inside Activity rather than from inside a fragment.

Thats all!


Attach a Spinner Style inside Android Layout File:

First, create a xml file the defines the style attribute (gradient_spinner.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
        <item><shape>
            <gradient android:angle="90"  android:type="linear" />

            <stroke android:width="1dp" android:color="@color/colorBackground" />

            <corners android:radius="2dp" />

            <padding android:bottom="1dp" android:left="1dp" android:right="1dp" android:top="1dp" />
        </shape></item>
        <item android:right="5dp">
            <bitmap android:gravity="center_horizontal|right" android:src="@drawable/expand_icon">
            <padding android:right="2dp" />
        </bitmap>
        </item>
    </layer-list></item>

</selector>

Next, inside the style.xml file specify the style and call the gradient_spinner as background

<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">1dp</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">5dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
</style>

Finally, attach the above style to the Spinner:

<Spinner
   android:id="@+id/agent_id_spinner"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:textSize="@dimen/title_text_view"
   style="@style/spinner_style"  />

Thats it!

How can I execute a PHP function in a form action?

You can put the username() function in another page, and send the form to that page...

How to say no to all "do you want to overwrite" prompts in a batch file copy?

You can make a text file with a single long line of "n" then run your command and put < nc.txt after it. I did this to copy over 145,000 instances where "No overwrite" was what I wanted and it worked fine this way.

Or you can just hold the n key down with something, but that takes longer than using the < to pipe it in.

Find distance between two points on map using Google Map API V2

you can use this function. I have used it in my project.

public String getDistance(LatLng my_latlong, LatLng frnd_latlong) {
    Location l1 = new Location("One");
    l1.setLatitude(my_latlong.latitude);
    l1.setLongitude(my_latlong.longitude);

    Location l2 = new Location("Two");
    l2.setLatitude(frnd_latlong.latitude);
    l2.setLongitude(frnd_latlong.longitude);

    float distance = l1.distanceTo(l2);
    String dist = distance + " M";

    if (distance > 1000.0f) {
        distance = distance / 1000.0f;
        dist = distance + " KM";
    }
    return dist;
}

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

Apple has made following changes so download new certificate developer.apple.com

renewed certificate and place it as below screen shots .In the keychain as below screen shots click on system and then certificate. Delete the expired certificate . Then drag and drop the AppleWWDRCA.cer that you downloaded from above link

Apple Worldwide Developer Relations Intermediate Certificate Expiration

To help protect customers and developers, we require that all third party apps, passes for Apple Wallet, Safari Extensions, Safari Push Notifications, and App Store purchase receipts are signed by a trusted certificate authority. The Apple Worldwide Developer Relations Certificate Authority issues the certificates you use to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Since different methods can be used for validating receipts and delivering remote notifications, we recommend that you test your services to ensure no implementation-specific issues exist. Your apps may experience receipt verification failure if the receipt checking code makes incorrect assumptions about the certificate. Make sure that your code adheres to the Receipt Validation Programming Guide and resolve all receipt validation issues before February 14, 2016.

enter image description here

Variables as commands in bash scripts

I am not sure, but it might be worth running an eval on the commands first.

This will let bash expand the variables $TAR_CMD and such to their full breadth(just as the echo command does to the console, which you say works)

Bash will then read the line a second time with the variables expanded.

eval $TAR_CMD | $ENCRYPT_CMD | $SPLIT_CMD 

I just did a Google search and this page looks like it might do a decent job at explaining why that is needed. http://fvue.nl/wiki/Bash:_Why_use_eval_with_variable_expansion%3F

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

websocket closing connection automatically

You can actually set the timeout interval at the Jetty server side configuration using the WebSocketServletFactory instance. For example:

WebSocketHandler wsHandler = new WebSocketHandler() {
    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(1500);
        factory.register(MyWebSocketAdapter.class);
        ...
    }
}

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

After much aggravation, I discovered how to scroll in iframes on my ipad. The secret was to do a vertical finger swipe (single finger was fine) on the LEFT side of the iframe area (and maybe slightly outside of the border). On a laptop or PC, the scroll bar is on the right, so naturally, I spent of lot of time on my ipad experimenting with finger motions on the right side. Only when I tried the left side would the iframe scroll.

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

Initial size for the ArrayList

Although your arraylist has a capacity of 10, the real list has no elements here. The add method is used to insert a element to the real list. Since it has no elements, you can't insert an element to the index of 5.

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

Nesting await in Parallel.ForEach

After introducing a bunch of helper methods, you will be able run parallel queries with this simple syntax:

const int DegreeOfParallelism = 10;
IEnumerable<double> result = await Enumerable.Range(0, 1000000)
    .Split(DegreeOfParallelism)
    .SelectManyAsync(async i => await CalculateAsync(i).ConfigureAwait(false))
    .ConfigureAwait(false);

What happens here is: we split source collection into 10 chunks (.Split(DegreeOfParallelism)), then run 10 tasks each processing its items one by one (.SelectManyAsync(...)) and merge those back into a single list.

Worth mentioning there is a simpler approach:

double[] result2 = await Enumerable.Range(0, 1000000)
    .Select(async i => await CalculateAsync(i).ConfigureAwait(false))
    .WhenAll()
    .ConfigureAwait(false);

But it needs a precaution: if you have a source collection that is too big, it will schedule a Task for every item right away, which may cause significant performance hits.

Extension methods used in examples above look as follows:

public static class CollectionExtensions
{
    /// <summary>
    /// Splits collection into number of collections of nearly equal size.
    /// </summary>
    public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, int slicesCount)
    {
        if (slicesCount <= 0) throw new ArgumentOutOfRangeException(nameof(slicesCount));

        List<T> source = src.ToList();
        var sourceIndex = 0;
        for (var targetIndex = 0; targetIndex < slicesCount; targetIndex++)
        {
            var list = new List<T>();
            int itemsLeft = source.Count - targetIndex;
            while (slicesCount * list.Count < itemsLeft)
            {
                list.Add(source[sourceIndex++]);
            }

            yield return list;
        }
    }

    /// <summary>
    /// Takes collection of collections, projects those in parallel and merges results.
    /// </summary>
    public static async Task<IEnumerable<TResult>> SelectManyAsync<T, TResult>(
        this IEnumerable<IEnumerable<T>> source,
        Func<T, Task<TResult>> func)
    {
        List<TResult>[] slices = await source
            .Select(async slice => await slice.SelectListAsync(func).ConfigureAwait(false))
            .WhenAll()
            .ConfigureAwait(false);
        return slices.SelectMany(s => s);
    }

    /// <summary>Runs selector and awaits results.</summary>
    public static async Task<List<TResult>> SelectListAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector)
    {
        List<TResult> result = new List<TResult>();
        foreach (TSource source1 in source)
        {
            TResult result1 = await selector(source1).ConfigureAwait(false);
            result.Add(result1);
        }
        return result;
    }

    /// <summary>Wraps tasks with Task.WhenAll.</summary>
    public static Task<TResult[]> WhenAll<TResult>(this IEnumerable<Task<TResult>> source)
    {
        return Task.WhenAll<TResult>(source);
    }
}

Bootstrap col-md-offset-* not working

Kindly use offset-md-4 instead of col-md-offset-4 in bootstrap 4. It's little changes adopted in bootstrap 4.

For more info

python request with authentication (access_token)

>>> import requests
>>> response = requests.get('https://website.com/id', headers={'Authorization': 'access_token myToken'})

If the above doesnt work , try this:

>>> import requests
>>> response = requests.get('https://api.buildkite.com/v2/organizations/orgName/pipelines/pipelineName/builds/1230', headers={ 'Authorization': 'Bearer <your_token>' })
>>> print response.json()

Concat scripts in order with Gulp

In my gulp setup, I'm specifying the vendor files first and then specifying the (more general) everything, second. And it successfully puts the vendor js before the other custom stuff.

gulp.src([
  // vendor folder first
  path.join(folder, '/vendor/**/*.js'),
  // custom js after vendor
  path.join(folder, '/**/*.js')
])    

HTTP test server accepting GET/POST requests

You can run the actual Ken Reitz's httpbin server locally (under docker or on bare metal):

https://github.com/postmanlabs/httpbin

Run dockerized

docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin

Run directly on your machine

## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml

## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent

Now you have your personal httpbin instance running on http://0.0.0.0:8000 (visible to all of your LAN)

Can't install Scipy through pip

Microsoft Windows users of 64 bit Python installations will need to download the 64 bit .whl of Scipy from here, then simply cd into the folder you've downloaded the .whl file and run:

pip install scipy-0.16.1-cp27-none-win_amd64.whl

How can I tell AngularJS to "refresh"

Use

$route.reload();

remember to inject $route to your controller.

Meaning of "[: too many arguments" error from if [] (square brackets)

Just bumped into this post, by getting the same error, trying to test if two variables are both empty (or non-empty). That turns out to be a compound comparison - 7.3. Other Comparison Operators - Advanced Bash-Scripting Guide; and I thought I should note the following:

  • I used -e thinking it means "empty" at first; but that means "file exists" - use -z for testing empty variable (string)
  • String variables need to be quoted
  • For compound logical AND comparison, either:
    • use two tests and && them: [ ... ] && [ ... ]
    • or use the -a operator in a single test: [ ... -a ... ]

Here is a working command (searching through all txt files in a directory, and dumping those that grep finds contain both of two words):

find /usr/share/doc -name '*.txt' | while read file; do \
  a1=$(grep -H "description" $file); \
  a2=$(grep -H "changes" $file); \
  [ ! -z "$a1" -a ! -z "$a2"  ] && echo -e "$a1 \n $a2" ; \
done

Edit 12 Aug 2013: related problem note:

Note that when checking string equality with classic test (single square bracket [), you MUST have a space between the "is equal" operator, which in this case is a single "equals" = sign (although two equals' signs == seem to be accepted as equality operator too). Thus, this fails (silently):

$ if [ "1"=="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi 
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi 
A

... but add the space - and all looks good:

$ if [ "1" = "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi 
B

Run Jquery function on window events: load, resize, and scroll?

You can use the following. They all wrap the window object into a jQuery object.

Load:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});

How to get a view table query (code) in SQL Server 2008 Management Studio

In Management Studio, open the Object Explorer.

  • Go to your database
  • There's a subnode Views
  • Find your view
  • Choose Script view as > Create To > New query window

and you're done!

enter image description here

If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:

SELECT  
    m.definition    
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'

Wait 5 seconds before executing next line

Use a delay function like this:

var delay = ( function() {
    var timer = 0;
    return function(callback, ms) {
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

Usage:

delay(function(){
    // do stuff
}, 5000 ); // end delay

Credits: How to delay the .keyup() handler until the user stops typing?

Python: Is there an equivalent of mid, right, and left from BASIC?

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True

Make the current Git branch a master branch

To add to Jefromi's answer, if you don't want to place a meaningless merge in the history of the source branch, you can create a temporary branch for the ours merge, then throw it away:

git checkout <source>
git checkout -b temp            # temporary branch for merge
git merge -s ours <target>      # create merge commit with contents of <source>
git checkout <target>           # fast forward <target> to merge commit
git merge temp                  # ...
git branch -d temp              # throw temporary branch away

That way the merge commit will only exist in the history of the target branch.

Alternatively, if you don't want to create a merge at all, you can simply grab the contents of source and use them for a new commit on target:

git checkout <source>                          # fill index with contents of <source>
git symbolic-ref HEAD <target>                 # tell git we're committing on <target>
git commit -m "Setting contents to <source>"   # make an ordinary commit with the contents of <source>

How to check all checkboxes using jQuery?

Usually you also want the master checkbox to be unchecked if at least 1 slave checkbox is unchecked and to be ckecked if all slave checkboxes are checked:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAll(masterId, slaveName) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

And if you want to enable any control (e.g. Remove All button or a Add Something button), when at least one checkbox is checked and disable when no checkbox is checked:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes,
 * enables or disables a control when a checkbox is checked
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAllAndSwitchControl(masterId, slaveName, controlId) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        switchControl(controlId, $slave.filter(':checked').length > 0);
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

/**
 * Enables or disables a control
 * @param controlId is the control-id
 * @param enable is true, if control must be enabled, or false if not
 */
function switchControl(controlId, enable) {
    var $control = $('#' + controlId);
    if (enable) {
        $control.removeProp('disabled');
    } else {
        $control.prop('disabled', 'disabled');
    }
}

How to read one single line of csv data in Python?

From the Python documentation:

And while the module doesn’t directly support parsing strings, it can easily be done:

import csv
for row in csv.reader(['one,two,three']):
    print row

Just drop your string data into a singleton list.

How do I use a custom Serializer with Jackson?

The problem in your case is the ItemSerializer is missing the method handledType() which needs to be overridden from JsonSerializer

    public class ItemSerializer extends JsonSerializer<Item> {

    @Override
    public void serialize(Item value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeNumberField("itemNr", value.itemNr);
        jgen.writeNumberField("createdBy", value.user.id);
        jgen.writeEndObject();
    }

   @Override
   public Class<Item> handledType()
   {
    return Item.class;
   }
}

Hence you are getting the explicit error that handledType() is not defined

Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() 

Hope it helps someone. Thanks for reading my answer.

View more than one project/solution in Visual Studio

Two ways come to mind...

  1. Open another visual studio window and open the second solution in it.

  2. It would be preferable to add your existing projects to one solution, just right click and add existing project and navigate to the project file(csproj). .... e.g. C:\Users\User\Documents\Visual Studio 2012\Projects\MySqlWindowsFormsApplication1\MySql Windows Forms Project1\MySql Windows Forms Project1.csproj ....In this second way you might want to setup multiple start up projects i.e. for people with client-server apps or apps with dependencies. ....To do this Select the solution then GoTo: Project>>Properties>>Startup Project>> Select Multiple Startup projects and set actions to Start. When you debug, the selected as start will run.

  3. For interest sake you could open another multiple solution windows to view different projects at the same time. http://www.schwammysays.net/visual-studio-2012-tip-multiple-solution-explorers/

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

PHP PDO returning single row

$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );

$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];

$DBH = null;

You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.

You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.

Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.

Javascript Thousand Separator / string format

All you need to do is just really this:

123000.9123.toLocaleString()
//result will be "123,000.912"

How do I change the text of a span element using JavaScript?

Using innerHTML is SO NOT RECOMMENDED. Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.

document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!

The right way:

span = document.getElementById("myspan");
txt = document.createTextNode("your cool text");
span.appendChild(txt);

For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP

Edited nov 4th 2017:

Modified third line of code according to @mumush suggestion: "use appendChild(); instead".
Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.

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

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

Unobviously, Comodo antivirus has an "Auto-Containment" setting that can cause this exact error as well. (e.g. the user can write to a location, but the java.exe and javaw.exe processes cannot).

In this edge-case scenario, adding an exception for the process and/or folder should help.

Temporarily disabling the antivirus feature will help understand if Comodo AV is the culprit.

I post this not because I use or prefer Comodo, but because it's a tremendously unobvious symptom to an otherwise functioning Java application and can cost many hours of troubleshooting file permissions that are sane and correct, but being blocked by a 3rd-party application.

JavaScript "cannot read property "bar" of undefined

Compound checking:

   if (thing.foo && thing.foo.bar) {
      ... thing.foor.bar exists;
   }

How to suppress "unused parameter" warnings in C?

I've seen this style being used:

if (when || who || format || data || len);

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Inverse dictionary lookup in Python

No, you can not do this efficiently without looking in all the keys and checking all their values. So you will need O(n) time to do this. If you need to do a lot of such lookups you will need to do this efficiently by constructing a reversed dictionary (can be done also in O(n)) and then making a search inside of this reversed dictionary (each search will take on average O(1)).

Here is an example of how to construct a reversed dictionary (which will be able to do one to many mapping) from a normal dictionary:

for i in h_normal:
    for j in h_normal[i]:
        if j not in h_reversed:
            h_reversed[j] = set([i])
        else:
            h_reversed[j].add(i)

For example if your

h_normal = {
  1: set([3]), 
  2: set([5, 7]), 
  3: set([]), 
  4: set([7]), 
  5: set([1, 4]), 
  6: set([1, 7]), 
  7: set([1]), 
  8: set([2, 5, 6])
}

your h_reversed will be

{
  1: set([5, 6, 7]),
  2: set([8]), 
  3: set([1]), 
  4: set([5]), 
  5: set([8, 2]), 
  6: set([8]), 
  7: set([2, 4, 6])
}

What's the best way to trim std::string?

http://ideone.com/nFVtEo

std::string trim(const std::string &s)
{
    std::string::const_iterator it = s.begin();
    while (it != s.end() && isspace(*it))
        it++;

    std::string::const_reverse_iterator rit = s.rbegin();
    while (rit.base() != it && isspace(*rit))
        rit++;

    return std::string(it, rit.base());
}

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

How to stop a vb script running in windows

Create a Name.bat file that has the following line in it.

taskkill /F /IM wscript.exe /T

Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.

Keyboard shortcut to clear cell output in Jupyter notebook

Just adding in for JupyterLab users. Ctrl, (advanced settings) and pasting the below in User References under keyboard shortcuts does the trick for me.

{
"shortcuts": [
        {
            "command": "notebook:hide-cell-outputs",
            "keys": [
                "H"
            ],
            "selector": ".jp-Notebook:focus"
        },
        {
            "command": "notebook:show-cell-outputs",
            "keys": [
                "Shift H"
            ],
            "selector": ".jp-Notebook:focus"
        }
    ]
}

What does git rev-parse do?

git rev-parse Also works for getting the current branch name using the --abbrev-ref flag like:

git rev-parse --abbrev-ref HEAD

UIButton title text color

In Swift:

Changing the label text color is quite different than changing it for a UIButton. To change the text color for a UIButton use this method:

self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)

Stop form refreshing page on submit

The best solution is onsubmit call any function whatever you want and return false after it.

onsubmit="xxx_xxx(); return false;"

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

In chrome to set the value you need to do YYYY-MM-DD i guess because this worked : http://jsfiddle.net/HudMe/6/

So to make it work you need to set the date as 2012-10-01

c++ array - expression must have a constant value

You can use #define as an alternative solution, which do not introduce vector and malloc, and you are still using the same syntax when defining an array.

#define row 8
#define col 8

int main()
{
int array_name[row][col];
}

Calculate percentage saved between two numbers?

The formula would be (original - discounted)/original. i.e. (365-165)/365 = 0.5479...

Get Value of a Edit Text field

Try this code

final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) 
    {
        String string = editText.getText().toString();
        Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
    }
});

How to display the string html contents into webbrowser control?

For some reason the code supplied by m3z (with the DisplayHtml(string) method) is not working in my case (except first time). I'm always displaying html from string. Here is my version after the battle with the WebBrowser control:

webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
    Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);

Working every time for me. I hope it helps someone.

Ant build failed: "Target "build..xml" does not exist"

Is this a problem Only when you run ant -d or ant -verbose, but works other times?

I noticed this error message line:

Could not load definitions from resource org/apache/tools/ant/antlib.xml. It could not be found.

The org/apache/tools/ant/antlib.xml file is embedded in the ant.jar. The ant command is really a shell script called ant or a batch script called ant.bat. If the environment variable ANT_HOME is not set, it will figure out where it's located by looking to see where the ant command itself is located.

Sometimes I've seen this where someone will move the ant shell/batch script to put it in their path, and have ANT_HOME either not set, or set incorrectly.

What platform are you on? Is this Windows or Unix/Linux/MacOS? If you're on Windows, check to see if %ANT_HOME% is set. If it is, make sure it's the right directory. Make sure you have set your PATH to include %ANT_HOME%/bin.

If you're on Unix, don't copy the ant shell script to an executable directory. Instead, make a symbolic link. I have a directory called /usr/local/bin where I put the command I want to override the commands in /bin and /usr/bin. My Ant is installed in /opt/ant-1.9.2, and I have a symbolic link from /opt/ant-1.9.2 to /opt/ant. Then, I have symbolic links from all commands in /opt/ant/bin to /usr/local/bin. The Ant shell script can detect the symbolic links and find the correct Ant HOME location.

Next, go to your Ant installation directory and look under the lib directory to make sure ant.jar is there, and that it contains org/apache/tools/ant/antlib.xml. You can use the jar tvf ant.jar command. The only thing I can emphasize is that you do have everything setup correctly. You have your Ant shell script in your PATH either because you included the bin directory of your Ant's HOME directory in your classpath, or (if you're on Unix/Linux/MacOS), you have that file symbolically linked to a directory in your PATH.

Make sure your JAVA_HOME is set correctly (on Unix, you can use the symbolic link trick to have the java command set it for you), and that you're using Java 1.5 or higher. Java 1.4 will no longer work with newer versions of Ant.

Also run ant -version and see what you get. You might get the same error as before which leads me to think you have something wrong.

Let me know what you find, and your OS, and I can give you directions on reinstalling Ant.

Can a CSV file have a comment?

In engineering data, it is common to see the # symbol in the first column used to signal a comment.

I use the ostermiller CSV parsing library for Java to read and process such files. That library allows you to set the comment character. After the parse operation you get an array just containing the real data, no comments.

"google is not defined" when using Google Maps V3 in Firefox remotely

In my case I was loading the google script via http while my server had SSL and its being loaded over https. So I had to load script via https

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

How do I initialize a TypeScript Object with a JSON-Object?

My approach is slightly different. I do not copy properties into new instances, I just change the prototype of existing POJOs (may not work well on older browsers). Each class is responsible for providing a SetPrototypes method to set the prototoypes of any child objects, which in turn provide their own SetPrototypes methods.

(I also use a _Type property to get the class name of unknown objects but that can be ignored here)

class ParentClass
{
    public ID?: Guid;
    public Child?: ChildClass;
    public ListOfChildren?: ChildClass[];

    /**
     * Set the prototypes of all objects in the graph.
     * Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
     * @param pojo Plain object received from API/JSON to be given the class prototype.
     */
    private static SetPrototypes(pojo: ParentClass): void
    {
        ObjectUtils.SetPrototypeOf(pojo.Child, ChildClass);
        ObjectUtils.SetPrototypeOfAll(pojo.ListOfChildren, ChildClass);
    }
}

class ChildClass
{
    public ID?: Guid;
    public GrandChild?: GrandChildClass;

    /**
     * Set the prototypes of all objects in the graph.
     * Used for recursive prototype assignment on a graph via ObjectUtils.SetPrototypeOf.
     * @param pojo Plain object received from API/JSON to be given the class prototype.
     */
    private static SetPrototypes(pojo: ChildClass): void
    {
        ObjectUtils.SetPrototypeOf(pojo.GrandChild, GrandChildClass);
    }
}

Here is ObjectUtils.ts:

/**
 * ClassType lets us specify arguments as class variables.
 * (where ClassType == window[ClassName])
 */
type ClassType = { new(...args: any[]): any; };

/**
 * The name of a class as opposed to the class itself.
 * (where ClassType == window[ClassName])
 */
type ClassName = string & {};

abstract class ObjectUtils
{
/**
 * Set the prototype of an object to the specified class.
 *
 * Does nothing if source or type are null.
 * Throws an exception if type is not a known class type.
 *
 * If type has the SetPrototypes method then that is called on the source
 * to perform recursive prototype assignment on an object graph.
 *
 * SetPrototypes is declared private on types because it should only be called
 * by this method. It does not (and must not) set the prototype of the object
 * itself - only the protoypes of child properties, otherwise it would cause a
 * loop. Thus a public method would be misleading and not useful on its own.
 * 
 * https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript
 */
public static SetPrototypeOf(source: any, type: ClassType | ClassName): any
{
    let classType = (typeof type === "string") ? window[type] : type;

    if (!source || !classType)
    {
        return source;
    }

    // Guard/contract utility
    ExGuard.IsValid(classType.prototype, "type", <any>type);

    if ((<any>Object).setPrototypeOf)
    {
        (<any>Object).setPrototypeOf(source, classType.prototype);
    }
    else if (source.__proto__)
    {
        source.__proto__ = classType.prototype.__proto__;
    }

    if (typeof classType["SetPrototypes"] === "function")
    {
        classType["SetPrototypes"](source);
    }

    return source;
}

/**
 * Set the prototype of a list of objects to the specified class.
 * 
 * Throws an exception if type is not a known class type.
 */
public static SetPrototypeOfAll(source: any[], type: ClassType): void
{
    if (!source)
    {
        return;
    }

    for (var i = 0; i < source.length; i++)
    {
        this.SetPrototypeOf(source[i], type);
    }
}
}

Usage:

let pojo = SomePlainOldJavascriptObjectReceivedViaAjax;

let parentObject = ObjectUtils.SetPrototypeOf(pojo, ParentClass);

// parentObject is now a proper ParentClass instance

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

how to update spyder on anaconda

Use this conda install spyder=4.0.0 This will not mess up your anaconda dependencies. https://github.com/spyder-ide/spyder/releases

How to select and change value of table cell with jQuery?

I wanted to change the column value in a specific row. Thanks to above answers and after some serching able to come up with below,

var dataTable = $("#yourtableid");
var rowNumber = 0;  
var columnNumber= 2;   
dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

jquery json to string?

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

What is the Difference Between Mercurial and Git?

If you are a Windows developer looking for basic disconnected revision control, go with Hg. I found Git to be incomprehensible while Hg was simple and well integrated with the Windows shell. I downloaded Hg and followed this tutorial (hginit.com) - ten minutes later I had a local repo and was back to work on my project.

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

How to inspect Javascript Objects

Here is my object inspector that is more readable. Because the code takes to long to write down here you can download it at http://etto-aa-js.googlecode.com/svn/trunk/inspector.js

Use like this :

document.write(inspect(object));

How to list all installed packages and their versions in Python?

Here's a way to do it using PYTHONPATH instead of the absolute path of your python libs dir:

for d in `echo "${PYTHONPATH}" | tr ':' '\n'`; do ls "${d}"; done

[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' '\n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig          python2.7
BaseHTTPServer.py      _pyio.pyc              cgitb.pyo              doctest.pyo            htmlentitydefs.pyc     mimetools.pyc          plat-mac               runpy.py               stringold.pyc          traceback.pyo
BaseHTTPServer.pyc     _pyio.pyo              chunk.py               dumbdbm.py             htmlentitydefs.pyo     mimetools.pyo          platform.py            runpy.pyc              stringold.pyo          tty.py
BaseHTTPServer.pyo     _strptime.py           chunk.pyc              dumbdbm.pyc            htmllib.py             mimetypes.py           platform.pyc           runpy.pyo              stringprep.py          tty.pyc
Bastion.py             _strptime.pyc          chunk.pyo              dumbdbm.pyo            htmllib.pyc            mimetypes.pyc          platform.pyo           sched.py               stringprep.pyc         tty.pyo
Bastion.pyc            _strptime.pyo          cmd.py
....

Commenting out a set of lines in a shell script

Depending of the editor that you're using there are some shortcuts to comment a block of lines.

Another workaround would be to put your code in an "if (0)" conditional block ;)

What is getattr() exactly and how do I use it?

Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr().

import os

class Log(object):
    def __init__(self):
        self.os = os.name
    def __getattr__(self, name):
        """ look for a 'save' attribute, or just 
          return whatever attribute was specified """
        if name == 'save':
            try:
                # try to dynamically return a save 
                # method appropriate for the user's system
                return getattr(self, self.os)
            except:
                # bail and try to return 
                # a default save method
                return getattr(self, '_save')
        else:
            return getattr(self, name)

    # each of these methods could have save logic specific to 
    # the system on which the script is executed
    def posix(self): print 'saving on a posix machine'
    def nt(self): print 'saving on an nt machine'
    def os2(self): print 'saving on an os2 machine'
    def ce(self): print 'saving on a ce machine'
    def java(self): print 'saving on a java machine'
    def riscos(self): print 'saving on a riscos machine'
    def _save(self): print 'saving on an unknown operating system'

    def which_os(self): print os.name

Now let's use this class in an example:

logger = Log()

# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along 
# somewhere else as 1st class:
save_func()

# or you can just call it directly:
logger.save()

# other attributes will hit the else 
# statement and still work as expected
logger.which_os()

How to display errors on laravel 4?

In the Laravel root folder chmod the storage directory to 777

Batch File: ( was unexpected at this time

you need double quotes in all your three if statements, eg.:

IF "%a%"=="2" (

@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.


set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection
    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if "!param1!"=="" goto :param1Prompt

    if "!param1!"=="1" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
         USB Write is Locked!
    )
    if "!param1!"=="2" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
         USB Write is Unlocked!
    )
)
pause

Edit a specific Line of a Text File in C#

I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps

using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
        {
            var destinationReader = StreamReader(fs);
            var writer = StreamWriter(fs);
            while ((line = reader.ReadLine()) != null)
            {
              if (line_number == line_to_edit)
                {
                    writer.WriteLine(lineToWrite);
                }
                else
                {
                    destinationReader .ReadLine();
                }
                line_number++;
            }
        }

Install numpy on python3.3 - Install pip for python3

From the terminal run:

  sudo apt-get install python3-numpy

This package contains Numpy for Python 3.

For scipy:

 sudo apt-get install python3-scipy

For for plotting graphs use pylab:

 sudo apt-get install python3-matplotlib

Single TextView with multiple colored text

Use SpannableStringBuilder

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

How can I run a PHP script in the background after a form is submitted?

On Linux/Unix servers, you can execute a job in the background by using proc_open:

$descriptorspec = array(
   array('pipe', 'r'),               // stdin
   array('file', 'myfile.txt', 'a'), // stdout
   array('pipe', 'w'),               // stderr
);

$proc = proc_open('php email_script.php &', $descriptorspec, $pipes);

The & being the important bit here. The script will continue even if the original script has ended.

Auto start print html page using javascript

Add the following code in your HTML page, and it will show print preview on page load.

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

<script type="text/javascript">

$(document).ready(function () {
    window.print();
});

</script>

Where does Chrome store cookies?

You can find a solution on SuperUser :

Chrome cookies folder in Windows 7:-

C:\Users\your_username\AppData\Local\Google\Chrome\User Data\Default\
You'll need a program like SQLite Database Browser to read it.

For Mac OS X, the file is located at :-
~/Library/Application Support/Google/Chrome/Default/Cookies

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

IOError: [Errno 32] Broken pipe: Python

I haven't reproduced the issue, but perhaps this method would solve it: (writing line by line to stdout rather than using print)

import sys
with open('a.txt', 'r') as f1:
    for line in f1:
        sys.stdout.write(line)

You could catch the broken pipe? This writes the file to stdout line by line until the pipe is closed.

import sys, errno
try:
    with open('a.txt', 'r') as f1:
        for line in f1:
            sys.stdout.write(line)
except IOError as e:
    if e.errno == errno.EPIPE:
        # Handle error

You also need to make sure that othercommand is reading from the pipe before it gets too big - https://unix.stackexchange.com/questions/11946/how-big-is-the-pipe-buffer

In Visual Studio C++, what are the memory allocation representations?

This link has more information:

https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values

* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory

How to find prime numbers between 0 - 100?

Luchian's answer gives you a link to the standard technique for finding primes.

A less efficient, but simpler approach is to turn your existing code into a nested loop. Observe that you are dividing by 2,3,4,5,6 and so on ... and turn that into a loop.

Given that this is homework, and given that the aim of the homework is to help you learn basic programming, a solution that is simple, correct but somewhat inefficient should be fine.

How do I use JDK 7 on Mac OSX?

What worked for me on Lion was installing the JDK7_u17 from Oracle, then editing ~/.bash_profile to include: export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home

Detect if string contains any spaces

var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

Search for executable files using find command

I had the same issue, and the answer was in the dmenu source code: the stest utility made for that purpose. You can compile the 'stest.c' and 'arg.h' files and it should work. There is a man page for the usage, that I put there for convenience:

STEST(1)         General Commands Manual         STEST(1)

NAME
       stest - filter a list of files by properties

SYNOPSIS
       stest  [-abcdefghlpqrsuwx]  [-n  file]  [-o  file]
       [file...]

DESCRIPTION
       stest takes a list of files  and  filters  by  the
       files'  properties,  analogous  to test(1).  Files
       which pass all tests are printed to stdout. If  no
       files are given, stest reads files from stdin.

OPTIONS
       -a     Test hidden files.

       -b     Test that files are block specials.

       -c     Test that files are character specials.

       -d     Test that files are directories.

       -e     Test that files exist.

       -f     Test that files are regular files.

       -g     Test  that  files  have  their set-group-ID
              flag set.

       -h     Test that files are symbolic links.

       -l     Test the contents of a directory  given  as
              an argument.

       -n file
              Test that files are newer than file.

       -o file
              Test that files are older than file.

       -p     Test that files are named pipes.

       -q     No  files are printed, only the exit status
              is returned.

       -r     Test that files are readable.

       -s     Test that files are not empty.

       -u     Test that files have their set-user-ID flag
              set.

       -v     Invert  the  sense  of  tests, only failing
              files pass.

       -w     Test that files are writable.

       -x     Test that files are executable.

EXIT STATUS
       0      At least one file passed all tests.

       1      No files passed all tests.

       2      An error occurred.

SEE ALSO
       dmenu(1), test(1)

                        dmenu-4.6                STEST(1)

Deny access to one specific folder in .htaccess

Creating index.php, index.html, index.htm is not secure. Becuse, anyone can get access on your files within specified directory by guessing files name. E.g.: http://yoursite.com/includes/file.dat So, recommended method is creating a .htaccess file to deny all visitors ;). Have fun !!

Android Studio-No Module

I had the same issue since I changed my app ID in config.xml file.

I used to open my Android project by choosing among recent projects of Android Studio.

I just File > Open > My project to get it working again.

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

How to Parse a JSON Object In Android

JSONArray jsonArray = new JSONArray(yourJsonString);

for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject obj1 = jsonArray.getJSONObject(i);
     JSONArray results = patient.getJSONArray("results");
     String indexForPhone =  patientProfile.getJSONObject(0).getString("indexForPhone"));
}

Change to JSONArray, then convert to JSONObject.

How to check the Angular version?

First install the Angular/cli globally in machine. to install the angular/cli run the command npm install -g @angular/cli

Above Angular7 , use these two commands enter image description hereto know the version of Angular/Cli 1. ng --version, 2.ng version

Changing plot scale by a factor in matplotlib

As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

A complete example showing both x and y scaling:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

And finally I have the credits for a picture:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

onMeasure custom view explanation

If you don't need to change something onMeasure - there's absolutely no need for you to override it.

Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).

You can check the onMeasure method here :

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
    case MeasureSpec.UNSPECIFIED:
        result = size;
        break;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
}

Overriding SDK code to be replaced with the exact same code makes no sense.

This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.

Browser Timeouts

It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

Firefox is around the same value I think as well.

Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

Error while sending QUERY packet

You cannot have the WHERE clause in an INSERT statement.

insert into table1(data) VALUES(:data) where sno ='45830'

Should be

insert into table1(data) VALUES(:data)


Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:

SET GLOBAL max_allowed_packet=32M

Change the 32M (32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.

git diff between two different files

I believe using --no-index is what you're looking for:

git diff [<options>] --no-index [--] <path> <path>

as mentioned in the git manual:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

What is the meaning of "Failed building wheel for X" in pip install?

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the "Failed building wheel for pycparser" message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we'll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you'd have wheel installed in those environments by default. :)

fatal error: mpi.h: No such file or directory #include <mpi.h>

As suggested above the inclusion of

/usr/lib/openmpi/include 

in the include path takes care of this (in my case)

Maven dependency for Servlet 3.0 API?

The Apache Geronimo project provides a Servlet 3.0 API dependency on the Maven Central repo:

<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-servlet_3.0_spec</artifactId>
    <version>1.0</version>
</dependency>

Could not load NIB in bundle

This is worked for me.. Make sure you typed nib name correctly.

[[NSBundle mainBundle]loadNibNamed:@"Graphview" owner:self options:nil];

Graphview(nib name)

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

Printing with sed or awk a line following a matching pattern

Actually sed -n '/pattern/{n;p}' filename will fail if the pattern match continuous lines:

$ seq 15 |sed -n '/1/{n;p}'
2
11
13
15

The expected answers should be:

2
11
12
13
14
15

My solution is:

$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename

For example:

$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'
2
11
12
13
14
15

Explains:

  1. x;: at the beginning of each line from input, use x command to exchange the contents in pattern space & hold space.
  2. /_/{x;p;x};: if pattern space, which is the hold space actually, contains _ (this is just a indicator indicating if last line matched the pattern or not), then use x to exchange the actual content of current line to pattern space, use p to print current line, and x to recover this operation.
  3. x: recover the contents in pattern space and hold space.
  4. /pattern/!s/.*//: if current line does NOT match pattern, which means we should NOT print the NEXT following line, then use s/.*// command to delete all contents in pattern space.
  5. /pattern/s/.*/_/: if current line matches pattern, which means we should print the NEXT following line, then we need to set a indicator to tell sed to print NEXT line, so use s/.*/_/ to substitute all contents in pattern space to a _(the second command will use it to judge if last line matched the pattern or not).
  6. h: overwrite the hold space with the contents in pattern space; then, the content in hold space is ^_$ which means current line matches the pattern, or ^$, which means current line does NOT match the pattern.
  7. the fifth step and sixth step can NOT exchange, because after s/.*/_/, the pattern space can NOT match /pattern/, so the s/.*// MUST be executed!

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

How to save an image locally using Python whose URL address I already know?

This can be done with requests. Load the page and dump the binary content to a file.

import os
import requests

url = 'https://apod.nasa.gov/apod/image/1701/potw1636aN159_HST_2048.jpg'
page = requests.get(url)

f_ext = os.path.splitext(url)[-1]
f_name = 'img{}'.format(f_ext)
with open(f_name, 'wb') as f:
    f.write(page.content)

extract the date part from DateTime in C#

When comparing only the date of the datatimes, use the Date property. So this should work fine for you

datetime1.Date == datetime2.Date

How to check if text fields are empty on form submit using jQuery?

function isEmpty(val) {
if(val.length ==0 || val.length ==null){
    return 'emptyForm';
}else{
    return 'not emptyForm';
}

}

$(document).ready(function(){enter code here
    $( "form" ).submit(function( event ) {
        $('input').each(function(){
           var getInputVal = $(this).val();
            if(isEmpty(getInputVal) =='emptyForm'){
                alert(isEmpty(getInputVal));
            }else{
                alert(isEmpty(getInputVal));
            }
        });
        event.preventDefault();
    });
});

How to set timeout on python's socket recv method?

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely. select() can also be used to wait on more than one socket at a time.

import select

mysocket.setblocking(0)

ready = select.select([mysocket], [], [], timeout_in_seconds)
if ready[0]:
    data = mysocket.recv(4096)

If you have a lot of open file descriptors, poll() is a more efficient alternative to select().

Another option is to set a timeout for all operations on the socket using socket.settimeout(), but I see that you've explicitly rejected that solution in another answer.

How can I force clients to refresh JavaScript files?

Appending the current time to the URL is indeed a common solution. However, you can also manage this at the web server level, if you want to. The server can be configured to send different HTTP headers for javascript files.

For example, to force the file to be cached for no longer than 1 day, you would send:

Cache-Control: max-age=86400, must-revalidate

For beta, if you want to force the user to always get the latest, you would use:

Cache-Control: no-cache, must-revalidate

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

How do I disable the security certificate check in Python requests

If you are writing a scraper and really don't care about the SSL certificate you can set it global:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

DO NOT USE IN PRODUCTION

Why doesn't git recognize that my file has been changed, therefore git add not working

Make sure not to create symlinks (ln -s source dest) from inside of Git Bash for Windows.

It does NOT make symlinks, but does a DEEP copy of the source to the dest

I experienced same behavior as OP on a MINGW64 terminal from Git Bash for Windows (version 2.16.2) to realize that my 'edited' changes actually were in the original directory, and my git bash commands were from within a deep copy that had remained unchanged.

How to automatically select all text on focus in WPF TextBox?

In App.xaml file:

<Application.Resources>
    <Style TargetType="TextBox">
        <EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
    </Style>
</Application.Resources>

In App.xaml.cs file:

private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
{
    ((TextBox)sender).SelectAll();
}

With this code you reach all TextBox in your application.

AWS ssh access 'Permission denied (publickey)' issue

Just adding to this list. I was having trouble this morning with a new user just added to an AWS EC2 instance. To cut to the chase, the problem was selinux (which was in enforcing mode), together with the fact that my user home dir was on a new EBS attached volume. Somehow I guess selinux doesn't like that other volume. Took me a while to figure out, as I looked through all the other usual ssh issues (/etc/ssh/sshd_config was fine, of course no password allowed, permissions were right, etc.)

The fix?

For now (until I understand how to allow a user to ssh to a different volume, or somehow make that volume a bona fide home dir point):

sudo perl -pi -e 's/^SELINUX=enforcing/SELINUX=permissive/' /etc/selinux/config
sudo setenforce 0

That's it. Now my new user can log in, using his own id_rsa key.

Mercurial — revert back to old version and continue from there

I just encountered a case of needing to revert just one file to previous revision, right after I had done commit and push. Shorthand syntax for specifying these revisions isn't covered by the other answers, so here's command to do that

hg revert path/to/file -r-2

That -2 will revert to the version before last commit, using -1 would just revert current uncommitted changes.

Insert array into MySQL database with PHP

function insertQuery($tableName,$cols,$values,$connection){
  $numberOfColsAndValues = count($cols);
  $query = 'INSERT INTO '.$tableName.' ('.getColNames($cols,$numberOfColsAndValues).') VALUES ('.getColValues($values,$numberOfColsAndValues).')';
   if(mysqli_query($connection, $query))
      return true;
   else{
      echo "Error: " . $query . "<br>" . mysqli_error($connection);
      return false;
   }
}

function getColNames($cols,$numberOfColsAndValues){
  $result = '';
  foreach($cols as $key => $val){
    $result = $result.$val.', ';
  }
    return substr($result,0,strlen($result)-2);
}


function getColValues($values,$numberOfColsAndValues){
  $result = '';
  foreach($values as $key => $val){
    $val = "'$val'";
    $result = $result.$val.', ';
  }
    return substr($result,0,strlen($result)-2);
}

JS map return object

If you want to alter the original objects, then a simple Array#forEach will do:

rockets.forEach(function(rocket) {
    rocket.launches += 10;
});

If you want to keep the original objects unaltered, then use Array#map and copy the objects using Object#assign:

var newRockets = rockets.forEach(function(rocket) {
    var newRocket = Object.assign({}, rocket);
    newRocket.launches += 10;
    return newRocket;
});

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

There is a difference between signed and unsigned APK files. Most likely you had an unsigned on there previously. You just need to delete the unsigned before you install the signed version. How this can be accomplished varies on the exact version, but in general, go on the emulator to settings-> application, long click your app, and delete/remove/uninstall it.

How to yum install Node.JS on Amazon Linux

sudo yum install nodejs npm --enablerepo=epel works for Amazon Linux AMI. curl --silent --location https://rpm.nodesource.com/setup_6.x | bash - yum -y install nodejs works for RedHat.

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

#pragma once vs include guards?

I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.

#pragma once is less prone to making mistakes and it is less code to type.

To speed up compile time more just forward declare instead of including in .h files when you can.

I prefer to use #pragma once.

See this wikipedia article about the possibility of using both.

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

How to change css property using javascript

Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.

document.getElementById("ele_id").style.color="blue";

But, for changing multiple properies the more robust way is using Object.assign() or, object spread operator {...};

See below:

const ele=document.getElementById("ele_id");
const custom_style={
    display: "block",
    color: "red"
}

//Object.assign():
Object.assign(ele.style,custum_style);

Spread operator works similarly, just the syntax is a little different.

Test if a string contains any of the strings from an array

We can also do like this:

if (string.matches("^.*?((?i)item1|item2|item3).*$"))
(?i): used for case insensitive
.*? & .*$: used for checking whether it is present anywhere in between the string.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

Node.js connect only works on localhost

I have a very simple solution for this problem: process.argv gives you a list of arguments passed to node app. So if you run:

node server.js 0.0.0.0

You'll get:

process.argv[0] //=> "node"
process.argv[1] //=> "server.js"
process.argv[2] //=> "0.0.0.0"

So you can use process.argv[2] to specify that as the IP address you want to listen to:

http.listen(3000, process.argv[2]);

Now, your app is listening to "all" IP addresses, for example http://192.168.1.4:3000/your_app.

I hope this will help someone!

Plotting histograms from grouped data in a pandas DataFrame

With recent version of Pandas, you can do df.N.hist(by=df.Letter)

Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.

Entity Framework is Too Slow. What are my options?

If you're purely fetching data, it's a big help to performance when you tell EF to not keep track of the entities it fetches. Do this by using MergeOption.NoTracking. EF will just generate the query, execute it and deserialize the results to objects, but will not attempt to keep track of entity changes or anything of that nature. If a query is simple (doesn't spend much time waiting on the database to return), I've found that setting it to NoTracking can double query performance.

See this MSDN article on the MergeOption enum:

Identity Resolution, State Management, and Change Tracking

This seems to be a good article on EF performance:

Performance and the Entity Framework

When use ResponseEntity<T> and @RestController for Spring RESTful applications

According to official documentation: Creating REST Controllers with the @RestController annotation

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

For example:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    @ResponseStatus(HttpStatus.OK)
    public User test() {
        User user = new User();
        user.setName("Name 1");

        return user;
    }

}

is the same as:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    public ResponseEntity<User> test() {
        User user = new User();
        user.setName("Name 1");

        HttpHeaders responseHeaders = new HttpHeaders();
        // ...
        return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
    }

}

This way, you can define ResponseEntity only when needed.

Update

You can use this:

    return ResponseEntity.ok().headers(responseHeaders).body(user);

Get latest from Git branch

use git pull:

git pull origin yourbranch

Last non-empty cell in a column

for textual data:

EQUIV("";A1:A10;-1)

for numerical data:

EQUIV(0;A1:A10;-1)

This give you the relative index of the last non empty cell in the range selected (here A1:A10).

If you want to get the value, access it via INDIRECT after building -textually- the absolute cell reference, eg:

INDIRECT("A" & (nb_line_where_your_data_start + EQUIV(...) - 1))

JavaScript equivalent to printf/String.Format

I use this one:

String.prototype.format = function() {
    var newStr = this, i = 0;
    while (/%s/.test(newStr))
        newStr = newStr.replace("%s", arguments[i++])

    return newStr;
}

Then I call it:

"<h1>%s</h1><p>%s</p>".format("Header", "Just a test!");

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

Memory address of an object in C#

Here's a simple way I came up with that doesn't involve unsafe code or pinning the object. Also works in reverse (object from address):

public static class AddressHelper
{
    private static object mutualObject;
    private static ObjectReinterpreter reinterpreter;

    static AddressHelper()
    {
        AddressHelper.mutualObject = new object();
        AddressHelper.reinterpreter = new ObjectReinterpreter();
        AddressHelper.reinterpreter.AsObject = new ObjectWrapper();
    }

    public static IntPtr GetAddress(object obj)
    {
        lock (AddressHelper.mutualObject)
        {
            AddressHelper.reinterpreter.AsObject.Object = obj;
            IntPtr address = AddressHelper.reinterpreter.AsIntPtr.Value;
            AddressHelper.reinterpreter.AsObject.Object = null;
            return address;
        }
    }

    public static T GetInstance<T>(IntPtr address)
    {
        lock (AddressHelper.mutualObject)
        {
            AddressHelper.reinterpreter.AsIntPtr.Value = address;
            return (T)AddressHelper.reinterpreter.AsObject.Object;
        }
    }

    // I bet you thought C# was type-safe.
    [StructLayout(LayoutKind.Explicit)]
    private struct ObjectReinterpreter
    {
        [FieldOffset(0)] public ObjectWrapper AsObject;
        [FieldOffset(0)] public IntPtrWrapper AsIntPtr;
    }

    private class ObjectWrapper
    {
        public object Object;
    }

    private class IntPtrWrapper
    {
        public IntPtr Value;
    }
}

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How to AUTO_INCREMENT in db2?

Added a few optional parameters for creating "future safe" sequences.

CREATE SEQUENCE <NAME>
  START WITH 1
  INCREMENT BY 1
  NO MAXVALUE
  NO CYCLE
  CACHE 10;

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Try putting this in your app/web.config:

<system.net>
    <settings>
        <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>

If this doesn't work you may also try setting the KeepAlive property to false.

Using Address Instead Of Longitude And Latitude With Google Maps API

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == 'OK') {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
});
}

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
 <div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">
 </div>
</body>

Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding

Disable button in WPF?

In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

<Button Command="Apply">Apply</Button>

The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

The linked article explains it in detail.

What is the difference between ndarray and array in numpy?

numpy.ndarray() is a class, while numpy.array() is a method / function to create ndarray.

In numpy docs if you want to create an array from ndarray class you can do it with 2 ways as quoted:

1- using array(), zeros() or empty() methods: Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

2- from ndarray class directly: There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

The example below gives a random array because we didn't assign buffer value:

np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None)

array([[ -1.13698227e+002,   4.25087011e-303],
       [  2.88528414e-306,   3.27025015e-309]])         #random

another example is to assign array object to the buffer example:

>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])

from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer

Conclusion: use numpy.array() if you want to make a numpy.ndarray() object"

Launch programs whose path contains spaces

set shell=CreateObject("Shell.Application")
' shell.ShellExecute "application", "arguments", "path", "verb", window
shell.ShellExecute  "slipery.bat",,"C:\Users\anthony\Desktop\dvx", "runas", 1
set shell=nothing 

ActiveRecord: size vs count

I recommended using the size function.

class Customer < ActiveRecord::Base
  has_many :customer_activities
end

class CustomerActivity < ActiveRecord::Base
  belongs_to :customer, counter_cache: true
end

Consider these two models. The customer has many customer activities.

If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

Consider one example: in my database, one customer has 20,000 customer activities and I try to count the number of records of customer activities of that customer with each of count, length and size method. here below the benchmark report of all these methods.

            user     system      total        real
Count:     0.000000   0.000000   0.000000 (  0.006105)
Size:      0.010000   0.000000   0.010000 (  0.003797)
Length:    0.030000   0.000000   0.030000 (  0.026481)

so I found that using :counter_cache Size is the best option to calculate the number of records.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

get basic SQL Server table structure information

sp_help will give you a whole bunch of information about a table including the columns, keys and constraints. For example, running

exec sp_help 'Address' 

will give you information about Address.

Finding last occurrence of substring in string, replacing that

You can use the function below which replaces the first occurrence of the word from right.

def replace_from_right(text: str, original_text: str, new_text: str) -> str:
    """ Replace first occurrence of original_text by new_text. """
    return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]

Detect if range is empty

Dim cel As Range, hasNoData As Boolean

    hasNoData = True
    For Each cel In Selection
        hasNoData = hasNoData And IsEmpty(cel)
    Next

This will return True if no cells in Selection contains any data. For a specific range, just substitute RANGE(...) for Selection.

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

How can I select random files from a directory in bash?

If you have more files in your folder, you can use the below piped command I found in unix stackexchange.

find /some/dir/ -type f -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/

Here I wanted to copy the files, but if you want to move files or do something else, just change the last command where I have used cp.

How to return a struct from a function in C++?

You have a scope problem. Define the struct before the function, not inside it.

JavaScript closures vs. anonymous functions

Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.

A simple explanation for closures:

  1. Take a function. Let's call it F.
  2. List all the variables of F.
  3. The variables may be of two types:
    1. Local variables (bound variables)
    2. Non-local variables (free variables)
  4. If F has no free variables then it cannot be a closure.
  5. If F has any free variables (which are defined in a parent scope of F) then:
    1. There must be only one parent scope of F to which a free variable is bound.
    2. If F is referenced from outside that parent scope, then it becomes a closure for that free variable.
    3. That free variable is called an upvalue of the closure F.

Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):

Case 1: Your Friend's Program

for (var i = 0; i < 10; i++) {
    (function f() {
        var i2 = i;
        setTimeout(function g() {
            console.log(i2);
        }, 1000);
    })();
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. i is a free variable.
    3. setTimeout is a free variable.
    4. g is a local variable.
    5. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. i is bound to the global scope.
    2. setTimeout is bound to the global scope.
    3. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence i is not closed over by f.
    2. Hence setTimeout is not closed over by f.
    3. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Bad for you: Your friend is using a closure. The inner function is a closure.

Case 2: Your Program

for (var i = 0; i < 10; i++) {
    setTimeout((function f(i2) {
        return function g() {
            console.log(i2);
        };
    })(i), 1000);
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. g is a local variable.
    3. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Good for you: You are using a closure. The inner function is a closure.

So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.

Edit: A simple explanation as to why are all functions closures (credits @Peter):

First let's consider the following program (it's the control):

_x000D_
_x000D_
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
    regularFunction();_x000D_
_x000D_
    function regularFunction() {_x000D_
        alert(eval("message"));_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that both lexicalScope and regularFunction aren't closures from the above definition.
  2. When we execute the program we expect message to be alerted because regularFunction is not a closure (i.e. it has access to all the variables in its parent scope - including message).
  3. When we execute the program we observe that message is indeed alerted.

Next let's consider the following program (it's the alternative):

_x000D_
_x000D_
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
    return function closureFunction() {_x000D_
        alert(eval("message"));_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that only closureFunction is a closure from the above definition.
  2. When we execute the program we expect message not to be alerted because closureFunction is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message).
  3. When we execute the program we observe that message is actually being alerted.

What do we infer from this?

  1. JavaScript interpreters do not treat closures differently from the way they treat other functions.
  2. Every function carries its scope chain along with it. Closures don't have a separate referencing environment.
  3. A closure is just like every other function. We just call them closures when they are referenced in a scope outside the scope to which they belong because this is an interesting case.

How to quickly check if folder is empty (.NET)?

Thanks, everybody, for replies. I tried to use Directory.GetFiles() and Directory.GetDirectories() methods. Good news! The performance improved ~twice! 229 calls in 221ms. But also I hope, that it is possible to avoid enumeration of all items in the folder. Agree, that still the unnecessary job is executing. Don't you think so?

After all investigations, I reached a conclusion, that under pure .NET further optimiation is impossible. I am going to play with WinAPI's FindFirstFile function. Hope it will help.

Specifying ssh key in ansible playbook file

The variable name you're looking for is ansible_ssh_private_key_file.

You should set it at 'vars' level:

  • in the inventory file:

    myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
    myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
    
  • in the host_vars:

    # hosts_vars/myHost.yml
    ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
    
    # hosts_vars/myOtherHost.yml
    ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
    
  • in a group_vars file if you use the same key for a group of hosts

  • in the vars section of your play:

    - hosts: myHost
      remote_user: ubuntu
      vars_files:
        - vars.yml
      vars:
        ansible_ssh_private_key_file: "{{ key1 }}"
      tasks:
        - name: Echo a hello message
          command: echo hello
    

Inventory documentation

Where can I find MySQL logs in phpMyAdmin?

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

How do I keep Python print from adding newlines or spaces?

import sys

sys.stdout.write('h')
sys.stdout.flush()

sys.stdout.write('m')
sys.stdout.flush()

You need to call sys.stdout.flush() because otherwise it will hold the text in a buffer and you won't see it.

Angular2 RC6: '<component> is not a known element'

I had the same issue with angular RC.6 for some reason it doesn't allow passing component to other component using directives as component decorator to the parent component

But it if you import the child component via app module and add it in the declaration array the error goes away. There are no much explanation to why this is an issue with angular rc.6

Get timezone from DateTime

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means.

DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset.

The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.

EDIT: Nearly four years later, I'd now suggest using Noda Time which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)