Programs & Examples On #Digits

Questions dealing with getting, manipulating, or changing the digits of numbers

Get number of digits with JavaScript

Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor(). Direct to the point check this out!

function digitCount ( num )
{
     return Math.floor( num.toString()).length;
}

 digitCount(2343) ;

// ES5+

 const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;

 console.log(digitCount2(3343))

Basically What's going on here. toString() and String() same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length.

Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs() in it;

Cheer You!

Gets last digit of a number

Use StringUtils, in case you need string result:

String last = StringUtils.right(number.toString(), 1);

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

How to tell if string starts with a number with Python?

You could use regular expressions.

You can detect digits using:

if(re.search([0-9], yourstring[:1])):
#do something

The [0-9] par matches any digit, and yourstring[:1] matches the first character of your string

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

Sum the digits of a number

Here is the best solution I found:

function digitsum(n) {
    n = n.toString();
    let result = 0;
    for (let i = 0; i < n.length; i++) {
        result += parseInt(n[i]);
    }
    return result;
}
console.log(digitsum(192));

C++ - how to find the length of an integer

Code for finding Length of int and decimal number:

#include<iostream>
    #include<cmath>
    using namespace std;
    int main()
    {
        int len,num;
        cin >> num;
        len = log10(num) + 1;
        cout << len << endl;
        return 0;
    }
    //sample input output
    /*45566
    5

    Process returned 0 (0x0)   execution time : 3.292 s
    Press any key to continue.
    */

How do I separate an integer into separate digits in an array in JavaScript?

let input = 12345664
const output = []
while (input !== 0) {
  const roundedInput = Math.floor(input / 10)
  output.push(input - roundedInput * 10)
  input = roundedInput
}
console.log(output)

in python how do I convert a single digit number into a double digits string?

Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.

My approach is to leave number as a number until the moment you want to convert it into string:

>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011

How to round a number to n decimal places in Java

Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so:

  Locale locale = Locale.ENGLISH;
  NumberFormat nf = NumberFormat.getNumberInstance(locale);
  // for trailing zeros:
  nf.setMinimumFractionDigits(2);
  // round to 2 digits:
  nf.setMaximumFractionDigits(2);

  System.out.println(nf.format(.99));
  System.out.println(nf.format(123.567));
  System.out.println(nf.format(123.0));

Will print in English locale (no matter what your locale is): 0.99 123.57 123.00

The example is taken from Farenda - how to convert double to String correctly.

Check if string contains only digits

String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false

Efficient way to determine number of digits in an integer

int x = 1000;
int numberOfDigits = x ? static_cast<int>(log10(abs(x))) + 1 : 1;

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Which characters need to be escaped when using Bash?

Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell should be escaped in Bash.

A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n. These are listed in the man bash pages under Quoting and echo.

Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.

The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.

One that has caught me out is !. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!" gives problems. Using single-quotes, as usual, removes the special meaning.

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

Compute mean and standard deviation by group for multiple variables in a data.frame

The updated dplyr solution, as for 2020

1: summarise_each_() is deprecated as of dplyr 0.7.0. and 2: funs() is deprecated as of dplyr 0.8.0.

ag.dplyr <- DF %>% group_by(ID) %>% summarise(across(.cols = everything(),list(mean = mean, sd = sd)))

How to show all privileges from a user in oracle?

There are various scripts floating around that will do that depending on how crazy you want to get. I would personally use Pete Finnigan's find_all_privs script.

If you want to write it yourself, the query gets rather challenging. Users can be granted system privileges which are visible in DBA_SYS_PRIVS. They can be granted object privileges which are visible in DBA_TAB_PRIVS. And they can be granted roles which are visible in DBA_ROLE_PRIVS (roles can be default or non-default and can require a password as well, so just because a user has been granted a role doesn't mean that the user can necessarily use the privileges he acquired through the role by default). But those roles can, in turn, be granted system privileges, object privileges, and additional roles which can be viewed by looking at ROLE_SYS_PRIVS, ROLE_TAB_PRIVS, and ROLE_ROLE_PRIVS. Pete's script walks through those relationships to show all the privileges that end up flowing to a user.

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

How do I save a String to a text file using Java?

In Java 7 you can do this:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403

BSTR to std::string (std::wstring) and vice versa

BSTR to std::wstring:

// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));

 
std::wstring to BSTR:

// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());

Doc refs:

  1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() const
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

How to convert current date to epoch timestamp?

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

So, you need to do below

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000

Get a resource using getResource()

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

adding 30 minutes to datetime php/mysql

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);

What are the rules for casting pointers in C?

When thinking about pointers, it helps to draw diagrams. A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

d in main is a pointer to c which is of type char. A char is one byte of memory, so when d is dereferenced, you get the value in that one byte of memory. In the diagram below, each cell represents one byte.

-+----+----+----+----+----+----+-
 |    | c  |    |    |    |    | 
-+----+----+----+----+----+----+-
       ^~~~
       | char
       d

When you cast d to int*, you're saying that d really points to an int value. On most systems today, an int occupies 4 bytes.

-+----+----+----+----+----+----+-
 |    | c  | ?1 | ?2 | ?3 |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       (int*)d

When you dereference (int*)d, you get a value that is determined from these four bytes of memory. The value you get depends on what is in these cells marked ?, and on how an int is represented in memory.

A PC is little-endian, which means that the value of an int is calculated this way (assuming that it spans 4 bytes): * ((int*)d) == c + ?1 * 28 + ?2 * 2¹6 + ?3 * 2²4. So you'll see that while the value is garbage, if you print in in hexadecimal (printf("%x\n", *n)), the last two digits will always be 35 (that's the value of the character '5').

Some other systems are big-endian and arrange the bytes in the other direction: * ((int*)d) == c * 2²4 + ?1 * 2¹6 + ?2 * 28 + ?3. On these systems, you'd find that the value always starts with 35 when printed in hexadecimal. Some systems have a size of int that's different from 4 bytes. A rare few systems arrange int in different ways but you're extremely unlikely to encounter them.

Depending on your compiler and operating system, you may find that the value is different every time you run the program, or that it's always the same but changes when you make even minor tweaks to the source code.

On some systems, an int value must be stored in an address that's a multiple of 4 (or 2, or 8). This is called an alignment requirement. Depending on whether the address of c happens to be properly aligned or not, the program may crash.

In contrast with your program, here's what happens when you have an int value and take a pointer to it.

int x = 42;
int *p = &x;
-+----+----+----+----+----+----+-
 |    |         x         |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       p

The pointer p points to an int value. The label on the arrow correctly describes what's in the memory cell, so there are no surprises when dereferencing it.

How do I make HttpURLConnection use a proxy?

This is fairly easy to answer from the internet. Set system properties http.proxyHost and http.proxyPort. You can do this with System.setProperty(), or from the command line with the -D syntax.

Show whitespace characters in Visual Studio Code

  1. Open User preferences. Keyboard Shortcut: CTR + SHIFT + P -> Preferences: Open User Settings;

  2. Insert in search field Whitespace, and select all parameter enter image description here

how to install python distutils

The simplest way to install setuptools when it isn't already there and you can't use a package manager is to download ez_setup.py and run it with the appropriate Python interpreter. This works even if you have multiple versions of Python around: just run ez_setup.py once with each Python.

Edit: note that recent versions of Python 3 include setuptools in the distribution so you no longer need to install separately. The script mentioned here is only relevant for old versions of Python.

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Garbage collector in Android

If you get an OutOfMemoryError then it's usually too late to call the garbage collector...

Here is quote from Android Developer:

Most of the time, garbage collection occurs because of tons of small, short-lived objects and some garbage collectors, like generational garbage collectors, can optimize the collection of these objects so that the application does not get interrupted too often. The Android garbage collector is unfortunately not able to perform such optimizations and the creation of short-lived objects in performance critical code paths is thus very costly for your application.

So to my understanding, there is no urgent need to call the gc. It's better to spend more effort in avoiding the unnecessary creation of objects (like creation of objects inside loops)

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Jquery: how to trigger click event on pressing enter key

_x000D_
_x000D_
     $('#Search').keyup(function(e)_x000D_
        {_x000D_
            if (event.keyCode === 13) {_x000D_
            e.preventDefault();_x000D_
            var searchtext = $('#Search').val();_x000D_
            window.location.href = "searchData.php?Search=" + searchtext + '&bit=1';_x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Using Excel OleDb to get sheet names IN SHEET ORDER

I don't see any documentation that says the order in app.xml is guaranteed to be the order of the sheets. It PROBABLY is, but not according to the OOXML specification.

The workbook.xml file, on the other hand, includes the sheetId attribute, which does determine the sequence - from 1 to the number of sheets. This is according to the OOXML specification. workbook.xml is described as the place where the sequence of the sheets is kept.

So reading workbook.xml after it is extracted form the XLSX would be my recommendation. NOT app.xml. Instead of docProps/app.xml, use xl/workbook.xml and look at the element, as shown here -

`

<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9303" /> 
  <workbookPr defaultThemeVersion="124226" /> 
- <bookViews>
  <workbookView xWindow="120" yWindow="135" windowWidth="19035" windowHeight="8445" /> 
  </bookViews>
- <sheets>
  <sheet name="By song" sheetId="1" r:id="rId1" /> 
  <sheet name="By actors" sheetId="2" r:id="rId2" /> 
  <sheet name="By pit" sheetId="3" r:id="rId3" /> 
  </sheets>
- <definedNames>
  <definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'By song'!$A$1:$O$59</definedName> 
  </definedNames>
  <calcPr calcId="145621" /> 
  </workbook>

`

SET NAMES utf8 in MySQL?

Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:

if (!$mysqli->set_charset("utf8")) 
 { printf("Can't set utf8: %s\n", $mysqli->error); }

or via procedure style mysqli_set_charset($db,"utf8")

How to access Winform textbox control from another class?

Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Cannot find module cv2 when using OpenCV

I solve it by running:

pip3 install opencv-python

What characters are valid for JavaScript variable names?

I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX as it's harder to break out of.

    function isValidVarName( name ) {
    try {
        return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
    } catch( e ) {
        return false;
    }
    return true;
}

// so we can see the test code
var _eval = eval;
window.eval = function(s) {
    console.log(s);
    return _eval(s);
}

console.log(isValidVarName('name'));
console.log(isValidVarName('$name'));
console.log(isValidVarName('not a name'));
console.log(isValidVarName('a:2,b'));
console.log(isValidVarName('"a string"'));

console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
console.log(isValidVarName('_;;;'));
console.log(isValidVarName('_=location="#!?"'));

console.log(isValidVarName('?'));
console.log(isValidVarName('HELLO'));
console.log(isValidVarName('????'));
console.log(isValidVarName('?????????????'));
console.log(isValidVarName('KingGeorge?'));
console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
console.log(isValidVarName('if'));

jQuery disable/enable submit button

It will work like this:

$('input[type="email"]').keyup(function() {
    if ($(this).val() != '') {
        $(':button[type="submit"]').prop('disabled', false);
    } else {
        $(':button[type="submit"]').prop('disabled', true);
    }
});

Make sure there is an 'disabled' attribute in your HTML

Pandas groupby: How to get a union of strings

If you'd like to overwrite column B in the dataframe, this should work:

    df = df.groupby('A',as_index=False).agg(lambda x:'\n'.join(x))

How to continue a Docker container which has exited

You can restart an existing container after it exited and your changes are still there.

docker start  `docker ps -q -l` # restart it in the background
docker attach `docker ps -q -l` # reattach the terminal & stdin

How can I merge the columns from two tables into one output?

When your are three tables or more, just add union and left outer join:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from 
(
    select category_id from a
    union
    select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

For me the solution was to download the Android SDK and launch adb devices which started the adb daemon.

jQuery changing style of HTML element

$('#navigation ul li').css({'display' : 'inline-block'});

It seems a typo there ...syntax mistake :))

How to call a parent method from child class in javascript?

There is a much easier and more compact solution for multilevel prototype lookup, but it requires Proxy support. Usage: SUPER(<instance>).<method>(<args>), for example, assuming two classes A and B extends A with method m: SUPER(new B).m().

function SUPER(instance) {
    return new Proxy(instance, {
        get(target, prop) {
            return Object.getPrototypeOf(Object.getPrototypeOf(target))[prop].bind(target);
        }
    });
}

Namenode not getting started

hadoop.tmp.dir in the core-site.xml is defaulted to /tmp/hadoop-${user.name} which is cleaned after every reboot. Change this to some other directory which doesn't get cleaned on reboot.

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.

Try

typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

postgres: upgrade a user to be a superuser?

alter user username superuser;

Convert XmlDocument to String

There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:

using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    xmlDoc.WriteTo(xmlTextWriter);
    xmlTextWriter.Flush();
    return stringWriter.GetStringBuilder().ToString();
}

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

RedirectToAction("actionName", "controllerName");

It has other overloads as well, please check up!

Also, If you are new and you are not using T4MVC, then I would recommend you to use it!

It gives you intellisence for actions,Controllers,views etc (no more magic strings)

Increasing the maximum number of TCP/IP connections in Linux

In an application level, here are something a developer can do:

From server side:

  1. Check if load balancer(if you have),works correctly.

  2. Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.

Eg: If you are using node server, u can use toobusy from npm. Implementation something like:

var toobusy = require('toobusy');
app.use(function(req, res, next) {
  if (toobusy()) res.send(503, "I'm busy right now, sorry.");
  else next();
});

Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html

We can do some work in client side too:

  1. Try to group calls in batch, reduce the traffic and total requests number b/w client and server.

  2. Try to build a cache mid-layer to handle unnecessary duplicates requests.

What is the difference between C# and .NET?

C# is a programming language, .NET is the framework that the language is built on.

Clear image on picturebox

You need the following:

pictbox.Image = null;
pictbox.update();

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

How to enable curl in xampp?

1) C:\Program Files\xampp\php\php.ini

2) Uncomment the following line on your php.ini file by removing the semicolon.

;extension=php_curl.dll

3) Restart your apache server.

Need table of key codes for android and presenter

Additionally, if you have the NDK installed, you can also find the listing in ${ndk_path}platforms\android-${api}\${architecture}\usr\include\android\keycodes.h.

I'm only mentioning it because I've found it simpler to navigate and read than the KeyEvent class or docs.

Hibernate: best practice to pull all lazy collections

Use Hibernate.initialize() within @Transactional to initialize lazy objects.

 start Transaction 
      Hibernate.initialize(entity.getAddresses());
      Hibernate.initialize(entity.getPersons());
 end Transaction 

Now out side of the Transaction you are able to get lazy objects.

entity.getAddresses().size();
entity.getPersons().size();

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

Import error: No module name urllib2

NOTE: urllib2 is no longer available in Python 3

You can try following code.

import urllib.request 
res = urllib.request.urlopen('url')
output = res.read()
print(output)

You can get more idea about urllib.request from this link.

Using :urllib3

import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'url')
print(r.status)
print( r.headers)
print(r.data)

Also if you want more details about urllib3. follow this link.

How to make child divs always fit inside parent div?

There are two techniques commonly used for this:

  1. Absolute Positioning
  2. Table Styles

Given the HTML you provided here is the solution using Absolute positioning:

_x000D_
_x000D_
body #one {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: auto;_x000D_
  height: auto;_x000D_
}_x000D_
body #two {_x000D_
  width: auto;  _x000D_
}_x000D_
body #three {_x000D_
  position: absolute;_x000D_
  top: 60px;_x000D_
  bottom: 0;_x000D_
  height: auto;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
html, body {width:100%;height:100%;margin:0;padding:0;}_x000D_
.border {border:1px solid black;}_x000D_
.margin { margin:5px;}_x000D_
#one {width:100%;height:100%;}_x000D_
#two {width:100%;height:50px;}_x000D_
#three {width:100px;height:100%;}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
 <div id="one" class="border">_x000D_
  <div id="two" class="border margin"></div>_x000D_
  <div id="three" class="border margin"></div>_x000D_
 </div>_x000D_
</body
_x000D_
_x000D_
_x000D_

You can always just use the table, tr, and td elements directly despite common criticisms as it will get the job done. If you prefer to use CSS there is no equivalent for colspan so you will likely end up with nested tables. Here is an example:

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
#one {_x000D_
  box-sizing: border-box;_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#two {_x000D_
    box-sizing: border-box;_x000D_
    display: table;_x000D_
    height: 50px;_x000D_
    padding: 5px;_x000D_
    width: 100%;_x000D_
}_x000D_
#three {_x000D_
  box-sizing: border-box;_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  padding-bottom: 60px;_x000D_
  padding-left: 5px;_x000D_
  _x000D_
}_x000D_
#four {_x000D_
  display: table-cell;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#five {_x000D_
  display: table-cell;_x000D_
  width: 100px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#six {_x000D_
  display: table-cell;  _x000D_
}
_x000D_
<html>_x000D_
 <div id="one">_x000D_
     <div id="two">_x000D_
            <div id="four"></div>_x000D_
        </div>_x000D_
        <div id="three">_x000D_
            <div id="five"></div>_x000D_
            <div id="six"></div>_x000D_
        </div>_x000D_
 </div>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

Powershell script to check if service is started, if not then start it

[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'

foreach($server in $servers)

{
    $srvc = Get-WmiObject -query "SELECT * FROM win32_service  WHERE   name LIKE '$service' " -computername $server  ;
    $res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;  
   $srvc.startservice() 
   $res
}

java.util.zip.ZipException: error in opening zip file

It could be related to log4j.

Do you have log4j.jar file in the websphere java classpath (as defined in the startup file) as well as the application classpath ?

If you do make sure that the log4j.jar file is in the java classpath and that it is NOT in the web-inf/lib directory of your webapp.


It can also be related with the ant version (may be not your case, but I do put it here for reference):

You have a .class file in your class path (i.e. not a directory or a .jar file). Starting with ant 1.6, ant will open the files in the classpath checking for manifest entries. This attempted opening will fail with the error "java.util.zip.ZipException"

The problem does not exist with ant 1.5 as it does not try to open the files. - so make sure that your classpath's do not contain .class files.


On a side note, did you consider having separate jars ?
You could in the manifest of your main jar, refer to the other jars with this attribute:

Class-Path: one.jar two.jar three.jar

Then, place all of your jars in the same folder.
Again, may be not valid for your case, but still there for reference.

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

How can I deploy an iPhone application from Xcode to a real iPhone device?

Free Provisioning after Xcode 7

In order to test your app on a real device rather than pay the Apple Developer fee (or jailbreak your device), you can use the new free provisioning that Xcode 7 and iOS 9 supports.

Here are the steps taken more or less from the documentation (which is pretty good, so give it a read):

1. Add your Apple ID in Xcode

Go to XCode > Preferences > Accounts tab > Add button (+) > Add Apple ID. See the docs for more help.

enter image description here

2. Click the General tab in the Project Navigator

enter image description here

3. Choose your Apple ID from the Team popup menu.

enter image description here

4. Connect your device and choose it in the scheme menu.

enter image description here

5. Click the Fix Issues button

enter image description here

If you get an error about the bundle name being invalid, change it to something unique.

6. Run your app

In Xcode, click the Build and run button.

enter image description here

7. Trust the app developer in the device settings

After running your app, you will get a security error because the app you want to run is not from the App Store.

enter image description here

On your device, go to Settings > General > Profile > your-Apple-ID-name > Trust your-Apple-ID-name > Trust.

8. Run your app on your device again.

That's it. You can now run your own (or any other apps that you have the source code for) without having to dish out the $99 dollars. Thank you, Apple, for finally allowing this.

PHPUnit assert that an exception was thrown?

If you're running on PHP 5.5+, you can use ::class resolution to obtain the name of the class with expectException/setExpectedException. This provides several benefits:

  • The name will be fully-qualified with its namespace (if any).
  • It resolves to a string so it will work with any version of PHPUnit.
  • You get code-completion in your IDE.
  • The PHP compiler will emit an error if you mistype the class name.

Example:

namespace \My\Cool\Package;

class AuthTest extends \PHPUnit_Framework_TestCase
{
    public function testLoginFailsForWrongPassword()
    {
        $this->expectException(WrongPasswordException::class);
        Auth::login('Bob', 'wrong');
    }
}

PHP compiles

WrongPasswordException::class

into

"\My\Cool\Package\WrongPasswordException"

without PHPUnit being the wiser.

Note: PHPUnit 5.2 introduced expectException as a replacement for setExpectedException.

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

I used quite @Eyuel method:

  • Download the nodejs msi from https://nodejs.org/en/#download
  • Download npm zip from github https://github.com/npm/npm
  • Extract the msi (with 7 Zip) in a directory "node"
  • Set the PATH environment variable to add the "node" directory
  • Extract the zip file from npm in a different directory (not under node directory)
  • CD to the npm directory and run the command node cli.js install npm -gf

Now you should have node + npm working, use theses commands to check: node --version and npm --version

Update 27/07/2017 : I noticed that the latest version of node 8.2.1 with the latest version of npm are quite different from the one I was using at the time of this answer. The install with theses versions won't work. It is working with node 6.11.1 and npm 5.2.3. Also if you are running with a proxy don't forget this to connect on internet :

How do search engines deal with AngularJS applications?

Update May 2014

Google crawlers now executes javascript - you can use the Google Webmaster Tools to better understand how your sites are rendered by Google.

Original answer
If you want to optimize your app for search engines there is unfortunately no way around serving a pre-rendered version to the crawler. You can read more about Google's recommendations for ajax and javascript-heavy sites here.

If this is an option I'd recommend reading this article about how to do SEO for Angular with server-side rendering.

I’m not sure what the crawler does when it encounters custom tags.

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

Java: using switch statement with enum under subclass

Change it to this:

switch (enumExample) {
    case VALUE_A: {
        //..
        break;
    }
}

The clue is in the error. You don't need to qualify case labels with the enum type, just its value.

Delegates in swift?

Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.

protocol YelpRequestDelegate {
    func getYelpData() -> AnyObject
    func processYelpData(data: NSData) -> NSData
}

class YelpAPI {
    var delegate: YelpRequestDelegate?

    func getData() {
        println("data being retrieved...")
        let data: AnyObject? = delegate?.getYelpData()
    }

    func processYelpData(data: NSData) {
        println("data being processed...")
        let data = delegate?.processYelpData(data)
    }
}

class Controller: YelpRequestDelegate {
    init() {
        var yelpAPI = YelpAPI()
        yelpAPI.delegate = self
        yelpAPI.getData()
    }
    func getYelpData() -> AnyObject {
        println("getYelpData called")
        return NSData()
    }
    func processYelpData(data: NSData) -> NSData {
        println("processYelpData called")
        return NSData()
    }
}

var controller = Controller()

What in layman's terms is a Recursive Function using PHP

Recursion is a fancy way of saying "Do this thing again until its done".

Two important things to have:

  1. A base case - You've got a goal to get to.
  2. A test - How to know if you've got to where you're going.

Imagine a simple task: Sort a stack of books alphabetically. A simple process would be take the first two books, sort them. Now, here comes the recursive part: Are there more books? If so, do it again. The "do it again" is the recursion. The "are there any more books" is the test. And "no, no more books" is the base case.

How to change working directory in Jupyter Notebook?

I have did it on windows machine. Detail mentioned below 1. From windows start menu open “Anaconda Prompt enter image description here 2. Find .jupyter folder file path . In command prompt just type enter image description here or enter image description here to find the .jupyter path

  1. After find the .jupyter folder, check there has “jupyter_notebook_config” file or not. If it is not there then run below command enter image description here After run the command it will create "jupyter_notebook_config.py"

if do not have administrator permission then Some time you could not find .jupyter folder . Still you can open config file from any of the text editor

  1. Open “jupyter_notebook_config.py” file from the the “.jypyter” folder.
  2. After open the file need to update the directory is use for notebooks and kernel. There are so many line in config file so find “#c.NotebookApp.notebook_dir” and update the path enter image description here After: enter image description here Save the file
  3. Now try to create or read some file from the location you set

XAMPP Start automatically on Windows 7 startup

In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:

  • open the directory where XAMPP is installed. By default it's installed at C:\xampp
  • Create Shortcut to the file xampp-control.exe, the XAMPP Control Panel
  • Paste it in

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

or

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

The XAMPP Control Panel should now auto-start whenever you reboot Windows.

Continue For loop

For i=1 To 10
    Do 
        'Do everything in here and

        If I_Dont_Want_Finish_This_Loop Then
            Exit Do
        End If 

        'Of course, if I do want to finish it,
        'I put more stuff here, and then...

    Loop While False 'quit after one loop
Next i

Difference in days between two dates in Java?

If you're looking for a solution that returns proper number or days between e.g. 11/30/2014 23:59 and 12/01/2014 00:01 here's solution using Joda Time.

private int getDayDifference(long past, long current) {
    DateTime currentDate = new DateTime(current);
    DateTime pastDate = new DateTime(past);
    return currentDate.getDayOfYear() - pastDate.getDayOfYear();
} 

This implementation will return 1 as a difference in days. Most of the solutions posted here calculate difference in milliseconds between two dates. It means that 0 would be returned because there's only 2 minutes difference between these two dates.

How to execute only one test spec with angular-cli

If you want to be able to control which files are selected from the command line, I managed to do this for Angular 7.

In summary, you need to install @angular-devkit/build-angular:browser and then create a custom webpack plugin to pass the test file regex through. For example:

angular.json - change the test builder from @angular-devkit/build-angular:browser and set a custom config file:

...

        "test": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js"
            },
...

extra-webpack.config.js - create a webpack configuration that reads the regex from the command line:

const webpack = require('webpack');
const FILTER = process.env.KARMA_FILTER;
let KARMA_SPEC_FILTER = '/.spec.ts$/';
if (FILTER) {
  KARMA_SPEC_FILTER = `/${FILTER}.spec.ts$/`;
}
module.exports = {
  plugins: [new webpack.DefinePlugin({KARMA_SPEC_FILTER})]
}

test.ts - edit the spec

...
// Then we find all the tests.
declare const KARMA_CONTEXT_SPEC: any;
const context = require.context('./', true, KARMA_CONTEXT_SPEC);

Then use as follows to override the default:

KARMA_FILTER='somefile-.*\.spec\.ts$' npm run test

I documented the backstory here, apologies in advance for types and mis-links. Credit to the answer above by @Aish-Anu for pointing me in the right direction.

How to extract filename.tar.gz file

The other scenario you mush verify is that the file you're trying to unpack is not empty and is valid.

In my case I wasn't downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.

Is there a Google Voice API?

There is a C# Google Voice API... there is limited documentation, however the download has an application that 'works' using the API that is included:

https://sourceforge.net/projects/gvoicedotnet/

Windows-1252 to UTF-8 encoding

You can change the encoding of a file with an editor such as notepad++. Just go to Encoding and select what you want.

I always prefer the Windows 1252

Retaining file permissions with Git

In pre-commit/post-checkout an option would be to use "mtree" (FreeBSD), or "fmtree" (Ubuntu) utility which "compares a file hierarchy against a specification, creates a specification for a file hierarchy, or modifies a specification."

The default set are flags, gid, link, mode, nlink, size, time, type, and uid. This can be fitted to the specific purpose with -k switch.

How to use ArrayAdapter<myClass>

Implement custom adapter for your class:

public class MyClassAdapter extends ArrayAdapter<MyClass> {

    private static class ViewHolder {
        private TextView itemView;
    }

    public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
        super(context, textViewResourceId, items);
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(this.getContext())
            .inflate(R.layout.listview_association, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        MyClass item = getItem(position);
        if (item!= null) {
            // My layout has only one TextView
                // do whatever you want with your string and long
            viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
        }

        return convertView;
    }
}

For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.

How do I get a YouTube video thumbnail from the YouTube API?

If you're using the public API, the best way to do it is using if statements.

If the video is public or unlisted, you set the thumbnail using the URL method. If the video is private you use the API to get the thumbnail.

<?php
    if($video_status == 'unlisted'){
        $video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
        $video_status = '<i class="fa fa-lock"></i>&nbsp;Unlisted';
    }
    elseif($video_status == 'public'){
        $video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
        $video_status = '<i class="fa fa-eye"></i>&nbsp;Public';
    }
    elseif($video_status == 'private'){
        $video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
        $video_status = '<i class="fa fa-lock"></i>&nbsp;Private';
    }

Axios get access to response header fields

There is one more hint that not in this conversation. for asp.net core 3.1 first add the key that you need to put it in the header, something like this:

Response.Headers.Add("your-key-to-use-it-axios", "your-value");

where you define the cors policy (normaly is in Startup.cs) you should add this key to WithExposedHeaders like this.

          services.AddCors(options =>
        {
        options.AddPolicy("CorsPolicy",
            builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .WithExposedHeaders("your-key-to-use-it-axios"));
        });
    }

you can add all the keys here. now in your client side you can easily access to the your-key-to-use-it-axios by using the response result.

          localStorage.setItem("your-key", response.headers["your-key-to-use-it-axios"]);

you can after use it in all the client side by accessing to it like this:

const jwt = localStorage.getItem("your-key")

How can I submit a POST form using the <a href="..."> tag?

You need to use javascript for this.

<form id="form1" action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

How to fix the height of a <div> element?

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

How can I convert a VBScript to an executable (EXE) file?

You can do this with PureBasic and MsScriptControl

All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below

InitScriptControl()
SCtr_AddCode("MsgBox 1")

How to download a file over HTTP?

In 2012, use the python requests library

>>> import requests
>>> 
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760

You can run pip install requests to get it.

Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.


2015-12-30

People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including tqdm:

from tqdm import tqdm
import requests

url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)

with open("10MB", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

This is essentially the implementation @kvance described 30 months ago.

Problems with entering Git commit message with Vim

I am assuming you are using msys git. If you are, the editor that is popping up to write your commit message is vim. Vim is not friendly at first. You may prefer to switch to a different editor. If you want to use a different editor, look at this answer: How do I use Notepad++ (or other) with msysgit?

If you want to use vim, type i to type in your message. When happy hit ESC. Then type :wq, and git will then be happy.

Or just type git commit -m "your message here" to skip the editor altogether.

Excel VBA Run Time Error '424' object required

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

I'm assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

How can I reload .emacs after changing it?

Others already answered your question as stated, but I find that I usually want to execute the lines that I just wrote. for that, CtrlAltx in the lisp works just fine.

Edit and Continue: "Changes are not allowed when..."

VS2019 - ASP.NET Forms In my case was Tools - Options - Windows Forms Designer - "Optimized Code Generation" <- to false

Multiplying Two Columns in SQL Server

Syntax:

SELECT <Expression>[Arithmetic_Operator]<expression>...
 FROM [Table_Name] 
 WHERE [expression];
  1. Expression : Expression made up of a single constant, variable, scalar function, or column name and can also be the pieces of a SQL query that compare values against other values or perform arithmetic calculations.
  2. Arithmetic_Operator : Plus(+), minus(-), multiply(*), and divide(/).
  3. Table_Name : Name of the table.

Multiline editing in Visual Studio Code

(Windows 10 pro x64) Here have some ways!

  1. Alt + click

  2. Alt + Ctrl + up/down

  3. Keybindings: Ctrl + click (??? it doesn't work!)

Enter image description here

Basic HTML - how to set relative path to current folder?

Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.

<a href=".">Link to this folder</a>

How to write one new line in Bitbucket markdown?

I was facing the same issue in bitbucket, and this worked for me:

line1
##<2 white spaces><enter>
line2

What is the purpose of flush() in Java streams?

Streams are often accessed by threads that periodically empty their content and, for example, display it on the screen, send it to a socket or write it to a file. This is done for performance reasons. Flushing an output stream means that you want to stop, wait for the content of the stream to be completely transferred to its destination, and then resume execution with the stream empty and the content sent.

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Fatal error: Call to undefined function imap_open() in PHP

During migration from Ubuntu 12.04 to 14.04 I stumbled over this as well and wanted to share that as of Ubuntu 14.04 LTS the IMAP extension seems no longer to be loaded per default.

Check to verify if the extension is installed:

dpkg -l | grep php5-imap

should give a response like this:

ii  php5-imap       5.4.6-0ubuntu5   amd64        IMAP module for php5

if not, install it.

To actually enable the extension

cd /etc/php5/apache2/conf.d
ln -s ../../mods-available/imap.ini 20-imap.ini
service apache2 restart

should fix it for apache. For CLI do the same in /etc/php5/cli/conf.d

Getting Excel to refresh data on sheet from within VBA

The following lines will do the trick:

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True  

Edit: The .Calculate() method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the .CalculateFull() method, but it may work.

NHibernate.MappingException: No persister for: XYZ

I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.

My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.

            OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
            OBJEKTE res = await _objRepo.UpdateAsync(t);

If inparam would go straight to UpdateAsync() it cannot find a matching persistor.

It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:

t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}

inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}

The fun thing though is that the source of inparam is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.

ALTER COLUMN in sqlite

While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:

PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;

You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

For example:

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT 
NULL);**  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
Error: BOOKS.publication_date may not be NULL  
sqlite> **PRAGMA writable_schema = 1;**  
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT 
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**  
sqlite> **PRAGMA writable_schema = 0;**  
sqlite> **.q**  

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
sqlite> **.q**  

REFERENCES FOLLOW:


pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

ALTER TABLE SYNTAX

Read response body in JAX-RS client from a post request

Try this:

String output = response.getEntity(String.class);

EDIT

Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use

String output = response.readEntity(String.class);

How do I unbind "hover" in jQuery?

Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):

$("#myElement").unbind('mouseenter mouseleave');

As of jQuery 1.7, you are also able use $.on() and $.off() for event binding, so to unbind the hover event, you would use the simpler and tidier:

$('#myElement').off('hover');

The pseudo-event-name "hover" is used as a shorthand for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using $.off() now allows you to drop both mouse events using the same shorthand.

Edit 2016:

Still a popular question so it's worth drawing attention to @Dennis98's point in the comments below that in jQuery 1.9+, the "hover" event was deprecated in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this:

$('#myElement').off('mouseenter mouseleave');

Updating address bar with new URL without hash or reloading the page

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);

Hiding user input on terminal in Linux script

Just supply -s to your read call like so:

$ read -s PASSWORD
$ echo $PASSWORD

WCF on IIS8; *.svc handler mapping doesn't work

I prefer to do this via a script nowadays

REM install the needed Windows IIS features for WCF
dism /Online /Enable-Feature /FeatureName:WAS-WindowsActivationService
dism /Online /Enable-Feature /FeatureName:WAS-ProcessModel
dism /Online /Enable-Feature /FeatureName:WAS-NetFxEnvironment
dism /Online /Enable-Feature /FeatureName:WAS-ConfigurationAPI
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45

REM Feature Install Complete
pause

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

/html/public/
- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

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

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

How do I shutdown, restart, or log off Windows via a bat file?

When remoted into a machine (target is Windows XP anyway; I am not sure about target Windows Vista), although Shutdown on the start menu is replaced by Disconnect Session or something like that, there should be one called 'Windows Security' which also does the same thing as Ctrl + Alt + End as pointed to by Owen.

How to hide TabPage from TabControl

Visiblity property has not been implemented on the Tabpages, and there is no Insert method also.

You need to manually insert and remove tab pages.

Here is a work around for the same.

http://www.dotnetspider.com/resources/18344-Hiding-Showing-Tabpages-Tabcontrol.aspx

Add target="_blank" in CSS

While waiting for the adoption of CSS3 targeting…

While waiting for the adoption of CSS3 targeting by the major browsers, one could run the following sed command once the (X)HTML has been created:

sed -i 's|href="http|target="_blank" href="http|g' index.html

It will add target="_blank" to all external hyperlinks. Variations are also possible.

EDIT

I use this at the end of the makefile which generates every web page on my site.

What is the difference between Integer and int in Java?

Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.

How to make bootstrap 3 fluid layout without horizontal scrollbar

Apply to the body seems to get rid of the horizontal scrollbar

overflow-x: hidden;

Multiple lines of text in UILabel

Method 1:

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

Now call simply like this

myLbl.lblFunction()//Replace your label name 

EX:

Import UIKit

class MyClassName: UIViewController {//For example this is your class. 

    override func viewDidLoad() {
    super.viewDidLoad()

        myLbl.lblFunction()//Replace your label name 

    }

}//After close of your class write this extension.

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

Method 2:

Programmatically

yourLabel.numberOfLines = 0
yourLabel.lineBreakMode = .byWordWrapping//If you want word wraping
//OR
yourLabel.lineBreakMode = .byCharWrapping//If you want character wraping

Method 3:

Through Story board

To display multiple lines set 0(Zero), this will display more than one line in your label.

If you want to display n lines, set n.

See below screen.

enter image description here

If you want to set minimum font size for label Click Autoshrink and Select Minimum Font Size option

See below screens

enter image description here

Here set minimum font size

EX: 9 (In this image)

If your label get more text at that time your label text will be shrink upto 9

enter image description here

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

Batch Extract path and filename from a variable

@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.


ceztko's test case (for reference)

@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Comment : please see comments.

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

How to host a Node.Js application in shared hosting

Connect with SSH and follow these instructions to install Node on a shared hosting

In short you first install NVM, then you install the Node version of your choice with NVM.

wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash

Your restart your shell (close and reopen your sessions). Then you

nvm install stable

to install the latest stable version for example. You can install any version of your choice. Check node --version for the node version you are currently using and nvm list to see what you've installed.

In bonus you can switch version very easily (nvm use <version>)

There's no need of PHP or whichever tricky workaround if you have SSH.

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

In javascript, how do you search an array for a substring match

Just search for the string in plain old indexOf

arr.forEach(function(a){
    if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
            console.log(a);
    }        
});

jQuery: serialize() form and other parameters

Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:

// ...

url: "MyUrl",       //  For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,  
data: 
    $('#myForm').serialize() +
    "&param1="xxx" +
    "&param2="33" +
    "&" + $.param({ paramArray: ["1","2","3"]}, true)
,             

// ...

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

How to find the extension of a file in C#?

You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.

[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.

How to read an entire file to a string using C#?

For the noobs out there who find this stuff fun and interesting, the fastest way to read an entire file into a string in most cases (according to these benchmarks) is by the following:

using (StreamReader sr = File.OpenText(fileName))
{
        string s = sr.ReadToEnd();
}
//you then have to process the string

However, the absolute fastest to read a text file overall appears to be the following:

using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
               //do what you have to here
        }
}

Put up against several other techniques, it won out most of the time, including against the BufferedReader.

How to retrieve Jenkins build parameters using the Groovy API?

The following can be used to retreive an environment parameter:

println System.getenv("MY_PARAM") 

What is the difference between <section> and <div>?

The <section> tag defines sections in a document, such as chapters, headers, footers, or any other sections of the document.

whereas:

The <div> tag defines a division or a section in an HTML document.

The <div> tag is used to group block-elements to format them with CSS.

How do I find the current directory of a batch file, and then use it for the path?

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt

And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.

public void Delete(int id)
{
 //some code here
}

If you hit with repeated 405 errors better reset the method signature to default as above and try.

The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under App_Start folder.

You may change the data type of the id though.

For example the below method should work just fine:

public void Delete(string id)
{
 //some code here
}

Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.

DELETE http://{url}/{action}/{id}

Example:

DELETE http://localhost/item/1

Hope it helps.

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

How do I use a char as the case in a switch-case?

public class SwitCase {
    public static void main (String[] args){
        String hello = JOptionPane.showInputDialog("Input a letter: ");
        char hi = hello.charAt(0); //get the first char.
        switch(hi){
            case 'a': System.out.println("a");
        }
    }   
}

Convert command line argument to string

You can create an std::string

#include <string>
#include <vector>
int main(int argc, char *argv[])
{
  // check if there is more than one argument and use the second one
  //  (the first argument is the executable)
  if (argc > 1)
  {
    std::string arg1(argv[1]);
    // do stuff with arg1
  }

  // Or, copy all arguments into a container of strings
  std::vector<std::string> allArgs(argv, argv + argc);
}

How do I install pip on macOS or OS X?

$ sudo port install py27-pip

Then update your PATH to include py27-pip bin directory (you can add this in ~/.bash_profile PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH

pip will be available in new terminal window.

Is it possible to implement a Python for range loop without an iterator variable?

If you really want to avoid putting something with a name (either an iteration variable as in the OP, or unwanted list or unwanted generator returning true the wanted amount of time) you could do it if you really wanted:

for type('', (), {}).x in range(somenumber):
    dosomething()

The trick that's used is to create an anonymous class type('', (), {}) which results in a class with empty name, but NB that it is not inserted in the local or global namespace (even if a nonempty name was supplied). Then you use a member of that class as iteration variable which is unreachable since the class it's a member of is unreachable.

Linker Error C++ "undefined reference "

This error tells you everything:

undefined reference toHash::insert(int, char)

You're not linking with the implementations of functions defined in Hash.h. Don't you have a Hash.cpp to also compile and link?

Installing a specific version of angular with angular cli

npm i -g @angular/[email protected]

x,y,z--> ur desired version number

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Will this answer Help you?
If you are receiving the following message in the EventViewer

The Module DLL aspnetcorev2.dll failed to load. The data is the error.

Then yes this will solve your problem


To check your event Viewer

  1. press Win+R and type: eventvwr, then press ENTER.
  2. On the left side of Windows Event Viewer click on Windows Logs -> Application.
  3. Now you need to find some ERRORS for source IIS-W3SVC-WP in the middle window.

if you receiving the previous message error then solution is :

Install Microsoft Visual C++ 2015 Redistributable 86x AND 64X (both of them)

Source

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);

Demo

How to send SMS in Java

TextMarks gives you access to its shared shortcode to send and receive text messages from your app via their API. Messages come from/to 41411 (instead of e.g. a random phone# and unlike e-mail gateways you have the full 160 chars to work with).

You can also tell people to text in your keyword(s) to 41411 to invoke various functionality in your app. There is a JAVA API client along with several other popular languages and very comprehensive documentation and technical support.

The 14 day free trial can be easily extended for developers who are still testing it out and building their apps.

Check it out here: TextMarks API Info

Install IPA with iTunes 11

In iTunes 11 you can go to the view menu, and "Show Sidebar", this will give you the sidebar, that you can drag 'n drop to.

You'll drag 'n drop to the open area that will be near the bottom of the sidebar (I'm typically doing this with both an IPA and a provisioning profile). After you do that, there will be an apps menu that appears in the sidebar with your app in it. Click on that, and you'll see your application in the main view. You can then drag your application from there to your device. Below, please find a video (it's private, so you'll need the URL) that outlines the steps visually: http://youtube.com/watch?v=0ACq4CRpEJ8&feature=youtu.be

json_decode to array

Please try this

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>

Check if string contains only digits

if you want to include float values also you can use the following code

theValue=$('#balanceinput').val();
var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 =  /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);

this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 , it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .

example :

 theValue=3.4; //isnum1=true , isnum2=true 
theValue=.4; //isnum1=true , isnum2=false 
theValue=3.; //isnum1=flase , isnum2=true 

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

How do I update the GUI from another thread?

just use synchronization context of ui

using System.Threading;

// ...

public partial class MyForm : Form
{
    private readonly SynchronizationContext uiContext;

    public MyForm()
    {
        InitializeComponent();
        uiContext = SynchronizationContext.Current; // get ui thread context
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(() =>
            {// set ui thread context to new thread context                            
             // for operations with ui elements to be performed in proper thread
             SynchronizationContext
                 .SetSynchronizationContext(uiContext);
             label1.Text = "some text";
            });
        t.Start();
    }
}

How to convert IPython notebooks to PDF and HTML?

For those who can't install wkhtmltopdf in their systems, one more method other than many already mentioned in the answers to this question is to simply download the file as an html file from the jupyter notebook, upload that to HTML to PDF, and download the converted pdf files from there.

Here you have your IPython notebook(.ipynb) converted to both PDF(.pdf) & HTML(.html) formats.

whitespaces in the path of windows filepath

(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.

    aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/"  --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '

    r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

ThreeJS: Remove object from scene

When you use : scene.remove(object); The object is removed from the scene, but the collision with it is still enabled !

To remove also the collsion with the object, you can use that (for an array) : objectsArray.splice(i, 1);

Example :

for (var i = 0; i < objectsArray.length; i++) {
//::: each object ::://
var object = objectsArray[i]; 
//::: remove all objects from the scene ::://
scene.remove(object); 
//::: remove all objects from the array ::://
objectsArray.splice(i, 1); 

}

Pretty printing JSON from Jackson 2.2's ObjectMapper

The jackson API has changed:

new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

The standard procedures are:

  1. Choose Project > app > scr > main
  2. Right click "res", choose "New" and choose "Android resource directory" Step 2
  3. In the opened dialog, at Resource Type choose "drawable" Step 3
  4. In the list Available qualifier choose Density, then click the right arrow at the middle. Step 4
  5. Choose the Density that you like then press OK Step 5

Angular cli generate a service and include the provider in one step

Add a service to the Angular 4 app using Angular CLI

An Angular 2 service is simply a javascript function along with it's associated properties and methods, that can be included (via dependency injection) into Angular 2 components.

To add a new Angular 4 service to the app, use the command ng g service serviceName. On creation of the service, the Angular CLI shows an error:

WARNING Service is generated but not provided, it must be provided to be used

To solve this, we need to provide the service reference to the src\app\app.module.ts inside providers input of @NgModule method.

Initially, the default code in the service is:


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

@Injectable()
export class ServiceNameService {

  constructor() { }

}

A service has to have a few public methods.

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

Just notice that if you work with Fragments using ViewPager, it's pretty easy. You only need to call this method: setOffscreenPageLimit().

Accordign to the docs:

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.

Similar issue here

Change color inside strings.xml

Just add your text between the font tags:

for blue color

<string name="hello_world"><font color='blue'>Hello world!</font></string>

or for red color

<string name="hello_world"><font color='red'>Hello world!</font></string>

Python dictionary get multiple values

No-one has mentioned the map function, which allows a function to operate element-wise on a list:

mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']

values = list( map(mydictionary.get, keys) )

# values = ['bear', 'castle']

How to install pip with Python 3?

This is the one-liner I copy-and-paste:

curl https://bootstrap.pypa.io/get-pip.py | python3

Alternate:

curl -L get-pip.io | python3

From Installing with get-pip.py:

To install pip, securely download get-pip.py by following this link: get-pip.py. Alternatively, use curl:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Then run the following command in the folder where you have downloaded get-pip.py:

python get-pip.py

Warning: Be cautious if you are using a Python install that is managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.

Execute PHP scripts within Node.js web server

I had the same question. I tried invoking php through the shell interface, and it produced the desired result:

var exec = require("child_process").exec;
app.get('/', function(req, res){exec("php index.php", function (error, stdout, stderr) {res.send(stdout);});});

I'm sure this is not high on the recommended practices list, but it seemed to do what I wanted. If, on the other hand, you don't want to execute PHP scripts directly from Node.js but want to relay them from another web server that does, this seems to do the trick:

var exec = require("child_process").exec;
app.get('/', function(req, res){exec("wget -q -O - http://localhost/", function (error, stdout, stderr) {res.send(stdout);});});

PHP ini file_get_contents external url

This will also give external links an absolute path without having to use php.ini

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
echo $result
?>

XAMPP Apache won't start

If you have skype shutdown and the problem still persists. Try this. It could be that apache is set to automatic on restart. Meaning apache is already using that port. Go to services in your XAMPP control and look for apache (whatever version you have). Look for startup type and double-click it to set it to manual.

Hope this works!

How do you kill a Thread in Java?

In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.

Often a volatile boolean field is used which the thread periodically checks and terminates when it is set to the corresponding value.

I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.

Certain blocking library methods support interruption.

Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:

public void run() {
   try {
      while (!interrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)
      /* Allow thread to exit */
   }
}

public void cancel() { interrupt(); }

Source code adapted from Java Concurrency in Practice. Since the cancel() method is public you can let another thread invoke this method as you wanted.

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Is there a concise way to iterate over a stream with indices in Java 8?

Here is code by AbacusUtil

Stream.of(names).indexed()
      .filter(e -> e.value().length() <= e.index())
      .map(Indexed::value).toList();

Disclosure: I'm the developer of AbacusUtil.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Is there a way to break a list into columns?

The CSS solution is: http://www.w3.org/TR/css3-multicol/

The browser support is exactly what you'd expect..

It works "everywhere" except Internet Explorer 9 or older: http://caniuse.com/multicolumn

ul {
    -moz-column-count: 4;
    -moz-column-gap: 20px;
    -webkit-column-count: 4;
    -webkit-column-gap: 20px;
    column-count: 4;
    column-gap: 20px;
}

See: http://jsfiddle.net/pdExf/

If IE support is required, you'll have to use JavaScript, for example:

http://welcome.totheinter.net/columnizer-jquery-plugin/

Another solution is to fallback to normal float: left for only IE. The order will be wrong, but at least it will look similar:

See: http://jsfiddle.net/NJ4Hw/

<!--[if lt IE 10]>
<style>
li {
    width: 25%;
    float: left
}
</style>
<![endif]-->

You could apply that fallback with Modernizr if you're already using it.

TypeError: unhashable type: 'list' when using built-in set function

Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.

Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.

result = sorted(set(map(tuple, my_list)), reverse=True)

Additional note: If a tuple contains a list, the tuple is still considered mutable.

Some examples:

>>> hash( tuple() )
3527539
>>> hash( dict() )

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    hash( list() )
TypeError: unhashable type: 'list'

Ruby: How to post a file via HTTP as multipart/form-data?

Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:

  def upload(photo)
    `curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`
  end

MySQL - Select the last inserted row easiest way

It would be best to have a TIMESTAMP column that defaults to CURRENT_TIMESTAMP .. it is the only true predictive behavior you can find here.

The second-best thing you can do is ORDER BY ID DESC LIMIT 1 and hope the newest ID is the largest value.

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end

Convert int to char in java

In java a char is an int. Your first snippet prints out the character corresponding to the value of 1 in the default character encoding scheme (which is probably Unicode). The Unicode character U+0001 is a non-printing character, which is why you don't see any output.

If you want to print out the character '1', you can look up the value of '1' in the encoding scheme you are using. In Unicode this is 49 (the same as ASCII). But this will only work for digits 0-9.

You might be better off using a String rather than a char, and using Java's built-in toString() method:

int a = 1;
String b = toString(a);
System.out.println(b);

This will work whatever your system encoding is, and will work for multi-digit numbers.

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

How do I get the last four characters from a string in C#?

string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)

How to get the server path to the web directory in Symfony2 from inside the controller?

For Symfony3 In your controller try

$request->server->get('DOCUMENT_ROOT').$request->getBasePath()

How to pass the password to su/sudo/ssh without overriding the TTY?

Hardcoding a password in an expect script is the same as having a passwordless sudo, actually worse, since sudo at least logs its commands.

Create Hyperlink in Slack

I am not sure if this is still bothering you but take a look at this page for slack text formatting:

https://api.slack.com/docs/message-formatting#linking_to_urls

For example using Python and the slack API:

from slackclient import SlackClient
slack_client = SlackClient(your_slack_token)
link_as_text_example = '<http://www.hyperlinkcode.com/|Hyperlink Code>'
slack_client.api_call("chat.postMessage", channel=channel_to_post, text=link_as_text_example , as_user=True)

You can also send a more advance JSON following the link: https://api.slack.com/docs/message-attachments

Splitting on first occurrence

You can also use str.partition:

>>> text = "123mango abcd mango kiwi peach"

>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')

>>> text.partition("mango")[-1]
' abcd mango kiwi peach'

>>> text.partition("mango")[-1].lstrip()  # if whitespace strip-ing is needed
'abcd mango kiwi peach'

The advantage of using str.partition is that it's always gonna return a tuple in the form:

(<pre>, <separator>, <post>)

So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.

Query to count the number of tables I have in MySQL

mysql> show tables;

it will show the names of the tables, then the count on tables.

source

How to import JSON File into a TypeScript file?

For Angular 7+,

1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):

declare module "*.json" {
    const value: any;
    export default value;
}

2) import and access JSON data either:

import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data.default);
    }

}

or:

import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data);
    }

}

How do I get the offset().top value of an element without using jQuery?

Seems you can just use the prop method on the angular element:

var top = $el.prop('offsetTop');

Works for me. Does anyone know any downside to this?

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

purple.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new tasks();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

How many files can I put in a directory?

For what it's worth, I just created a directory on an ext4 file system with 1,000,000 files in it, then randomly accessed those files through a web server. I didn't notice any premium on accessing those over (say) only having 10 files there.

This is radically different from my experience doing this on ntfs a few years back.

Is there a way I can capture my iPhone screen as a video?

For a nice looking screencast, have a look at SimFinger. You will still need a screen recoder such as Snapz Pro.

Is there a simple way to remove multiple spaces in a string?

import re

Text = " You can select below trims for removing white space!!   BR Aliakbar     "
  # trims all white spaces
print('Remove all space:',re.sub(r"\s+", "", Text), sep='') 
# trims left space
print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='') 
# trims right space
print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')  
# trims both
print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
# replace more than one white space in the string with one white space
print('Remove more than one space:',re.sub(' +', ' ',Text), sep='') 

Result:

Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar Remove leading space:You can select below trims for removing white space!! BR Aliakbar
Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar Remove more than one space: You can select below trims for removing white space!! BR Aliakbar

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

How to work with complex numbers in C?

Complex types are in the C language since C99 standard (-std=c99 option of GCC). Some compilers may implement complex types even in more earlier modes, but this is non-standard and non-portable extension (e.g. IBM XL, GCC, may be intel,... ).

You can start from http://en.wikipedia.org/wiki/Complex.h - it gives a description of functions from complex.h

This manual http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html also gives some info about macros.

To declare a complex variable, use

  double _Complex  a;        // use c* functions without suffix

or

  float _Complex   b;        // use c*f functions - with f suffix
  long double _Complex c;    // use c*l functions - with l suffix

To give a value into complex, use _Complex_I macro from complex.h:

  float _Complex d = 2.0f + 2.0f*_Complex_I;

(actually there can be some problems here with (0,-0i) numbers and NaNs in single half of complex)

Module is cabs(a)/cabsl(c)/cabsf(b); Real part is creal(a), Imaginary is cimag(a). carg(a) is for complex argument.

To directly access (read/write) real an imag part you may use this unportable GCC-extension:

 __real__ a = 1.4;
 __imag__ a = 2.0;
 float b = __real__ a;

Should I use <i> tag for icons instead of <span>?

I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i> tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.

It does make really bad practice because when I saw it I went through the template and changed all the <i> tags to <span style="font-style:italic"> instead and then wondered why the entire template looked strange.

This is the main reason it is a bad idea to use the <i> tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code

<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">

that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i> - and also it passes W3C standard.

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

Get text of label with jquery

It's simple, set a specific value for that label (XXXXXXX for example) and run it, open html source of output (in browser) and look for XXXXXXX, you will see something like this <span id="mylabel">XXXXXX</span> it's what you want, the ID of <span> (I think it's usually same as Label name in asp code) now you can get its value by innerHTML or another method in JQuery

How do you install an APK file in the Android emulator?

Late, but to be completed with options here: A handy tool to install any apk via gui to a running emulator is: http://apkinstaller.com

This can directly connect to a running instance via adb and can successfully install any kind of apk packages.

Maybe this is also helpful for other people. ;)

Could not commit JPA transaction: Transaction marked as rollbackOnly

Save sub object first and then call final repository save method.

@PostMapping("/save")
    public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
        Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
        if (existingShortcode != null) {
            result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
        }
        if (result.hasErrors()) {
            return "redirect:/shortcode/create";
        }
        **shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
        shortcodeService.save(shortcode);
        return "redirect:/shortcode/create?success";
    }

How to compare two dates?

datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2) will return True.

datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2) will return datetime.timedelta(-1).

datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2) will return datetime.timedelta(1).

see the docs.

jQuery Call to WebService returns "No Transport" error

Add this: jQuery.support.cors = true;

It enables cross-site scripting in jQuery (introduced after 1.4x, I believe).

We were using a really old version of jQuery (1.3.2) and swapped it out for 1.6.1. Everything was working, except .ajax() calls. Adding the above line fixed the problem.

Select all 'tr' except the first one

Though the question has a decent answer already, I just want to stress that the :first-child tag goes on the item type that represents the children.

For example, in the code:

<div id"someDiv">
     <input id="someInput1" /> 
     <input id="someInput2" />
     <input id="someInput2" />
</div

If you want to affect only the second two elements with a margin, but not the first, you would do:

#someDiv > input {
     margin-top: 20px;
}
#someDiv > input:first-child{
     margin-top: 0px;
}

that is, since the inputs are the children, you would place first-child on the input portion of the selector.

addEventListener for keydown on Canvas

encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.

Parsing xml using powershell

First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]

$doc = [xml]@'
<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>
'@

Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:

$doc.xml.Section.BEName

Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where

$doc.xml.Section.BEName | ? { $_.Status -eq 1 }

The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).

If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:

$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }

Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.

PHPExcel - set cell type before writing a value in it

The same way as you'd set the type (number format mask) after writing a value to it:

$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_GENERAL
    );

or

$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );

Though "Number" isn't a valid format mask.

You can find a list of pre-defined format masks in Classes/PHPExcel/Style/NumberFormat.php or set the value to any valid Excel number format masking string.

Is there a combination of "LIKE" and "IN" in SQL?

May be you think the combination like this:

SELECT  * 
FROM    table t INNER JOIN
(
  SELECT * FROM (VALUES('bla'),('foo'),('batz')) AS list(col)
) l ON t.column  LIKE '%'+l.Col+'%'

If you have defined full text index for your target table then you may use this alternative:

SELECT  * 
FROM    table t
WHERE CONTAINS(t.column, '"bla*" OR "foo*" OR "batz*"')

How do I get the color from a hexadecimal color code using .NET?

Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or      = (Color) ColorConverter.ConvertFromString("#FFCC66") ;

Aggregate / summarize multiple variables per group (e.g. sum, mean)

With the dplyr package, you can use summarise_all, summarise_at or summarise_if functions to aggregate multiple variables simultaneously. For the example dataset you can do this as follows:

library(dplyr)
# summarising all non-grouping variables
df2 <- df1 %>% group_by(year, month) %>% summarise_all(sum)

# summarising a specific set of non-grouping variables
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(x1, x2), sum)
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(-date), sum)

# summarising a specific set of non-grouping variables using select_helpers
# see ?select_helpers for more options
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(starts_with('x')), sum)
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(matches('.*[0-9]')), sum)

# summarising a specific set of non-grouping variables based on condition (class)
df2 <- df1 %>% group_by(year, month) %>% summarise_if(is.numeric, sum)

The result of the latter two options:

    year month        x1         x2
   <dbl> <dbl>     <dbl>      <dbl>
1   2000     1 -73.58134  -92.78595
2   2000     2 -57.81334 -152.36983
3   2000     3 122.68758  153.55243
4   2000     4 450.24980  285.56374
5   2000     5 678.37867  384.42888
6   2000     6 792.68696  530.28694
7   2000     7 908.58795  452.31222
8   2000     8 710.69928  719.35225
9   2000     9 725.06079  914.93687
10  2000    10 770.60304  863.39337
# ... with 14 more rows

Note: summarise_each is deprecated in favor of summarise_all, summarise_at and summarise_if.


As mentioned in my comment above, you can also use the recast function from the reshape2-package:

library(reshape2)
recast(df1, year + month ~ variable, sum, id.var = c("date", "year", "month"))

which will give you the same result.

ElasticSearch: Unassigned Shards, how to fix?

When dealing with corrupted shards you can set the replication factor to 0 and then set it back to the original value. This should clear up most if not all your corrupted shards and relocate the new replicas in the cluster.

Setting indexes with unassigned replicas to use a replication factor of 0:

curl -XGET http://localhost:9200/_cat/shards |\
  grep UNASSIGNED | grep ' r ' |\
  awk '{print $1}' |\
  xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
  -d '{ "index":{ "number_of_replicas": 0}}'

Setting them back to 1:

curl -XGET http://localhost:9200/_cat/shards |\
  awk '{print $1}' |\
  xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
  -d '{ "index":{ "number_of_replicas": 1}}'

Note: Do not run this if you have different replication factors for different indexes. This would hardcode the replication factor for all indexes to 1.

Best way to do nested case statement logic in SQL Server

You could try some sort of COALESCE trick, eg:

SELECT COALESCE(
  CASE WHEN condition1 THEN calculation1 ELSE NULL END,
  CASE WHEN condition2 THEN calculation2 ELSE NULL END,
  etc...
)

PHP Remove elements from associative array

for single array Item use reset($item)

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.