Programs & Examples On #Terminal color

How to change the output color of echo in Linux

I have just amalgamated the good catches in all solutions and ended up with:

cecho(){
    RED="\033[0;31m"
    GREEN="\033[0;32m"
    YELLOW="\033[1;33m"
    # ... ADD MORE COLORS
    NC="\033[0m" # No Color

    printf "${!1}${2} ${NC}\n"
}

And you can just call it as:

cecho "RED" "Helloworld"

Eslint: How to disable "unexpected console statement" in Node.js?

Alternatively instead of turning 'no-console' off, you can allow. In the .eslintrc.js file put

  rules: {
    "no-console": [
     "warn",
     { "allow": ["clear", "info", "error", "dir", "trace", "log"] }
    ]
  }

This will allow you to do console.log and console.clear etc without throwing errors.

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

Eclipse will not start and I haven't changed anything

Removing workbench.xmi under workspace/.metadata/.plugins/org.eclipse.e4.workbench/ worked for me. It did not remove the existing projects.

How to assign pointer address manually in C programming language?

Like this:

void * p = (void *)0x28ff44;

Or if you want it as a char *:

char * p = (char *)0x28ff44;

...etc.

If you're pointing to something you really, really aren't meant to change, add a const:

const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;

...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Without any SMTP server sending mail,use this code for sending mail....

click below for mail sending code

Click here

listen guys first you can do this less secure your gmail account after send mail with your gmail account

You can use this php.ini setting

;smtp = smtp.gmail.com
;smtp-port = 25
;sendmail_from = my gmail is here

And sendmail.ini settings

smtp_server = smtp.gmail.com
smtp_port = 465
smtp_ssl = auto
auth_username = my gmail is here
auth_password = password
hostname = localhost

you can try this changes and i hope this code sent mail....

How to set a timeout on a http.request() in Node?

For me - here is a less confusing way of doing the socket.setTimeout

var request=require('https').get(
    url
   ,function(response){
        var r='';
        response.on('data',function(chunk){
            r+=chunk;
            });
        response.on('end',function(){
            console.dir(r);            //end up here if everything is good!
            });
        }).on('error',function(e){
            console.dir(e.message);    //end up here if the result returns an error
            });
request.on('error',function(e){
    console.dir(e);                    //end up here if a timeout
    });
request.on('socket',function(socket){
    socket.setTimeout(1000,function(){
        request.abort();                //causes error event ?
        });
    });

How to access the local Django webserver from outside world

If you are using Docker you need to make sure ports are exposed as well

Change language of Visual Studio 2017 RC

You can CHANGE user interface LANGUAGE like this:

Open VS > VS Community > Preferences > Environment > Visual Style > User Interface language

Woala!!!

Dynamically updating plot in matplotlib

Here is a way which allows to remove points after a certain number of points plotted:

import matplotlib.pyplot as plt
# generate axes object
ax = plt.axes()

# set limits
plt.xlim(0,10) 
plt.ylim(0,10)

for i in range(10):        
     # add something to axes    
     ax.scatter([i], [i]) 
     ax.plot([i], [i+1], 'rx')

     # draw the plot
     plt.draw() 
     plt.pause(0.01) #is necessary for the plot to update for some reason

     # start removing points if you don't want all shown
     if i>2:
         ax.lines[0].remove()
         ax.collections[0].remove()

Delaying AngularJS route change until model loaded to prevent flicker

This snippet is dependency injection friendly (I even use it in combination of ngmin and uglify) and it's a more elegant domain driven based solution.

The example below registers a Phone resource and a constant phoneRoutes, which contains all your routing information for that (phone) domain. Something I didn't like in the provided answer was the location of the resolve logic -- the main module should not know anything or be bothered about the way the resource arguments are provided to the controller. This way the logic stays in the same domain.

Note: if you're using ngmin (and if you're not: you should) you only have to write the resolve functions with the DI array convention.

angular.module('myApp').factory('Phone',function ($resource) {
  return $resource('/api/phone/:id', {id: '@id'});
}).constant('phoneRoutes', {
    '/phone': {
      templateUrl: 'app/phone/index.tmpl.html',
      controller: 'PhoneIndexController'
    },
    '/phone/create': {
      templateUrl: 'app/phone/edit.tmpl.html',
      controller: 'PhoneEditController',
      resolve: {
        phone: ['$route', 'Phone', function ($route, Phone) {
          return new Phone();
        }]
      }
    },
    '/phone/edit/:id': {
      templateUrl: 'app/phone/edit.tmpl.html',
      controller: 'PhoneEditController',
      resolve: {
        form: ['$route', 'Phone', function ($route, Phone) {
          return Phone.get({ id: $route.current.params.id }).$promise;
        }]
      }
    }
  });

The next piece is injecting the routing data when the module is in the configure state and applying it to the $routeProvider.

angular.module('myApp').config(function ($routeProvider, 
                                         phoneRoutes, 
                                         /* ... otherRoutes ... */) {

  $routeProvider.when('/', { templateUrl: 'app/main/index.tmpl.html' });

  // Loop through all paths provided by the injected route data.

  angular.forEach(phoneRoutes, function(routeData, path) {
    $routeProvider.when(path, routeData);
  });

  $routeProvider.otherwise({ redirectTo: '/' });

});

Testing the route configuration with this setup is also pretty easy:

describe('phoneRoutes', function() {

  it('should match route configuration', function() {

    module('myApp');

    // Mock the Phone resource
    function PhoneMock() {}
    PhoneMock.get = function() { return {}; };

    module(function($provide) {
      $provide.value('Phone', FormMock);
    });

    inject(function($route, $location, $rootScope, phoneRoutes) {
      angular.forEach(phoneRoutes, function (routeData, path) {

        $location.path(path);
        $rootScope.$digest();

        expect($route.current.templateUrl).toBe(routeData.templateUrl);
        expect($route.current.controller).toBe(routeData.controller);
      });
    });
  });
});

You can see it in full glory in my latest (upcoming) experiment. Although this method works fine for me, I really wonder why the $injector isn't delaying construction of anything when it detects injection of anything that is a promise object; it would make things soooOOOOOooOOOOO much easier.

Edit: used Angular v1.2(rc2)

Swift UIView background color opacity

in Swift 3.0

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)

This works for me in xcode 8.2.

It may helps you.

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

     //WorkAround 
    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 
            textArea.setForeground(kolorIkony);
        }
    });

    mnForeground.add(Jmi);
}

}

Opposite of append in jquery

What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:

   var newUL = $('<ul><li>test</li></ul>');
   $(this).append(newUL);

   // Later ...

   newUL.remove();

How do I add a delay in a JavaScript loop?

You do it:

_x000D_
_x000D_
console.log('hi')_x000D_
let start = 1_x000D_
setTimeout(function(){_x000D_
  let interval = setInterval(function(){_x000D_
    if(start == 10) clearInterval(interval)_x000D_
    start++_x000D_
    console.log('hello')_x000D_
  }, 3000)_x000D_
}, 3000)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

How to check whether particular port is open or closed on UNIX?

Try (maybe as root)

lsof -i -P

and grep the output for the port you are looking for.

For example to check for port 80 do

lsof -i -P | grep :80

Permutation of array

If you're using C++, you can use std::next_permutation from the <algorithm> header file:

int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
  // print a's elements
} while(std::next_permutation(a, a+size));

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

How to convert a string into double and vice versa?

Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

NSString *tempStr = @"8,765.4";  
     // localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
     // next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial

NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
    tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release];  // good citizen

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

How to ping an IP address

InetAddress is not always return correct value. It is successful in case of Local Host but for other hosts this shows that the host is unreachable. Try using ping command as given below.

try {
    String cmd = "cmd /C ping -n 1 " + ip + " | find \"TTL\"";        
    Process myProcess = Runtime.getRuntime().exec(cmd);
    myProcess.waitFor();

    if(myProcess.exitValue() == 0) {

    return true;
    }
    else {
        return false;
    }
}
catch (Exception e) {
    e.printStackTrace();
    return false;
}

How to use if-else logic in Java 8 stream forEach

The problem by using stream().forEach(..) with a call to add or put inside the forEach (so you mutate the external myMap or myList instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.

One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.

Map<Boolean, List<Map.Entry<K, V>>> partitions =
    animalMap.entrySet()
             .stream()
             .collect(partitioningBy(e -> e.getValue() == null));

Map<K, V> myMap = 
    partitions.get(false)
              .stream()
              .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

List<K> myList =
    partitions.get(true)
              .stream()
              .map(Map.Entry::getKey) 
              .collect(toList());

... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2> class exists, you can create your own), e.g:

public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
    return Collector.of(
            () -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
            (pair, entry) -> {
                if(entry.getValue() == null) {
                    pair._2.add(entry.getKey());
                } else {
                    pair._1.put(entry.getKey(), entry.getValue());
                }
            },
            (p1, p2) -> {
                p1._1.putAll(p2._1);
                p1._2.addAll(p2._2);
                return p1;
            });
}

with its usage:

Tuple2<Map<K, V>, List<K>> pair = 
    animalMap.entrySet().parallelStream().collect(customCollector());

You can tune it more if you want, for example by providing a predicate as parameter.

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

Eclipse/Maven error: "No compiler is provided in this environment"

I tried all the things; the one that worked for me is:

  1. Right click on Eclipse project and navigate to properties.
  2. Click on Java Build Path and go to the Libraries tab.
  3. Check which version of Java is added there; is it JRE or JDK?
  4. If you are using Maven project and want to build a solution.
  5. Select the JRE added their and click remove.
  6. Click Add external class folder and add the JDK install by selecting from the system.
  7. Click Apply and OK.
  8. Restart Eclipse.
  9. Build succeeded.

In Chart.js set chart title, name of x axis and y axis?

If you have already set labels for your axis like how @andyhasit and @Marcus mentioned, and would like to change it at a later time, then you can try this:

chart.options.scales.yAxes[ 0 ].scaleLabel.labelString = "New Label";

Full config for reference:

var chartConfig = {
    type: 'line',
    data: {
      datasets: [ {
        label: 'DefaultLabel',
        backgroundColor: '#ff0000',
        borderColor: '#ff0000',
        fill: false,
        data: [],
      } ]
    },
    options: {
      responsive: true,
      scales: {
        xAxes: [ {
          type: 'time',
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Date'
          },
          ticks: {
            major: {
              fontStyle: 'bold',
              fontColor: '#FF0000'
            }
          }
        } ],
        yAxes: [ {
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'value'
          }
        } ]
      }
    }
  };

UTF-8 encoding in JSP page

You have to make sure the file is been saved with UTF-8 encoding. You can do it with several plain text editors. With Notepad++, i.e., you can choose in the menu Encoding-->Encode in UTF-8. You can also do it even with Windows' Notepad (Save As --> Encoding UTF-8). If you are using Eclipse, you can set it in the file's Properties.

Also, check if the problem is that you have to escape those characters. It wouldn't be strange that were your problem, as one of the characters is &.

How to set base url for rest in spring boot?

You can create a custom annotation for your controllers:

Use it instead of the usual @RestController on your controller classes and annotate methods with @RequestMapping.

Works fine in Spring 4.2!

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

How to get a parent element to appear above child

Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

HTML:

<div class="wrapper">
    <div class="parent">
        <div class="child">
            ...
        </div>
    </div>
</div>

CSS:

.wrapper {
    position: relative;
    z-index: 0;
}

.child {
    position: relative;
    z-index: -1;
}

I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

http://jsfiddle.net/g7nP5/

Could not connect to React Native development server on Android

and first of all I appreciate you for posting your doubt. It's mainly because maybe your expo or the app in which you run your react native project may not be in the same local connected wifi or LAN. Also, there is a chance that there is disturbance in your connection frequently due to which it loses its connectivity.

I too face this problem and I personally clear the cache and then restart again and boom it restarts perfectly. I hope this works for you too!

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I had this problem with only with redirectMode="ResponseRewrite" (redirectMode="ResponseRedirect" worked fine) and none of the above solutions helped my resolve the issue. However, once I changed the server's application pool's "Managed Pipeline Mode" from "Classic" to "Integrated" the custom error page appeared as expected.

Android "Only the original thread that created a view hierarchy can touch its views."

If you are within a fragment, then you also need to get the activity object as runOnUIThread is a method on the activity.

An example in Kotlin with some surrounding context to make it clearer - this example is navigating from a camera fragment to a gallery fragment:

// Setup image capture listener which is triggered after photo has been taken
imageCapture.takePicture(
       outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {

           override fun onError(exc: ImageCaptureException) {
           Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
        }

        override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                        val savedUri = output.savedUri ?: Uri.fromFile(photoFile)
                        Log.d(TAG, "Photo capture succeeded: $savedUri")
               
             //Do whatever work you do when image is saved         
             
             //Now ask navigator to move to new tab - as this
             //updates UI do on the UI thread           
             activity?.runOnUiThread( {
                 Navigation.findNavController(
                        requireActivity(), R.id.fragment_container
                 ).navigate(CameraFragmentDirections
                        .actionCameraToGallery(outputDirectory.absolutePath))
              })

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.

Example:

myvar1 = userInput['param1']
myvar2 = userInput['param2']

to:

myvar = userInput

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

How to resize an image to fit in the browser window?

I know there's already a few answers here, but here is what I used:

max-width: 100%;
max-height: 100vh;
width: auto;
margin: auto;

CSS @media print issues with background-color;

To enable background printing in Chrome:

body {
  -webkit-print-color-adjust: exact !important;
}

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to jump back to NERDTree from file in tab?

Since it's not mentioned and it's really helpful:

ctrl-wp

which I memorize as go to the previously selected window.

It works as a there and back command. After having opened a new file from the tree in a new window press ctrl-wp to switch back to the NERDTree and use it again to return to your previous window.

PS: it is worth to mention that ctrl-wp is actually documented as go to the preview window (see: :help preview-window and :help ctrl-w).

It is also the only keystroke which works to switch inside and explore the COC preview documentation window.

Difference between Subquery and Correlated Subquery

A subquery is a select statement that is embedded in a clause of another select statement.

EX:

select ename, sal 
from emp  where sal > (select sal 
                       from emp where ename ='FORD');

A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.

Ex:

select empno,sal,deptid 
from emp e 
where sal=(select avg(sal) 
           from emp where deptid=e.deptid);

DIFFERENCE

The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)

Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)

For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html

Jquery - How to get the style display attribute "none / block"

//animated show/hide

function showHide(id) {
      var hidden= ("none" == $( "#".concat(id) ).css("display"));
      if(hidden){
          $( "#".concat(id) ).show(1000);
      }else{
          $("#".concat(id) ).hide(1000);
      }
  }

XPath test if node value is number

The shortest possible way to test if the value contained in a variable $v can be used as a number is:

number($v) = number($v)

You only need to substitute the $v above with the expression whose value you want to test.

Explanation:

number($v) = number($v) is obviously true, if $v is a number, or a string that represents a number.

It is true also for a boolean value, because a number(true()) is 1 and number(false) is 0.

Whenever $v cannot be used as a number, then number($v) is NaN

and NaN is not equal to any other value, even to itself.

Thus, the above expression is true only for $v whose value can be used as a number, and false otherwise.

CKEditor instance already exists

I've had similar issue where we were making several instances of CKeditor for the content loaded via ajax.

CKEDITOR.remove()

Kept the DOM in the memory and didn't remove all the bindings.

CKEDITOR.instance[instance_id].destroy()

Gave the error i.contentWindow error whenever I create new instance with new data from ajax. But this was only until I figured out that I was destroying the instance after clearing the DOM.

Use destroy() while the instance & it's DOM is present on the page, then it works perfectly fine.

How to customize a Spinner in Android

You can create fully custom spinner design like as

Step1: In drawable folder make background.xml for a border of the spinner.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<corners android:radius="5dp" />
<stroke
android:width="1dp"
   android:color="@android:color/darker_gray" />
</shape>

Step2: for layout design of spinner use this drop-down icon or any image drop.png enter image description here

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="3dp"
    android:layout_weight=".28"
    android:background="@drawable/spinner_border"
    android:orientation="horizontal">

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:layout_marginLeft="5dp"
        android:spinnerMode="dropdown" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:src="@mipmap/drop" />

</RelativeLayout>

Finally looks like below image and it is everywhere clickable in round area and no need to write click Lister for imageView.

enter image description here

Step3: For drop-down design, remove the line from Dropdown ListView and change the background color, Create custom adapter like as

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
String[] years = {"1996","1997","1998","1998"};
ArrayAdapter<CharSequence> langAdapter = new ArrayAdapter<CharSequence>(getActivity(), R.layout.spinner_text, years );
langAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
mSpinner5.setAdapter(langAdapter);

In layout folder create R.layout.spinner_text.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layoutDirection="ltr"
android:id="@android:id/text1"
style="@style/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:paddingLeft="2dp"
/>

In layout folder create simple_spinner_dropdown.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:singleLine="true" />

In styles, you can add custom dimensions and height as per your requirement.

<style name="spinnerItemStyle" parent="android:Widget.TextView.SpinnerItem">
</style>

<style name="spinnerDropDownItemStyle" parent="android:TextAppearance.Widget.TextView.SpinnerItem">
</style>

Finally looks like as

enter image description here

According to the requirement, you can change background color and text of drop-down color by changing the background color or text color of simple_spinner_dropdown.xml

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

it will also check white spaces (' ') along with following:

  • null ,undefined ,NaN ,empty ,string ("") ,0 ,false

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

Using a custom typeface in Android

Setting a custom font to a regular ProgressDialog/AlertDialog:

font=Typeface.createFromAsset(getAssets(),"DroidSans.ttf");

ProgressDialog dialog = ProgressDialog.show(this, "titleText", "messageText", true);
((TextView)dialog.findViewById(Resources.getSystem().getIdentifier("message", "id", "android"))).setTypeface(font);
((TextView)dialog.findViewById(Resources.getSystem().getIdentifier("alertTitle", "id", "android"))).setTypeface(font);

Change drawable color programmatically

You could try a ColorMatrixColorFilter, since your key color is white:

// Assuming "color" is your target color
float r = Color.red(color) / 255f;
float g = Color.green(color) / 255f;
float b = Color.blue(color) / 255f;

ColorMatrix cm = new ColorMatrix(new float[] {
        // Change red channel
        r, 0, 0, 0, 0,
        // Change green channel
        0, g, 0, 0, 0,
        // Change blue channel
        0, 0, b, 0, 0,
        // Keep alpha channel
        0, 0, 0, 1, 0,
});
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
myDrawable.setColorFilter(cf);

How do I clone a generic list in C#?

For a deep clone I use reflection as follows:

public List<T> CloneList<T>(IEnumerable<T> listToClone) {
    Type listType = listToClone.GetType();
    Type elementType = listType.GetGenericArguments()[0];
    List<T> listCopy = new List<T>();
    foreach (T item in listToClone) {
        object itemCopy = Activator.CreateInstance(elementType);
        foreach (PropertyInfo property in elementType.GetProperties()) {
            elementType.GetProperty(property.Name).SetValue(itemCopy, property.GetValue(item));
        }
        listCopy.Add((T)itemCopy);
    }
    return listCopy;
}

You can use List or IEnumerable interchangeably.

How to copy static files to build directory with Webpack?

The way I load static images and fonts:

module: {
    rules: [
      ....

      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        /* Exclude fonts while working with images, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/fonts'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'images/'
          }
        }]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
        /* Exclude images while working with fonts, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/images'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts/'
          },
        }
    ]
}

Don't forget to install file-loader to have that working.

How many concurrent requests does a single Flask process receive?

Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True parameter to the app.run() call, like:

app.run(host="your.host", port=4321, threaded=True)

Another option as per what we can see in the werkzeug docs, is to use the processes parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:

  • threaded – should the process handle each request in a separate thread?
  • processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.

Something like:

app.run(host="your.host", port=4321, processes=3) #up to 3 processes

More info on the run() method here, and the blog post that led me to find the solution and api references.


Note: on the Flask docs on the run() methods it's indicated that using it in a Production Environment is discouraged because (quote): "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well."

However, they do point to their Deployment Options page for the recommended ways to do this when going for production.

Detecting the onload event of a window opened with window.open

If the pop-up's document is from a different domain, this is simply not possible.

Update April 2015: I was wrong about this: if you own both domains, you can use window.postMessage and the message event in pretty much all browsers that are relevant today.

If not, there's still no way you'll be able to make this work cross-browser without some help from the document being loaded into the pop-up. You need to be able to detect a change in the pop-up that occurs once it has loaded, which could be a variable that JavaScript in the pop-up page sets when it handles its own load event, or if you have some control of it you could add a call to a function in the opener.

How to use UIPanGestureRecognizer to move object? iPhone/iPad

I found the tutorial Working with UIGestureRecognizers, and I think that is what I am looking for. It helped me come up with the following solution:

-(IBAction) someMethod {
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
    [panRecognizer setMinimumNumberOfTouches:1];
    [panRecognizer setMaximumNumberOfTouches:1];
    [ViewMain addGestureRecognizer:panRecognizer];
    [panRecognizer release];
}

-(void)move:(UIPanGestureRecognizer*)sender {
    [self.view bringSubviewToFront:sender.view];
    CGPoint translatedPoint = [sender translationInView:sender.view.superview];

    if (sender.state == UIGestureRecognizerStateBegan) {
        firstX = sender.view.center.x;
        firstY = sender.view.center.y;
    }


    translatedPoint = CGPointMake(sender.view.center.x+translatedPoint.x, sender.view.center.y+translatedPoint.y);

    [sender.view setCenter:translatedPoint];
    [sender setTranslation:CGPointZero inView:sender.view];

    if (sender.state == UIGestureRecognizerStateEnded) {
        CGFloat velocityX = (0.2*[sender velocityInView:self.view].x);
        CGFloat velocityY = (0.2*[sender velocityInView:self.view].y);

        CGFloat finalX = translatedPoint.x + velocityX;
        CGFloat finalY = translatedPoint.y + velocityY;// translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);

        if (finalX < 0) {
            finalX = 0;
        } else if (finalX > self.view.frame.size.width) {
            finalX = self.view.frame.size.width;
        }

        if (finalY < 50) { // to avoid status bar
            finalY = 50;
        } else if (finalY > self.view.frame.size.height) {
            finalY = self.view.frame.size.height;
        }

        CGFloat animationDuration = (ABS(velocityX)*.0002)+.2;

        NSLog(@"the duration is: %f", animationDuration);

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:animationDuration];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(animationDidFinish)];
        [[sender view] setCenter:CGPointMake(finalX, finalY)];
        [UIView commitAnimations];
    }
}

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

Get selected option text with JavaScript

HTML:

<select id="box1" onChange="myNewFunction(this);">

JavaScript:

function myNewFunction(element) {
    var text = element.options[element.selectedIndex].text;
    // ...
}

DEMO: http://jsfiddle.net/6dkun/1/

from list of integers, get number closest to a given value

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.


If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

Unable to start Service Intent

For anyone else coming across this thread I had this issue and was pulling my hair out. I had the service declaration OUTSIDE of the '< application>' end tag DUH!

RIGHT:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>    

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        
</application>

<uses-permission android:name="..." />

WRONG but still compiles without errors:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>

</application>

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        

<uses-permission android:name="..." />

How to center a (background) image within a div?

try background-position:center;

EDIT: since this question is getting lots of views, its worth adding some extra info:

text-align: center will not work because the background image is not part of the document and is therefore not part of the flow.

background-position:center is shorthand for background-position: center center; (background-position: horizontal vertical);

How to find and replace all occurrences of a string recursively in a directory tree?

For me works the next command:

find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'

if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

For example: 's@string/to/replace@new/string@g'

Hide Spinner in Input Number - Firefox 29

Faced the same issue post Firefox update to 29.0.1, this is also listed out here https://bugzilla.mozilla.org/show_bug.cgi?id=947728

Solutions: They(Mozilla guys) have fixed this by introducing support for "-moz-appearance" for <input type="number">. You just need to have a style associated with your input field with "-moz-appearance:textfield;".

I prefer the CSS way E.g.:-

.input-mini{
-moz-appearance:textfield;}

Or

You can do it inline as well:

<input type="number" style="-moz-appearance: textfield">

How to show "Done" button on iPhone number pad

I describe one solution for iOS 4.2+ here but the dismiss button fades in after the keyboard appears. It's not terrible, but not ideal either.

The solution described in the question linked above includes a more elegant illusion to dismiss the button, where I fade and vertically displace the button to provide the appearance that the keypad and the button are dismissing together.

How to get the size of a varchar[n] field in one SQL statement?

For t-SQL I use the following query for varchar columns (shows the collation and is_null properties):

SELECT
    s.name
    , o.name as table_name
    , c.name as column_name
    , t.name as type
    , c.max_length
    , c.collation_name
    , c.is_nullable
FROM
    sys.columns c
    INNER JOIN sys.objects o ON (o.object_id = c.object_id)
    INNER JOIN sys.schemas s ON (s.schema_id = o.schema_id)
    INNER JOIN sys.types t ON (t.user_type_id = c.user_type_id)
WHERE
    s.name = 'dbo'
    AND t.name IN ('varchar') -- , 'char', 'nvarchar', 'nchar')
ORDER BY
    o.name, c.name

Can I remove the URL from my print css, so the web address doesn't print?

Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.

http://css-discuss.incutio.com/wiki/Print_Stylesheets#Print_headers.2Ffooters_and_print_margins

However, as of 2017, the @page at-rule has been standardized, which can be used to hide the page title and date in modern browsers:

@page { size: auto; margin: 0mm; }

Credit to Vigneswaran S for this tip.

Convert nullable bool? to bool

The easiest way is to use the null coalescing operator: ??

bool? x = ...;
if (x ?? true) { 

}

The ?? with nullable values works by examining the provided nullable expression. If the nullable expression has a value the it's value will be used else it will use the expression on the right of ??

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

Trying to SSH into an Amazon Ec2 instance - permission error

Change permission for the key file with :

chmod 400 key-file-name.pem

See AWS documentation for connecting to the instance:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#EC2_ConnectToInstance_Linux

Oracle client ORA-12541: TNS:no listener

I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.

IPython/Jupyter Problems saving notebook as PDF

For converting any Jupyter notebook to PDF, please follow the below instructions:

(Be inside Jupyter notebook):

On Mac OS:

command + P --> you will get a print dialog box --> change destination as PDF --> Click print

On Windows:

Ctrl + P --> you will get a print dialog box --> change destination as PDF --> Click print

If the above steps doesn't generate full PDF of the Jupyter notebook (probably because Chrome, some times, don't print all the outputs because Jupyter make a scroll for big outputs),

Try performing below steps for removing the auto scroll in the menu:-

Credits: @ÂngeloPolotto

  1. In your Jupyter Notebook, click Cell on top of the jupyter notebook enter image description here

  2. Next click All output --> Toggle scrolling for removing auto scroll.

enter image description here

Updating a JSON object using Javascript

var i = jsonObj.length;
while ( i --> 0 ) {
    if ( jsonObj[i].Id === 3 ) {
        jsonObj[ i ].Username = 'Thomas';
        break;
    }
}

Or, if the array is always ordered by the IDs:

jsonObj[ 2 ].Username = 'Thomas';

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

I have solved it with adding some key in info.plist. The steps I followed are:

  1. Opened my Project target's info.plist file

  2. Added a Key called NSAppTransportSecurity as a Dictionary.

  3. Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image.

enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link: https://stackoverflow.com/a/32609970

EDIT: OR In source code of info.plist file we can add that:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>yourdomain.com</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
            </dict>
       </dict>
  </dict>

How do I convert a list of ascii values to a string in python?

l = [83, 84, 65, 67, 75]

s = "".join([chr(c) for c in l])

print s

What's the best way to cancel event propagation between nested ng-click calls?

This works for me:

<a href="" ng-click="doSomething($event)">Action</a>

this.doSomething = function($event) {
  $event.stopPropagation();
  $event.preventDefault();
};

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How to send a POST request using volley with string body?

I created a function for a Volley Request. You just need to pass the arguments :

public void callvolly(final String username, final String password){
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = "http://your_url.com/abc.php"; // <----enter your post url here
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //This code is executed if the server responds, whether or not the response contains data.
            //The String 'response' contains the server's response.
        }
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
        }
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("username", username);             
            MyData.put("password", password);                
            return MyData;
        }
    };


    MyRequestQueue.add(MyStringRequest);
}

Format output string, right alignment

Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"\n{'Wins:':<15}{wins:>10}",
    f"\n{'Losses:':<15}{losses:>10}",
    f"\n{'Breakeven:':<15}{evens:>10}",
    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Mean:':<15}{mean_trd:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I manually filled NAs by exporting the CSV then editing it and reimporting, as below.

Perhaps one of you experts might explain why this procedure worked so well (the first file had columns with data of types char, INT and num (floating point numbers)), which all became char type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).

# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
                            header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:    
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
                            header=T,stringsAsFactors=FALSE)

On arrival back in R, all columns had their correct measurement levels automatically recognized by R!

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

How do I read all classes from a Java package in the classpath?

use dependency maven:

groupId: net.sf.extcos
artifactId: extcos
version: 0.4b

then use this code :

ComponentScanner scanner = new ComponentScanner();
        Set classes = scanner.getClasses(new ComponentQuery() {
            @Override
            protected void query() {
                select().from("com.leyton").returning(allExtending(DynamicForm.class));
            }
        });

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

Split function equivalent in T-SQL?

You've tagged this SQL Server 2008 but future visitors to this question (using SQL Server 2016+) will likely want to know about STRING_SPLIT.

With this new builtin function you can now just use

SELECT TRY_CAST(value AS INT)
FROM   STRING_SPLIT ('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15', ',') 

Some restrictions of this function and some promising results of performance testing are in this blog post by Aaron Bertrand.

Git push rejected "non-fast-forward"

In Eclipse do the following:

GIT Repositories > Remotes > Origin > Right click and say fetch

GIT Repositories > Remote Tracking > Select your branch and say merge

Go to project, right click on your file and say Fetch from upstream.

How to remove all namespaces from XML with C#?

I know this question is supposedly solved, but I wasn't totally happy with the way it was implemented. I found another source over here on the MSDN blogs that has an overridden XmlTextWriter class that strips out the namespaces. I tweaked it a bit to get some other things I wanted in such as pretty formatting and preserving the root element. Here is what I have in my project at the moment.

http://blogs.msdn.com/b/kaevans/archive/2004/08/02/206432.aspx

Class

/// <summary>
/// Modified XML writer that writes (almost) no namespaces out with pretty formatting
/// </summary>
/// <seealso cref="http://blogs.msdn.com/b/kaevans/archive/2004/08/02/206432.aspx"/>
public class XmlNoNamespaceWriter : XmlTextWriter
{
    private bool _SkipAttribute = false;
    private int _EncounteredNamespaceCount = 0;

    public XmlNoNamespaceWriter(TextWriter writer)
        : base(writer)
    {
        this.Formatting = System.Xml.Formatting.Indented;
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement(null, localName, null);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        //If the prefix or localname are "xmlns", don't write it.
        //HOWEVER... if the 1st element (root?) has a namespace we will write it.
        if ((prefix.CompareTo("xmlns") == 0
                || localName.CompareTo("xmlns") == 0)
            && _EncounteredNamespaceCount++ > 0)
        {
            _SkipAttribute = true;
        }
        else
        {
            base.WriteStartAttribute(null, localName, null);
        }
    }

    public override void WriteString(string text)
    {
        //If we are writing an attribute, the text for the xmlns
        //or xmlns:prefix declaration would occur here.  Skip
        //it if this is the case.
        if (!_SkipAttribute)
        {
            base.WriteString(text);
        }
    }

    public override void WriteEndAttribute()
    {
        //If we skipped the WriteStartAttribute call, we have to
        //skip the WriteEndAttribute call as well or else the XmlWriter
        //will have an invalid state.
        if (!_SkipAttribute)
        {
            base.WriteEndAttribute();
        }
        //reset the boolean for the next attribute.
        _SkipAttribute = false;
    }

    public override void WriteQualifiedName(string localName, string ns)
    {
        //Always write the qualified name using only the
        //localname.
        base.WriteQualifiedName(localName, null);
    }
}

Usage

//Save the updated document using our modified (almost) no-namespace XML writer
using(StreamWriter sw = new StreamWriter(this.XmlDocumentPath))
using(XmlNoNamespaceWriter xw = new XmlNoNamespaceWriter(sw))
{
    //This variable is of type `XmlDocument`
    this.XmlDocumentRoot.Save(xw);
}

What causes a java.lang.StackOverflowError

One of the (optional) arguments to the JVM is the stack size. It's -Xss. I don't know what the default value is, but if the total amount of stuff on the stack exceeds that value, you'll get that error.

Generally, infinite recursion is the cause of this, but if you were seeing that, your stack trace would have more than 5 frames.

Try adding a -Xss argument (or increasing the value of one) to see if this goes away.

Generating Fibonacci Sequence

Here is another one with proper tail call.

The recursive inner fib function can reuse the stack because everything is needed (the array of numbers) to produce the next number is passed in as an argument, no additional expressions to evaluate.

However tail call optimization introduced in ES2015.

Also one drawback is it gets the array length in every iteration (but only once) to generate the following number and getting the elements of the array upon their index (it is faster though than pop or splice or other array methods) but I did not performance tested the whole solution.

_x000D_
_x000D_
var fibonacci = function(len) {_x000D_
  var fib = function(seq) {_x000D_
    var seqLen = seq.length;_x000D_
    if (seqLen === len) {_x000D_
      return seq;_x000D_
    } else {_x000D_
      var curr = seq[seqLen - 1];_x000D_
      var prev = seq[seqLen - 2];_x000D_
      seq[seqLen] = curr + prev;_x000D_
      return fib(seq);_x000D_
    }_x000D_
  }_x000D_
  return len < 2 ? [0] : fib([0, 1]);_x000D_
}_x000D_
_x000D_
console.log(fibonacci(100));
_x000D_
_x000D_
_x000D_

How do I know the script file name in a Bash script?

In bash you can get the script file name using $0. Generally $1, $2 etc are to access CLI arguments. Similarly $0 is to access the name which triggers the script(script file name).

#!/bin/bash
echo "You are running $0"
...
...

If you invoke the script with path like /path/to/script.sh then $0 also will give the filename with path. In that case need to use $(basename $0) to get only script file name.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel

and then just add controls to it

   for ( int i = 0; i < COUNT; i++ ) {


    Label lblTitle = new Label();
    lblTitle.Text = i+"Your Text";
    youlayOut.Controls.Add( lblTitle, 0, i );

    TextBox txtValue = new TextBox();
    youlayOut.Controls.Add( txtValue, 2, i );
}

How to get the first element of the List or Set?

I'm surprised that nobody suggested guava solution yet:

com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)

or if you expect single element:

com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)

Determine file creation date in Java

As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.

On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;

public class TestFA {
  static void getAttributes(String pathStr) throws IOException {
    Path p = Paths.get(pathStr);
    BasicFileAttributes view
       = Files.getFileAttributeView(p, BasicFileAttributeView.class)
              .readAttributes();
    System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
  }
  public static void main(String[] args) throws IOException {
    for (String s : args) {
        getAttributes(s);
    }
  }
}

Re-assign host access permission to MySQL user

The accepted answer only renamed the user but the privileges were left behind.

I'd recommend using:

RENAME USER 'foo'@'1.2.3.4' TO 'foo'@'1.2.3.5';

According to MySQL documentation:

RENAME USER causes the privileges held by the old user to be those held by the new user.

javascript: Disable Text Select

One might also use, works ok in all browsers, require javascript:

onselectstart = (e) => {e.preventDefault()}

Example:

_x000D_
_x000D_
onselectstart = (e) => {_x000D_
  e.preventDefault()_x000D_
  console.log("nope!")_x000D_
  }
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


One other js alternative, by testing CSS supports, and disable userSelect, or MozUserSelect for Firefox.

_x000D_
_x000D_
let FF_x000D_
if (CSS.supports("( -moz-user-select: none )")){FF = 1} else {FF = 0}_x000D_
(FF===1) ? document.body.style.MozUserSelect="none" : document.body.style.userSelect="none"
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


Pure css, same logic. Warning you will have to extend those rules to every browser, this can be verbose.

_x000D_
_x000D_
@supports (user-select:none) {_x000D_
  div {_x000D_
    user-select:none_x000D_
  }_x000D_
}_x000D_
_x000D_
@supports (-moz-user-select:none) {_x000D_
  div {_x000D_
    -moz-user-select:none_x000D_
  }_x000D_
}
_x000D_
<div>Select me!</div>
_x000D_
_x000D_
_x000D_

Sort JavaScript object by key

Object.keys(unordered).sort().reduce(
    (acc,curr) => ({...acc, [curr]:unordered[curr]})
    , {}
)

Display rows with one or more NaN values in pandas dataframe

Can try this too, almost similar previous answers.

    d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
    df = pd.DataFrame(d).set_index('filename')

enter image description here

Count of null values in each column.

df.isnull().sum()

enter image description here

df.isnull().any(axis=1)

enter image description here

PHP remove special character from string

preg_replace('#[^\w()/.%\-&]#',"",$string);

How can I go back/route-back on vue-router?

If you're using Vuex you can use https://github.com/vuejs/vuex-router-sync

Just initialize it in your main file with:

import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);

Each route change will update route state object in Vuex. You can next create getter to use the from Object in route state or just use the state (better is to use getters, but it's other story https://vuex.vuejs.org/en/getters.html), so in short it would be (inside components methods/values):

this.$store.state.route.from.fullPath

You can also just place it in <router-link> component:

<router-link :to="{ path: $store.state.route.from.fullPath }"> 
  Back 
</router-link>

So when you use code above, link to previous path would be dynamically generated.

Creating files in C++

Do this with a file stream. When a std::ofstream is closed, the file is created. I personally like the following code, because the OP only asks to create a file, not to write in it:

#include <fstream>

int main()
{
    std::ofstream file { "Hello.txt" };
    // Hello.txt has been created here
}

The temporary variable file is destroyed right after its creation, so the stream is closed and thus the file is created.

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

For SQL Server 2012 and up , with leading zeroes:

 SELECT FORMAT(GETDATE(),'MM') 

without:

SELECT    MONTH(GETDATE())

How to Scroll Down - JQuery

If you want to scroll down to the div (id="div1"). Then you can use this code.

 $('html, body').animate({
     scrollTop: $("#div1").offset().top
 }, 1500);

Struct inheritance in C++

Of course. In C++, structs and classes are nearly identical (things like defaulting to public instead of private are among the small differences).

How to create an array of 20 random bytes?

Create a Random object with a seed and get the array random by doing:

public static final int ARRAY_LENGTH = 20;

byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);

Where can I download IntelliJ IDEA Color Schemes?

The Solarized color theme (both light and dark versions) for IntelliJ IDEA is available here.

Solarized color theme for IntelliJ IDEA

First Heroku deploy failed `error code=H10`

I want to register here what was my solution for this error which was a simple file not updated to Github.

I have a full stack project, and my files are structured both root directory for backend and client for the frontend (I am using React.js). All came down to the fact that I was mistakenly pushing the client folder only to Github and all my changes which had an error (missing a comma in a object's instance in my index.js) was not updated in the backend side. Since this Heroku fetches all updates from Github Repository, I couldn't access my server and the error persisted. Then all I had to do was to commit and push to the root directory and update all the changes of the project and everything came back to work again.

"Unknown class <MyClass> in Interface Builder file" error at runtime

I ran into this in Swift.

Moving the .xib file into the project's Base.lproj folder got rid of this error.

ant warning: "'includeantruntime' was not set"

If you like me work from commandline the quick answer is executing

export ANT_OPTS=-Dbuild.sysclasspath=ignore

And then run your ant script again.

How to change a css class style through Javascript?

document.getElementById("my").className = 'myclass';

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

How to get the selected radio button’s value?

You can do something like this:

_x000D_
_x000D_
var radios = document.getElementsByName('genderS');_x000D_
_x000D_
for (var i = 0, length = radios.length; i < length; i++) {_x000D_
  if (radios[i].checked) {_x000D_
    // do whatever you want with the checked radio_x000D_
    alert(radios[i].value);_x000D_
_x000D_
    // only one radio can be logically checked, don't check the rest_x000D_
    break;_x000D_
  }_x000D_
}
_x000D_
<label for="gender">Gender: </label>_x000D_
<input type="radio" name="genderS" value="1" checked="checked">Male</input>_x000D_
<input type="radio" name="genderS" value="0">Female</input>
_x000D_
_x000D_
_x000D_

jsfiddle

Edit: Thanks HATCHA and jpsetung for your edit suggestions.

How to run vbs as administrator from vbs?

fun lil batch file

@set E=ECHO &set S=SET &set CS=CScript //T:3 //nologo %~n0.vbs /REALTIME^>nul^& timeout 1 /NOBREAK^>nul^& del /Q %~n0.vbs&CLS
@%E%off&color 4a&title %~n0&%S%CX=CLS^&EXIT&%S%BS=^>%~n0.vbs&%S%G=GOTO &%S%H=shell&AT>NUL
IF %ERRORLEVEL% EQU 0 (
    %G%2
) ELSE (
    if not "%minimized%"=="" %G%1
)
%S%minimized=true & start /min cmd /C "%~dpnx0"&%CX%
:1
%E%%S%%H%=CreateObject("%H%.Application"):%H%.%H%Execute "%~dpnx0",,"%CD%", "runas", 1:%S%%H%=nothing%BS%&%CS%&%CX%
:2
%E%%~dpnx0 fvcLing admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"& timeout 3 /NOBREAK>nul
:3
%E%x=msgbox("end of line" ,48, "%~n0")%BS%&%CS%&%CX%

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

The APK file does not exist on disk

In my case, I was using a special character in my app file path. I closed the Android Studio and removed the ' character from my app file path. Everything worked fine when I reopned the project.

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

How to set an environment variable from a Gradle build?

Please try this one option:

 task RunTest(type: Test) {
         systemProperty "spring.profiles.active", System.getProperty("DEV")
         include 'com/db/project/Test1.class'
     }

Finding moving average from data points in Python

There is a problem with the accepted answer. I think we need to use "valid" instead of "same" here - return numpy.convolve(interval, window, 'same') .

As an Example try out the MA of this data-set = [1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6] - the result should be [4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6,4.6,7.0,6.8], but having "same" gives us an incorrect output of [2.6,3.0,4.2,5.4,6.0,5.0,5.0,5.2,5.4,4.4,5.4,5.6,5.6, 4.6,7.0,6.8,6.2,4.8]

Rusty code to try this out -:

result=[]
dataset=[1,5,7,2,6,7,8,2,2,7,8,3,7,3,7,3,15,6]
window_size=5
for index in xrange(len(dataset)):
    if index <=len(dataset)-window_size :
        tmp=(dataset[index]+ dataset[index+1]+ dataset[index+2]+ dataset[index+3]+ dataset[index+4])/5.0
        result.append(tmp)
    else:
      pass

result==movingaverage(y, window_size) 

Try this with valid & same and see whether the math makes sense.

See also -: http://sentdex.com/sentiment-analysisbig-data-and-python-tutorials-algorithmic-trading/how-to-chart-stocks-and-forex-doing-your-own-financial-charting/calculate-simple-moving-average-sma-python/

Assign multiple values to array in C

Exactly, you nearly got it:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

How do I rotate a picture in WinForms

This is an old thread, and there are several other threads about C# WinForms image rotation, but now that I've come up with my solution I figure this is as good a place to post it as any.

  /// <summary>
  /// Method to rotate an Image object. The result can be one of three cases:
  /// - upsizeOk = true: output image will be larger than the input, and no clipping occurs 
  /// - upsizeOk = false & clipOk = true: output same size as input, clipping occurs
  /// - upsizeOk = false & clipOk = false: output same size as input, image reduced, no clipping
  /// 
  /// A background color must be specified, and this color will fill the edges that are not 
  /// occupied by the rotated image. If color = transparent the output image will be 32-bit, 
  /// otherwise the output image will be 24-bit.
  /// 
  /// Note that this method always returns a new Bitmap object, even if rotation is zero - in 
  /// which case the returned object is a clone of the input object. 
  /// </summary>
  /// <param name="inputImage">input Image object, is not modified</param>
  /// <param name="angleDegrees">angle of rotation, in degrees</param>
  /// <param name="upsizeOk">see comments above</param>
  /// <param name="clipOk">see comments above, not used if upsizeOk = true</param>
  /// <param name="backgroundColor">color to fill exposed parts of the background</param>
  /// <returns>new Bitmap object, may be larger than input image</returns>
  public static Bitmap RotateImage(Image inputImage, float angleDegrees, bool upsizeOk, 
                                   bool clipOk, Color backgroundColor)
  {
     // Test for zero rotation and return a clone of the input image
     if (angleDegrees == 0f)
        return (Bitmap)inputImage.Clone();

     // Set up old and new image dimensions, assuming upsizing not wanted and clipping OK
     int oldWidth = inputImage.Width;
     int oldHeight = inputImage.Height;
     int newWidth = oldWidth;
     int newHeight = oldHeight;
     float scaleFactor = 1f;

     // If upsizing wanted or clipping not OK calculate the size of the resulting bitmap
     if (upsizeOk || !clipOk)
     {
        double angleRadians = angleDegrees * Math.PI / 180d;

        double cos = Math.Abs(Math.Cos(angleRadians));
        double sin = Math.Abs(Math.Sin(angleRadians));
        newWidth = (int)Math.Round(oldWidth * cos + oldHeight * sin);
        newHeight = (int)Math.Round(oldWidth * sin + oldHeight * cos);
     }

     // If upsizing not wanted and clipping not OK need a scaling factor
     if (!upsizeOk && !clipOk)
     {
        scaleFactor = Math.Min((float)oldWidth / newWidth, (float)oldHeight / newHeight);
        newWidth = oldWidth;
        newHeight = oldHeight;
     }

     // Create the new bitmap object. If background color is transparent it must be 32-bit, 
     //  otherwise 24-bit is good enough.
     Bitmap newBitmap = new Bitmap(newWidth, newHeight, backgroundColor == Color.Transparent ? 
                                      PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb);
     newBitmap.SetResolution(inputImage.HorizontalResolution, inputImage.VerticalResolution);

     // Create the Graphics object that does the work
     using (Graphics graphicsObject = Graphics.FromImage(newBitmap))
     {
        graphicsObject.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsObject.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphicsObject.SmoothingMode = SmoothingMode.HighQuality;

        // Fill in the specified background color if necessary
        if (backgroundColor != Color.Transparent)
           graphicsObject.Clear(backgroundColor);

        // Set up the built-in transformation matrix to do the rotation and maybe scaling
        graphicsObject.TranslateTransform(newWidth / 2f, newHeight / 2f);

        if (scaleFactor != 1f)
           graphicsObject.ScaleTransform(scaleFactor, scaleFactor);

        graphicsObject.RotateTransform(angleDegrees);
        graphicsObject.TranslateTransform(-oldWidth / 2f, -oldHeight / 2f);

        // Draw the result 
        graphicsObject.DrawImage(inputImage, 0, 0);
     }

     return newBitmap;
  }

This is the result of many sources of inspiration, here at StackOverflow and elsewhere. Naveen's answer on this thread was especially helpful.

How to use sys.exit() in Python

In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:

so:

import sys

and when finished:

sys.exit()

Cant get text of a DropDownList in code - can get value but not text

had the same problem and just solved it, i used string [variable_Name] =dropdownlist1.SelectedItem.Text;

Run "mvn clean install" in Eclipse

Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there

Why doesn't catching Exception catch RuntimeException?

catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.

Access parent's parent from javascript object

I simply added in first function

parentThis = this;

and use parentThis in subfunction. Why? Because in JavaScript, objects are soft. A new member can be added to a soft object by simple assignment (not like ie. Java where classical objects are hard. The only way to add a new member to a hard object is to create a new class) More on this here: http://www.crockford.com/javascript/inheritance.html

And also at the end you don't have to kill or destroy the object. Why I found here: http://bytes.com/topic/javascript/answers/152552-javascript-destroy-object

Hope this helps

Android, getting resource ID from string?

Since you said you only wanted to pass one parameter and it did not seem to matter which, you could pass the resource identifier in and then find out the string name for it, thus:

String name = getResources().getResourceEntryName(id);

This might be the most efficient way of obtaining both values. You don't have to mess around finding just the "icon" part from a longer string.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Clearing the terminal screen?

Another kick at the can:

void setup(){     /*123456789 123456789 123456789 123456789 123*/
  String newRow="\n|________________________________________";
  String scrSiz="\n|\n|\n|\n|\n|\n|\n|\n|\n|\t";
  Serial.begin(115200);  
       // this baudrate should not have flicker but it does as seen when
       // the persistence of vision threshold is insufficiently exceeded
       // 115200 baud should display ~10000 cps or a char every 0.1 msec
       // each 'for' loop iteration 'should' print 65 chars. in < 7 msec
       // Serial.print() artifact inefficiencies are the flicker culprit
       // unfortunately '\r' does not render in the IDE's Serial Monitor

  Serial.print( scrSiz+"\n|_____ size screen vertically to fit _____"  );
  for(int i=0;i<30;i++){
     delay(1000); 
     Serial.print((String)scrSiz +i +"\t" + (10*i) +newRow);}
}
void loop(){}

Batch file to perform start, run, %TEMP% and delete all

Just use

del /f /q C:\Users\%username%\AppData\Local\temp

And it will work.

Note: It will delete the whole folder however, Windows will remake it as it needs.

How to upload a file in Django?

You can refer to server examples in Fine Uploader, which has django version. https://github.com/FineUploader/server-examples/tree/master/python/django-fine-uploader

It's very elegant and most important of all, it provides featured js lib. Template is not included in server-examples, but you can find demo on its website. Fine Uploader: http://fineuploader.com/demos.html

django-fine-uploader

views.py

UploadView dispatches post and delete request to respective handlers.

class UploadView(View):

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(UploadView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        """A POST request. Validate the form and then handle the upload
        based ont the POSTed data. Does not handle extra parameters yet.
        """
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_upload(request.FILES['qqfile'], form.cleaned_data)
            return make_response(content=json.dumps({ 'success': True }))
        else:
            return make_response(status=400,
                content=json.dumps({
                    'success': False,
                    'error': '%s' % repr(form.errors)
                }))

    def delete(self, request, *args, **kwargs):
        """A DELETE request. If found, deletes a file with the corresponding
        UUID from the server's filesystem.
        """
        qquuid = kwargs.get('qquuid', '')
        if qquuid:
            try:
                handle_deleted_file(qquuid)
                return make_response(content=json.dumps({ 'success': True }))
            except Exception, e:
                return make_response(status=400,
                    content=json.dumps({
                        'success': False,
                        'error': '%s' % repr(e)
                    }))
        return make_response(status=404,
            content=json.dumps({
                'success': False,
                'error': 'File not present'
            }))

forms.py

class UploadFileForm(forms.Form):

    """ This form represents a basic request from Fine Uploader.
    The required fields will **always** be sent, the other fields are optional
    based on your setup.
    Edit this if you want to add custom parameters in the body of the POST
    request.
    """
    qqfile = forms.FileField()
    qquuid = forms.CharField()
    qqfilename = forms.CharField()
    qqpartindex = forms.IntegerField(required=False)
    qqchunksize = forms.IntegerField(required=False)
    qqpartbyteoffset = forms.IntegerField(required=False)
    qqtotalfilesize = forms.IntegerField(required=False)
    qqtotalparts = forms.IntegerField(required=False)

How to include css files in Vue 2

Try using the @ symbol before the url string. Import your css in the following manner:

import Vue from 'vue'

require('@/assets/styles/main.css')

In your App.vue file you can do this to import a css file in the style tag

<template>
  <div>
  </div>
</template>

<style scoped src="@/assets/styles/mystyles.css">
</style>

Visual Studio loading symbols

I faced a similar problem. In my case I had set _NT_SYMBOL_PATH to download from Microsoft Servers for use in WinDbg and it looks like when set, Visual Studio will use that with no way to ignore it. Removing that environment variable resolved my issue.

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

What should be the package name of android app?

As you stated, package names are usually in the form of 'com.organizationName.appName' - all lowercase and no spaces. It sounds like the package name that you entered when uploading the app was different from the one declared in the AndroidManifest.

AngularJS : Clear $watch

scope.$watch returns a function that you can call and that will unregister the watch.

Something like:

var unbindWatch = $scope.$watch("myvariable", function() {
    //...
});

setTimeout(function() {
    unbindWatch();
}, 1000);

How to echo with different colors in the Windows command line

I'm adding an answer to address an issue noted in some comments above: that inline ansi color codes can misbehave when inside a FOR loop (actually, within any parenthesized block of code). The .bat code below demonstrates (1) the use of inline color codes, (2) the color failure that can occur when inline color codes are used in a FOR loop or within a parenthesized block of code, and (3) a solution to the problem. When the .bat code executes, tests 2 and 3 demonstrate the colorcode failure, and test 4 shows no failure because it implements the solution.

[EDIT 2020-04-07: I found another solution that's presumably more efficient than calling a subroutine. Enclose the FINDSTR phrase in parentheses, as in the following line:

   echo success | (findstr /R success)

ENDEDIT]

Note: In my (limited) experience, the color code problem manifests only after input is piped to FINDSTR inside the block of code. That's how the following .bat reproduces the problem. It's possible the color code problem is more general than after piping to FINDSTR. If someone can explain the nature of the problem, and if there's a better way to solve it, I'd appreciate it.

@goto :main
:resetANSI
EXIT /B
rem  The resetANSI subroutine is used to fix the colorcode
rem  bug, even though it appears to do nothing.

:main
@echo off
setlocal EnableDelayedExpansion

rem  Define some useful colorcode vars:
for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "ESCchar=%%E"
set "green=%ESCchar%[92m"
set "yellow=%ESCchar%[93m"
set "magenta=%ESCchar%[95m"
set "cyan=%ESCchar%[96m"
set "white=%ESCchar%[97m"
set "black=%ESCchar%[30m"

echo %white%Test 1 is NOT in a FOR loop nor within parentheses, and color works right.
   echo %yellow%[Test 1] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   echo %magenta%This is magenta and FINDSTR found and displayed 'success'.%yellow%
   echo %green%This is green.
echo %cyan%Test 1 completed.

echo %white%Test 2 is within parentheses, and color stops working after the pipe to FINDSTR.
(  echo %yellow%[Test 2] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   echo %magenta%This is supposed to be magenta and FINDSTR found and displayed 'success'.
   echo %green%This is supposed to be green.
)
echo %cyan%Test 2 completed.

echo %white%Test 3 is within a FOR loop, and color stops working after the pipe to FINDSTR.
for /L %%G in (3,1,3) do (
   echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   echo %magenta%This is supposed to be magenta and FINDSTR found and displayed 'success'.
   echo %green%This is supposed to be green.
)
echo %cyan%Test 3 completed.

echo %white%Test 4 is in a FOR loop but color works right because subroutine :resetANSI is 
echo called after the pipe to FINDSTR, before the next color code is used.
for /L %%G in (4,1,4) do (
   echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   call :resetANSI
   echo %magenta%This is magenta and FINDSTR found and displayed 'success'.
   echo %green%This is green.
)
echo %cyan%Test 4 completed.%white%

EXIT /B

Has Facebook sharer.php changed to no longer accept detailed parameters?

If you encode the & in your URL to %26 it works correctly. Just tested and verified.

Why Doesn't C# Allow Static Methods to Implement an Interface?

To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.

The above arguments all seem to miss this point about contracts.

How to merge a Series and DataFrame

If I could suggest setting up your dataframes like this (auto-indexing):

df = pd.DataFrame({'a':[np.nan, 1, 2], 'b':[4, 5, 6]})

then you can set up your s1 and s2 values thus (using shape() to return the number of rows from df):

s = pd.DataFrame({'s1':[5]*df.shape[0], 's2':[6]*df.shape[0]})

then the result you want is easy:

display (df.merge(s, left_index=True, right_index=True))

Alternatively, just add the new values to your dataframe df:

df = pd.DataFrame({'a':[nan, 1, 2], 'b':[4, 5, 6]})
df['s1']=5
df['s2']=6
display(df)

Both return:

     a  b  s1  s2
0  NaN  4   5   6
1  1.0  5   5   6
2  2.0  6   5   6

If you have another list of data (instead of just a single value to apply), and you know it is in the same sequence as df, eg:

s1=['a','b','c']

then you can attach this in the same way:

df['s1']=s1

returns:

     a  b s1
0  NaN  4  a
1  1.0  5  b
2  2.0  6  c

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

How to create a density plot in matplotlib?

The density plot can also be created by using matplotlib: The function plt.hist(data) returns the y and x values necessary for the density plot (see the documentation https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html). Resultingly, the following code creates a density plot by using the matplotlib library:

import matplotlib.pyplot as plt
dat=[-1,2,1,4,-5,3,6,1,2,1,2,5,6,5,6,2,2,2]
a=plt.hist(dat,density=True)
plt.close()
plt.figure()
plt.plot(a[1][1:],a[0])      

This code returns the following density plot

enter image description here

Check if application is on its first run

The accepted answer doesn't differentiate between a first run and subsequent upgrades. Just setting a boolean in shared preferences will only tell you if it is the first run after the app is first installed. Later if you want to upgrade your app and make some changes on the first run of that upgrade, you won't be able to use that boolean any more because shared preferences are saved across upgrades.

This method uses shared preferences to save the version code rather than a boolean.

import com.yourpackage.BuildConfig;
...

private void checkFirstRun() {

    final String PREFS_NAME = "MyPrefsFile";
    final String PREF_VERSION_CODE_KEY = "version_code";
    final int DOESNT_EXIST = -1;

    // Get current version code
    int currentVersionCode = BuildConfig.VERSION_CODE;

    // Get saved version code
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);

    // Check for first run or upgrade
    if (currentVersionCode == savedVersionCode) {

        // This is just a normal run
        return;

    } else if (savedVersionCode == DOESNT_EXIST) {

        // TODO This is a new install (or the user cleared the shared preferences)

    } else if (currentVersionCode > savedVersionCode) {

        // TODO This is an upgrade
    }

    // Update the shared preferences with the current version code
    prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}

You would probably call this method from onCreate in your main activity so that it is checked every time your app starts.

public class MainActivity extends AppCompatActivity {

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

        checkFirstRun();
    }

    private void checkFirstRun() {
        // ...
    }
}

If you needed to, you could adjust the code to do specific things depending on what version the user previously had installed.

Idea came from this answer. These also helpful:

If you are having trouble getting the version code, see the following Q&A:

Check a radio button with javascript

Do not mix CSS/JQuery syntax (# for identifier) with native JS.

Native JS solution:

document.getElementById("_1234").checked = true;

JQuery solution:

$("#_1234").prop("checked", true);

Java ArrayList how to add elements at the beginning

import com.google.common.collect.Lists;

import java.util.List;

/**
 * @author Ciccotta Andrea on 06/11/2020.
 */
public class CollectionUtils {

    /**
     * It models the prepend O(1), used against the common append/add O(n)
     * @param head first element of the list
     * @param body rest of the elements of the list
     * @return new list (with different memory-reference) made by [head, ...body]
     */
    public static <E> List<Object> prepend(final E head, List<E> final body){
        return Lists.asList(head, body.toArray());
    }

    /**
     * it models the typed version of prepend(E head, List<E> body)
     * @param type the array into which the elements of this list are to be stored
     */
    public static <E> List<E> prepend(final E head, List<E> body, final E[] type){
        return Lists.asList(head, body.toArray(type));
    }
}

Can you use CSS to mirror/flip text?

For cross browser compatibility create this class

.mirror-icon:before {
    -webkit-transform: scale(-1, 1);
    -moz-transform: scale(-1, 1);
    -ms-transform: scale(-1, 1);
    -o-transform: scale(-1, 1);
    transform: scale(-1, 1);
}

And add it to your icon class, i.e.

<i class="icon-search mirror-icon"></i>

to get a search icon with the handle on the left

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

$result2 is resource link not a string to echo it or to replace some of its parts with str_replace().

http://php.net/manual/en/function.mysql-query.php

isPrime Function for Python Language

I have a new solution which I think might be faster than any of the mentioned Function in Python

It's based on the idea that: N/D = R for any arbitrary number N, the least possible number to divide N (if not prime) is D=2 and the corresponding result R is (N/2) (highest).

As D goes bigger the result R gets smaller ex: divide by D = 3 results R = (N/3) so when we are checking if N is divisible by D we are also checking if it's divisible by R

so as D goes bigger and R goes smaller till (D == R == square root(N))

then we only need to check numbers from 2 to sqrt(N) another tip to save time, we only need to check the odd numbers as it the number is divisible by any even number it will also be divisible by 2.

so the sequence will be 3,5,7,9,......,sqrt(N).

import math
def IsPrime (n): 
    if (n <= 1 or n % 2 == 0):return False
    if n == 2:return True
    for i in range(3,int(math.sqrt(n))+1,2):
        if (n % i) == 0:
            return False
    return True

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

For PHP-FPM just search config file for error_log:

# cat /etc/php-fpm.d/www.conf | grep error_log
php_admin_value[error_log] = /var/log/php-fpm/www-error.log

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

Error: Unexpected value 'undefined' imported by the module

Unused "private http: Http" argument in the constructor of app.component.ts had caused me the same error and it resolved upon removing the unused argument of the constructor

Enable IIS7 gzip

Global Gzip in HttpModule

If you don't have access to the final IIS instance (shared hosting...) you can create a HttpModule that adds this code to every HttpApplication.Begin_Request event :

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

Testing

Kudos, no solution is done without testing. I like to use the Firefox plugin "Liveheaders" it shows all the information about every http message between the browser and server, including compression, file size (which you could compare to the file size on the server).

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

I just ran into this issue myself, in the context of ASP.NET make sure your Web.config looks like this:

  <system.webServer>
<modules>
  <remove name="FormsAuthentication" />
</modules>

<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <!--<remove name="OPTIONSVerbHandler"/>-->
  <remove name="TRACEVerbHandler" />
  <!--
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  -->
</handlers>

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

Notice the Authorization value for the Access-Control-Allow-Headers key. I was missing the Authorization value, this config solves my issue.

Calculate a MD5 hash from a string

A faster alternative of existing answer for .NET Core 2.1 and higher:

public static string CreateMD5(string s)
{
    using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
    {
        var encoding = Encoding.ASCII;
        var data = encoding.GetBytes(s);

        Span<byte> hashBytes = stackalloc byte[16];
        md5.TryComputeHash(data, hashBytes, out int written);
        if(written != hashBytes.Length)
            throw new OverflowException();


        Span<char> stringBuffer = stackalloc char[32];
        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashBytes[i].TryFormat(stringBuffer.Slice(2 * i), out _, "x2");
        }
        return new string(stringBuffer);
    }
}

You can optimize it even more if you are sure that your strings are small enough and replace encoding.GetBytes by unsafe int GetBytes(ReadOnlySpan chars, Span bytes) alternative.

How to study design patterns?

Design patterns are just tools--kind of like library functions. If you know that they are there and their approximate function, you can go dig them out of a book when needed.

There is nothing magic about design patterns, and any good programmer figured 90% of them out for themselves before any books came out. For the most part I consider the books to be most useful at simply defining names for the various patterns so we can discuss them more easily.

PHPUnit assert that an exception was thrown?

Comprehensive Solution

PHPUnit's current "best practices" for exception testing seem.. lackluster (docs).

Since I wanted more than the current expectException implementation, I made a trait to use on my test cases. It's only ~50 lines of code.

  • Supports multiple exceptions per test
  • Supports assertions called after the exception is thrown
  • Robust and clear usage examples
  • Standard assert syntax
  • Supports assertions for more than just message, code, and class
  • Supports inverse assertion, assertNotThrows
  • Supports PHP 7 Throwable errors

Library

I published the AssertThrows trait to Github and packagist so it can be installed with composer.

Simple Example

Just to illustrate the spirit behind the syntax:

<?php

// Using simple callback
$this->assertThrows(MyException::class, [$obj, 'doSomethingBad']);

// Using anonymous function
$this->assertThrows(MyException::class, function() use ($obj) {
    $obj->doSomethingBad();
});

Pretty neat?


Full Usage Example

Please see below for a more comprehensive usage example:

<?php

declare(strict_types=1);

use Jchook\AssertThrows\AssertThrows;
use PHPUnit\Framework\TestCase;

// These are just for illustration
use MyNamespace\MyException;
use MyNamespace\MyObject;

final class MyTest extends TestCase
{
    use AssertThrows; // <--- adds the assertThrows method

    public function testMyObject()
    {
        $obj = new MyObject();

        // Test a basic exception is thrown
        $this->assertThrows(MyException::class, function() use ($obj) {
            $obj->doSomethingBad();
        });

        // Test custom aspects of a custom extension class
        $this->assertThrows(MyException::class, 
            function() use ($obj) {
                $obj->doSomethingBad();
            },
            function($exception) {
                $this->assertEquals('Expected value', $exception->getCustomThing());
                $this->assertEquals(123, $exception->getCode());
            }
        );

        // Test that a specific exception is NOT thrown
        $this->assertNotThrows(MyException::class, function() use ($obj) {
            $obj->doSomethingGood();
        });
    }
}

?>

Understanding checked vs unchecked exceptions in Java

  1. Is the above considered to be a checked exception? No The fact that you are handling an exception does not make it a Checked Exception if it is a RuntimeException.

  2. Is RuntimeException an unchecked exception? Yes

Checked Exceptions are subclasses of java.lang.Exception Unchecked Exceptions are subclasses of java.lang.RuntimeException

Calls throwing checked exceptions need to be enclosed in a try{} block or handled in a level above in the caller of the method. In that case the current method must declare that it throws said exceptions so that the callers can make appropriate arrangements to handle the exception.

Hope this helps.

Q: should I bubble up the exact exception or mask it using Exception?

A: Yes this is a very good question and important design consideration. The class Exception is a very general exception class and can be used to wrap internal low level exceptions. You would better create a custom exception and wrap inside it. But, and a big one - Never ever obscure in underlying original root cause. For ex, Don't ever do following -

try {
     attemptLogin(userCredentials);
} catch (SQLException sqle) {
     throw new LoginFailureException("Cannot login!!"); //<-- Eat away original root cause, thus obscuring underlying problem.
}

Instead do following:

try {
     attemptLogin(userCredentials);
} catch (SQLException sqle) {
     throw new LoginFailureException(sqle); //<-- Wrap original exception to pass on root cause upstairs!.
}

Eating away original root cause buries the actual cause beyond recovery is a nightmare for production support teams where all they are given access to is application logs and error messages. Although the latter is a better design but many people don't use it often because developers just fail to pass on the underlying message to caller. So make a firm note: Always pass on the actual exception back whether or not wrapped in any application specific exception.

On try-catching RuntimeExceptions

RuntimeExceptions as a general rule should not be try-catched. They generally signal a programming error and should be left alone. Instead the programmer should check the error condition before invoking some code which might result in a RuntimeException. For ex:

try {
    setStatusMessage("Hello Mr. " + userObject.getName() + ", Welcome to my site!);
} catch (NullPointerException npe) {
   sendError("Sorry, your userObject was null. Please contact customer care.");
}

This is a bad programming practice. Instead a null-check should have been done like -

if (userObject != null) {
    setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!);
} else {
   sendError("Sorry, your userObject was null. Please contact customer care.");
}

But there are times when such error checking is expensive such as number formatting, consider this -

try {
    String userAge = (String)request.getParameter("age");
    userObject.setAge(Integer.parseInt(strUserAge));
} catch (NumberFormatException npe) {
   sendError("Sorry, Age is supposed to be an Integer. Please try again.");
}

Here pre-invocation error checking is not worth the effort because it essentially means to duplicate all the string-to-integer conversion code inside parseInt() method - and is error prone if implemented by a developer. So it is better to just do away with try-catch.

So NullPointerException and NumberFormatException are both RuntimeExceptions, catching a NullPointerException should replaced with a graceful null-check while I recommend catching a NumberFormatException explicitly to avoid possible introduction of error prone code.

How do I return multiple values from a function?

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.

Example (From the docs):

class Employee(NamedTuple):  # inherit from typing.NamedTuple
    name: str
    id: int = 3  # default value

employee = Employee('Guido')
assert employee.id == 3

Read file from aws s3 bucket using node fs

Since you seem to want to process an S3 text file line-by-line. Here is a Node version that uses the standard readline module and AWS' createReadStream()

const readline = require('readline');

const rl = readline.createInterface({
    input: s3.getObject(params).createReadStream()
});

rl.on('line', function(line) {
    console.log(line);
})
.on('close', function() {
});

How to both read and write a file in C#

Don't forget the easy route:

    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"C:\words.txt");
        File.WriteAllText(@"C:\words.txt", text + "DERP");
    }

Currency format for display

The problem with taking a given number and displaying it with .ToString("C", culture) is that it effectively changes the amount to the default currency of the given culture. If you have a given amount, the ISO currency code of that amount, and you want to display it for a given culture, I would recommend just creating a decimal extension method like the one below. This will not automatically assume that the currency is in the default currency of the culture:

public static string ToFormattedCurrencyString(
    this decimal currencyAmount,
    string isoCurrencyCode,
CultureInfo userCulture)
{
    var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;

    if (userCurrencyCode == isoCurrencyCode)
    {
        return currencyAmount.ToString("C", userCulture);
    }

    return string.Format(
        "{0} {1}", 
        isoCurrencyCode, 
        currencyAmount.ToString("N2", userCulture));
}

This will either use the local currency symbol or the ISO currency code with the amount -- whichever is more appropriate. More on the topic in this blog post.

Remove an item from array using UnderscoreJS

Please exercise care if you are filtering strings and looking for case insensitive filters. _.without() is case sensitive. You can also use _.reject() as shown below.

var arr = ["test","test1","test2"];

var filtered = _.filter(arr, function(arrItem) {
    return arrItem.toLowerCase() !== "TEST".toLowerCase();
});
console.log(filtered);
// ["test1", "test2"]

var filtered1 = _.without(arr,"TEST");
console.log(filtered1);
// ["test", "test1", "test2"]

var filtered2 = _.reject(arr, function(arrItem){ 
    return arrItem.toLowerCase() === "TEST".toLowerCase();
});
console.log(filtered2);
// ["test1", "test2"]

Python: tf-idf-cosine: to find document similarity

I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.

Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III

the output will be as follows :

[[ 1.          0.07102631  0.02731343  0.06348799]]

here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.

Ant is using wrong java version

According to the Ant Documentation, set JAVACMD environment variable to complete path to java.exe of the JRE version that you want to run Ant under.

jQuery Selector: Id Ends With?

In order to find an iframe id ending with "iFrame" within a page containing many iframes.

jQuery(document).ready(function (){     
                  jQuery("iframe").each(function(){                     
                    if( jQuery(this).attr('id').match(/_iFrame/) ) {
                            alert(jQuery(this).attr('id'));

                     }                   
                  });     
         });

Example: Communication between Activity and Service using Messaging

Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

Checked myself, everything works like a charm (activity and service names may differ from original).

Two inline-block, width 50% elements wrap to second line

You can remove the whitespaces via css using white-space so you can keep your pretty HTML layout. Don't forget to set the white-space back to normal again if you want your text to wrap inside the columns.

Tested in IE9, Chrome 18, FF 12

.container { white-space: nowrap; }
.column { display: inline-block; width: 50%; white-space: normal; }

<div class="container">
  <div class="column">text that can wrap</div>
  <div class="column">text that can wrap</div>
</div>

Create a .csv file with values from a Python list

The best option I've found was using the savetxt from the numpy module:

import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)

In case you have multiple lists that need to be stacked

np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)

Loading a properties file from Java package

Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.

How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties

Which JRE am I using?

I had a problem where my Java applications quit work with no discernible evidence that I could find. It turned out my system started using the 64-bit version rather than the 32-bit version was needed (Windows Server 2012). In Windows, the command:

Javaw -version

just brought me back to the command prompt without any information. It wasn't until I tried

Javaw -Version 2>x.txt
type x.txt

that it gave me what was being executed was the 64-bit version. It boiled down to my PATH environment variable finding the 64-bit version first.

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Kill a postgresql session/connection

There is no need to drop it. Just delete and recreate the public schema. In most cases this have exactly the same effect.

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end

How do I increase the capacity of the Eclipse output console?

Alternative

If your console is not empty, right click on the Console area > Preferences... > change the value for the Console buffer size (characters) (recommended) or uncheck the Limit console output (not recommended):

enter image description here enter image description here

Fullscreen Activity in Android?

On Android 10, none worked for me.

But I that worked perfectly fine (1st line in oncreate):

    View decorView = getWindow().getDecorView();
    int uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE;
    decorView.setSystemUiVisibility(uiOptions);

    setContentView(....);

    if (getSupportActionBar() != null) {
        getSupportActionBar().hide();
    }

enjoy :)

How to hide collapsible Bootstrap 4 navbar on click

I am using ANGULAR and since it gave me problems the routerLink just add the data-toggle and target in the li tag.... or use jquery like "ZimSystem"

_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
        <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">_x000D_
          <a class="nav-link" routerLink="/inicio" routerLinkActive="active" >Inicio</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Converting year and month ("yyyy-mm" format) to a date?

Since dates correspond to a numeric value and a starting date, you indeed need the day. If you really need your data to be in Date format, you can just fix the day to the first of each month manually by pasting it to the date:

month <- "2009-03"
as.Date(paste(month,"-01",sep=""))

Check whether number is even or odd

You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:

public static void main(String[] args) {        
    System.out.println("Enter a number to check if it is even or odd");        
    System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));        
}

How to prevent Screen Capture in Android

about photo screenshot, FLAG_SECURE not working rooted device.

but if you monitor the screenshot file, you can prevent from getting original file.

try this one.

1. monitoring screenshot(file monitor) with android remote service
2. delete original screenshot image.
3. deliver the bitmap instance so you can modify.

How to open link in new tab on html?

Use target="_blank":

<a href="http://www.example.com/" target="_blank" rel="noopener noreferrer">This will open in a new window!</a>

How do I truncate a .NET string?

The popular library Humanizer has a Truncate method. To install with NuGet:

Install-Package Humanizer

How can I make Visual Studio wrap lines at 80 characters?

Tools >> Options >> Text Editor >> All Languages >> General >> Select Word Wrap.

I dont know if you can select a specific number of columns?

EOFError: EOF when reading a line

convert your inputs to ints:

width = int(input())
height = int(input())

ASP.NET MVC ActionLink and post method

You can't use an ActionLink because that just renders an anchor <a> tag.
You can use a jQuery AJAX post.
Or just call the form's submit method with or without jQuery (which would be non-AJAX), perhaps in the onclick event of whatever control takes your fancy.

pip not working in Python Installation in Windows 10

Make sure the path to scripts folder for the python version is added to the path environment/system variable in order to use pip command directly without the whole path to pip.exe which is inside the scripts folder.

The scripts folder would be inside the python folder for the version that you are using, which by default would be inside c drive or in c:/program files or c:/program files (x86).

Then use commands as mentioned below. You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator.

python -m pip install packagename
python -m pip uninstall packagename
python -m pip install --upgrade packagename

In case you have more than one version of python. You may replace python with py -versionnumber for example py -2 for python 2 or you may replace it with the path to the corresponding python.exe file. For example "c:\python27\python".

json_decode to array

json_decode($data, true); // Returns data in array format 

json_decode($data); // Returns collections 

So, If want an array than you can pass the second argument as 'true' in json_decode function.

docker mounting volumes on host

If you came here because you were looking for a simple way to browse any VOLUME:

  1. Find out the name of the volume with docker volume list
  2. Shut down all running containers to which this volume is attached to
  3. Run docker run -it --rm --mount source=[NAME OF VOLUME],target=/volume busybox
  4. A shell will open. cd /volume to enter the volume.

Dealing with float precision in Javascript

From this post: How to deal with floating point number precision in JavaScript?

You have a few options:

  • Use a special datatype for decimals, like decimal.js
  • Format your result to some fixed number of significant digits, like this: (Math.floor(y/x) * x).toFixed(2)
  • Convert all your numbers to integers

nginx: [emerg] "server" directive is not allowed here

There might be just a typo anywhere inside a file imported by the config. For example, I made a typo deep inside my config file:

loccation /sense/movies/ {
                  mp4;
        }

(loccation instead of location), and this causes the error:

nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-enabled/xxx.xx:1

Peak memory usage of a linux/unix process

If the process runs for at least a couple seconds, then you can use the following bash script, which will run the given command line then print to stderr the peak RSS (substitute for rss any other attribute you're interested in). It's somewhat lightweight, and it works for me with the ps included in Ubuntu 9.04 (which I can't say for time).

#!/usr/bin/env bash
"$@" & # Run the given command line in the background.
pid=$! peak=0
while true; do
  sleep 1
  sample="$(ps -o rss= $pid 2> /dev/null)" || break
  let peak='sample > peak ? sample : peak'
done
echo "Peak: $peak" 1>&2

Android YouTube app Play Video Intent

/**
 * Intent to open a YouTube Video
 * 
 * @param pm
 *            The {@link PackageManager}.
 * @param url
 *            The URL or YouTube video ID.
 * @return the intent to open the YouTube app or Web Browser to play the video
 */
public static Intent newYouTubeIntent(PackageManager pm, String url) {
    Intent intent;
    if (url.length() == 11) {
        // youtube video id
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + url));
    } else {
        // url to video
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    }
    try {
        if (pm.getPackageInfo("com.google.android.youtube", 0) != null) {
            intent.setPackage("com.google.android.youtube");
        }
    } catch (NameNotFoundException e) {
    }
    return intent;
}

How to show two figures using matplotlib?

I had this same problem.


Did:

f1 = plt.figure(1)

# code for figure 1

# don't write 'plt.show()' here


f2 = plt.figure(2)

# code for figure 2

plt.show()


Write 'plt.show()' only once, after the last figure. Worked for me.

get dataframe row count based on conditions

You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking

In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))

In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]: 
           A         B         C         D
12  0.491683  0.137766  0.859753 -1.041487
13  0.376200  0.575667  1.534179  1.247358
14  0.428739  1.539973  1.057848 -1.254489

In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]: 
A    3
B    3
C    3
D    3
dtype: int64

In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3

Convert string to date then format the date

In one line:

String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));

Where:

String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));

Can a CSS class inherit one or more other classes?

Unfortunately, CSS does not provide 'inheritance' in the way that programming languages like C++, C# or Java do. You can't declare a CSS class an then extend it with another CSS class.

However, you can apply more than a single class to an tag in your markup ... in which case there is a sophisticated set of rules that determine which actual styles will get applied by the browser.

<span class="styleA styleB"> ... </span>

CSS will look for all the styles that can be applied based on what your markup, and combine the CSS styles from those multiple rules together.

Typically, the styles are merged, but when conflicts arise, the later declared style will generally win (unless the !important attribute is specified on one of the styles, in which case that wins). Also, styles applied directly to an HTML element take precedence over CSS class styles.

How to submit an HTML form on loading the page?

You can try also using below script

<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>

<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html> 

How to remove tab indent from several lines in IDLE?

By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection

Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)

Find size of an array in Perl

All three give the same result if we modify the second one a bit:

my @arr = (2, 4, 8, 10);

print "First result:\n";
print scalar @arr; 

print "\n\nSecond result:\n";
print $#arr + 1; # Shift numeration with +1 as it shows last index that starts with 0.

print "\n\nThird result:\n";
my $arrSize = @arr;
print $arrSize;