Programs & Examples On #Gpsignaturefile

Display string as html in asp.net mvc view

I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.

I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.

So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.

I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

How to solve SyntaxError on autogenerated manage.py?

We have to create a virtual environment inside the project, not outside the project.. Then it will solve..

How to use Git for Unity3D source control?

Just adding in on the subjet of Gitignore. The recommended way only ignores Library and Temp, if its wihtin root of your git project. if you are like me and sometimes need unity project to be a part of the repo, not the whole of the repo, the correct strings in gitignore would be:

**/[Tt]emp
**/[Ll]ibrary
**/[Bb]uild

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

How to close Android application?

This is the way I did it:

I just put

Intent intent = new Intent(Main.this, SOMECLASSNAME.class);
Main.this.startActivityForResult(intent, 0);

inside of the method that opens an activity, then inside of the method of SOMECLASSNAME that is designed to close the app I put:

setResult(0);
finish();

And I put the following in my Main class:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == 0) {
        finish();
    }
}

Make javascript alert Yes/No Instead of Ok/Cancel

I shall try the solution with jQuery, for sure it should give a nice result. Of course you have to load jQuery ... What about a pop-up with something like this? Of course this is dependant on the user authorizing pop-ups.

<html>
    <head>
    <script language="javascript">
    var ret;
    function returnfunction()
    {
        alert(ret);
    }
    </script>
</head>
    <body>
        <form>
            <label id="QuestionToAsk" name="QuestionToAsk">Here is talked.</label><br />
            <input type="button" value="Yes" name="yes" onClick="ret=true;returnfunction()" />
            <input type="button" value="No" onClick="ret=false;returnfunction()" />
        </form>
    </body>
</html>

PHP string concatenation

$personCount=1;
while ($personCount < 10) {
    $result=0;
    $result.= $personCount . "person ";
    $personCount++;
    echo $result;
}

Mockito : how to verify method was called on an object created within a method?

Yes, if you really want / need to do it you can use PowerMock. This should be considered a last resort. With PowerMock you can cause it to return a mock from the call to the constructor. Then do the verify on the mock. That said, csturtz's is the "right" answer.

Here is the link to Mock construction of new objects

ANTLR: Is there a simple example?

version 4.7.1 was slightly different : for import:

import org.antlr.v4.runtime.*;

for the main segment - note the CharStreams:

CharStream in = CharStreams.fromString("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);

AND/OR in Python?

As Matt Ball's answer explains, or is "and/or". But or doesn't work with in the way you use it above. You have to say if "a" in someList or "á" in someList or.... Or better yet,

if any(c in someList for c in ("a", "á", "à", "ã", "â")):
    ...

That's the answer to your question as asked.

Other Notes

However, there are a few more things to say about the example code you've posted. First, the chain of someList.remove... or someList remove... statements here is unnecessary, and may result in unexpected behavior. It's also hard to read! Better to break it into individual lines:

someList.remove("a")
someList.remove("á")
...

Even that's not enough, however. As you observed, if the item isn't in the list, then an error is thrown. On top of that, using remove is very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.

Instead, I would suggest a very different approach. Filter the list using a set, like so:

chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]

Or, change the list in-place without creating a copy:

someList[:] = (c for c in someList if c not in chars_to_remove)

These both use list comprehension syntax to create a new list. They look at every character in someList, check to see of the character is in chars_to_remove, and if it is not, they include the character in the new list.

This is the most efficient version of this code. It has two speed advantages:

  1. It only passes through someList once. Instead of performing 1000 tests, in the above scenario, it performs only 100.
  2. It can test all characters with a single operation, because chars_to_remove is a set. If it chars_to_remove were a list or tuple, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.

Global npm install location on windows?

According to: https://docs.npmjs.com/files/folders

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.

prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary.

The docs might be a little outdated, but they explain why global installs can end up in different directories:

(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"

Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.

This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):

mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm

open a new cmd.exe window and reinstall all global packages.

Explanation (by lineno.):

  1. Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn't write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
  2. The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
  3. Tell npm to use this new path. (Note: folder isn't visible in %PATH% in this shell, so you must open a new window).

How to write URLs in Latex?

Here is all the information you need in order to format clickable hyperlinks in LaTeX:

http://en.wikibooks.org/wiki/LaTeX/Hyperlinks

Essentially, you use the hyperref package and use the \url or \href tag depending on what you're trying to achieve.

How does functools partial do what it does?

This answer is more of an example code. All the above answers give good explanations regarding why one should use partial. I will give my observations and use cases about partial.

from functools import partial
 def adder(a,b,c):
    print('a:{},b:{},c:{}'.format(a,b,c))
    ans = a+b+c
    print(ans)
partial_adder = partial(adder,1,2)
partial_adder(3)  ## now partial_adder is a callable that can take only one argument

Output of the above code should be:

a:1,b:2,c:3
6

Notice that in the above example a new callable was returned that will take parameter (c) as it's argument. Note that it is also the last argument to the function.

args = [1,2]
partial_adder = partial(adder,*args)
partial_adder(3)

Output of the above code is also:

a:1,b:2,c:3
6

Notice that * was used to unpack the non-keyword arguments and the callable returned in terms of which argument it can take is same as above.

Another observation is: Below example demonstrates that partial returns a callable which will take the undeclared parameter (a) as an argument.

def adder(a,b=1,c=2,d=3,e=4):
    print('a:{},b:{},c:{},d:{},e:{}'.format(a,b,c,d,e))
    ans = a+b+c+d+e
    print(ans)
partial_adder = partial(adder,b=10,c=2)
partial_adder(20)

Output of the above code should be:

a:20,b:10,c:2,d:3,e:4
39

Similarly,

kwargs = {'b':10,'c':2}
partial_adder = partial(adder,**kwargs)
partial_adder(20)

Above code prints

a:20,b:10,c:2,d:3,e:4
39

I had to use it when I was using Pool.map_async method from multiprocessing module. You can pass only one argument to the worker function so I had to use partial to make my worker function look like a callable with only one input argument but in reality my worker function had multiple input arguments.

How do I import a sql data file into SQL Server?

If you are talking about an actual database (an mdf file) you would Attach it

.sql files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.

Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's

How do I escape the wildcard/asterisk character in bash?

If you don't want to bother with weird expansions from bash you can do this

me$ FOO="BAR \x2A BAR"   # 2A is hex code for *
me$ echo -e $FOO
BAR * BAR
me$ 

Explanation here why using -e option of echo makes life easier:

Relevant quote from man here:

SYNOPSIS
   echo [SHORT-OPTION]... [STRING]...
   echo LONG-OPTION

DESCRIPTION
   Echo the STRING(s) to standard output.

   -n     do not output the trailing newline

   -e     enable interpretation of backslash escapes

   -E     disable interpretation of backslash escapes (default)

   --help display this help and exit

   --version
          output version information and exit

   If -e is in effect, the following sequences are recognized:

   \\     backslash

   ...

   \0NNN  byte with octal value NNN (1 to 3 digits)

   \xHH   byte with hexadecimal value HH (1 to 2 digits)

For the hex code you can check man ascii page (first line in octal, second decimal, third hex):

   051   41    29    )                           151   105   69    i
   052   42    2A    *                           152   106   6A    j
   053   43    2B    +                           153   107   6B    k

Deleting folders in python recursively

Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.

def deltree(target):
    print("deltree", target)
    for d in os.listdir(target):
        try:
            deltree(target + '/' + d)
        except OSError:
            os.remove(target + '/' + d)

    os.rmdir(target)

How to localise a string inside the iOS info.plist file?

As RGML say, you can create an InfoPlist.strings, localize it then add your key and the value like this: "NSLocationWhenInUseUsageDescription" = "Help To locate me!";

It will add the key to your info.plist for the specified language.

if block inside echo statement?

You can always use the ( <condition> ? <value if true> : <value if false> ) syntax (it's called the ternary operator - thanks to Mark for remining me :) ).

If <condition> is true, the statement would be evaluated as <value if true>. If not, it would be evaluated as <value if false>

For instance:

$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";

This is the same as:

$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
  echo "Fourteen is more than twelve";
}else{
  echo "Fourteen is not more than twelve";
}

Java - creating a new thread

Please try this. You will understand all perfectly after you will take a look on my solution.

There are only 2 ways of creating threads in java

with implements Runnable

class One implements Runnable {
@Override
public void run() {
    System.out.println("Running thread 1 ... ");
}

with extends Thread

class Two extends Thread {
@Override
public void run() {
    System.out.println("Running thread 2 ... ");
}

Your MAIN class here

public class ExampleMain {
public static void main(String[] args) {

    One demo1 = new One();
    Thread t1 = new Thread(demo1);
    t1.start();

    Two demo2 = new Two();
    Thread t2 = new Thread(demo2);
    t2.start();
}

}

JavaScript by reference vs. by value

Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.

An example:

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};

changeParam(a, b, c);

// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...

Unicode (UTF-8) reading and writing to files in Python

In the notation

u'Capit\xe1n\n'

the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write

Capit\xc3\xa1n

into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:

>>> open('f2').read()
'Capit\\xc3\\xa1n\n'

You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3".

Edit:

As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.

If you actually have a string in this format you can use the string_escape codec to decode it into a normal string:

In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape')
Capitán

The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written \\xc3\\xa1 in the original string. If you want to have a unicode string you have to decode again with UTF-8.

To your edit: you don't have UTF-8 in your file. To actually see how it would look like:

s = u'Capit\xe1n\n'
sutf8 = s.encode('UTF-8')
open('utf-8.out', 'w').write(sutf8)

Compare the content of the file utf-8.out to the content of the file you saved with your editor.

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

Why is @font-face throwing a 404 error on woff files?

IIS Mime Type: .woff font/x-woff (not application/x-woff, or application/x-font-woff)

Replace duplicate spaces with a single space in T-SQL

This is the solution via multiple replace, which works for any strings (does not need special characters, which are not part of the string).

declare @value varchar(max)
declare @result varchar(max)
set @value = 'alpha   beta gamma  delta       xyz'

set @result = replace(replace(replace(replace(replace(replace(replace(
  @value,'a','ac'),'x','ab'),'  ',' x'),'x ',''),'x',''),'ab','x'),'ac','a')

select @result -- 'alpha beta gamma delta xyz'

How to vertically center content with variable height within a div?

For me the best way to do this is:

.container{
  position: relative;
}

.element{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

The advantage is not having to make the height explicit

How to drop all tables from the database with manage.py CLI in Django?

It is better to use ./manage.py sqlflush | ./manage.py dbshell because sqlclear requires app to flush.

Is there an equivalent of 'which' on the Windows command line?

Here is a function which I made to find executable similar to the Unix command 'WHICH`

app_path_func.cmd:

@ECHO OFF
CLS

FOR /F "skip=2 tokens=1,2* USEBACKQ" %%N IN (`reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\%~1" /t REG_SZ  /v "Path"`) DO (
 IF /I "%%N" == "Path" (
  SET wherepath=%%P%~1
  GoTo Found
 )
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES%" %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES(x86)%" %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%WINDIR%" %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

:Found
SET %2=%wherepath%
:End

Test:

@ECHO OFF
CLS

CALL "app_path_func.cmd" WINWORD.EXE PROGPATH
ECHO %PROGPATH%

PAUSE

Result:

C:\Program Files (x86)\Microsoft Office\Office15\
Press any key to continue . . .

https://www.freesoftwareservers.com/display/FREES/Find+Executable+via+Batch+-+Microsoft+Office+Example+-+WINWORD+-+Find+Microsoft+Office+Path

Use of alloc init instead of new

For a side note, I personally use [Foo new] if I want something in init to be done without using it's return value anywhere. If you do not use the return of [[Foo alloc] init] anywhere then you will get a warning. More or less, I use [Foo new] for eye candy.

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

Where are Magento's log files located?

You can find the log within you Magento root directory under

var/log

there are two types of log files system.log and exception.log

you need to give the correct permission to var folder, then enable logging from your Magento admin by going to

System > Configuration> Developer > Log Settings > Enable = Yes

system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.

exception.log is reserved for exceptions only, for example when you are using try-catch statement.

To output to either the default system.log or the exception.log see the following code examples:

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);

You can create your own log file for more debugging

Mage::log('My log entry', null, 'mylogfile.log');

How to use moment.js library in angular 2 typescript app?

for angular2 RC5 this worked for me...

first install moment via npm

npm install moment --save

Then import moment in the component that you want to use it

import * as moment from 'moment';

lastly configure moment in systemjs.config.js "map" and "packages"

// map tells the System loader where to look for things
  var map = {
  ....
  'moment':                     'node_modules/moment'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    ...
    'moment':                       { main:'moment', defaultExtension: 'js'}
  };

The AWS Access Key Id does not exist in our records

You may have configured AWS credentials correctly, but using these credentials, you may be connecting to some specific S3 endpoint (as was the case with me).

Instead of using:

aws s3 ls

try using:

aws --endpoint-url=https://<your_s3_endpoint_url> s3 ls

Hope this helps those facing the similar problem.

Unable to establish SSL connection, how do I fix my SSL cert?

I meet this same question. The port 443 wasn't open in Centos.

Check the 443 port with the following command:

sudo lsof -i tcp:443

In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:

LoadModule ssl_module modules/mod_ssl.so
Listen 443

Save array in mysql database

Store it in multi valued column with a comma separator in an RDBMs table.

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:

Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.

In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:

Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.

It turned out to be a result of the following actions on a Solution:

  1. NuGet Package Restore was turned on for the Solution.

  2. A Project was added, and a Nuget package was installed into it (AjaxMin in this case).

  3. The Project was moved to different folder in the Solution.

  4. The Nuget package was updated to a newer version.

And slowly but surely this bug started showing up for some users.

The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:

  <repository path="..\Old\packages.config" />

And this after the reorg:

  <repository path="..\Old\packages.config" />
  <repository path="..\New\packages.config" />

So the first line now refers to a Project that, while on disk, is no longer part of my Solution.

With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.

Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.

The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.

What is Java Servlet?

You just got the answer for a normally servlet. However, I want to share you about something about Servlet 3.0

What is first a Servlet?

A servlet is a Web component that is managed by a container and generates dynamic content. Servlets are Java classes that are compiled to byte code that can be loaded dynamically into and run by a Java technology-enabled Web server or Servlet container.

Servlet 3.0 is an update to the existing Servlet 2.5 specification. Servlet 3.0 required API of the Java Platform, Enterprise Edition 6. Servlet 3.0 is focussed on extensibility and web framework pluggability. Servlet 3.0 bring you up some extensions such as Ease of Development (EoD), Pluggability, Async Support and Security Enhancements

Ease of Development

You can declare Servlets, Filter, Listeners, Init Params, and almost everything can be configured by using annotations

Pluggability

You can create a sub-project or a module with a web-fragment.xml. It means that it allows to implement pluggable functional requirements independently.

Async Support

Servlet 3.0 provides the ability of asynchronous processing, for example: Waiting for a resource to become available, Generating response asynchronously.

Security Enhancements

Support for the authenticate, login and logout servlet security methods

I found it from Java Servlet Tutorial

How to check if bootstrap modal is open, so I can use jquery validate?

Bootstrap 2 , 3 Check is any modal open in page :

if($('.modal.in').length)

compatible version Bootstrap 2 , 3 , 4+

if($('.modal.in, .modal.show').length)

Only Bootstrap 4+

if($('.modal.show').length)

Get all photos from Instagram which have a specific hashtag with PHP

If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.

 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = 'YOUR_TAG_HERE';
    $client_id = "YOUR_CLIENT_ID";
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;

    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);

    //Now parse through the $results array to display your results... 
    foreach($results['data'] as $item){
        $image_link = $item['images']['low_resolution']['url'];
        echo '<img src="'.$image_link.'" />';
    }

Simple dictionary in C++

A table out of char array:

char map[256] = { 0 };
map['T'] = 'A'; 
map['A'] = 'T';
map['C'] = 'G';
map['G'] = 'C';
/* .... */

SSH to Elastic Beanstalk instance

Elastic beanstalk CLI v3 now supports direct SSH with the command eb ssh. E.g.

eb ssh your-environment-name

No need for all the hassle of setting up security groups of finding out the EC2 instance address.

There's also this cool trick:

eb ssh --force

That'll temporarily force port 22 open to 0.0.0.0, and keep it open until you exit. This blends a bit of the benefits of the top answer, without the hassle. You can temporarily grant someone other than you access for debugging and whatnot. Of course you'll still need to upload their public key to the host for them to have access. Once you do that (and as long as you're inside eb ssh), the other person can

ssh [email protected]

How to put text over images in html?

You can create a div with the exact same size as the image.

<div class="imageContainer">Some Text</div>

use the css background-image property to show the image

 .imageContainer {
       width:200px; 
       height:200px; 
       background-image: url(locationoftheimage);
 }

more here

note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.

How to increase the gap between text and underlining in CSS

This is what i use:

html:

<h6><span class="horizontal-line">GET IN</span> TOUCH</h6>

css:

.horizontal-line { border-bottom: 2px solid  #FF0000; padding-bottom: 5px; }

Remove space above and below <p> tag HTML

I don't why you would put a<p>element there. But another way of removing spaces in between the paragraphs is by declaring only one paragraph

<ul>
   <p><li>HI THERE</li>
    <br>
    <li>ME</li>
     </p>
   </ul>

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Concatenating strings doesn't work as expected

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

Load and execution sequence of a web page?

Dynatrace AJAX Edition shows you the exact sequence of page loading, parsing and execution.

Replace words in the body text

Sometimes changing document.body.innerHTML breaks some JS scripts on page. Here is version, that only changes content of text elements:

function replace(element, from, to) {
    if (element.childNodes.length) {
        element.childNodes.forEach(child => replace(child, from, to));
    } else {
        const cont = element.textContent;
        if (cont) element.textContent = cont.replace(from, to);
    }
};

replace(document.body, new RegExp("hello", "g"), "hi");

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

How can I call controller/view helper methods from the console in Ruby on Rails?

If you have added your own helper and you want its methods to be available in console, do:

  1. In the console execute include YourHelperName
  2. Your helper methods are now available in console, and use them calling method_name(args) in the console.

Example: say you have MyHelper (with a method my_method) in 'app/helpers/my_helper.rb`, then in the console do:

  1. include MyHelper
  2. my_helper.my_method

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

How to drop all tables from a database with one SQL query?

For me I just do


DECLARE @cnt INT = 0;

WHILE @cnt < 10 --Change this if all tables are not dropped with one run
BEGIN
SET @cnt = @cnt + 1;
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
END

Retrofit and GET using parameters

AFAIK, {...} can only be used as a path, not inside a query-param. Try this instead:

public interface FooService {    

    @GET("/maps/api/geocode/json?sensor=false")
    void getPositionByZip(@Query("address") String address, Callback<String> cb);
}

If you have an unknown amount of parameters to pass, you can use do something like this:

public interface FooService {    

    @GET("/maps/api/geocode/json")
    @FormUrlEncoded
    void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}

1030 Got error 28 from storage engine

I had a similar issue, because of my replication binary logs.

If this is the case, just create a cronjob to run this query every day:

PURGE BINARY LOGS BEFORE DATE_SUB( NOW(), INTERVAL 2 DAY );

This will remove all binary logs older than 2 days.

I found this solution here.

How to ignore the certificate check when ssl

Rather than adding a callback to ServicePointManager which will override certificate validation globally, you can set the callback on a local instance of HttpClient. This approach should only affect calls made using that instance of HttpClient.

Here is sample code showing how ignoring certificate validation errors for specific servers might be implemented in a Web API controller.

using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class MyController : ApiController
{

    // use this HttpClient instance when making calls that need cert errors suppressed
    private static readonly HttpClient httpClient;

    static MyController()
    {
        // create a separate handler for use in this controller
        var handler = new HttpClientHandler();

        // add a custom certificate validation callback to the handler
        handler.ServerCertificateCustomValidationCallback = ((sender, cert, chain, errors) => ValidateCert(sender, cert, chain, errors));

        // create an HttpClient that will use the handler
        httpClient = new HttpClient(handler);
    }

    protected static ValidateCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
    {

        // set a list of servers for which cert validation errors will be ignored
        var overrideCerts = new string[]
        {
            "myproblemserver",
            "someotherserver",
            "localhost"
        };

        // if the server is in the override list, then ignore any validation errors
        var serverName = cert.Subject.ToLower();
        if (overrideCerts.Any(overrideName => serverName.Contains(overrideName))) return true;

        // otherwise use the standard validation results
        return errors == SslPolicyErrors.None;
    }

}

PHP strtotime +1 month adding an extra month

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.

Checking if a field contains a string

How to ignore HTML tags in a RegExp match:

var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';

var rx = '';
searchString.split(' ').forEach(e => {
  rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});

rx = new RegExp(rx, 'igm');

console.log(text.match(rx));

This is probably very easy to turn into a MongoDB aggregation filter.

List all the files and folders in a Directory with PHP recursive function

Ready for copy and paste function for common use cases, improved/extended version of one answer above:

function getDirContents(string $dir, int $onlyFiles = 0, string $excludeRegex = '~/\.git/~', int $maxDepth = -1): array {
    $results = [];
    $scanAll = scandir($dir);
    sort($scanAll);
    $scanDirs = []; $scanFiles = [];
    foreach($scanAll as $fName){
        if ($fName === '.' || $fName === '..') { continue; }
        $fPath = str_replace(DIRECTORY_SEPARATOR, '/', realpath($dir . '/' . $fName));
        if (strlen($excludeRegex) > 0 && preg_match($excludeRegex, $fPath . (is_dir($fPath) ? '/' : ''))) { continue; }
        if (is_dir($fPath)) {
            $scanDirs[] = $fPath;
        } elseif ($onlyFiles >= 0) {
            $scanFiles[] = $fPath;
        }
    }

    foreach ($scanDirs as $pDir) {
        if ($onlyFiles <= 0) {
            $results[] = $pDir;
        }
        if ($maxDepth !== 0) {
            foreach (getDirContents($pDir, $onlyFiles, $excludeRegex, $maxDepth - 1) as $p) {
                $results[] = $p;
            }
        }
    }
    foreach ($scanFiles as $p) {
        $results[] = $p;
    }

    return $results;
}

And if you need relative paths:

function updateKeysWithRelPath(array $paths, string $baseDir, bool $allowBaseDirPath = false): array {
    $results = [];
    $regex = '~^' . preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath($baseDir)), '~') . '(?:/|$)~s';
    $regex = preg_replace('~/~', '/(?:(?!\.\.?/)(?:(?!/).)+/\.\.(?:/|$))?(?:\.(?:/|$))*', $regex); // limited to only one "/xx/../" expr
    if (DIRECTORY_SEPARATOR === '\\') {
        $regex = preg_replace('~/~', '[/\\\\\\\\]', $regex) . 'i';
    }
    foreach ($paths as $p) {
        $rel = preg_replace($regex, '', $p, 1);
        if ($rel === $p) {
            throw new \Exception('Path relativize failed, path "' . $p . '" is not within basedir "' . $baseDir . '".');
        } elseif ($rel === '') {
            if (!$allowBaseDirPath) {
                throw new \Exception('Path relativize failed, basedir path "' . $p . '" not allowed.');
            } else {
                $results[$rel] = './';
            }
        } else {
            $results[$rel] = $p;
        }
    }
    return $results;
}

function getDirContentsWithRelKeys(string $dir, int $onlyFiles = 0, string $excludeRegex = '~/\.git/~', int $maxDepth = -1): array {
    return updateKeysWithRelPath(getDirContents($dir, $onlyFiles, $excludeRegex, $maxDepth), $dir);
}

This version solves/improves:

  1. warnings from realpath when PHP open_basedir does not cover the .. directory.
  2. does not use reference for the result array
  3. allows to exclude directories and files
  4. allows to list files/directories only
  5. allows to limit the search depth
  6. it always sort output with directories first (so directories can be removed/emptied in reverse order)
  7. allows to get paths with relative keys
  8. heavy optimized for hundred of thousands or even milions of files
  9. write for more in the comments :)

Examples:

// list only `*.php` files and skip .git/ and the current file
$onlyPhpFilesExcludeRegex = '~/\.git/|(?<!/|\.php)$|^' . preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath(__FILE__)), '~') . '$~is';

$phpFiles = getDirContents(__DIR__, 1, $onlyPhpFilesExcludeRegex);
print_r($phpFiles);

// with relative keys
$phpFiles = getDirContentsWithRelKeys(__DIR__, 1, $onlyPhpFilesExcludeRegex);
print_r($phpFiles);

// with "include only" regex to include only .html and .txt files with "/*_mails/en/*.(html|txt)" path
'~/\.git/|^(?!.*/(|' . '[^/]+_mails/en/[^/]+\.(?:html|txt)' . ')$)~is'

What is the best way to delete a component with CLI

destroy or something similar may come to the CLI, but it is not a primary focus at this time. So you will need to do this manually.

Delete the component directory (assuming you didn't use --flat) and then remove it from the NgModule in which it is declared.

If you are unsure of what to do, I suggest you have a "clean" app meaning no current git changes. Then generate a component and see what is changed in the repo so you can backtrack from there what you will need to do to delete a component.

Update

If you're just experimenting about what you want to generate, you can use the --dry-run flag to not produce any files on disk, just see the updated file list.

How to subtract X days from a date using Java calendar?

Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.

FYI in Joda Time you could do

DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

i found another solution:

  1. start session in TEAM
  2. go to SOURCE CONTROL and select WORKSPACE (mark in red)
  3. then Add new Workspace... why?
  4. because you dont work in the same workspace whey you change your account in TFS (i dont know why)
  5. and ready to MAP your project again.

Its 100% guaranteed to work.

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

It happen if there are two more ContextLoaderListener exist in your project.

For ex: in my case 2 ContextLoaderListener was exist using

  1. java configuration
  2. web.xml

So, remove any one ContextLoaderListener from your project and run your application.

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

Probably because you're using unsafe code.

Are you doing something with pointers or unmanaged assemblies somewhere?

Submit form with Enter key without submit button?

Change #form to your form's ID

$('#form input').keydown(function(e) {
    if (e.keyCode == 13) {
        $('#form').submit();
    }
});

Or alternatively

$('input').keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).closest('form').submit();
    }
});

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

pip install failing with: OSError: [Errno 13] Permission denied on directory

Just clarifying what worked for me after much pain in linux (ubuntu based) on permission denied errors, and leveraging from Bert's answer above, I now use ...

$ pip install --user <package-name>

or if running pip on a requirements file ...

$ pip install --user -r requirements.txt

and these work reliably for every pip install including creating virtual environments.

However, the cleanest solution in my further experience has been to install python-virtualenv and virtualenvwrapper with sudo apt-get install at the system level.

Then, inside virtual environments, use pip install without the --user flag AND without sudo. Much cleaner, safer, and easier overall.

What is the difference between a static and a non-static initialization code block

"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

I like the idea of seting tomcat6 memory based on available server memory (it is cool because I don't have to change the setup after hardware upgrade). Here is my (a bit extended memory setup):

export CATALINA_OPTS="-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k -Xms`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k -XX:NewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k -XX:MaxNewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k -XX:PermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k -XX:MaxPermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`k"

Put it to: "{tomcat}/bin/startup.sh" (e.g. "/usr/share/tomcat6/bin" for Ubuntu 10.10)

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

Faced the problem of missing stdlib.h and stdio.h (and maybe more) after installing VS2017 Community on a new computer and migrating a solution from VS2013 to VS2017.

Used @Maxim Akristiniy's proposal, but still got error message regarding toolset compatibility. However VS itself suggested to do solution retarget by right-clicking on the solution in Solution Explorer, then selecting Retarget solution from the menu and the updated Windows SDK Version from the drop-down list.

Now my projects build w/o a problem.

Note that you may need to make the project your startup project for the retargeting to catch.

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

adding onclick event to dynamically added button?

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

You can Try this also :

 public static String convertToNameCase(String s)
    {
        if (s != null)
        {
            StringBuilder b = new StringBuilder();
            String[] split = s.split(" ");
            for (String srt : split)
            {
                if (srt.length() > 0)
                {
                    b.append(srt.substring(0, 1).toUpperCase()).append(srt.substring(1).toLowerCase()).append(" ");
                }
            }
            return b.toString().trim();
        }
        return s;
    }

git replace local version with remote version

I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).

Simply do

git checkout remote/branch -- a/file b/another/file

If you want to do this for extensive subtrees and instead wish to affect the index directly use

git read-tree remote/branch:subdir/

You can then (optionally) update your working copy by doing

git checkout-index -u --force

REST API 404: Bad URI, or Missing Resource?

404 Not Found technically means that uri does not currently map to a resource. In your example, I interpret a request to http://mywebsite/api/user/13 that returns a 404 to imply that this url was never mapped to a resource. To the client, that should be the end of conversation.

To address concerns with ambiguity, you can enhance your API by providing other response codes. For example, suppose you want to allow clients to issue GET requests the url http://mywebsite/api/user/13, you want to communicate that clients should use the canonical url http://mywebsite/restapi/user/13. In that case, you may want to consider issuing a permanent redirect by returning a 301 Moved Permanently and supply the canonical url in the Location header of the response. This tells the client that for future requests they should use the canonical url.

Environment Specific application.properties file in Spring Boot application

Yes you can. Since you are using spring, check out @PropertySource anotation.

Anotate your configuration with

@PropertySource("application-${spring.profiles.active}.properties")

You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).

@PropertySources({
  @PropertySource("application-${spring.profiles.active}.properties"),
  @PropertySource("my-special-${spring.profiles.active}.properties"),
  @PropertySource("overridden.properties")})

Then you can start the application with environment

-Dspring.active.profiles=test

In this example, name will be replaced with application-test-properties and so on.

SQL Server loop - how do I loop through a set of records

By using T-SQL and cursors like this :

DECLARE @MyCursor CURSOR;
DECLARE @MyField YourFieldDataType;
BEGIN
    SET @MyCursor = CURSOR FOR
    select top 1000 YourField from dbo.table
        where StatusID = 7      

    OPEN @MyCursor 
    FETCH NEXT FROM @MyCursor 
    INTO @MyField

    WHILE @@FETCH_STATUS = 0
    BEGIN
      /*
         YOUR ALGORITHM GOES HERE   
      */
      FETCH NEXT FROM @MyCursor 
      INTO @MyField 
    END; 

    CLOSE @MyCursor ;
    DEALLOCATE @MyCursor;
END;

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

With Postman, select Body tab and choose the raw option and type the following:

grant_type=password&username=yourusername&password=yourpassword

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

I know that we are (n-1) * (n times), but why the division by 2?

It's only (n - 1) * n if you use a naive bubblesort. You can get a significant savings if you notice the following:

  • After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.

  • After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.

Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + .... This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.

Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.

Memcached vs. Redis?

We thought of Redis as a load-takeoff for our project at work. We thought that by using a module in nginx called HttpRedis2Module or something similar we would have awesome speed but when testing with AB-test we're proven wrong.

Maybe the module was bad or our layout but it was a very simple task and it was even faster to take data with php and then stuff it into MongoDB. We're using APC as caching-system and with that php and MongoDB. It was much much faster then nginx Redis module.

My tip is to test it yourself, doing it will show you the results for your environment. We decided that using Redis was unnecessary in our project as it would not make any sense.

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

c#: getter/setter

Those are Auto-Implemented Properties (Auto Properties for short).

The compiler will auto-generate the equivalent of the following simple implementation:

private string _type;

public string Type
{
    get { return _type; }
    set { _type = value; }
}

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.10</version>
    </dependency>

reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

Eclipse error: indirectly referenced from required .class files?

This error occurs when the classes in the jar file does not follow the same structure as of the folder structure of the jar..

e.g. if you class file has package com.test.exam and the classes.jar created out of this class file has structure test.exam... error will be thrown. You need to correct the package structure of your classes.jar and then include it in ecplipse build path...

How to obtain the number of CPUs/cores in Linux from the command line?

You can use one of the following methods to determine the number of physical CPU cores.

  • Count the number of unique core ids (roughly equivalent to grep -P '^core id\t' /proc/cpuinfo | sort -u | wc -l).

    awk '/^core id\t/ {cores[$NF]++} END {print length(cores)}' /proc/cpuinfo

  • Multiply the number of 'cores per socket' by the number of sockets.

    lscpu | awk '/^Core\(s\) per socket:/ {cores=$NF}; /^Socket\(s\):/ {sockets=$NF}; END{print cores*sockets}'

  • Count the number of unique logical CPU's as used by the Linux kernel. The -p option generates output for easy parsing and is compatible with earlier versions of lscpu.

    lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'


Just to reiterate what others have said, there are a number of related properties.

To determine the number of processors available:

getconf _NPROCESSORS_ONLN
grep -cP '^processor\t' /proc/cpuinfo

To determine the number of processing units available (not necessarily the same as the number of cores). This is hyperthreading-aware.

nproc

I don't want to go too far down the rabbit-hole, but you can also determine the number of configured processors (as opposed to simply available/online processors) via getconf _NPROCESSORS_CONF. To determine total number of CPU's (offline and online) you'd want to parse the output of lscpu -ap.

Transfer data from one database to another database

There are several ways to do this, below are two options:

Option 1 - Right click on the database you want to copy

  • Choose 'Tasks' > 'Generate scripts'

  • 'Select specific database objects'

  • Check 'Tables'

  • Mark 'Save to new query window'

  • Click 'Advanced'

  • Set 'Types of data to script' to 'Schema and data'

  • Next, Next

You can now run the generated query on the new database.

Option 2

  • Right click on the database you want to copy

  • 'Tasks' > 'Export Data'

  • Next, Next

  • Choose the database to copy the tables to

  • Mark 'Copy data from one or more tables or views'

  • Choose the tables you want to copy

  • Finish

How to kill/stop a long SQL query immediately?

  1. First, you need to display/check all running queries using below query-

    SELECT text, GETDATE(), *
    FROM sys.dm_exec_requests
    CROSS APPLY sys.dm_exec_sql_text(sql_handle)
    
  2. Find Session-Id and Description for respective all running queries and then copy specific query's Session-Id which you want to kill/stop immediately.

  3. Kill/stop specific query using Session-Id using this query:

    Kill Session-id
    

    Example:

    kill 125 --125 is my Session-Id
    

Traverse all the Nodes of a JSON Object Tree with JavaScript

I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791

You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/

Examples of usage: You should always have root object which is the first parameter of each method:

var rootObj = {
  name: 'rootObject',
  children: [
    {
      'name': 'child1',
       children: [ ... ]
    },
    {
       'name': 'child2',
       children: [ ... ]
    }
  ]
};

The second parameter is always the name of property that holds nested objects. In above case it would be 'children'.

The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1} as the third parameter.

And you can:

  1. findFirst(rootObj, 'children', { id: 1 }) to find first object with id === 1
  2. findAll(rootObj, 'children', { id: 1 }) to find all objects with id === 1
  3. findAndDeleteFirst(rootObj, 'children', { id: 1 }) to delete first matching object
  4. findAndDeleteAll(rootObj, 'children', { id: 1 }) to delete all matching objects

replacementObj is used as the last parameter in two last methods:

  1. findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change first found object with id === 1 to the { id: 2, name: 'newObj'}
  2. findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change all objects with id === 1 to the { id: 2, name: 'newObj'}

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.

Compression/Decompression string with C#

With the advent of .NET 4.0 (and higher) with the Stream.CopyTo() methods, I thought I would post an updated approach.

I also think the below version is useful as a clear example of a self-contained class for compressing regular strings to Base64 encoded strings, and vice versa:

public static class StringCompression
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Here’s another approach using the extension methods technique to extend the String class to add string compression and decompression. You can drop the class below into an existing project and then use thusly:

var uncompressedString = "Hello World!";
var compressedString = uncompressedString.Compress();

and

var decompressedString = compressedString.Decompress();

To wit:

public static class Extensions
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(this string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(this string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Scroll back to the top of scrollable div

If the html content overflow a single viewport, this worked for me using only javascript:

document.getElementsByTagName('body')[0].scrollTop = 0;

Regards,

python pip on Windows - command 'cl.exe' failed

  1. Install Microsoft visual c++ 14.0 build tool.(Windows 7)
  2. create a virtual environment using conda.
  3. Activate the environment and use conda to install the necessary package.

For example: conda install -c conda-forge spacy

OS X cp command in Terminal - No such file or directory

On OS X Sierra 10.12, None of the above work. cd then drag and drop does not work. No spacing or other fixes work. I cannot cd into ~/Library Support using any technique that I can find. Is this a security feature?
I'm going to try disabling SIP and see if it makes a difference.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

Bootstrap close responsive menu "on click"

$('.navbar-toggle').trigger('click');

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

in my case it was the path lenght (incl. file name).

..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Debug\boost_unit_test_framework-vc90-mt-gd-1_57.lib;

as for the release the path was (this has worked correctly):

..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Release\boost_unit_test_framework-vc90-mt-1_57.lib;

==> one char shorter.

  1. i have also verified this by renaming the lib file (using shorter name) and changing this in the

Linker -> input -> additoinal dependencies

  1. i have also verified this by adding absolut path instead of relative path as all those ".." has extended the path string, too. this has also worked.

so the problem for me was the total size of the path + filename string was too long!

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Yes, It should be alright to have both versions installed. It's actually pretty much expected nowadays. A lot of stuff is written in 2.7, but 3.5 is becoming the norm. I would recommend updating all your python to 3.5 ASAP, though.

How to extract text from an existing docx file using python-docx

I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP

Can't run Curl command inside my Docker Container

So I added curl AFTER my docker container was running.

(This was for debugging the container...I did not need a permanent addition)

I ran my image

docker run -d -p 8899:8080 my-image:latest

(the above makes my "app" available on my machine on port 8899) (not important to this question)

Then I listed and created terminal into the running container.

docker ps
docker exec -it my-container-id-here /bin/sh

If the exec command above does not work, check this SOF article:

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

then I ran:

apk

just to prove it existed in the running container, then i ran:

apk add curl

and got the below:

apk add curl

fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz

fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/community/x86_64/APKINDEX.tar.gz

(1/5) Installing ca-certificates (20171114-r3)

(2/5) Installing nghttp2-libs (1.32.0-r0)

(3/5) Installing libssh2 (1.8.0-r3)

(4/5) Installing libcurl (7.61.1-r1)

(5/5) Installing curl (7.61.1-r1)

Executing busybox-1.28.4-r2.trigger

Executing ca-certificates-20171114-r3.trigger

OK: 18 MiB in 35 packages

then i ran curl:

/ # curl
curl: try 'curl --help' or 'curl --manual' for more information
/ # 

Note, to get "out" of the drilled-in-terminal-window, I had to open a new terminal window and stop the running container:

docker ps
docker stop my-container-id-here

APPEND:

If you don't have "apk" (which depends on which base image you are using), then try to use "another" installer. From other answers here, you can try:

apt-get -qq update

apt-get -qq -y install curl

TypeError: coercing to Unicode: need string or buffer

You're trying to open each file twice! First you do:

infile=open('110331_HS1A_1_rtTA.result','r')

and then you pass infile (which is a file object) to the open function again:

with open (infile, mode='r', buffering=-1)

open is of course expecting its first argument to be a file name, not an opened file!

Open the file once only and you should be fine.

Compare two DataFrames and output their differences side-by-side

pandas >= 1.1: DataFrame.compare

With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:

pd.__version__
# '1.1.0'

df1.compare(df2)

  score       isEnrolled       Comment             
   self other       self other    self        other
1  1.11  1.21        NaN   NaN     NaN          NaN
2   NaN   NaN        1.0   0.0     NaN  On vacation

Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use

df1.compare(df2, keep_equal=True, keep_shape=True) 

  score       isEnrolled           Comment             
   self other       self  other       self        other
1  1.11  1.21      False  False  Graduated    Graduated
2  4.12  4.12       True  False        NaN  On vacation

You can also change the axis of comparison using align_axis:

df1.compare(df2, align_axis='index')

         score  isEnrolled      Comment
1 self    1.11         NaN          NaN
  other   1.21         NaN          NaN
2 self     NaN         1.0          NaN
  other    NaN         0.0  On vacation

This compares values row-wise, instead of column-wise.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

PYTHONPATH only affects import statements, not the top-level Python interpreter's lookup of python files given as arguments.

Needing PYTHONPATH to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.

Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.

How do you remove Subversion control for a folder?

Without subshells in Linux to delete .svn folders:

find . -name .svn -exec rm -r -f {} +

rm = remove
-r = recursive (folders)
-f = force, avoids a lot of "a your sure you want to delete file XY".

PostgreSQL ERROR: canceling statement due to conflict with recovery

As stated here about hot_standby_feedback = on :

Well, the disadvantage of it is that the standby can bloat the master, which might be surprising to some people, too

And here:

With what setting of max_standby_streaming_delay? I would rather default that to -1 than default hot_standby_feedback on. That way what you do on the standby only affects the standby


So I added

max_standby_streaming_delay = -1

And no more pg_dump error for us, nor master bloat :)

For AWS RDS instance, check http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

In the shell, what does " 2>&1 " mean?

Redirecting Input

Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.

The general format for redirecting input is:

[n]<word

Redirecting Output

Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.

The general format for redirecting output is:

[n]>word

Moving File Descriptors

The redirection operator,

[n]<&digit-

moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n.

Similarly, the redirection operator

[n]>&digit-

moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.

Ref:

man bash

Type /^REDIRECT to locate to the redirection section, and learn more...

An online version is here: 3.6 Redirections

PS:

Lots of the time, man was the powerful tool to learn Linux.

How do I multiply each element in a list by a number?

Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.

using for loop

lst = [5, 20 ,15]
product = []
for i in lst:
    product.append(i*5)
print product

using list comprehension, this is also same as using for-loop but more 'pythonic'

lst = [5, 20 ,15]

prod = [i * 5 for i in lst]
print prod

Angular2: custom pipe could not be found

This didnt worked for me. (Im with Angular 2.1.2). I had NOT to import MainPipeModule in app.module.ts and importe it instead in the module where the component Im using the pipe is imported too.

Looks like if your component is declared and imported in a different module, you need to include your PipeModule in that module too.

Starting of Tomcat failed from Netbeans

It affects at least NetBeans versions 7.4 through 8.0.2. It was first reported from version 8.0 and fixed in NetBeans 8.1. It would have had the problem for any tomcat version (confirmed for versions 7.0.56 through 8.0.28).

Specifics are described as Netbeans bug #248182.

This problem is also related to postings mentioning the following error output:

'127.0.0.1*' is not recognized as an internal or external command, operable program or batch file.

For a tomcat installed from the zip file, I fixed it by changing the catalina.bat file in the tomcat bin directory.

Find the bellow configuration in your catalina.bat file.

:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

And change it as in below by removing the double quotes:

:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%

:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%

Now save your changes, and start your tomcat from within NetBeans.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

ANDROID STUDIO Users try this:-

You need to add the following to your gradle file dependencies:

compile 'com.android.support:multidex:1.0.0'

And then add below line ( multidex support application ) to your manifest's application tag:

android:name="android.support.multidex.MultiDexApplication"

Storing money in a decimal column - what precision and scale?

If you were using IBM Informix Dynamic Server, you would have a MONEY type which is a minor variant on the DECIMAL or NUMERIC type. It is always a fixed-point type (whereas DECIMAL can be a floating point type). You can specify a scale from 1 to 32, and a precision from 0 to 32 (defaulting to a scale of 16 and a precision of 2). So, depending on what you need to store, you might use DECIMAL(16,2) - still big enough to hold the US Federal Deficit, to the nearest cent - or you might use a smaller range, or more decimal places.

Python function as a function argument?

Sure, that is why python implements the following methods where the first parameter is a function:

  • map(function, iterable, ...) - Apply function to every item of iterable and return a list of the results.
  • filter(function, iterable) - Construct a list from those elements of iterable for which function returns true.
  • reduce(function, iterable[,initializer]) - Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
  • lambdas

How to search in array of object in mongodb

as explained in above answers Also, to return only one field from the entire array you can use projection into find. and use $

db.getCollection("sizer").find(
  { awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
  { "awards.$": 1, name: 1 }
);

will be reutrn

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

Are HTTPS URLs encrypted?

Althought there are some good answers already here, most of them are focusing in browser navigation. I'm writing this in 2018 and probably someone wants to know about the security of mobile apps.

For mobile apps, if you control both ends of the application (server and app), as long as you use HTTPS you're secure. iOS or Android will verify the certificate and mitigate possible MiM attacks (that would be the only weak point in all this). You can send sensitive data through HTTPS connections that it will be encrypted during transport. Just your app and the server will know any parameters sent through https.

The only "maybe" here would be if client or server are infected with malicious software that can see the data before it is wrapped in https. But if someone is infected with this kind of software, they will have access to the data, no matter what you use to transport it.

How to convert a JSON string to a Map<String, String> with Jackson JSON

Converting from String to JSON Map:

Map<String,String> map = new HashMap<String,String>();

ObjectMapper mapper = new ObjectMapper();

map = mapper.readValue(string, HashMap.class);

What regex will match every character except comma ',' or semi-colon ';'?

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

How to open generated pdf using jspdf in new window

Generally you can download it, show, or get a blob string:

const pdfActions = {
    save: () => doc.save(filename),
    getBlob: () => {
      const blob = doc.output('datauristring');
      console.log(blob)
      return blob
    },
    show: () => doc.output('dataurlnewwindow')
  }

How do I declare a model class in my Angular 2 component using TypeScript?

my code is

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

class model {
  username : string;
  password : string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})



export class AppComponent {

 username : string;
 password : string;
  usermodel = new model();

  login(){
  if(this.usermodel.username == "admin"){
    alert("hi");
  }else{
    alert("bye");
    this.usermodel.username = "";
  }    
  }
}

and the html goes like this :

<div class="login">
  Usernmae : <input type="text" [(ngModel)]="usermodel.username"/>
  Password : <input type="text" [(ngModel)]="usermodel.password"/>
  <input type="button" value="Click Me" (click)="login()" />
</div>

creating batch script to unzip a file without additional zip tools

Try this:

@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b

:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%

Revision

To have it perform the unzip on each zip file creating a folder for each use:

@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
    Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b

If you don't want it to create a folder for each zip, change Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa" to Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

or, simply put:

JsonConvert.SerializeObject(
    <YOUR OBJECT>, 
    new JsonSerializerSettings 
    { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    });

For instance:

return new ContentResult
{
    ContentType = "application/json",
    Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
    ContentEncoding = Encoding.UTF8
};

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

For right menu you can do it:

public static Drawable setTintDrawable(Drawable drawable, @ColorInt int color) {
            drawable.clearColorFilter();
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawable.invalidateSelf();
            Drawable wrapDrawable = DrawableCompat.wrap(drawable).mutate();
            DrawableCompat.setTint(wrapDrawable, color);
            return wrapDrawable;
        }

And in your activity

@Override
 public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_profile, menu);
        Drawable send = menu.findItem(R.id.send);
        Drawable msg = menu.findItem(R.id.message);
        DrawableUtils.setTintDrawable(send.getIcon(), Color.WHITE);
        DrawableUtils.setTintDrawable(msg.getIcon(), Color.WHITE);
        return true;
    }

This is the result:

enter image description here

Populating a ListView using an ArrayList?

Try the below answer to populate listview using ArrayList

public class ExampleActivity extends Activity
{
    ArrayList<String> movies;

    public void onCreate(Bundle saveInstanceState)
    {
       super.onCreate(saveInstanceState);
       setContentView(R.layout.list);

       // Get the reference of movies
       ListView moviesList=(ListView)findViewById(R.id.listview);

       movies = new ArrayList<String>();
       getMovies();

       // Create The Adapter with passing ArrayList as 3rd parameter
       ArrayAdapter<String> arrayAdapter =      
                 new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, movies);
       // Set The Adapter
       moviesList.setAdapter(arrayAdapter); 

       // register onClickListener to handle click events on each item
       moviesList.setOnItemClickListener(new OnItemClickListener()
       {
           // argument position gives the index of item which is clicked
           public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
           {
               String selectedmovie=movies.get(position);
               Toast.makeText(getApplicationContext(), "Movie Selected : "+selectedmovie,   Toast.LENGTH_LONG).show();
           }
        });
    }

    void getmovies()
    {
        movies.add("X-Men");
        movies.add("IRONMAN");
        movies.add("SPIDY");
        movies.add("NARNIA");
        movies.add("LIONKING");
        movies.add("AVENGERS");   
    }
}

What does "\r" do in the following script?

\r is the ASCII Carriage Return (CR) character.

There are different newline conventions used by different operating systems. The most common ones are:

  • CR+LF (\r\n);
  • LF (\n);
  • CR (\r).

The \n\r (LF+CR) looks unconventional.

edit: My reading of the Telnet RFC suggests that:

  1. CR+LF is the standard newline sequence used by the telnet protocol.
  2. LF+CR is an acceptable substitute:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

Where is debug.keystore in Android Studio

On Windows,

All you need to do is goto command prompt and cd C:\Program Files\Java\jdk-10.0.2\bin>where jdk-10.0.2 or full path can be different in your case. once you are in the bin, enter this code keytool -keystore C:\Users\GB\.android/debug.keystore -list -v where C:\Users\GB\.android/debug.keystore is path to keystore in my case.

You will get results like this.

enter image description here

Toolbar Navigation Hamburger Icon missing

For that you just need write to some lines

   DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
   ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
   drawer.addDrawerListener(toggle);
   toggle.setDrawerIndicatorEnabled(true);
   toggle.syncState();

toggle.setDrawerIndicatorEnabled(true); if this is false make it true or remove this line

Operator overloading in Java

No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.

For a Java-like (and JVM-based) language which does support operator overloading, you could look at Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Call Python function from MATLAB

Starting from Matlab 2014b Python functions can be called directly. Use prefix py, then module name, and finally function name like so:

result = py.module_name.function_name(parameter1);

Make sure to add the script to the Python search path when calling from Matlab if you are in a different working directory than that of the Python script.

See more details here.

How to set layout_weight attribute dynamically from code?

Use LinearLayout.LayoutParams:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);

EDIT: Ah, Erich's answer is easier!

How can I post data as form data instead of a request payload?

As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.

It can be used like this:

$http.post('http://example.com', $httpParamSerializer(formDataObj)).
    success(function(data){/* response status 200-299 */}).
    error(function(data){/* response status 400-999 */});

Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

To do this only for the current post, the headers property of the request-object needs to be modified:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 data: $httpParamSerializer(formDataObj)
};

$http(req);

Is there a REAL performance difference between INT and VARCHAR primary keys?

As for Primary Key, whatever physically makes a row unique should be determined as the primary key.

For a reference as a foreign key, using an auto incrementing integer as a surrogate is a nice idea for two main reasons.
- First, there's less overhead incurred in the join usually.
- Second, if you need to update the table that contains the unique varchar then the update has to cascade down to all the child tables and update all of them as well as the indexes, whereas with the int surrogate, it only has to update the master table and it's indexes.

The drawaback to using the surrogate is that you could possibly allow changing of the meaning of the surrogate:

ex.
id value
1 A
2 B
3 C

Update 3 to D
id value
1 A
2 B
3 D

Update 2 to C
id value
1 A
2 C
3 D

Update 3 to B
id value
1 A
2 C
3 B

It all depends on what you really need to worry about in your structure and what means most.

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

What does the question mark operator mean in Ruby?

It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.

Calling Javascript from a html form

Pretty example by Miquel (#32) should be refilled:

<html>
 <head>
  <script type="text/javascript">
   function handleIt(txt) {   // txt == content of form input
    alert("Entered value: " + txt);
   }
  </script>
 </head>
 <body>
 <!-- javascript function in form action must have a parameter. This 
    parameter contains a value of named input -->
  <form name="myform" action="javascript:handleIt(lastname.value)">  
   <input type="text" name="lastname" id="lastname" maxlength="40"> 
   <input name="Submit"  type="submit" value="Update"/>
  </form>
 </body>
</html>

And the form should have:

<form name="myform" action="javascript:handleIt(lastname.value)"> 

Bash script and /bin/bash^M: bad interpreter: No such file or directory

For Eclipse users, you can either change the file encoding directly from the menu File > Convert Line Delimiters To > Unix (LF, \n, 0?, ¶):

Eclipse change file encoding

Or change the New text file line delimiter to Other: Unix on Window > Preferences > General > Workspace panel:

Eclipse workspace settings

How to set Java classpath in Linux?

You have to use ':' colon instead of ';' semicolon.

As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.

And the variable must be CLASSPATH not classpath.

Markdown `native` text alignment

To center align, surround the text you wish to center align with arrows (-> <-) like so:

-> This is center aligned <-

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

How to get the day of week and the month of the year?

Write the Date = document.write(Date());

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:

jqGrid

DataTables.net

UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            };
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);
                input.addClass(options.css);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                        $(this).children("td").addClass("ui-state-hover");
                    } else {
                        $(this).children("td").removeClass("ui-state-hover");
                    }
                });

                input.find("th").addClass("ui-state-default");
                input.find("td").addClass("ui-widget-content");

                input.find("tr").each(function () {
                    $(this).children("td:not(:first)").addClass("first");
                    $(this).children("th:not(:first)").addClass("first");
                });
            });
        };
    })(jQuery);

    $(document).ready(function () {
        $("#Table1").styleTable();
    });

</script>

<table id="Table1" class="full">
    <tr>
        <th>one</th>
        <th>two</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

difference between System.out.println() and System.err.println()

this answer most probably help you it is so much easy System.err and System.out both are the same both are defined in System class as reference variable of PrintStream class as public final static PrintStream out = null; and public final static PrintStream err = null;

means both are ref. variable of PrintStream class. normally System.err is used for printing an error messages, which increase the redability for the programmer.

A minor difference comes in both when we are working with Redirection operator.

JQuery Find #ID, RemoveClass and AddClass

$('#testID2').addClass('test3').removeClass('test2');

jQuery addClass API reference

How to 'foreach' a column in a DataTable using C#?

You can do it like this:

DataTable dt = new DataTable("MyTable");

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        if (row[column] != null) // This will check the null values also (if you want to check).
        {
               // Do whatever you want.
        }
     }
}

how to avoid extra blank page at end while printing?

if None of those works, try this

@media print {

    html, body {
      height:100vh; 
      margin: 0 !important; 
      padding: 0 !important;
      overflow: hidden;
    }

}

make sure it is 100vh

My Application Could not open ServletContext resource

I encountered this exception in WebLogic, turns out it is a bug in WebLogic. Please see here for more details: Spring Boot exception: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]

how to exit a python script in an if statement

This works fine for me:

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

edit: use input in python 3.2 instead of raw_input

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

One liner for If string is not null or empty else

Old question, but thought I'd add this to help out,

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

Spring jUnit Testing properties file

Firstly, application.properties in the @PropertySource should read application-test.properties if that's what the file is named (matching these things up matters):

@PropertySource("classpath:application-test.properties ")

That file should be under your /src/test/resources classpath (at the root).

I don't understand why you'd specify a dependency hard coded to a file called application-test.properties. Is that component only to be used in the test environment?

The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.

In a typically laid out application, you'd have:

src/test/resources/application.properties

and

src/main/resources/application.properties

And then inject it like this:

@PropertySource("classpath:application.properties")

The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

Sort arrays of primitive types in descending order

Double[] d = {5.5, 1.3, 8.8};
Arrays.sort(d, Collections.reverseOrder());
System.out.println(Arrays.toString(d));

Collections.reverseOrder() doesn't work on primitives, but Double, Integer etc works with Collections.reverseOrder()

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

Multiple modals overlay

Check count of modals and add the value to backdrop as z-index

    var zIndex = 1500 + ($('.modal').length*2) + 1;
    this.popsr.css({'z-index': zIndex});

    this.popsr.on('shown.bs.modal', function () {
        $(this).next('.modal-backdrop').css('z-index', zIndex - 1);
    });

    this.popsr.modal('show');

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

How to check if object has any properties in JavaScript?

With jQuery you can use:

$.isEmptyObject(obj); // Returns: Boolean

As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).

With ECMAScript 5th Edition in modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;

Or plain old JavaScript:

var isEmpty = function(obj) {
               for(var p in obj){
                  return false;
               }
               return true;
            };

Apache 13 permission denied in user's home directory

Can't you set the Loglevel in httpd.conf to debug? (I'm using FreeBSD)

ee usr/local/etc/apache22/httpd.conf

change loglevel :

'LogLevel: Control the number of messages logged to the error_log. Possible values include: debug, info, notice, warn, error, crit, alert, emerg.'

Try changing to debug and re-checking the error log after that.

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

Using jQuery to center a DIV on the screen

Edit:

If the question taught me anything, it's this: don't change something that already works :)

I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:

.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper    {#position:absolute; #top:50%;
            display:table-cell; vertical-align:middle;}
.content   {#position:relative; #top:-50%;
            margin:0 auto; width:200px; border:1px solid orange;}

Fiddle: http://jsfiddle.net/S9upd/4/

I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.

Original:

Looks like I'm late to the party!

There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:

.container {
    position:absolute;
    left: 50%;
    top: 50%;
    overflow:visible;
}
.content {
    position:relative;
    margin:-50% 50% 50% -50%;
}

Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/

Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.


Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:

<table class="super-centered"><tr><td>
    <div class="content">
        <p>I am centered like a boss!</p>
    </div>
</td></tr></table>

And than the content's position is fine-tuned with good old margin:0 auto;:

.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}?

Working fiddle as promised: http://jsfiddle.net/teDQ2/

C++ convert hex string to signed integer

use std::stringstream

unsigned int x;   
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;

the following example produces -65538 as its result:

#include <sstream>
#include <iostream>

int main() {
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "fffefffe";
    ss >> x;
    // output it as a signed type
    std::cout << static_cast<int>(x) << std::endl;
}

In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string

So, the simplest answer for newer code would probably look like this:

std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);

NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).

It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.

Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:

try {
    unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
    // whatever you want to do...
}

If you don't feel like using boost, here's a light version of lexical cast which does no error checking:

template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
    T2 out;
    std::stringstream ss;
    ss << in;
    ss >> out;
    return out;
}

which you can use like this:

// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef"); 

iPad WebApp Full Screen in Safari

Looks like most of the answers on this thread have not kept up. iOS Safari on iPads have fullscreen support now and it's very easy to implement using javascript.

Here's my full article on how to implement fullscreen capability on your web app.

SSH to Vagrant box in Windows?

note too: when the login as: prompt appears, enter 'vagrant' as the user name (without quotes). – Snorkpete Jun 28 '12 at 14:14

Or you can go to Category->Connection->Rlogin and set the 'Auto-login username' field to 'Vagrant'.

Save the session.

Is it possible to run one logrotate check manually?

Created a shell script to solve the problem.

https://antofthy.gitlab.io/software/#logrotate_one

This script will run just the single logrotate sub-configuration file found in "/etc/logrotate.d", but include the global settings from in the global configuration file "/etc/logrotate.conf". You can also use other otpions for testing it...

For example...

  logrotate_one -d syslog

Getting the class name of an instance?

Good question.

Here's a simple example based on GHZ's which might help someone:

>>> class person(object):
        def init(self,name):
            self.name=name
        def info(self)
            print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__)
>>> bob = person(name='Robert')
>>> bob.info()
My name is Robert, I am a person

What are the differences between Visual Studio Code and Visual Studio?

For Unity3D users ...

  • VSCode is incredibly faster than VS. Files open instantly from Unity. VS is very slow. VSCode launches instantly. VS takes forever to launch.

  • VS can literally compile code, build apps and so on, it's a huge IDE like Unity itself or XCode. VSCode is indeed "just" a full-featured text editor. VSCode is NOT a compiler (far less a huge, build-everything system that can literally create apps and software of all types): VSCode is literally "just a text editor".

  • With VSCode, you DO need to install the "Visual Studio Code" package. (Not to be confused with the "Visual Studio" package.) (It seems to me that VS works fine without the VS package, but, with VS Code, you must install Unity's VSCode package.)

enter image description here

  • When you first download and install VSCode, simply open any C# file on your machine. It will instantly prompt you to install the needed C# package. This is harmless and easy.

  • Unfortunately VSCode generally has only one window! You cannot, really, easily drag files to separate windows. If this is important to you, you may need to go with VS.

  • The biggest problem with VS is that the overall concept of settings and preferences are absolutely horrible. In VS, it is all-but impossible to change the font, etc. In contrast, VSCode has FANTASTIC preferences - dead simple, never a problem.

  • As far as I can see, every single feature in VS which you use in Unity is present in VSCode. (So, code coloring, jump to definitions, it understands/autocompletes every single thing in Unity, it opens from Unity, double clicking something in the Unity console opens the file to that line, etc etc)

  • If you are used to VS. And you want to change to VSCode. It's always hard changing editors, they are so intimate, but it's pretty similar; you won't have a big heartache.

In short if you're a VS for Unity3D user,

and you're going to try VSCode...

  1. VSCode is on the order of 19 trillion times faster in every way. It will blow your mind.

  2. It does seem to have every feature.

  3. Basically VS is the world's biggest IDE and application building system: VSCode is just an editor. (Indeed, that's exactly what you want with Unity, since Unity itself is the IDE.)

  4. Don't forget to just click to install the relevant Unity package.

If I'm not mistaken, there is no reason whatsoever to use VS with Unity.

Unity is an IDE so you just need a text editor, and that is what VSCode is. VSCode is hugely better in both speed and preferences. The only possible problem - multiple-windows are a bit clunky in VSCode!

That horrible "double copy" problem in VS ... solved!

If you are using VS with Unity. There is an infuriating problem where often VS will try to open twice, that is you will end up with two or more copies of VS running. Nobody has ever been able to fix this or figure out what the hell causes it. Fortunately, this problem never happens with VSCode.

Installing VSCode on a Mac - unbelievably easy.

There are no installers, etc etc etc. On the download page, you download a zipped Mac app. Put it in the Applications folder and you're done.

Folding! (Mac/Windows keystrokes are different)

Bizarrely there's no menu entry / docu whatsoever for folding, but here are the keys:

https://stackoverflow.com/a/30077543/294884

Setting colors and so on in VSCode - the critical tips

Particularly for Mac users who may find the colors strange:

Priceless post #1:

https://stackoverflow.com/a/45640244/294884

Priceless post #2:

https://stackoverflow.com/a/63303503/294884

Meta files ...

To keep the "Explorer" list of files on the left tidy, in the Unity case:

enter image description here

Transport endpoint is not connected

I get this error from the sshfs command from Fedora 17 linux to debian linux on the Mindstorms EV3 brick over the LAN and through a wireless connection.

Bash command:

el@defiant /mnt $ sshfs [email protected]:/root -p 22 /mnt/ev3
fuse: bad mount point `/mnt/ev3': Transport endpoint is not connected

This is remedied with the following command and trying again:

fusermount -u /mnt/ev3

These additional sshfs options prevent the above error from concurring:

sudo sshfs -d -o allow_other -o reconnect -o ServerAliveInterval=15 [email protected]:/var/lib/redmine/plugins /mnt -p 12345 -C

In order to use allow_other above, you need to uncomment the last line in /etc/fuse.conf:

# Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#
#mount_max = 1000

# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.
#
user_allow_other

Source: http://slopjong.de/2013/04/26/sshfs-transport-endpoint-is-not-connected/

Python, add items from txt file into a list

f = open('file.txt','r')

for line in f:
    myNames.append(line.strip()) # We don't want newlines in our list, do we?

SmartGit Installation and Usage on Ubuntu

You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).

To add the PPA run:

sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update

To install smartgit (after adding the PPA) run:

sudo apt-get install smartgit

To install smartgithg (after adding the PPA) run:

sudo apt-get install smartgithg

This should add a menu option for you

For more information, see Eugene San PPA.

This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release

How to parse XML using shellscript?

Here's a solution using xml_grep (because xpath wasn't part of our distributable and I didn't want to add it to all production machines)...

If you are looking for a specific setting in an XML file, and if all elements at a given tree level are unique, and there are no attributes, then you can use this handy function:

# File to be parsed
xmlFile="xxxxxxx"

# use xml_grep to find settings in an XML file
# Input ($1): path to setting
function getXmlSetting() {

    # Filter out the element name for parsing
    local element=`echo $1 | sed 's/^.*\///'`

    # Verify the element is not empty
    local check=${element:?getXmlSetting invalid input: $1}

    # Parse out the CDATA from the XML element
    # 1) Find the element (xml_grep)
    # 2) Remove newlines (tr -d \n)
    # 3) Extract CDATA by looking for *element> CDATA <element*
    # 4) Remove leading and trailing spaces
    local getXmlSettingResult=`xml_grep --cond $1 $xmlFile 2>/dev/null | tr -d '\n' | sed -n -e "s/.*$element>[[:space:]]*\([^[:space:]].*[^[:space:]]\)[[:space:]]*<\/$element.*/\1/p"`

    # Return the result
    echo $getXmlSettingResult
}

#EXAMPLE
logPath=`getXmlSetting //config/logs/path`
check=${logPath:?"XML file missing //config/logs/path"}

This will work with this structure:

<config>
  <logs>
     <path>/path/to/logs</path>
  <logs>
</config>

It will also work with this (but it won't keep the newlines):

<config>
  <logs>
     <path>
          /path/to/logs
     </path>
  <logs>
</config>

If you have duplicate <config> or <logs> or <path>, then it will only return the last one. You can probably modify the function to return an array if it finds multiple matches.

FYI: This code works on RedHat 6.3 with GNU BASH 4.1.2, but I don't think I'm doing anything particular to that, so should work everywhere.

NOTE: For anybody new to scripting, make sure you use the right types of quotes, all three are used in this code (normal single quote '=literal, backward single quote `=execute, and double quote "=group).

Initializing an Array of Structs in C#

You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;

    readonly MyStruct[] MyArray = new MyStruct[]{
      new MyStruct{ label = "a", id = 1},
      new MyStruct{ label = "b", id = 5},
      new MyStruct{ label = "c", id = 1}
    };

FirstOrDefault returns NullReferenceException if no match is found

FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null. Thats the reason for the exception.

So you just have to check for null first:

string displayName = null;
var keyValue = Dictionary
    .FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue  != null)
{
    displayName = keyValue.Value.DisplayName;
} 

But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue> is used to find a value by the key. Maybe you should refactor it.

Another option is to provide a default value with DefaultIfEmpty:

string displayName = Dictionary
    .Where(kv => kv.Value.ID == long.Parse(options.ID))
    .Select(kv => kv.Value.DisplayName)   // not a problem even if no item matches
    .DefaultIfEmpty("--Option unknown--") // or no argument -> null
    .First();                             // cannot cause an exception

getResources().getColor() is deprecated

I found that the useful getResources().getColor(R.color.color_name) is deprecated.

It is not deprecated in API Level 21, according to the documentation.

It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor() that takes the color resource ID and a Resources.Theme object) is only available in the M Developer Preview.

Hence, right now, continue using the single-parameter getColor() method. Later this year, consider using the two-parameter getColor() method on Android M devices, falling back to the deprecated single-parameter getColor() method on older devices.

How to change default text color using custom theme?

    <style name="Mytext" parent="@android:style/TextAppearance.Medium"> 
    <item name="android:textSize">20sp</item> 
    <item name="android:textColor">@color/white</item> 
    <item name="android:textStyle">bold</item>
    <item name="android:typeface">sans</item>
</style>

try this one ...

How to assign bean's property an Enum value in Spring config file?

You can write Bean Editors (details are in the Spring Docs) if you want to add further value and write to custom types.

Reading json files in C++

storing peoples like this

{"Anna" : { 
  "age": 18,
  "profession": "student"},
"Ben" : {
  "age" : "nineteen",
  "profession": "mechanic"}
 }

will cause problems, particularly if differents peoples have same name..

rather use array storing objects like this

{
  "peoples":[
       { 
           "name":"Anna",  
           "age": 18,
           "profession": "student"
       },
       {
           "name":"Ben",
           "age" : "nineteen",
           "profession": "mechanic"
       } 
  ]
}

like this, you can enumerates objects, or acces objects by numerical index. remember that json is storage structure, not dynamically sorter or indexer. use data stored in json to build indexes as you need and acces data.

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

How do I convert a Django QuerySet into list of dicts?

Use the .values() method:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

Note: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

C# Iterate through Class properties

You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.

For a hint, you could possibly do something like:

Record record = new Record();

PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
    property.SetValue(record, value);
}

Where value is the value you're wanting to write in (so from your resultItems array).

Does PHP have threading?

I have a PHP threading class that's been running flawlessly in a production environment for over two years now.

EDIT: This is now available as a composer library and as part of my MVC framework, Hazaar MVC.

See: https://git.hazaarlabs.com/hazaar/hazaar-thread

How to create a custom string representation for a class object?

If you have to choose between __repr__ or __str__ go for the first one, as by default implementation __str__ calls __repr__ when it wasn't defined.

Custom Vector3 example:

class Vector3(object):
    def __init__(self, args):
        self.x = args[0]
        self.y = args[1]
        self.z = args[2]

    def __repr__(self):
        return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)

    def __str__(self):
        return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)

In this example, repr returns again a string that can be directly consumed/executed, whereas str is more useful as a debug output.

v = Vector3([1,2,3])
print repr(v)    #Vector3([1,2,3])
print str(v)     #x:1, y:2, z:3

Media Queries: How to target desktop, tablet, and mobile?

Media queries for common device breakpoints

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

How do I set a cookie on HttpClient's HttpRequestMessage

After spending hours on this issue, none of the answers above helped me so I found a really useful tool.

Firstly, I used Telerik's Fiddler 4 to study my Web Requests in details

Secondly, I came across this useful plugin for Fiddler:

https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode

It will just generate the C# code for you. An example was:

        var uriBuilder = new UriBuilder("test.php", "test");
        var httpClient = new HttpClient();


        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());



        httpRequestMessage.Headers.Add("Host", "test.com");
        httpRequestMessage.Headers.Add("Connection", "keep-alive");
     //   httpRequestMessage.Headers.Add("Content-Length", "138");
        httpRequestMessage.Headers.Add("Pragma", "no-cache");
        httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
        httpRequestMessage.Headers.Add("Origin", "test.com");
        httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
    //    httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
        httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
        httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
        httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");


        var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;

        var httpContent = httpResponseMessage.Content;
        string result = httpResponseMessage.Content.ReadAsStringAsync().Result;

Note that I had to comment out two lines as this plugin is not totally perfect yet but it did the job nevertheless.

DISCLAIMER: I am not associated or endorsed by either Telerik or the plugin's author in anyway.

What is the difference between JDK and JRE?

The answer above (by Pablo) is very right. This is just additional information.

The JRE is, as the name implies, an environment. It's basically a bunch of directories with Java-related files, to wit:

  • bin/ contains Java's executable programs. The most important is java (and for Windows, javaw as well), which launches the JVM. There are some other utilities here as well, such as keytool and policytool.
  • conf/ holds user-editable configuration files for Java experts to play with.
  • lib/ has a large number of supporting files: some .jars, configuration files, property files, fonts, translations, certs, etc. – all the "trimmings" of Java. The most important is modules, a file that contains the .class files of the Java standard library.
  • At a certain level, the Java standard library needs to call into native code. For this purpose, the JRE contains some .dll (Windows) or .dylib (macOS) or .so (Linux) files under bin/ or lib/ with supporting, system-specific native binary code.

The JDK is also a set of directories. It is a superset of the JRE, with some additions:

  • bin/ has been enlarged with development tools. The most important of them is javac; others include jar, javadoc and jshell.
  • jmods/, which holds JMOD files for the standard library, has been added. These files allow the standard library to be used with jlink.

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

laravel foreach loop in controller

Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:

$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();

Further you may also make sure if $products has data:

if($product) {
    return View:make('viewname')->with('products', $products);
}

Then in the view:

foreach ($products as $product) {
    // If Product has sku (collection object, probably related models)
    foreach ($product->sku as $sku) {
        // Code Here        
    }
}

List files with certain extensions with ls and grep

ls -R | findstr ".mp3"

ls -R => lists subdirectories recursively

horizontal scrollbar on top and bottom of table

Expanding on StanleyH's answer, and trying to find the minimum required, here is what I implemented:

JavaScript (called once from somewhere like $(document).ready()):

function doubleScroll(){
        $(".topScrollVisible").scroll(function(){
            $(".tableWrapper")
                .scrollLeft($(".topScrollVisible").scrollLeft());
        });
        $(".tableWrapper").scroll(function(){
            $(".topScrollVisible")
                .scrollLeft($(".tableWrapper").scrollLeft());
        });
}

HTML (note that the widths will change the scroll bar length):

<div class="topScrollVisible" style="overflow-x:scroll">
    <div class="topScrollTableLength" style="width:1520px; height:20px">
    </div>
</div>
<div class="tableWrapper" style="overflow:auto; height:100%;">
    <table id="myTable" style="width:1470px" class="myTableClass">
...
    </table>

That's it.

How to remove all subviews of a view in Swift?

EDIT: (thanks Jeremiah / Rollo)

By far the best way to do this in Swift for iOS is:

view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array

^^ These features are fun!

let funTimes = ["Awesome","Crazy","WTF"]
extension String { 
    func readIt() {
        print(self)
    }
}

funTimes.forEach({ $0.readIt() })

//// END EDIT

Just do this:

for view in self.view.subviews {
    view.removeFromSuperview()
}

Or if you are looking for a specific class

for view:CustomViewClass! in self.view.subviews {
        if view.isKindOfClass(CustomViewClass) {
            view.doClassThing()
        }
    }

Label axes on Seaborn Barplot

Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

UINavigationBar custom back button without title

This works, but it will remove the title of the previous item, even if you pop back to it:

self.navigationController.navigationBar.topItem.title = @"";

Just set this property on viewDidLoad of the pushed View Controller.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Turns out that I had this problem and it was because I used "tabs" to indent lines instead of spaces. Just posting, in case it helps anyone.

Image library for Python 3

Depending on what is needed, scikit-image may be the best choice, with manipulations going way beyond PIL and the current version of Pillow. Very well-maintained, at least as much as Pillow. Also, the underlying data structures are from Numpy and Scipy, which makes its code incredibly interoperable. Examples that pillow can't handle:

Region Adjacency Graph Merging

Radon Transform

Histogram of oriented gradients

Approximate and subdivide polygons

You can see its power in the gallery. This paper provides a great intro to it. Good luck!

What is a simple command line program or script to backup SQL server databases?

Eventual if you don't have a trusted connection as the –E switch declares

Use following command line

"[program dir]\[sql server version]\Tools\Binn\osql.exe" -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak'" -S [server] –U [login id] -P [password]

Where

[program dir] is the directory where the osql.exe exists

On 32bit OS c:\Program Files\Microsoft SQL Server\
On 64bit OS c:\Program Files (x86)\Microsoft SQL Server\

[sql server version] your sql server version 110 or 100 or 90 or 80 begin with the largest number

[server] your servername or server ip

[login id] your ms-sql server user login name

[password] the required login password

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

react button onClick redirect page

This can be done very simply, you don't need to use a different function or library for it.

onClick={event =>  window.location.href='/your-href'}