Programs & Examples On #Yui charts

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

How to split a string to 2 strings in C

char *line = strdup("user name"); // don't do char *line = "user name"; see Note

char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " ");   //sec_part points to "name"

Note: strtok modifies the string, so don't hand it a pointer to string literal.

Why dict.get(key) instead of dict[key]?

A gotcha to be aware of when using .get():

If the dictionary contains the key used in the call to .get() and its value is None, the .get() method will return None even if a default value is supplied.

For example, the following returns None, not 'alt_value' as may be expected:

d = {'key': None}
assert None is d.get('key', 'alt_value')

.get()'s second value is only returned if the key supplied is NOT in the dictionary, not if the return value of that call is None.

Passing event and argument to v-on in Vue.js

You can also do something like this...

<input @input="myHandler('foo', 'bar', ...arguments)">

Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

That's called a ternary operator and it's mainly used in place of an if-else statement.

In the example you gave it can be used to retrieve a value from an array given isset returns true

isset($_GET['something']) ? $_GET['something'] : ''

is equivalent to

if (isset($_GET['something'])) {
  $_GET['something'];
} else {
  '';
}

Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.

$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'

How to add colored border on cardview?

CardView extends FrameLayout, so it support foreground attribute. Using foreground attribute can also add border easily.

layout as follows:

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/link_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="@drawable/bg_roundrect_ripple_light_border"
    app:cardCornerRadius="23dp"
    app:cardElevation="0dp">
</androidx.cardview.widget.CardView>

bg_roundrect_ripple_light_border.xml

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

    <item>
        <shape android:shape="rectangle">
            <stroke
                android:width="0.5dp"
                android:color="#DDDDDD" />
            <corners android:radius="23dp" />
        </shape>
    </item>

    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <corners android:radius="23dp" />
            <solid android:color="@color/background" />
        </shape>
    </item>

</ripple>

Visual Studio Code Tab Key does not insert a tab

As of December 2018 on macOS Mojave 10.14.2 using VSCode 1.29.1 the default keybinding for 'Toggle Tab Key Moves Focus' is set to Command+Shift+M. If you got stuck with this, using that key combo should fix the issue.

Do Command+K Command+S to pull up the Hotkeys Settings and then search for Toggle Tab Key Moves Focus or editor.action.toggleTabFocusMode if you want to change the key combo.

Format ints into string of hex

''.join('%02x'%i for i in input)

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

It happens when your HTTP request's headers claim that the content is gzip encoded, but it isn't. Turn off gzip encoding setting or make sure the content is in fact encoded.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Setting a height on your body and html of 100% should fix you up. Without a defined height your content is not overflowing, so you will not get the desired behavior.

html, body {
  overflow-y:hidden;
  height:100%;
}

jwt check if token expired

You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I think you download the wrong version. I meet this problem just now, no method work after searching and searching. Finally, I found that maven I downloaded is Source zip archive. After I change to Binary zip archive, everything go to be fine.

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

How can I remove jenkins completely from linux

For sentOs, it's works for me At first stop service by sudo service jenkins stop

Than remove by sudo yum remove jenkins

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

Replace first occurrence of pattern in a string

There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.

Return values from the row above to the current row

Easier way for me is to switch to R1C1 notation and just use R[-1]C1 and switch back when done.

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

Will using 'var' affect performance?

I always use the word var in web articles or guides writings.

The width of the text editor of online article is small.

If I write this:

SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();

You will see that above rendered pre code text is too long and flows out of the box, it gets hidden. The reader needs to scroll to the right to see the complete syntax.

That's why I always use the keyword var in web article writings.

var coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();

The whole rendered pre code just fit within the screen.

In practice, for declaring object, I seldom use var, I rely on intellisense to declare object faster.

Example:

SomeCoolNamespace.SomeCoolObject coolObject = new SomeCoolNamespace.SomeCoolObject();

But, for returning object from a method, I use var to write code faster.

Example:

var coolObject = GetCoolObject(param1, param2);

Byte[] to InputStream or OutputStream

byte[] data = dbEntity.getBlobData();
response.getOutputStream().write();

I think this is better since you already have an existing OutputStream in the response object. no need to create a new OutputStream.

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

Notepad++ Multi editing

Notepad++ has a powerful regex engine, capable to search and replace patterns at will.

In your scenario:

  1. Click the menu item Search\Replace...

  2. Fill the 'Find what' field with the search pattern:

    ^(\d{4})\s+(\w{3})\s+(\w{3})$
    
  3. Fill the replace pattern:

    Insert into tbl (\1, \2) where clm = \3
    
  4. Click the Replace All button.

And that's it.

NotePad++ replace window screenshot

How to get records randomly from the oracle database?

We have to use some queries which will gives us random column from

table

We have Teacher table

Oracle Syntax

SELECT * FROM   
(
SELECT column_name FROM table_name  
ORDER BY dbms_random.value
)  
WHERE rownum = 1;

For better understanding follow screenshot

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How do I set an absolute include path in PHP?

hey all...i had a similar problem with my cms system. i needed a hard path for some security aspects. think the best way is like rob wrote. for quick an dirty coding think this works also..:-)

<?php
$path   = getcwd(); 
$myfile = "/test.inc.php";

/* 

getcwd () points to: /usr/srv/apache/htdocs/myworkingdir (as example)

echo ($path.$myfile);
would return...

/usr/srv/apache/htdocs/myworkingdir/test.inc.php

access outside your working directory is not allowed.
*/


includ_once ($path.$myfile);

//some code

?>

nice day strtok

Send array with Ajax to PHP script

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Disable vertical scroll bar on div overflow: auto

How about a shorthand notation?

{overflow: auto hidden;}

Python BeautifulSoup extract text between element

Learn more about how to navigate through the parse tree in BeautifulSoup. Parse tree has got tags and NavigableStrings (as THIS IS A TEXT). An example

from BeautifulSoup import BeautifulSoup 
doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
       '</html>']
soup = BeautifulSoup(''.join(doc))

print soup.prettify()
# <html>
#  <head>
#   <title>
#    Page title
#   </title>
#  </head>
#  <body>
#   <p id="firstpara" align="center">
#    This is paragraph
#    <b>
#     one
#    </b>
#    .
#   </p>
#   <p id="secondpara" align="blah">
#    This is paragraph
#    <b>
#     two
#    </b>
#    .
#   </p>
#  </body>
# </html>

To move down the parse tree you have contents and string.

  • contents is an ordered list of the Tag and NavigableString objects contained within a page element

  • if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]

For the above, that is to say you can get

soup.b.string
# u'one'
soup.b.contents[0]
# u'one'

For several children nodes, you can have for instance

pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']

so here you may play with contents and get contents at the index you want.

You also can iterate over a Tag, this is a shortcut. For instance,

for i in soup.body:
    print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

The thread has exited with code 0 (0x0) with no unhandled exception

I have also faced this problem and the solution is:

  1. open Solution Explore
  2. double click on Program.cs file

I added this code again and my program ran accurately:

Application.Run(new PayrollSystem()); 
//File name this code removed by me accidentally.

CSS @font-face not working with Firefox, but working with Chrome and IE

In my case, I sloved problem with inserting font-face style code

<style type="text/css">
@font-face { 
font-family: 'Amazone';font-style: normal; 
/*font-weight:100; -webkit-font-smoothing: antialiased; font-smooth:always;*/ 
src: local('Amazone'), url(font/Amazone.woff) format('woff');} 
</style>

direclty in header on your index.html or php page, in style tag. Works for me!

How to check for a Null value in VB.NET

I find the safest way is

If Not editTransactionRow.pay_id Is Nothing

It might read terribly, but the ISIL is actually very different from IsNot Nothing, and it doesn't try and evaluate the expression, which could give a null reference exception.

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

How can I URL encode a string in Excel VBA?

For the sake of bringing this up to date, since Excel 2013 there is now a built-in way of encoding URLs using the worksheet function ENCODEURL.

To use it in your VBA code you just need to call

EncodedUrl = WorksheetFunction.EncodeUrl(InputString)

Documentation

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

Force page scroll position to top at page refresh in HTML

The supercalifragilisticexpialidocious answer is:

add this at the top of your js file or script tag

document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

document.body.scrollTop = 0; // For Safari

Concat strings by & and + in VB.Net

& and + are both concatenation operators but when you specify an integer while using +, vb.net tries to cast "Hello" into integer to do an addition. If you change "Hello" with "123", you will get the result 124.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

$ seq 4
1
2
3
4

$ seq 2 5
2
3
4
5

$ seq 4 2 12
4
6
8
10
12

$ seq -w 4 2 12
04
06
08
10
12

$ seq -s, 4 2 12
4,6,8,10,12

How can I set Image source with base64

In case you prefer to use jQuery to set the image from Base64:

$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

How do I find out my python path using python?

sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
try:
    user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
    user_paths = []

Remove part of a string

Maybe the most intuitive solution is probably to use the stringr function str_remove which is even easier than str_replace as it has only 1 argument instead of 2.

The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern).

See example:

strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")

[1] "_1121" "_1432" "_1121"

What characters are allowed in an email address?

A good read on the matter.

Excerpt:

These are all valid email addresses!

"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/[email protected]
\[email protected]
!def!xyz%[email protected]
[email protected]

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

Best database field type for a URL

I don't know about other browsers, but IE7 has a 2083 character limit for HTTP GET operations. Unless any other browsers have lower limits, I don't see why you'd need any more characters than 2083.

How to print a dictionary line by line in Python?

Here is my solution to the problem. I think it's similar in approach, but a little simpler than some of the other answers. It also allows for an arbitrary number of sub-dictionaries and seems to work for any datatype (I even tested it on a dictionary which had functions as values):

def pprint(web, level):
    for k,v in web.items():
        if isinstance(v, dict):
            print('\t'*level, f'{k}: ')
            level += 1
            pprint(v, level)
            level -= 1
        else:
            print('\t'*level, k, ": ", v)

Get the last element of a std::string

In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!

How to convert an address to a latitude/longitude?

Nothing much new to add, but I have had a lot of real-world experience in GIS and geocoding from a previous job. Here is what I remember:

If it is a "every once in a while" need in your application, I would definitely recommend the Google or Yahoo Geocoding APIs, but be careful to read their licensing terms.

I know that the Google Maps API in general is easy to license for even commercial web pages, but can't be used in a pay-to-access situation. In other words you can use it to advertise or provide a service that drives ad revenue, but you can't charge people to acess your site or even put it behind a password system.

Despite these restrictions, they are both excellent choices because they frequently update their street databases. Most of the free backend tools and libraries use Census and TIGER road data that is updated infrequently, so you are less likely to successfully geocode addresses in rapidly growing areas or new subdivisions.

Most of the services also restrict the number of geocoding queries you can make per day, so it's OK to look up addresses of, say, new customers who get added to your database, but if you run a batch job that feeds thousands of addresses from your database into the geocoder, you're going to get shutoff.

I don't think this one has been mentioned yet, but ESRI has ArcWeb web services that include geocoding, although they aren't very cheap. Last time I used them it cost around 1.5cents per lookup, but you had to prepay a certain amount to get started. Again the major advantage is that the road data they use is kept up to date in a timely manner and you can use the data in commercial situations that Google doesn't allow. The ArcWeb service will also serve up high-resolution satellite and aerial photos a la Google Maps, again priced per request.

If you want to roll your own or have access to much more accurate data, you can purchase subscriptions to GIS data from companies like TeleAtlas, but that ain't cheap. You can buy only a state or county worth of data if your needs are extremely local. There are several tiers of data - GIS features only, GIS plus detailed streets, all that plus geocode data, all of that plus traffic flow/direction/speed limits for routing. Of course, the price goes up as you go up the tiers.

Finally, the Wikipedia article on Geocoding has some good information on the algorithms and techniques. Even if you aren't doing it in your own code, it's useful to know what kind of errors and accuracy you can expect from various kinds of data sources.

XOR operation with two strings in java

Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).

You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.

Does java.util.List.isEmpty() check if the list itself is null?

Yes, it will throw an Exception. maybe you are used to PHP code, where empty($element) does also check for isset($element)? In Java this is not the case.

You can memorize that easily because the method is directly called on the list (the method belongs to the list). So if there is no list, then there is no method. And Java will complain that there is no list to call this method on.

Javamail Could not convert socket to TLS GMail

above application.properties worked amazing for me:

spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com

AngularJs event to call after content is loaded

According to documentation of $viewContentLoaded, it supposed to work

Emitted every time the ngView content is reloaded.

$viewContentLoaded event is emitted that means to receive this event you need a parent controller like

<div ng-controller="MainCtrl">
  <div ng-view></div>
</div>

From MainCtrl you can listen the event

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

Check the Demo

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

How to calculate UILabel height dynamically?

In my case, I was using a fixed size header for each section but with a dynamically cell size in each header. The cell's height, depends on the label's height.

Working with:

tableView.estimatedRowHeight = SomeNumber
tableView.rowHeight = UITableViewAutomaticDimension

Works but when using:

tableView.reloadSections(IndexSet(integer: sender.tag) , with: .automatic)

when a lot of headers are not collapsed, creates a lot of bugs such as header duplication (header type x below the same type) and weird animations when the framework reloads with animation, even when using with type .none (FYI, a fixed header height and cell height works).

The solution is making the use of heightForRowAt callback and calculate the height of the label by your self (plus the animation looks a lot better). Remember that the height is being called first.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    let object = dataDetailsController.getRowObject(forIndexPath: indexPath)
    let label = UILabel(frame: tableView.frame)
    let font = UIFont(name: "HelveticaNeue-Bold", size: 25)
    label.text = object?.name
    label.font = font
    label.numberOfLines = 0
    label.textAlignment = .center
    label.sizeToFit()
    let size = label.frame.height
    return Float(size) == 0 ? 34 : size
}

How to call Stored Procedures with EntityFramework?

Based up the OP's original request to be able to called a stored proc like this...

using (Entities context = new Entities())
{
    context.MyStoreadProcedure(Parameters); 
}

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

What's your favorite "programmer" cartoon?

I wrote a production website that has the path /dev/random/ return 4 because of this comic.

int get_rand_number(){ return 4;}

ASP.net Repeater get current index, pointer, or counter

Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.

ASPX

<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
    <ItemTemplate>
        <div id="width:50%;height:30px;background:#0f0a0f;">
            <asp:Label ID="lblSr" runat="server" 
               style="width:30%;float:left;text-align:right;text-indent:-2px;" />
            <span 
               style="width:65%;float:right;text-align:left;text-indent:-2px;" >
            <%# Eval("Item") %>
            </span>
        </div>
    </ItemTemplate>
</asp:Repeater>

Code Behind:

    protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblSr") as Label;
        if (l != null)
            l.Text = e.Item.ItemIndex + 1+"";
    }

How to check whether a str(variable) is empty or not?

use "not" in if-else

x = input()

if not x:
   print("Value is not entered")
else:
   print("Value is entered")

How to automatically add user account AND password with a Bash script?

For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:

#!/bin/sh
echo -n "Enter username: "
read uname

echo -n "Enter password: "
read -s passwd

adduser "$uname"
echo $uname:$passwd | sudo chpasswd

gpasswd wheel -a $uname

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.

The one I've just found and I could absolutely recommend is The Uniform Server

It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.

They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!

Versions in Uniform Server as of today:

  • Apache 2.4.2
  • MySQL 5.5.23-community
  • PHP 5.4.1
  • phpMyAdmin 3.5.0

Versions in XAMPP as of today:

  • Apache 2.2.21
  • MySQL 5.5.16
  • PHP 5.3.8
  • phpMyAdmin 3.4.5

Install Android App Bundle on device

If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.

  1. Go to Edit Configurations
    enter image description here
  2. Select the Deploy dropdown and change it from "Default apk" to "APK from app bundle".enter image description here
  3. Apply the changes and then run it on the device connected. Build time will increase after making this change.

This will install an apk directly on the device connected from the aab.

html5 audio player - jquery toggle click play/pause?

if anyone else has problem with the above mentioned solutions, I ended up just going for the event:

$("#jquery_audioPlayer").jPlayer({
    ready:function () {
        $(this).jPlayer("setMedia", {
            mp3:"media/song.mp3"
        })
        ...
    pause: function () {
      $('#yoursoundcontrol').click(function () {
            $("#jquery_audioPlayer").jPlayer('play');
      })
    },
    play: function () {
    $('#yoursoundcontrol').click(function () {
            $("#jquery_audioPlayer").jPlayer('pause');
    })}
});

works for me.

Excel: VLOOKUP that returns true or false?

Just use a COUNTIF ! Much faster to write and calculate than the other suggestions.


EDIT:

Say you cell A1 should be 1 if the value of B1 is found in column C and otherwise it should be 2. How would you do that?

I would say if the value of B1 is found in column C, then A1 will be positive, otherwise it will be 0. Thats easily done with formula: =COUNTIF($C$1:$C$15,B1), which means: count the cells in range C1:C15 which are equal to B1.

You can combine COUNTIF with VLOOKUP and IF, and that's MUCH faster than using 2 lookups + ISNA. IF(COUNTIF(..)>0,LOOKUP(..),"Not found")

A bit of Googling will bring you tons of examples.

How to remove button shadow (android)

Using this as the background for your button might help, change the color to your needs

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_light" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_dark" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
</selector>

How to use a findBy method with comparative criteria

You have to use either DQL or the QueryBuilder. E.g. in your Purchase-EntityRepository you could do something like this:

$q = $this->createQueryBuilder('p')
          ->where('p.prize > :purchasePrize')
          ->setParameter('purchasePrize', 200)
          ->getQuery();

$q->getResult();

For even more complex scenarios take a look at the Expr() class.

Implementing IDisposable correctly

The following example shows the general best practice to implement IDisposable interface. Reference

Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory for two garbage cycles (Note: Read how Finalization works). Below example elaborate all above.

public class DisposeExample
{
    // A base class that implements IDisposable. 
    // By implementing IDisposable, you are announcing that 
    // instances of this type allocate scarce resources. 
    public class MyResource: IDisposable
    {
        // Pointer to an external unmanaged resource. 
        private IntPtr handle;
        // Other managed resource this class uses. 
        private Component component = new Component();
        // Track whether Dispose has been called. 
        private bool disposed = false;

        // The class constructor. 
        public MyResource(IntPtr handle)
        {
            this.handle = handle;
        }

        // Implement IDisposable. 
        // Do not make this method virtual. 
        // A derived class should not be able to override this method. 
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method. 
            // Therefore, you should call GC.SupressFinalize to 
            // take this object off the finalization queue 
            // and prevent finalization code for this object 
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios. 
        // If disposing equals true, the method has been called directly 
        // or indirectly by a user's code. Managed and unmanaged resources 
        // can be disposed. 
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed. 
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called. 
            if(!this.disposed)
            {
                // If disposing equals true, dispose all managed 
                // and unmanaged resources. 
                if(disposing)
                {
                    // Dispose managed resources.
                    component.Dispose();
                }

                // Call the appropriate methods to clean up 
                // unmanaged resources here. 
                // If disposing is false, 
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;

            }
        }

        // Use interop to call the method necessary 
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code. 
        // This destructor will run only if the Dispose method 
        // does not get called. 
        // It gives your base class the opportunity to finalize. 
        // Do not provide destructors in types derived from this class.
        ~MyResource()
        {
            // Do not re-create Dispose clean-up code here. 
            // Calling Dispose(false) is optimal in terms of 
            // readability and maintainability.
            Dispose(false);
        }
    }
    public static void Main()
    {
        // Insert code here to create 
        // and use the MyResource object.
    }
}

How to print formatted BigDecimal values?

BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

Good Linux (Ubuntu) SVN client

Anjuta has a built in SVN plugin which is integrated with the IDE.

How to get substring in C

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "SexDrugsRocknroll";
    char dest[5] = { 0 }; // 4 chars + terminator */
    int len = strlen(src);
    int i = 0;

    while (i*4 < len) {
        strncpy(dest, src+(i*4), 4);
        i++;

        printf("loop %d : %s\n", i, dest);
    }
}

How do I return multiple values from a function in C?

Create a struct and set two values inside and return the struct variable.

struct result {
    int a;
    char *string;
}

You have to allocate space for the char * in your program.

How to get Selected Text from select2 when using <input>

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via ajax

 $("#vendor-brands").select2({
   ajax: {
   url:site_url('general/get_brand_ajax_json'),
  dataType: 'json',
  delay: 250,
  data: function (params) {
  return {
    q: params.term, // search term
    page: params.page
  };
},
processResults: function (data, params) {
  // parse the results into the format expected by Select2
  // since we are using custom formatting functions we do not need to
  // alter the remote JSON data, except to indicate that infinite
  // scrolling can be used
  params.page = params.page || 1;

  return {
    results: data,
    pagination: {
      more: (params.page * 30) < data.total_count
    }
  };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom    formatter work
minimumInputLength: 1,
}).on("change", function(e) {


  var lastValue = $("#vendor-brands option:last-child").val();
  var lastText = $("#vendor-brands option:last-child").text();

  alert(lastValue+' '+lastText);
 });

Difference between Java SE/EE/ME?

Java SE is use for the desktop applications and simple core functions. Java EE is used for desktop, but also web development, networking, and advanced things.

Copy Paste in Bash on Ubuntu on Windows

You can use AutoHotkey (third party application), the command below is good with plain alphanumeric text, however some other characters like =^"%#! are mistyped in console like bash or cmd. (In any non-console window this command works fine with all characters.)

^+v::SendRaw %clipboard%

UIView with rounded corners and drop shadow?

Swift 4 Solution for making UICollectionViewCell round and adding Shadows, without any extensions and complications :)

Note: For simple views e.g Buttons. See the @suragch's Answer in this post. https://stackoverflow.com/a/34984063/7698092. Tested successfully for buttons

In case if any one still struggling to round the corners and add shadows at the same time. Although this solution works with UICollectionViewCell, it can be generalized to any view.

This technique worked for me without making any extensions and all the complicated stuff. I am working with storyBoard.

Technique

You must add a UIView (lets say it "containerView") inside your UICollectionViewCell in storyBoard and add all the required views (buttons, images etc) inside this containerView. See the Screenshot. Structure of Cell

Connect the outlet for containerView. Add following lines of code in CellforItemAtIndexPath delegate function.

//adds shadow to the layer of cell

cell.layer.cornerRadius = 3.0
    cell.layer.masksToBounds = false
    cell.layer.shadowColor = UIColor.black.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 0)
    cell.layer.shadowOpacity = 0.6

//makes the cell round 

let containerView = cell.containerView!
    containerView.layer.cornerRadius = 8
    containerView.clipsToBounds = true

Output

See the simulator Screenshot Rounded corners with Shadows (UICollectionViewCell)

How do I remove an item from a stl vector with a certain value?

If you have an unsorted vector, then you can simply swap with the last vector element then resize().

With an ordered container, you'll be best off with ?std::vector::erase(). Note that there is a std::remove() defined in <algorithm>, but that doesn't actually do the erasing. (Read the documentation carefully).

Python executable not finding libpython shared library

On Solaris 11

Use LD_LIBRARY_PATH_64 to resolve symlink to python libs.

In my case for python3.6 LD_LIBRARY_PATH didn't work but LD_LIBRARY_PATH_64 did.

Hope this helps.
Regards

Current Subversion revision command

There is also a more convenient (for some) svnversion command.

Output might be a single revision number or something like this (from -h):

  4123:4168     mixed revision working copy
  4168M         modified working copy
  4123S         switched working copy
  4123:4168MS   mixed revision, modified, switched working copy

I use this python code snippet to extract revision information:

import re
import subprocess

p = subprocess.Popen(["svnversion"], stdout = subprocess.PIPE, 
    stderr = subprocess.PIPE)
p.wait()
m = re.match(r'(|\d+M?S?):?(\d+)(M?)S?', p.stdout.read())
rev = int(m.group(2))
if m.group(3) == 'M':
    rev += 1

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

How exactly do you configure httpOnlyCookies in ASP.NET?

If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:

<httpCookies httpOnlyCookies="true"/>

bash: npm: command not found?

in redhat base OS (tested in centos 7)

yum install nodejs npm -y

in debian base OS

apt-get install -y npm    

Is there an auto increment in sqlite?

You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not.

If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column.

ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value.

Also, you should try to avoid:

 INSERT INTO people VALUES ("John", "Smith");

and use

 INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");

instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns).

How to change column order in a table using sql query in sql server 2005?

Example: Change position of field_priority after field_price in table status.

ALTER TABLE `status` CHANGE `priority` `priority` INT(11) NULL DEFAULT NULL AFTER `price`;

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

what is Promotional and Feature graphic in Android Market/Play Store?

In market client on phones at least featured apps with high ratings get to display the promotional graphic.

This is the one that shows up on top even before you start searching the market for a specific app.

See this answer from Android market forum.

Edited: One of the google employee gives some clarifications here

Update: Both links above are now broken but the detailed information can be found here

Selected applications have the ability to be featured atop their respective categories. This is not a guaranteed feature, but uploading promotional graphics is something that we recommend.

SQL Server Management Studio – tips for improving the TSQL coding process

Use a SELECT INTO query to quickly/easily make backup tables to work and experiment with.

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

For a CSS-only (and icon-free) solution using Bootstrap 3 I had to do a bit of fiddling based on Martin Wickman's answer above.

I didn't use the accordion-* notation because it's done with panels in BS3.

Also, I had to include in the initial HTML aria-expanded="true" on the item that's open at page load.

Here is the CSS I used.

.accordion-toggle:hover { text-decoration: none; }
.accordion-toggle:hover span, .accordion-toggle:hover strong { text-decoration: underline; }
.accordion-toggle:before { font-size: 25px; }
.accordion-toggle[data-toggle="collapse"]:before { content: "+"; margin-right: 0px; }
.accordion-toggle[aria-expanded="true"]:before { content: "-"; margin-right: 0px; }

Here is my sanitized HTML:

<div id="acc1">    
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" aria-expanded="true" data-parent="#acc1" href="#acc1-1">Title 1
                    </a>
            </span>
        </div>
        <div id=“acc1-1” class="panel-collapse collapse in">
            <div class="panel-body">
                Text 1
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#acc1” href=“#acc1-2”>Title 2
                    </a>
            </span>
        </div>
        <div id=“acc1-2” class="panel-collapse collapse">
            <div class="panel-body">
                Text 2                  
            </div>
        </div>
    </div>
</div>

How to change color of Android ListView separator line?

Use android:divider="#FF0000" and android:dividerHeight="2px" for ListView.

<ListView 
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0099FF"
android:dividerHeight="2px"/>

Background color for Tk in Python

config is another option:

widget1.config(bg='black')
widget2.config(bg='#000000')

or:

widget1.config(background='black')
widget2.config(background='#000000')

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

Just run below to your pem's

sudo chmod 600 /path/to/my/key.pem 

Anaconda site-packages

At least with Miniconda (I assume it's the same for Anaconda), within the environment folder, the packages are installed in a folder called \conda-meta.

i.e.

C:\Users\username\Miniconda3\envs\environmentname\conda-meta

If you install on the base environment, the location is:

C:\Users\username\Miniconda3\pkgs

check if jquery has been loaded, then load it if false

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

Search and replace a line in a file in Python

if you remove the indent at the like below, it will search and replace in multiple line. See below for example.

def replace(file, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    print fh, abs_path
    new_file = open(abs_path,'w')
    old_file = open(file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file)
    #Move new file
    move(abs_path, file)

How to download files using axios

The function to make the API call with axios:

  function getFileToDownload (apiUrl) {
     return axios.get(apiUrl, {
       responseType: 'arraybuffer',
       headers: {
         'Content-Type': 'application/json'
       }
     })
  }

Call the function and then download the excel file you get:

getFileToDownload('putApiUrlHere')
  .then (response => {
      const type = response.headers['content-type']
      const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'file.xlsx'
      link.click()
  })

Gradle project refresh failed after Android Studio update

  1. Close Android Studio
  2. Go to C:\Users\Username
  3. delete the .gradle folder

That's it you are done

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

your dependency based on data is trying to find their respective entities which one has not been created, comments the dependencies based on data and runs the app again.

<!-- <dependency> -->
        <!-- <groupId>org.springframework.boot</groupId> -->
        <!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
        <!-- </dependency> -->

Append integer to beginning of list in Python

None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

How does cellForRowAtIndexPath work?

1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view. But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question

2)NSIndexPath is essentially two things-

  • Your Section
  • Your row

Because your table might be divided to many sections and each with its own rows, this NSIndexPath will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.

It is called if you implement the UITableViewDataSource protocol in your view controller. A simpler way would be to add a UITableViewController class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).

As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.

Readably print out a python dict() sorted by key

Actually pprint seems to sort the keys for you under python2.5

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

But not always under python 2.4

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

Reading the source code of pprint.py (2.5) it does sort the dictionary using

items = object.items()
items.sort()

for multiline or this for single line

for k, v in sorted(object.items()):

before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.

So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.

Python3 Update

Pretty print by sorted keys (lambda x: x[0]):

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

Pretty print by sorted values (lambda x: x[1]):

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

Getting multiple values with scanf()

Passable for getting multiple values with scanf()

int r,m,v,i,e,k;

scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);

Make anchor link go some pixels above where it's linked to

Using only css and having no problems with covered and unclickable content before (the point of this is the pointer-events:none):

CSS

.anchored::before {
    content: '';
    display: block;
    position: relative;
    width: 0;
    height: 100px;
    margin-top: -100px;
}

HTML

<a href="#anchor">Click me!</a>
<div style="pointer-events:none;">
<p id="anchor" class="anchored">I should be 100px below where I currently am!</p>
</div>

OpenCV Python rotate image by X degrees around specific point

You can easily rotate the images using opencv python-

def funcRotate(degree=0):
    degree = cv2.getTrackbarPos('degree','Frame')
    rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
    rotated_image = cv2.warpAffine(original, rotation_matrix, (width, height))
    cv2.imshow('Rotate', rotated_image)

If you are thinking of creating a trackbar, then simply create a trackbar using cv2.createTrackbar() and the call the funcRotate()fucntion from your main script. Then you can easily rotate it to any degree you want. Full details about the implementation can be found here as well- Rotate images at any degree using Trackbars in opencv

Git: how to reverse-merge a commit?

To create a new commit that 'undoes' the changes of a past commit, use:

$ git revert <commit-hash>

It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).

If your previous commit is a merge commit you can run this command

$ git revert -m 1 <commit-hash>

See schacon.github.com/git/howto/revert-a-faulty-merge.txt for proper ways to re-merge an un-merged branch

How to use orderby with 2 fields in linq?

If you have two or more field to order try this:

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

You can add other fields with clasole "ThenBy"

How to read AppSettings values from a .json file in ASP.NET Core

The following works for console applications;

  1. Install the following NuGet packages (.csproj);

    <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
        <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
    </ItemGroup>
    
  2. Create appsettings.json at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".

  3. Sample configuration file:

    {
      "AppConfig": {
        "FilePath": "C:\\temp\\logs\\output.txt"
      }
    }
    
  4. Program.cs

    configurationSection.Key and configurationSection.Value will have config properties.

    static void Main(string[] args)
    {
        try
        {
    
            IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
            IConfigurationRoot configuration = builder.Build();
            // configurationSection.Key => FilePath
            // configurationSection.Value => C:\\temp\\logs\\output.txt
            IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
    
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    

ImportError: No module named google.protobuf

If you are a windows user and try to start py-script in cmd - don't forget to type python before filename.

python script.py

I have "No module named google" error if forget to type it.

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

How to type ":" ("colon") in regexp?

Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.

For more info about Java regular expressions, see the docs.

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

how to download file using AngularJS and calling MVC API?

per various post... you cannot trigger a download via XHR. I needed to implement condition for the download, so, My solution was:

//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
     //confirm that the ID is validated
     if (data.isIdConfirmed) {
         //get the token from the validation and issue another call
         //to trigger the download
         window.open('someapi/print/:someId?token='+ data.token);
     }
});

I wish that somehow, or someday the download can be triggered using XHR to avoid the second call. // _e

(WAMP/XAMP) send Mail using SMTP localhost

If any one of you are getting error like following after following answer given by Afwe Wef

 Warning: mail() [<a href='function.mail'>function.mail</a>]: SMTP server response:

 550 The address is not valid. in c:\wamp\www\email.php

Go to php.ini

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = [email protected]

Enter [email protected] as your email id which you used to configure the hMailserver in front of sendmail_from .

your problem will be solved.

Tested on Wamp server2.2(Apache 2.2.22, php 5.3.13) on windows 8

If you are also getting following error

"APPLICATION"   6364    "2014-03-24 13:13:33.979"   "SMTPDeliverer - Message 2: Relaying to host smtp.gmail.com."
"APPLICATION"   6364    "2014-03-24 13:13:34.415"   "SMTPDeliverer - Message 2: Message could not be delivered. Scheduling it for later delivery in 60 minutes."
"APPLICATION"   6364    "2014-03-24 13:13:34.430"   "SMTPDeliverer - Message 2: Message delivery thread completed."

You might have forgot to change the port from 25 to 465

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

Number of days between past date and current date in Google spreadsheet

If you are using the two formulas at the same time, it will not work... Here is a simple spreadsheet with it working: https://docs.google.com/spreadsheet/ccc?key=0AiOy0YDBXjt4dDJSQWg1Qlp6TEw5SzNqZENGOWgwbGc If you are still getting problems I would need to know what type of erroneous result you are getting.

Today() returns a numeric integer value: Returns the current computer system date. The value is updated when your document recalculates. TODAY is a function without arguments.

Python display text with font & color?

Yes. It is possible to draw text in pygame:

# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5

How to install popper.js with Bootstrap 4?

I had problems installing it Bootstrap as well, so I did:

Install popper.js: npm install popper.js@^1.12.3 --save

Install jQuery: npm install [email protected] --save

Then I had a high severity vulnerability message when installing [email protected] and got this message:

run npm audit fix to fix them, or npm audit for details

So I did npm audit fix, and after another npm audit fix --force it successfully installed!

How do you simulate Mouse Click in C#?

I have combined several sources to produce the code below, which I am currently using. I have also removed the Windows.Forms references so I can use it from console and WPF applications without additional references.

using System;
using System.Runtime.InteropServices;

public class MouseOperations
{
    [Flags]
    public enum MouseEventFlags
    {
        LeftDown = 0x00000002,
        LeftUp = 0x00000004,
        MiddleDown = 0x00000020,
        MiddleUp = 0x00000040,
        Move = 0x00000001,
        Absolute = 0x00008000,
        RightDown = 0x00000008,
        RightUp = 0x00000010
    }

    [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetCursorPos(int x, int y);      

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetCursorPos(out MousePoint lpMousePoint);

    [DllImport("user32.dll")]
    private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

    public static void SetCursorPosition(int x, int y) 
    {
        SetCursorPos(x, y);
    }

    public static void SetCursorPosition(MousePoint point)
    {
        SetCursorPos(point.X, point.Y);
    }

    public static MousePoint GetCursorPosition()
    {
        MousePoint currentMousePoint;
        var gotPoint = GetCursorPos(out currentMousePoint);
        if (!gotPoint) { currentMousePoint = new MousePoint(0, 0); }
        return currentMousePoint;
    }

    public static void MouseEvent(MouseEventFlags value)
    {
        MousePoint position = GetCursorPosition();

        mouse_event
            ((int)value,
             position.X,
             position.Y,
             0,
             0)
            ;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct MousePoint
    {
        public int X;
        public int Y;

        public MousePoint(int x, int y)
        {
            X = x;
            Y = y;
        }
    }
}

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

PHP code to get selected text of a combo box

Put whatever you want to send to PHP in the value attribute.

  <select id="cmbMake" name="Make" >
     <option value="">Select Manufacturer</option>
     <option value="--Any--">--Any--</option>
     <option value="Toyota">Toyota</option>
     <option value="Nissan">Nissan</option>
  </select>

You can also omit the value attribute. It defaults to using the text.

If you don't want to change the HTML, you can put an array in your PHP to translate the values:

$makes = array(2 => 'Toyota',
               3 => 'Nissan');

$maker = $makes[$_POST['Make']];

Difference Between Schema / Database in MySQL

Refering to MySql documentation,

CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.

background:none vs background:transparent what is the difference?

As aditional information on @Quentin answer, and as he rightly says, background CSS property itself, is a shorthand for:

background-color
background-image
background-repeat
background-attachment
background-position

That's mean, you can group all styles in one, like:

background: red url(../img.jpg) 0 0 no-repeat fixed;

This would be (in this example):

background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;

So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none; and all the others to the initial state (as they are not being declared).
So, background:none; is:

background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

Now, when you define only the color (in your case transparent) then you are basically saying:

background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

I repeat, as @Quentin rightly says the default transparent and none values in this case are the same, so in your example and for your original question, No, there's no difference between them.

But!.. if you say background:none Vs background:red then yes... there's a big diference, as I say, the first would set all properties to none/default and the second one, will only change the color and remains the rest in his default state.

So in brief:

Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.


Upd1: Initial value (aka default)

Initial value the concatenation of the initial values of its longhand properties:

background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent

See more background descriptions here


Upd2: Clarify better the background:none; specification.

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

In ASP.NET MVC 5 you could use the [DataType(DataType.MultilineText)] attribute. It will render a TextArea tag.

public class MyModel
{
    [DataType(DataType.MultilineText)]
    public string MyField { get; set; }
}

Then in the view if you need to specify the rows you can do it like this:

@Html.EditorFor(model => model.MyField, new { htmlAttributes = new { rows = 10 } })

Or just use the TextAreaFor with the right overload:

@Html.TextAreaFor(model => model.MyField, 10, 20, null)

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

How many spaces will Java String.trim() remove?

From the source code (decompiled) :

  public String trim()
  {
    int i = this.count;
    int j = 0;
    int k = this.offset;
    char[] arrayOfChar = this.value;
    while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
      ++j;
    while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
      --i;
    return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
  }

The two while that you can see mean all the characters whose unicode is below the space character's, at beginning and end, are removed.

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

Go to control panel, uninstall the java related stuff(close eclipse if opened), then re-install java and open eclipse, clean projects.

int object is not iterable?

One possible answer to OP-s question ("I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?") is to use built-in function divmod()

num = int(input('Enter a number: ')
nums_sum = 0

while num:
    num, reminder = divmod(num, 10)
    nums_sum += reminder

what is the difference between const_iterator and iterator?

if you have a list a and then following statements

list<int>::iterator it; // declare an iterator
    list<int>::const_iterator cit; // declare an const iterator 
    it=a.begin();
    cit=a.begin();

you can change the contents of the element in the list using “it” but not “cit”, that is you can use “cit” for reading the contents not for updating the elements.

*it=*it+1;//returns no error
    *cit=*cit+1;//this will return error

Gets byte array from a ByteBuffer in java

If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

Add onclick event to newly added element in JavaScript

JQuery:

elemm.attr("onclick", "yourFunction(this)");

or:

elemm.attr("onclick", "alert('Hi!')");

Resize to fit image in div, and center horizontally and vertically

Only tested in Chrome 44.

Example: http://codepen.io/hugovk/pen/OVqBoq

HTML:

<div>
<img src="http://lorempixel.com/1600/900/">
</div>

CSS:

<style type="text/css">
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    max-width: 100%;
    max-height: 100%;
}
</style>

Standardize data columns in R

Again, even though this is an old question, it is very relevant! And I have found a simple way to normalise certain columns without the need of any packages:

normFunc <- function(x){(x-mean(x, na.rm = T))/sd(x, na.rm = T)}

For example

x<-rnorm(10,14,2)
y<-rnorm(10,7,3)
z<-rnorm(10,18,5)
df<-data.frame(x,y,z)

df[2:3] <- apply(df[2:3], 2, normFunc)

You will see that the y and z columns have been normalised. No packages needed :-)

Video streaming over websockets using JavaScript

The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.

How to round the minute of a datetime object

Here is a simpler generalized solution without floating point precision issues and external library dependencies:

import datetime

def time_mod(time, delta, epoch=None):
    if epoch is None:
        epoch = datetime.datetime(1970, 1, 1, tzinfo=time.tzinfo)
    return (time - epoch) % delta

def time_round(time, delta, epoch=None):
    mod = time_mod(time, delta, epoch)
    if mod < (delta / 2):
       return time - mod
    return time + (delta - mod)

In your case:

>>> tm = datetime.datetime(2010, 6, 10, 3, 56, 23)
>>> time_round(tm, datetime.timedelta(minutes=10))
datetime.datetime(2010, 6, 10, 4, 0)

Converting file size in bytes to human-readable string

Here is a prototype to convert a number to a readable string respecting the new international standards.

There are two ways to represent big numbers: You could either display them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If you divide by 1000, you probably use the SI prefix names, if you divide by 1024, you probably use the IEC prefix names. The problem starts with dividing by 1024. Many applications use the SI prefix names for it and some use the IEC prefix names. The current situation is a mess. If you see SI prefix names you do not know whether the number is divided by 1000 or 1024

https://wiki.ubuntu.com/UnitsPolicy

http://en.wikipedia.org/wiki/Template:Quantities_of_bytes

Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
 return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
 d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
 +' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});

This function contains no loop, and so it's probably faster than some other functions.

Usage:

IEC prefix

console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

SI prefix

console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB 
//kB,MB,GB,TB,PB,EB,ZB,YB

i set the IEC as default because i always used binary mode to calculate the size of a file... using the power of 1024


If you just want one of them in a short oneliner function:

SI

function fileSizeSI(a,b,c,d,e){
 return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB

IEC

function fileSizeIEC(a,b,c,d,e){
 return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
 +' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB

Usage:

console.log(fileSizeIEC(7412834521));

if you have some questions about the functions just ask

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

Handling JSON Post Request in Go

Please use json.Decoder instead of json.Unmarshal.

func test(rw http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

Fast way to get the min/max values among properties of object

Using the lodash library you can write shorter

_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();

Printing PDFs from Windows Command Line

First response - wanted to finally give back to a helpful community...

Wanted to add this to the responses for people still looking for simple a solution. I'm using a free product by Foxit Software - FoxItReader.
Here is the link to the version that works with the silent print - newer versions the silent print feature is still not working. FoxitReader623.815_Setup

FOR %%f IN (*.pdf) DO ("C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe" /t %%f "SPST-SMPICK" %%f & del %%f) 

I simply created a command to loop through the directory and for each pdf file (FOR %%f IN *.pdf) open the reader silently (/t) get the next PDF (%%f) and send it to the print queue (SPST-SMPICK), then delete each PDF after I send it to the print queue (del%%f). Shashank showed an example of moving the files to another directory if that what you need to do

FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

Amazon S3 boto - how to create a folder?

It's really easy to create folders. Actually it's just creating keys.

You can see my below code i was creating a folder with utc_time as name.

Do remember ends the key with '/' like below, this indicates it's a key:

Key='folder1/' + utc_time + '/'

client = boto3.client('s3')
utc_timestamp = time.time()


def lambda_handler(event, context):

    UTC_FORMAT = '%Y%m%d'
    utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
    utc_time = utc_time.strftime(UTC_FORMAT)
    print 'start to create folder for => ' + utc_time

    putResponse = client.put_object(Bucket='mybucketName',
                                    Key='folder1/' + utc_time + '/')

    print putResponse

Shell script to set environment variables

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.

Meanwhile you have to use double quotes not single quote to expand variables:

export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"

Semicolons at the end of a single command are also unnecessary.

So far:

#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

For su you can run it with:

su -c 'sh /path/to/script.sh'

Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

Rails: Get Client IP address

For anyone interested and using a newer rails and the Devise gem: Devise's "trackable" option includes a column for current/last_sign_in_ip in the users table.

How to change the port number for Asp.Net core app?

Go to your program.cs file add UseUrs method to set your url, make sure you don't use a reserved url or port

 public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()

                // params string[] urls
                .UseUrls(urls: "http://localhost:10000")

                .Build();
    }

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Try going to IIS and checking to make sure the App Pool you are using is started. A lot of times, you will produce an error that shuts down the app pool. You just need to right click and Start and you should be good to go.

'foo' was not declared in this scope c++

In C++ you are supposed to declare functions before you can use them. In your code integrate is not declared before the point of the first call to integrate. The same applies to sum. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.

Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable, getSkewNormal, integrate etc. have no business being in header file.

Also SkewNormalEvalutatable e(); declaration in C++ declares a function e, not an object e as you seem to assume. The simple SkewNormalEvalutatable e; will declare an object initialized by default constructor.

Also, you receive the last parameter of integrate (and of sum) by value as an object of Evaluatable type. That means that attempting to pass SkewNormalEvalutatable as last argument of integrate will result in SkewNormalEvalutatable getting sliced to Evaluatable. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.

Clear icon inside input text

Here's a jQuery plugin (and a demo at the end).

http://jsfiddle.net/e4qhW/3/

I did it mostly to illustrate an example (and a personal challenge). Although upvotes are welcome, the other answers are well handed out on time and deserve their due recognition.

Still, in my opinion, it is over-engineered bloat (unless it makes part of a UI library).

How do I cancel a build that is in progress in Visual Studio?

For users of Lenovo Thinkpad T470s like me, you can simulate the break key by hitting Ctrl+Fn+P, which cancels the build.

Looping through a hash, or using an array in PowerShell

Here is another quick way, just using the key as an index into the hash table to get the value:

$hash = @{
    'a' = 1;
    'b' = 2;
    'c' = 3
};

foreach($key in $hash.keys) {
    Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}

How do I update Anaconda?

Here's the best practice (in my humble experience). Selecting these four packages will also update all other dependencies to the appropriate versions that will help you keep your environment consistent. The latter is a common problem others have expressed in earlier responses. This solution doesn't need the terminal.

Updating and upgrading Anaconda 3 or Anaconda 2 best practice

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

It seems that there is a typo, since 1104*1104*50=60940800 and you are trying to reshape to dimensions 50,1104,104. So it seems that you need to change 104 to 1104.

List file names based on a filename pattern and file content?

Assume LMN2011* files are inside /home/me but skipping anything in /home/me/temp or below:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'

Writing handler for UIAlertAction

create alert, tested in xcode 9

let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)

and the function

func finishAlert(alert: UIAlertAction!)
{
}

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

How to find whether a ResultSet is empty or not in Java?

If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?

    public void fetchData(ResultSet res, JTable table) throws SQLException{     
    ResultSetMetaData metaData = res.getMetaData();
    int fieldsCount = metaData.getColumnCount();
    for (int i = 1; i <= fieldsCount; i++)
        ((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
    if (!res.first())
        JOptionPane.showMessageDialog(rootPane, "no data!");
    else
        do {
            Vector<Object> v = new Vector<Object>();
            for (int i = 1; i <= fieldsCount; i++)              
                v.addElement(res.getObject(i));         
            ((DefaultTableModel) table.getModel()).addRow(v);
        } while (res.next());
        res.close();
}

jQuery get value of select onChange

You can try this (using jQuery)-

_x000D_
_x000D_
$('select').on('change', function()_x000D_
{_x000D_
    alert( this.value );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>_x000D_
    <option value="3">Option 3</option>_x000D_
    <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Or you can use simple Javascript like this-

_x000D_
_x000D_
function getNewVal(item)_x000D_
{_x000D_
    alert(item.value);_x000D_
}
_x000D_
<select onchange="getNewVal(this);">_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>_x000D_
    <option value="3">Option 3</option>_x000D_
    <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Displaying Windows command prompt output and redirecting it to a file

I was also looking for the same solution, after a little try, I was successfully able to achieve that in Command Prompt. Here is my solution :

@Echo off
for /f "Delims=" %%a IN (xyz.bat) do (
%%a > _ && type _ && type _ >> log.txt
)
@Echo on

It even captures any PAUSE command as well.

How to change font-size of a tag using inline css?

use this attribute in style

font-size: 11px !important;//your font size

by !important it override your css

Convert boolean result into number/integer

I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.

var j = bool & 1;

A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.

function toInt( val ) {
    return val & 1;
}

var j = toInt(bool);

Edit - September 10th, 2014

No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.

var j = boolValue === true ? 1 : 0;

Test for yourself: http://jsperf.com/boolean-int-conversion/2

In FireFox and Internet Explorer, using the version I posted is faster generally.

Edit - July 14th, 2017

Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.

Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.

Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
    return this & 1;
}});

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
BEGIN
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);

    SET @myID = SCOPE_IDENTITY();
END
GO

RegEx: Grabbing values between quotation marks

I liked Axeman's more expansive version, but had some trouble with it (it didn't match for example

foo "string \\ string" bar

or

foo "string1"   bar   "string2"

correctly, so I tried to fix it:

# opening quote
(["'])
   (
     # repeat (non-greedy, so we don't span multiple strings)
     (?:
       # anything, except not the opening quote, and not 
       # a backslash, which are handled separately.
       (?!\1)[^\\]
       |
       # consume any double backslash (unnecessary?)
       (?:\\\\)*       
       |
       # Allow backslash to escape characters
       \\.
     )*?
   )
# same character as opening quote
\1

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Strip all non-numeric characters from string in JavaScript

we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

1238

How to change TextField's height and width?

To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.

The cast to value type 'Int32' failed because the materialized value is null

Had this error message when I was trying to select from a view.

The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).

The column had to be Nullable type for it to work.

var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault();

Before view refresh:

public int SubscriberId { get; set; }

After view refresh:

public Nullable<int> SubscriberId { get; set; }

Deleting and adding the view back in EDMX worked.

Hope it helps someone.

How to set opacity to the background color of a div?

CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.

Working with select using AngularJS's ng-options

In CoffeeScript:

#directive
app.directive('select2', ->
    templateUrl: 'partials/select.html'
    restrict: 'E'
    transclude: 1
    replace: 1
    scope:
        options: '='
        model: '='
    link: (scope, el, atr)->
        el.bind 'change', ->
            console.log this.value
            scope.model = parseInt(this.value)
            console.log scope
            scope.$apply()
)
<!-- HTML partial -->
<select>
  <option ng-repeat='o in options'
          value='{{$index}}' ng-bind='o'></option>
</select>

<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>

<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>

Exporting result of select statement to CSV format in DB2

According to the docs, you want to export of type del (the default delimiter looks like a comma, which is what you want). See the doc page for more information on the EXPORT command.

How do I get the classes of all columns in a data frame?

Hello was looking for the same, and it could be also

unlist(lapply(mtcars,class))

How to redirect 404 errors to a page in ExpressJS?

You can put a middleware at the last position that throws a NotFound error,
or even renders the 404 page directly:

app.use(function(req,res){
    res.status(404).render('404.jade');
});

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I got the problem when instelled MS SQL 2012 with IngegrationService, the MS Visual Studio 2010 (Isolated) was installed from sql installer .

This VS returned error: Invalid license data. Reinstall is required.

I've fixed the problem by reinstalling SSDT with MS VS 2012 (Integrated) http://msdn.microsoft.com/en-us/jj650015

Laravel 5 Clear Views Cache

please try this below command :

sudo php artisan cache:clear

sudo php artisan view:clear

sudo php artisan config:cache

ClassCastException, casting Integer to Double

The code posted in the question is obviously not a a complete example (it's not adding anything to the arraylist, it's not defining i anywhere).

First as others have said you need to understand the difference between primitive types and the class types that box them. E.g. Integer boxes int, Double boxes double, Long boxes long and so-on. Java automatically boxes and unboxes in various scenarios (it used to be you had to box and unbox manually with library calls but that was deemed an ugly PITA).

http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

You can mostly cast from one primitive type to another (the exception being boolean) but you can't do the same for boxed types. To convert one boxed type to another is a bit more complex. Especially if you don't know the box type in advance. Usually it will involve converting via one or more primitive types.

So the answer to your question depends on what is in your arraylist, if it's just objects of type Integer you can do.

sum = ((double)(int)marks.get(i));

The cast to int will behind the scenes first cast the result of marks.get to Integer, then it will unbox that integer. We then use another cast to convert the primitive int to a primitive double. Finally the result will be autoboxed back into a Double when it is assigned to the sum variable. (asside, it would probablly make more sense for sum to be of type double rather than Double in most cases).

If your arraylist contains a mixture of types but they all implement the Number interface (Integer, Short, Long, Float and Double all do but Character and Boolean do not) then you can do.

sum = ((Number)marks.get(i)).doubleValue();

If there are other types in the mix too then you might need to consider using the instanceof operator to identify them and take appropriate action.

Installing Java 7 on Ubuntu

Open Applicaction -> Accessories -> Terminal

Type commandline as below...

sudo apt-get install openjdk-7-jdk

Type commandline as below...

apt-cache search jdk

(Note: openjdk-7-jdk is symbolically used here. You can choose the JDK version as per your requirement.)

For "JAVA_HOME" (Environment Variable) type command as shown below, in "Terminal" using your installation path...

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk

(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)

For "PATH" (Environment Variable) type command as shown below, in "Terminal" using your installation path...

export PATH=$PATH:/usr/lib/jvm/java-7-openjdk/bin

(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)

Check for "open jdk" installation, just type command in "Terminal" as shown below

javac -version

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

Switch with if, else if, else, and loops inside case

In this case, I'd recommend using break labels.

http://www.java-examples.com/break-statement

This way you can specifically call it outside of the for loop.

How to use enums in C++

Much of this should give you compilation errors.

// note the lower case enum keyword
enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };

Now, Saturday, Sunday, etc. can be used as top-level bare constants,and Days can be used as a type:

Days day = Saturday;   // Days.Saturday is an error

And similarly later, to test:

if (day == Saturday)
    // ...

These enum values are like bare constants - they're un-scoped - with a little extra help from the compiler: (unless you're using C++11 enum classes) they aren't encapsulated like object or structure members for instance, and you can't refer to them as members of Days.

You'll have what you're looking for with C++11, which introduces an enum class:

enum class Days
{
    SUNDAY,
    MONDAY,
    // ... etc.
}

// ...

if (day == Days::SUNDAY)
    // ...

Note that this C++ is a little different from C in a couple of ways, one is that C requires the use of the enum keyword when declaring a variable:

// day declaration in C:
enum Days day = Saturday;

sass :first-child not working

I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

When should you NOT use a Rules Engine?

The one poit I've noticed to be "the double edged sword" is:

placing the logic in hands of non technical staff

I've seen this work great, when you have one or two multidisciplinary geniuses on the non technical side, but I've also seen the lack of technicity leading to bloat, more bugs, and in general 4x the development/maintenance cost.

Thus you need to consider your user-base seriously.

Request is not available in this context

When you have custom logging logic, it is rather annoying to be forced either not to log application_start or to have to let an exception occurs in the logger (even if handled).

It appears that rather than testing for Request availability, you can test for Handler availability: when there is no Request, it would be strange to still have a request handler. And testing for Handler does not raise that dreaded Request is not available in this context exception.

So you may change your code to:

var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)

Beware, in the context of a http module, Handler may not be defined though Request and Response are defined (I have seen that in BeginRequest event). So if you need request/response logging in a custom http module, my answer may not be suitable.

Does Enter key trigger a click event?

For ENTER key, why not use (keyup.enter):

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="values=box.value">
    <p>{{values}}</p>
  `
})
export class KeyUpComponent_v3 {
  values = '';
}

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

What is the difference between new/delete and malloc/free?

The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.

There are other differences:

  • new is type-safe, malloc returns objects of type void*

  • new throws an exception on error, malloc returns NULL and sets errno

  • new is an operator and can be overloaded, malloc is a function and cannot be overloaded

  • new[], which allocates arrays, is more intuitive and type-safe than malloc

  • malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized

  • malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types

Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.

Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.

What is the difference between '/' and '//' when used for division?

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

Get Folder Size from Windows Command Line

I solved similar problem. Some of methods in this page are slow and some are problematic in multilanguage environment (all suppose english). I found simple workaround using vbscript in cmd. It is tested in W2012R2 and W7.

>%TEMP%\_SFSTMP$.VBS ECHO/Set objFSO = CreateObject("Scripting.FileSystemObject"):Set objFolder = objFSO.GetFolder(%1):WScript.Echo objFolder.Size
FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%\_SFSTMP$.VBS') DO (SET "S_=%%?"&&(DEL %TEMP%\_SFSTMP$.VBS))

It set environment variable S_. You can, of course, change last line to directly display result to e.g.

FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%\_SFSTMP$.VBS') DO (ECHO "Size of %1 is %%?"&&(DEL %TEMP%\_SFSTMP$.VBS))

You can use it as subroutine or as standlone cmd. Parameter is name of tested folder closed in quotes.

Mongod complains that there is no /data/db folder

Tilo has the answer that worked for me up until THIS:

sudo chown -R 126:135 /data/db 

I had to use:

sudo chown -R $USER /data/db